"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/server/functionsDevWorker.ts
var functionsDevWorker_exports = {};
__export(functionsDevWorker_exports, {
  createWorker: () => createWorker
});
module.exports = __toCommonJS(functionsDevWorker_exports);
var import_node_events = require("events");
var import_worker_threads = require("worker_threads");
var path = __toESM(require("path"));
var import_node_module = require("module");
var fs = __toESM(require("fs/promises"));
var vm = __toESM(require("vm"));
var url = __toESM(require("url"));
var import_node_fetch = __toESM(require("node-fetch"));
var import_errors = require("@mui/toolpad-utils/errors");
function getCircularReplacer() {
  const ancestors = [];
  return function replacer(key, value) {
    if (typeof value !== "object" || value === null) {
      return value;
    }
    while (ancestors.length > 0 && ancestors.at(-1) !== this) {
      ancestors.pop();
    }
    if (ancestors.includes(value)) {
      return "[Circular]";
    }
    ancestors.push(value);
    return value;
  };
}
var fileContents = /* @__PURE__ */ new Map();
var moduleCache = /* @__PURE__ */ new Map();
function loadModule(fullPath, content) {
  const moduleRequire = (0, import_node_module.createRequire)(url.pathToFileURL(fullPath));
  const moduleObject = { exports: {} };
  vm.runInThisContext(`((require, exports, module) => {
${content}
})`)(
    moduleRequire,
    moduleObject.exports,
    moduleObject
  );
  return moduleObject;
}
async function resolveFunctions(filePath) {
  const fullPath = path.resolve(filePath);
  const content = await fs.readFile(fullPath, "utf-8");
  if (content !== fileContents.get(fullPath)) {
    moduleCache.delete(fullPath);
    fileContents.set(fullPath, content);
  }
  let cachedModule = moduleCache.get(fullPath);
  if (!cachedModule) {
    cachedModule = loadModule(fullPath, content);
    moduleCache.set(fullPath, cachedModule);
  }
  return Object.fromEntries(
    Object.entries(cachedModule.exports).flatMap(
      ([key, value]) => typeof value === "function" ? [[key, value]] : []
    )
  );
}
async function execute(msg) {
  const fns = await resolveFunctions(msg.filePath);
  const fn = fns[msg.name];
  if (typeof fn !== "function") {
    throw new Error(`Function "${msg.name}" not found`);
  }
  const result = await fn(...msg.parameters);
  return result;
}
async function handleMessage(msg) {
  switch (msg.kind) {
    case "execute":
      return execute(msg);
    default:
      throw new Error(`Unknown kind "${msg.kind}"`);
  }
}
if (!import_worker_threads.isMainThread && import_worker_threads.parentPort) {
  if (!global.fetch) {
    global.fetch = import_node_fetch.default;
    global.Headers = import_node_fetch.Headers;
    global.Request = import_node_fetch.Request;
    global.Response = import_node_fetch.Response;
  }
  import_worker_threads.parentPort.on("message", (msg) => {
    (async () => {
      try {
        const result = await handleMessage(msg);
        msg.port.postMessage({ result: JSON.stringify(result, getCircularReplacer()) });
      } catch (rawError) {
        msg.port.postMessage({ error: (0, import_errors.serializeError)((0, import_errors.errorFrom)(rawError)) });
      }
    })();
  });
}
function createWorker(env) {
  const worker = new import_worker_threads.Worker(path.join(__dirname, "functionsDevWorker.js"), { env });
  const runOnWorker = async (msg) => {
    const { port1, port2 } = new import_worker_threads.MessageChannel();
    worker.postMessage({ port: port1, ...msg }, [port1]);
    const [{ error, result }] = await (0, import_node_events.once)(port2, "message");
    if (error) {
      throw (0, import_errors.errorFrom)(error);
    }
    return result ? JSON.parse(result) : void 0;
  };
  return {
    async terminate() {
      return worker.terminate();
    },
    async execute(filePath, name, parameters) {
      return runOnWorker({
        kind: "execute",
        filePath,
        name,
        parameters
      });
    }
  };
}
process.on("unhandledRejection", (error) => {
  console.error(error);
  process.exit(1);
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createWorker
});
//# sourceMappingURL=functionsDevWorker.js.map