"use strict";
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.tsCodegen = void 0;
const shared_1 = require("@vue/shared");
const alien_signals_1 = require("alien-signals");
const path = __importStar(require("path-browserify"));
const script_1 = require("../codegen/script");
const style_1 = require("../codegen/style");
const template_1 = require("../codegen/template");
const compilerOptions_1 = require("../compilerOptions");
const scriptRanges_1 = require("../parsers/scriptRanges");
const scriptSetupRanges_1 = require("../parsers/scriptSetupRanges");
const vueCompilerOptions_1 = require("../parsers/vueCompilerOptions");
const signals_1 = require("../utils/signals");
exports.tsCodegen = new WeakMap();
const validLangs = new Set(['js', 'jsx', 'ts', 'tsx']);
const plugin = ({ modules: { typescript: ts }, vueCompilerOptions, }) => {
    return {
        version: 2.2,
        getEmbeddedCodes(_fileName, ir) {
            const lang = computeLang(ir);
            return [{ lang, id: 'script_' + lang }];
        },
        resolveEmbeddedCode(fileName, ir, embeddedFile) {
            if (/script_(js|jsx|ts|tsx)/.test(embeddedFile.id)) {
                let codegen = exports.tsCodegen.get(ir);
                if (!codegen) {
                    exports.tsCodegen.set(ir, codegen = useCodegen(ts, vueCompilerOptions, fileName, ir));
                }
                const generatedScript = codegen.getGeneratedScript();
                embeddedFile.content = [...generatedScript.codes];
            }
        },
    };
    function computeLang(ir) {
        let lang = ir.scriptSetup?.lang ?? ir.script?.lang;
        if (ir.script && ir.scriptSetup) {
            if (ir.scriptSetup.lang !== 'js') {
                lang = ir.scriptSetup.lang;
            }
            else {
                lang = ir.script.lang;
            }
        }
        if (lang && validLangs.has(lang)) {
            return lang;
        }
        return 'ts';
    }
};
exports.default = plugin;
function useCodegen(ts, vueCompilerOptions, fileName, ir) {
    const getResolvedOptions = (0, alien_signals_1.computed)(() => {
        const options = (0, vueCompilerOptions_1.parseVueCompilerOptions)(ir.comments);
        if (options) {
            const resolver = new compilerOptions_1.CompilerOptionsResolver(ts, () => undefined /* does not support resolving target="auto" */);
            resolver.addConfig(options, path.dirname(fileName));
            return resolver.build(vueCompilerOptions);
        }
        return vueCompilerOptions;
    });
    const getScriptRanges = (0, alien_signals_1.computed)(() => ir.script && validLangs.has(ir.script.lang)
        ? (0, scriptRanges_1.parseScriptRanges)(ts, ir.script.ast, getResolvedOptions())
        : undefined);
    const getScriptSetupRanges = (0, alien_signals_1.computed)(() => ir.scriptSetup && validLangs.has(ir.scriptSetup.lang)
        ? (0, scriptSetupRanges_1.parseScriptSetupRanges)(ts, ir.scriptSetup.ast, getResolvedOptions())
        : undefined);
    const getImportedComponents = (0, signals_1.computedSet)(() => {
        const names = new Set();
        const scriptSetupRanges = getScriptSetupRanges();
        if (ir.scriptSetup && scriptSetupRanges) {
            for (const range of scriptSetupRanges.components) {
                names.add(ir.scriptSetup.content.slice(range.start, range.end));
            }
            const scriptRange = getScriptRanges();
            if (ir.script && scriptRange) {
                for (const range of scriptRange.components) {
                    names.add(ir.script.content.slice(range.start, range.end));
                }
            }
        }
        return names;
    });
    const getSetupConsts = (0, signals_1.computedSet)(() => {
        const scriptSetupRanges = getScriptSetupRanges();
        const names = new Set([
            ...scriptSetupRanges?.defineProps?.destructured?.keys() ?? [],
            ...getImportedComponents(),
        ]);
        const rest = scriptSetupRanges?.defineProps?.destructuredRest;
        if (rest) {
            names.add(rest);
        }
        return names;
    });
    const getSetupRefs = (0, signals_1.computedSet)(() => {
        return new Set(getScriptSetupRanges()?.useTemplateRef
            .map(({ name }) => name)
            .filter(name => name !== undefined));
    });
    const hasDefineSlots = (0, alien_signals_1.computed)(() => !!getScriptSetupRanges()?.defineSlots);
    const getSetupPropsAssignName = (0, alien_signals_1.computed)(() => getScriptSetupRanges()?.defineProps?.name);
    const getSetupSlotsAssignName = (0, alien_signals_1.computed)(() => getScriptSetupRanges()?.defineSlots?.name);
    const getInheritAttrs = (0, alien_signals_1.computed)(() => {
        const value = getScriptSetupRanges()?.defineOptions?.inheritAttrs
            ?? getScriptRanges()?.exportDefault?.options?.inheritAttrs;
        return value !== 'false';
    });
    const getComponentName = (0, alien_signals_1.computed)(() => {
        let name;
        const componentOptions = getScriptRanges()?.exportDefault?.options;
        if (ir.script && componentOptions?.name) {
            name = ir.script.content.slice(componentOptions.name.start + 1, componentOptions.name.end - 1);
        }
        else {
            const { defineOptions } = getScriptSetupRanges() ?? {};
            if (ir.scriptSetup && defineOptions?.name) {
                name = defineOptions.name;
            }
            else {
                const baseName = path.basename(fileName);
                name = baseName.slice(0, baseName.lastIndexOf('.'));
            }
        }
        return (0, shared_1.capitalize)((0, shared_1.camelize)(name));
    });
    const getGeneratedTemplate = (0, alien_signals_1.computed)(() => {
        if (getResolvedOptions().skipTemplateCodegen || !ir.template) {
            return;
        }
        return (0, template_1.generateTemplate)({
            typescript: ts,
            vueCompilerOptions: getResolvedOptions(),
            template: ir.template,
            componentName: getComponentName(),
            setupConsts: getSetupConsts(),
            setupRefs: getSetupRefs(),
            hasDefineSlots: hasDefineSlots(),
            propsAssignName: getSetupPropsAssignName(),
            slotsAssignName: getSetupSlotsAssignName(),
            inheritAttrs: getInheritAttrs(),
        });
    });
    const getGeneratedStyle = (0, alien_signals_1.computed)(() => {
        if (!ir.styles.length) {
            return;
        }
        return (0, style_1.generateStyle)({
            typescript: ts,
            vueCompilerOptions: getResolvedOptions(),
            styles: ir.styles,
            setupConsts: getSetupConsts(),
            setupRefs: getSetupRefs(),
        });
    });
    const getSetupExposed = (0, signals_1.computedSet)(() => {
        const allVars = new Set();
        const scriptSetupRanges = getScriptSetupRanges();
        if (!ir.scriptSetup || !scriptSetupRanges) {
            return allVars;
        }
        for (const range of scriptSetupRanges.bindings) {
            const name = ir.scriptSetup.content.slice(range.start, range.end);
            allVars.add(name);
        }
        const scriptRanges = getScriptRanges();
        if (ir.script && scriptRanges) {
            for (const range of scriptRanges.bindings) {
                const name = ir.script.content.slice(range.start, range.end);
                allVars.add(name);
            }
        }
        if (!allVars.size) {
            return allVars;
        }
        return new Set([
            ...getGeneratedTemplate()?.componentAccessMap.keys() ?? [],
            ...getGeneratedStyle()?.componentAccessMap.keys() ?? [],
            ...ir.template?.ast?.components.flatMap(name => [(0, shared_1.camelize)(name), (0, shared_1.capitalize)((0, shared_1.camelize)(name))]) ?? [],
        ].filter(name => allVars.has(name)));
    });
    const getGeneratedScript = (0, alien_signals_1.computed)(() => {
        return (0, script_1.generateScript)({
            vueCompilerOptions: getResolvedOptions(),
            fileName,
            script: ir.script,
            scriptSetup: ir.scriptSetup,
            exposed: getSetupExposed(),
            scriptRanges: getScriptRanges(),
            scriptSetupRanges: getScriptSetupRanges(),
            templateAndStyleTypes: new Set([
                ...getGeneratedTemplate()?.generatedTypes ?? [],
                ...getGeneratedStyle()?.generatedTypes ?? [],
            ]),
            templateAndStyleCodes: [
                ...getGeneratedStyle()?.codes ?? [],
                ...getGeneratedTemplate()?.codes ?? [],
            ],
        });
    });
    return {
        getScriptRanges,
        getScriptSetupRanges,
        getGeneratedScript,
        getGeneratedTemplate,
        getImportedComponents,
        getSetupExposed,
    };
}
//# sourceMappingURL=vue-tsx.js.map