"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initParser = initParser;
exports.registerLanguage = registerLanguage;
exports.isLanguageSupported = isLanguageSupported;
exports.parseSource = parseSource;
exports.getMapper = getMapper;
exports.listLanguages = listLanguages;
const path_1 = __importDefault(require("path"));
/** Map from language name (matching file-lang.ts names) to entry. */
const languages = new Map();
/** WASM directory containing grammar .wasm files */
const WASM_DIR = path_1.default.join(path_1.default.dirname(require.resolve('@vscode/tree-sitter-wasm/package.json')), 'wasm');
let _initPromise = null;
/** web-tree-sitter module (lazy loaded) */
let _wts = null;
/** Initialize the WASM parser runtime. Must be called before parsing. */
async function initParser() {
    if (_wts)
        return;
    if (_initPromise)
        return _initPromise;
    _initPromise = (async () => {
        _wts = require('web-tree-sitter');
        await _wts.Parser.init();
    })();
    return _initPromise;
}
/** Register a language (sync — only stores metadata). */
function registerLanguage(name, wasmFile, mapper) {
    languages.set(name, { wasmFile, language: null, mapper });
}
/** Load a language WASM if not already loaded. */
async function loadLanguage(entry) {
    if (entry.language)
        return entry.language;
    await initParser();
    const wasmPath = path_1.default.join(WASM_DIR, entry.wasmFile);
    entry.language = await _wts.Language.load(wasmPath);
    return entry.language;
}
/** Check if a language is registered. */
function isLanguageSupported(languageName) {
    return languages.has(languageName);
}
/** Reusable parser per language (avoids WASM memory leak from creating Parser on every call). */
const parsers = new Map();
/** Parse source code with the appropriate language grammar. Returns tree (caller must call tree.delete() when done) or null. */
async function parseSource(code, languageName) {
    const entry = languages.get(languageName);
    if (!entry)
        return null;
    await initParser();
    const lang = await loadLanguage(entry);
    let parser = parsers.get(languageName);
    if (!parser) {
        parser = new _wts.Parser();
        parser.setLanguage(lang);
        parsers.set(languageName, parser);
    }
    const tree = parser.parse(code);
    return tree ?? null;
}
/** Get the mapper for a language. Returns undefined for unsupported languages. */
function getMapper(languageName) {
    return languages.get(languageName)?.mapper;
}
/** List all registered language names. */
function listLanguages() {
    return [...languages.keys()];
}
