"use strict";
(() => {
var exports = {};
exports.id = 398;
exports.ids = [398];
exports.modules = {

/***/ 9460:
/***/ ((module) => {

module.exports = require("lokijs");

/***/ }),

/***/ 9456:
/***/ ((module) => {

module.exports = require("phin");

/***/ }),

/***/ 7773:
/***/ ((module) => {

module.exports = require("winston");

/***/ }),

/***/ 7564:
/***/ ((module) => {

module.exports = import("chalk");;

/***/ }),

/***/ 3906:
/***/ ((module) => {

module.exports = import("docmq");;

/***/ }),

/***/ 2353:
/***/ ((module) => {

module.exports = import("luxon");;

/***/ }),

/***/ 8433:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (/* binding */ handler)
/* harmony export */ });
/* harmony import */ var db_loki__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4276);
/* harmony import */ var db_mq__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7947);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2353);
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(9456);
/* harmony import */ var phin__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(phin__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var winston_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2053);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([db_mq__WEBPACK_IMPORTED_MODULE_1__, luxon__WEBPACK_IMPORTED_MODULE_2__, winston_logger__WEBPACK_IMPORTED_MODULE_4__]);
([db_mq__WEBPACK_IMPORTED_MODULE_1__, luxon__WEBPACK_IMPORTED_MODULE_2__, winston_logger__WEBPACK_IMPORTED_MODULE_4__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);





/** Stats a worker cron that polls and manages events in development */ async function handler(req, res) {
    // begin processing. Workers are idempotent. Adding a new worker sets the worker for future runs safely
    const q = await (0,db_mq__WEBPACK_IMPORTED_MODULE_1__/* .getQueue */ .w)();
    const jc = (0,db_loki__WEBPACK_IMPORTED_MODULE_0__/* .getCollection */ ._)("tds-jobs");
    const runs = (0,db_loki__WEBPACK_IMPORTED_MODULE_0__/* .getCollection */ ._)("tds-runs");
    q.process(async (job, api)=>{
        const j = jc.findOne({
            id: job.jobId
        });
        if (!j) {
            return api.fail("No matching job found");
        }
        const headers = {
            ...j.headers ? JSON.parse(j.headers) : {},
            "user-agent": "Taskless DevServer Worker",
            "content-type": "application/json",
            "x-taskless-queue": job.queueName,
            "x-taskless-id": job.projectId
        };
        const request = {
            url: j.endpoint,
            method: "POST",
            headers,
            // attach data if set
            ...j.body ? {
                data: j.body
            } : {},
            followRedirects: true,
            timeout: 15000
        };
        let statusCode;
        let responseBody;
        try {
            const resp = await phin__WEBPACK_IMPORTED_MODULE_3___default()({
                ...request,
                parse: "json"
            });
            statusCode = resp.statusCode ?? 200;
            responseBody = JSON.stringify(resp.body);
            if (`${resp.statusCode}`.indexOf("2") !== 0) {
                const err = new db_mq__WEBPACK_IMPORTED_MODULE_1__/* .WorkerRequestError */ .O("Received non-2xx response");
                err.code = statusCode;
                err.body = responseBody;
                return api.fail(err);
            }
        } catch (e) {
            console.error(e);
            return api.fail("Unknown error from phin");
        }
        return api.ack({
            statusCode: statusCode ?? 200,
            body: responseBody ?? ""
        });
    });
    // informational sync on next, fail, and dead
    q.events.on("ack", (info)=>{
        winston_logger__WEBPACK_IMPORTED_MODULE_4__/* .logger.info */ .k.info(`ACK of ${info.ref}`);
        const now = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.now();
        runs.insertOne({
            ts: now.toISO(),
            metadata: {
                id: info.ref,
                name: info.payload.name
            },
            success: true,
            statusCode: 200,
            payload: JSON.stringify(info.payload),
            body: JSON.stringify(info.result)
        });
        jc.chain().find({
            id: info.ref
        }).update((doc)=>{
            if (info.next) {
                doc.runAt = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromJSDate(info.next).toISO();
            }
            doc.summary = {
                nextRun: info.next ? luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromJSDate(info.next).toISO() : undefined,
                lastRun: now.toISO(),
                lastStatus: true
            };
        }).data();
    });
    // on fail, add to job db runs
    q.events.on("fail", (info)=>{
        var ref;
        winston_logger__WEBPACK_IMPORTED_MODULE_4__/* .logger.info */ .k.info(`FAIL of ${info.ref}`);
        winston_logger__WEBPACK_IMPORTED_MODULE_4__/* .logger.error */ .k.error(info.error);
        const now = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.now();
        const code = info.error instanceof db_mq__WEBPACK_IMPORTED_MODULE_1__/* .WorkerRequestError */ .O ? info.error.code ?? 500 : info.statusCode ?? 500;
        const body = info.error instanceof db_mq__WEBPACK_IMPORTED_MODULE_1__/* .WorkerRequestError */ .O ? info.error.body : JSON.stringify(info.result) ?? "";
        const name = ((ref = info.payload) === null || ref === void 0 ? void 0 : ref.name) ?? info.ref;
        runs.insertOne({
            ts: now.toISO(),
            metadata: {
                id: info.ref,
                name
            },
            success: false,
            statusCode: code,
            payload: JSON.stringify(info.payload),
            body
        });
        jc.chain().find({
            id: info.ref
        }).update((doc)=>{
            if (info.next) {
                doc.runAt = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromJSDate(info.next).toISO();
            }
            doc.summary = {
                nextRun: info.next ? luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromJSDate(info.next).toISO() : undefined,
                lastRun: now.toISO(),
                lastStatus: true
            };
        }).data();
    });
    // on dead, update next if needed
    q.events.on("dead", (info)=>{
        winston_logger__WEBPACK_IMPORTED_MODULE_4__/* .logger.info */ .k.info(`DEAD ITEM: ${info.ref}`);
        jc.chain().find({
            id: info.ref
        }).update((doc)=>{
            if (!info.next) {
                return;
            }
            doc.runAt = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromJSDate(info.next).toISO();
        }).data();
    });
    q.events.on("error", (err)=>{
        console.error(err);
    });
    winston_logger__WEBPACK_IMPORTED_MODULE_4__/* .logger.info */ .k.info("Worker Started");
    return res.status(200).json({
        watch: true
    });
}

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ }),

/***/ 2053:
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.a(module, async (__webpack_handle_async_dependencies__, __webpack_async_result__) => { try {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "k": () => (/* binding */ logger)
/* harmony export */ });
/* harmony import */ var winston__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7773);
/* harmony import */ var winston__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(winston__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var chalk__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7564);
/* harmony import */ var luxon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2353);
var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([chalk__WEBPACK_IMPORTED_MODULE_1__, luxon__WEBPACK_IMPORTED_MODULE_2__]);
([chalk__WEBPACK_IMPORTED_MODULE_1__, luxon__WEBPACK_IMPORTED_MODULE_2__] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);



const { combine , timestamp , printf  } = winston__WEBPACK_IMPORTED_MODULE_0__.format;
const getDebugLevel = ()=>{
    const level = process.env.TASKLESS_DEV_DEBUG ?? "info";
    return [
        "debug",
        "log",
        "info",
        "warn",
        "error"
    ].includes(level) ? level : "info";
};
const colorizedLabel = {
    info: chalk__WEBPACK_IMPORTED_MODULE_1__["default"].blue,
    warn: chalk__WEBPACK_IMPORTED_MODULE_1__["default"].yellow,
    error: chalk__WEBPACK_IMPORTED_MODULE_1__["default"].red
};
const logFormat = printf(({ level , message , label , job , timestamp  })=>{
    const colorizer = colorizedLabel[level] || colorizedLabel.info;
    const dt = luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.fromISO(timestamp);
    const lbl = label ?? "root";
    const jobLabel = job ? `${lbl} ${job}` : null;
    const fullLabel = jobLabel ?? lbl;
    const ts = `${dt.toLocaleString(luxon__WEBPACK_IMPORTED_MODULE_2__.DateTime.TIME_24_WITH_SECONDS)}.${dt.get("millisecond")}`;
    return `${colorizer(level).padEnd(6, " ")} - ${chalk__WEBPACK_IMPORTED_MODULE_1__["default"].gray(`${ts} (${fullLabel})`)} ${message}`;
});
const logger = (0,winston__WEBPACK_IMPORTED_MODULE_0__.createLogger)({
    format: combine(timestamp(), logFormat),
    transports: [
        new winston__WEBPACK_IMPORTED_MODULE_0__.transports.Console({
            level: getDebugLevel()
        }), 
    ]
});

__webpack_async_result__();
} catch(e) { __webpack_async_result__(e); } });

/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = __webpack_require__.X(0, [947], () => (__webpack_exec__(8433)));
module.exports = __webpack_exports__;

})();