"use strict";
// ---------------------------------------------------------------------------
// Vite Plugin for SimpleSteps Transformer
//
// Wraps the TypeScript transformer for use with Vite builds.
// Applies the SimpleSteps transform during the Vite build pipeline.
// ---------------------------------------------------------------------------
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.simpleStepsVitePlugin = simpleStepsVitePlugin;
const typescript_1 = __importDefault(require("typescript"));
const index_js_1 = require("../index.js");
/**
 * Vite plugin that applies the SimpleSteps TypeScript transformer.
 *
 * @example
 * ```ts
 * // vite.config.ts
 * import { simpleStepsVitePlugin } from '@simplesteps/core/transformer/plugins/vite';
 *
 * export default defineConfig({
 *   plugins: [simpleStepsVitePlugin()],
 * });
 * ```
 */
function simpleStepsVitePlugin(options = {}) {
    const extensions = options.extensions ?? ['.ts', '.tsx'];
    const tsconfigPath = options.tsconfig ?? './tsconfig.json';
    let program;
    return {
        name: 'simplesteps-transformer',
        enforce: 'pre',
        transform(code, id) {
            // Only process TypeScript files
            if (!extensions.some(ext => id.endsWith(ext)))
                return null;
            // Quick check: skip files that don't reference SimpleStepsStateMachine
            if (!code.includes('SimpleStepsStateMachine'))
                return null;
            // Build or reuse the program
            if (!program) {
                const configFile = typescript_1.default.readConfigFile(tsconfigPath, typescript_1.default.sys.readFile);
                if (configFile.error)
                    return null;
                const parsed = typescript_1.default.parseJsonConfigFileContent(configFile.config, typescript_1.default.sys, process.cwd());
                program = typescript_1.default.createProgram(parsed.fileNames, parsed.options);
            }
            // Apply the transformer
            const sourceFile = program.getSourceFile(id);
            if (!sourceFile)
                return null;
            const transformer = (0, index_js_1.createSimpleStepsTransformer)(program);
            const result = typescript_1.default.transform(sourceFile, [transformer]);
            const transformedFile = result.transformed[0];
            const printer = typescript_1.default.createPrinter({ newLine: typescript_1.default.NewLineKind.LineFeed });
            const output = printer.printFile(transformedFile);
            result.dispose();
            // Only return if the code actually changed
            if (output === code)
                return null;
            return { code: output, map: null };
        },
    };
}
exports.default = simpleStepsVitePlugin;
//# sourceMappingURL=vite.js.map