"use strict";
// src/orchestrator/graph/TreeSitterRegistry.ts
// v1.14.0 — Lazy grammar loader for tree-sitter.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectLanguage = detectLanguage;
exports.parseFile = parseFile;
const path = __importStar(require("path"));
const PARSE_CHUNK_BYTES = 1024;
/**
 * tree-sitter@0.21 Node bindings throw "Invalid argument" on sources larger
 * than ~32KB when passed as a single string. The callback-based input API
 * bypasses that limit by streaming the source in fixed-size chunks. Cost is
 * negligible (a few extra function calls per file) and it works for every
 * file we care about (the v1.14 build had 5 silent failures — Gateway.ts
 * and 4 others — all >32KB).
 */
function streamingInput(source) {
    return (index) => {
        if (index >= source.length)
            return null;
        return source.slice(index, Math.min(index + PARSE_CHUNK_BYTES, source.length));
    };
}
let cachedParserCtor = null;
const grammarCache = {};
function loadParser() {
    if (cachedParserCtor)
        return cachedParserCtor;
    cachedParserCtor = require('tree-sitter');
    return cachedParserCtor;
}
function loadGrammar(lang) {
    if (grammarCache[lang])
        return grammarCache[lang];
    try {
        if (lang === 'ts') {
            grammarCache.ts = require('tree-sitter-typescript').typescript;
        }
        else if (lang === 'tsx') {
            grammarCache.tsx = require('tree-sitter-typescript').tsx;
        }
        else if (lang === 'js') {
            grammarCache.js = require('tree-sitter-javascript');
        }
        else if (lang === 'py') {
            grammarCache.py = require('tree-sitter-python');
        }
        return grammarCache[lang] || null;
    }
    catch (err) {
        if ((process.env.OPENLIFE_DEBUG || '').toLowerCase() === 'true') {
            console.warn(`[GRAPH] grammar "${lang}" unavailable: ${err instanceof Error ? err.message : String(err)}`);
        }
        return null;
    }
}
function detectLanguage(filePath) {
    const ext = path.extname(filePath).toLowerCase();
    switch (ext) {
        case '.ts': return 'ts';
        case '.tsx': return 'tsx';
        case '.js':
        case '.mjs':
        case '.cjs':
        case '.jsx': return 'js';
        case '.py': return 'py';
        default: return null;
    }
}
function parseFile(filePath, source) {
    const lang = detectLanguage(filePath);
    if (!lang)
        return null;
    const grammar = loadGrammar(lang);
    if (!grammar)
        return null;
    const Parser = loadParser();
    const p = new Parser();
    p.setLanguage(grammar);
    // Always use streaming input — bypasses tree-sitter@0.21's 32KB string
    // buffer limit. See PARSE_CHUNK_BYTES comment above.
    try {
        const tree = p.parse(streamingInput(source));
        return { language: lang, rootNode: tree.rootNode };
    }
    catch (err) {
        if ((process.env.OPENLIFE_DEBUG || '').toLowerCase() === 'true') {
            console.warn(`[GRAPH] parseFile failed for ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
        }
        return null;
    }
}
