"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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CronDetector = exports.detectQuirrelCronJob = void 0;
const index_1 = require("../client/index");
const index_2 = require("../client/index");
const fs_1 = __importDefault(require("fs"));
const chokidar = __importStar(require("chokidar"));
const parse_gitignore_1 = require("./parse-gitignore");
const babel = __importStar(require("@babel/parser"));
const traverse_1 = __importDefault(require("@babel/traverse"));
const path_1 = __importDefault(require("path"));
const config = __importStar(require("../client/config"));
function detectQuirrelCronJob(file) {
    const quirrelImport = /["']quirrel\/(.*)["']/.exec(file);
    if (!quirrelImport) {
        return null;
    }
    const clientFramework = quirrelImport[1];
    let jobName;
    let cronSchedule;
    let cronTimezone;
    try {
        const ast = babel.parse(file, {
            sourceType: "unambiguous",
            plugins: ["typescript"],
        });
        (0, traverse_1.default)(ast, {
            CallExpression(path) {
                const { callee } = path.node;
                if (callee.type !== "Identifier" || callee.name !== "CronJob") {
                    return;
                }
                if (path.node.arguments.length < 3) {
                    return;
                }
                const [jobNameNode, cronScheduleNode] = path.node.arguments;
                if (jobNameNode.type !== "StringLiteral") {
                    return;
                }
                jobName = jobNameNode.value;
                if (cronScheduleNode.type === "StringLiteral") {
                    cronSchedule = cronScheduleNode.value;
                }
                else if (cronScheduleNode.type === "ArrayExpression") {
                    if (cronScheduleNode.elements.length > 2) {
                        return;
                    }
                    const [scheduleNode, timezoneNode] = cronScheduleNode.elements;
                    if ((scheduleNode === null || scheduleNode === void 0 ? void 0 : scheduleNode.type) !== "StringLiteral") {
                        return;
                    }
                    cronSchedule = scheduleNode.value;
                    if ((timezoneNode === null || timezoneNode === void 0 ? void 0 : timezoneNode.type) !== "StringLiteral") {
                        return;
                    }
                    cronTimezone = timezoneNode.value;
                }
                path.stop();
            },
        });
        if (!cronSchedule || !jobName) {
            return null;
        }
        return {
            route: config.withoutLeadingSlash(jobName),
            schedule: cronSchedule,
            timezone: cronTimezone !== null && cronTimezone !== void 0 ? cronTimezone : "Etc/UTC",
            framework: clientFramework,
            isValid: index_2.cron.safeParse(cronSchedule).success &&
                index_1.timezone.optional().safeParse(cronTimezone).success,
        };
    }
    catch (error) {
        return null;
    }
}
exports.detectQuirrelCronJob = detectQuirrelCronJob;
class CronDetector {
    constructor(cwd, onChange) {
        this.cwd = cwd;
        this.onChange = onChange;
        this.ready = false;
        this.pathToCronJob = {};
        const rules = (0, parse_gitignore_1.parseChokidarRulesFromGitignore)(cwd);
        this.watcher = chokidar.watch(["**/*.[jt]s", "**/*.[jt]sx"], {
            ignored: ["node_modules", "**/node_modules", ...rules.ignoredPaths],
            cwd,
        });
        this.watcher.on("add", this.on("added"));
        this.watcher.on("change", this.on("changed"));
        this.watcher.on("unlink", this.on("deleted"));
        this.watcher.on("ready", () => {
            this.ready = true;
        });
    }
    async close() {
        await this.watcher.close();
    }
    async awaitReady() {
        if (this.ready) {
            return;
        }
        await new Promise((resolve) => {
            this.watcher.on("ready", resolve);
        });
    }
    getDetectedJobs() {
        return Object.values(this.pathToCronJob);
    }
    async onNewJob(job, filePath) {
        await this.onJobChanged(job, filePath);
    }
    emitChange() {
        var _a;
        (_a = this.onChange) === null || _a === void 0 ? void 0 : _a.call(this, this.getDetectedJobs());
    }
    async onJobRemoved(job, filePath) {
        delete this.pathToCronJob[filePath];
        this.emitChange();
    }
    async onJobChanged(job, filePath) {
        this.pathToCronJob[filePath] = job;
        this.emitChange();
    }
    on(fileChangeType) {
        return async (filePath) => {
            const previousJob = this.pathToCronJob[filePath];
            if (fileChangeType === "deleted") {
                if (previousJob) {
                    await this.onJobRemoved(previousJob, filePath);
                }
                return;
            }
            const contents = fs_1.default.readFileSync(path_1.default.join(this.cwd, filePath), "utf-8");
            const newJob = detectQuirrelCronJob(contents);
            if (!newJob) {
                if (previousJob) {
                    await this.onJobRemoved(previousJob, filePath);
                }
                return;
            }
            if (!newJob.isValid) {
                console.error(`🚨Encountered invalid cron expression: ${newJob.schedule}`);
                return;
            }
            if (!previousJob && newJob) {
                return await this.onNewJob(newJob, filePath);
            }
            if (previousJob && newJob) {
                return await this.onJobChanged(newJob, filePath);
            }
        };
    }
}
exports.CronDetector = CronDetector;
//# sourceMappingURL=cron-detector.js.map