"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/functionsTypesWorker.ts
var functionsTypesWorker_exports = {};
__export(functionsTypesWorker_exports, {
  default: () => extractTypes
});
module.exports = __toCommonJS(functionsTypesWorker_exports);
var path = __toESM(require("path"));
var import_invariant = __toESM(require("invariant"));
var ts2 = __toESM(require("typescript"));
var import_glob = require("glob");

// ../../node_modules/chalk/source/vendor/ansi-styles/index.js
var ANSI_BACKGROUND_OFFSET = 10;
var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
var styles = {
  modifier: {
    reset: [0, 0],
    // 21 isn't widely supported and 22 does the same thing
    bold: [1, 22],
    dim: [2, 22],
    italic: [3, 23],
    underline: [4, 24],
    overline: [53, 55],
    inverse: [7, 27],
    hidden: [8, 28],
    strikethrough: [9, 29]
  },
  color: {
    black: [30, 39],
    red: [31, 39],
    green: [32, 39],
    yellow: [33, 39],
    blue: [34, 39],
    magenta: [35, 39],
    cyan: [36, 39],
    white: [37, 39],
    // Bright color
    blackBright: [90, 39],
    gray: [90, 39],
    // Alias of `blackBright`
    grey: [90, 39],
    // Alias of `blackBright`
    redBright: [91, 39],
    greenBright: [92, 39],
    yellowBright: [93, 39],
    blueBright: [94, 39],
    magentaBright: [95, 39],
    cyanBright: [96, 39],
    whiteBright: [97, 39]
  },
  bgColor: {
    bgBlack: [40, 49],
    bgRed: [41, 49],
    bgGreen: [42, 49],
    bgYellow: [43, 49],
    bgBlue: [44, 49],
    bgMagenta: [45, 49],
    bgCyan: [46, 49],
    bgWhite: [47, 49],
    // Bright color
    bgBlackBright: [100, 49],
    bgGray: [100, 49],
    // Alias of `bgBlackBright`
    bgGrey: [100, 49],
    // Alias of `bgBlackBright`
    bgRedBright: [101, 49],
    bgGreenBright: [102, 49],
    bgYellowBright: [103, 49],
    bgBlueBright: [104, 49],
    bgMagentaBright: [105, 49],
    bgCyanBright: [106, 49],
    bgWhiteBright: [107, 49]
  }
};
var modifierNames = Object.keys(styles.modifier);
var foregroundColorNames = Object.keys(styles.color);
var backgroundColorNames = Object.keys(styles.bgColor);
var colorNames = [...foregroundColorNames, ...backgroundColorNames];
function assembleStyles() {
  const codes = /* @__PURE__ */ new Map();
  for (const [groupName, group] of Object.entries(styles)) {
    for (const [styleName, style] of Object.entries(group)) {
      styles[styleName] = {
        open: `\x1B[${style[0]}m`,
        close: `\x1B[${style[1]}m`
      };
      group[styleName] = styles[styleName];
      codes.set(style[0], style[1]);
    }
    Object.defineProperty(styles, groupName, {
      value: group,
      enumerable: false
    });
  }
  Object.defineProperty(styles, "codes", {
    value: codes,
    enumerable: false
  });
  styles.color.close = "\x1B[39m";
  styles.bgColor.close = "\x1B[49m";
  styles.color.ansi = wrapAnsi16();
  styles.color.ansi256 = wrapAnsi256();
  styles.color.ansi16m = wrapAnsi16m();
  styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
  styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
  Object.defineProperties(styles, {
    rgbToAnsi256: {
      value(red, green, blue) {
        if (red === green && green === blue) {
          if (red < 8) {
            return 16;
          }
          if (red > 248) {
            return 231;
          }
          return Math.round((red - 8) / 247 * 24) + 232;
        }
        return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
      },
      enumerable: false
    },
    hexToRgb: {
      value(hex) {
        const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
        if (!matches) {
          return [0, 0, 0];
        }
        let [colorString] = matches;
        if (colorString.length === 3) {
          colorString = [...colorString].map((character) => character + character).join("");
        }
        const integer = Number.parseInt(colorString, 16);
        return [
          /* eslint-disable no-bitwise */
          integer >> 16 & 255,
          integer >> 8 & 255,
          integer & 255
          /* eslint-enable no-bitwise */
        ];
      },
      enumerable: false
    },
    hexToAnsi256: {
      value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
      enumerable: false
    },
    ansi256ToAnsi: {
      value(code) {
        if (code < 8) {
          return 30 + code;
        }
        if (code < 16) {
          return 90 + (code - 8);
        }
        let red;
        let green;
        let blue;
        if (code >= 232) {
          red = ((code - 232) * 10 + 8) / 255;
          green = red;
          blue = red;
        } else {
          code -= 16;
          const remainder = code % 36;
          red = Math.floor(code / 36) / 5;
          green = Math.floor(remainder / 6) / 5;
          blue = remainder % 6 / 5;
        }
        const value = Math.max(red, green, blue) * 2;
        if (value === 0) {
          return 30;
        }
        let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
        if (value === 2) {
          result += 60;
        }
        return result;
      },
      enumerable: false
    },
    rgbToAnsi: {
      value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
      enumerable: false
    },
    hexToAnsi: {
      value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
      enumerable: false
    }
  });
  return styles;
}
var ansiStyles = assembleStyles();
var ansi_styles_default = ansiStyles;

// ../../node_modules/chalk/source/vendor/supports-color/index.js
var import_node_process = __toESM(require("process"), 1);
var import_node_os = __toESM(require("os"), 1);
var import_node_tty = __toESM(require("tty"), 1);
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process.default.argv) {
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
  const position = argv.indexOf(prefix + flag);
  const terminatorPosition = argv.indexOf("--");
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
}
var { env } = import_node_process.default;
var flagForceColor;
if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
  flagForceColor = 0;
} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
  flagForceColor = 1;
}
function envForceColor() {
  if ("FORCE_COLOR" in env) {
    if (env.FORCE_COLOR === "true") {
      return 1;
    }
    if (env.FORCE_COLOR === "false") {
      return 0;
    }
    return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
  }
}
function translateLevel(level) {
  if (level === 0) {
    return false;
  }
  return {
    level,
    hasBasic: true,
    has256: level >= 2,
    has16m: level >= 3
  };
}
function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
  const noFlagForceColor = envForceColor();
  if (noFlagForceColor !== void 0) {
    flagForceColor = noFlagForceColor;
  }
  const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
  if (forceColor === 0) {
    return 0;
  }
  if (sniffFlags) {
    if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
      return 3;
    }
    if (hasFlag("color=256")) {
      return 2;
    }
  }
  if ("TF_BUILD" in env && "AGENT_NAME" in env) {
    return 1;
  }
  if (haveStream && !streamIsTTY && forceColor === void 0) {
    return 0;
  }
  const min = forceColor || 0;
  if (env.TERM === "dumb") {
    return min;
  }
  if (import_node_process.default.platform === "win32") {
    const osRelease = import_node_os.default.release().split(".");
    if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
      return Number(osRelease[2]) >= 14931 ? 3 : 2;
    }
    return 1;
  }
  if ("CI" in env) {
    if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
      return 3;
    }
    if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
      return 1;
    }
    return min;
  }
  if ("TEAMCITY_VERSION" in env) {
    return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
  }
  if (env.COLORTERM === "truecolor") {
    return 3;
  }
  if (env.TERM === "xterm-kitty") {
    return 3;
  }
  if ("TERM_PROGRAM" in env) {
    const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
    switch (env.TERM_PROGRAM) {
      case "iTerm.app": {
        return version >= 3 ? 3 : 2;
      }
      case "Apple_Terminal": {
        return 2;
      }
    }
  }
  if (/-256(color)?$/i.test(env.TERM)) {
    return 2;
  }
  if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
    return 1;
  }
  if ("COLORTERM" in env) {
    return 1;
  }
  return min;
}
function createSupportsColor(stream, options = {}) {
  const level = _supportsColor(stream, {
    streamIsTTY: stream && stream.isTTY,
    ...options
  });
  return translateLevel(level);
}
var supportsColor = {
  stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
  stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
};
var supports_color_default = supportsColor;

// ../../node_modules/chalk/source/utilities.js
function stringReplaceAll(string, substring, replacer) {
  let index = string.indexOf(substring);
  if (index === -1) {
    return string;
  }
  const substringLength = substring.length;
  let endIndex = 0;
  let returnValue = "";
  do {
    returnValue += string.slice(endIndex, index) + substring + replacer;
    endIndex = index + substringLength;
    index = string.indexOf(substring, endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}
function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
  let endIndex = 0;
  let returnValue = "";
  do {
    const gotCR = string[index - 1] === "\r";
    returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
    endIndex = index + 1;
    index = string.indexOf("\n", endIndex);
  } while (index !== -1);
  returnValue += string.slice(endIndex);
  return returnValue;
}

// ../../node_modules/chalk/source/index.js
var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
var GENERATOR = Symbol("GENERATOR");
var STYLER = Symbol("STYLER");
var IS_EMPTY = Symbol("IS_EMPTY");
var levelMapping = [
  "ansi",
  "ansi",
  "ansi256",
  "ansi16m"
];
var styles2 = /* @__PURE__ */ Object.create(null);
var applyOptions = (object, options = {}) => {
  if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
    throw new Error("The `level` option should be an integer from 0 to 3");
  }
  const colorLevel = stdoutColor ? stdoutColor.level : 0;
  object.level = options.level === void 0 ? colorLevel : options.level;
};
var chalkFactory = (options) => {
  const chalk2 = (...strings) => strings.join(" ");
  applyOptions(chalk2, options);
  Object.setPrototypeOf(chalk2, createChalk.prototype);
  return chalk2;
};
function createChalk(options) {
  return chalkFactory(options);
}
Object.setPrototypeOf(createChalk.prototype, Function.prototype);
for (const [styleName, style] of Object.entries(ansi_styles_default)) {
  styles2[styleName] = {
    get() {
      const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
      Object.defineProperty(this, styleName, { value: builder });
      return builder;
    }
  };
}
styles2.visible = {
  get() {
    const builder = createBuilder(this, this[STYLER], true);
    Object.defineProperty(this, "visible", { value: builder });
    return builder;
  }
};
var getModelAnsi = (model, level, type, ...arguments_) => {
  if (model === "rgb") {
    if (level === "ansi16m") {
      return ansi_styles_default[type].ansi16m(...arguments_);
    }
    if (level === "ansi256") {
      return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
    }
    return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
  }
  if (model === "hex") {
    return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
  }
  return ansi_styles_default[type][model](...arguments_);
};
var usedModels = ["rgb", "hex", "ansi256"];
for (const model of usedModels) {
  styles2[model] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
  const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
  styles2[bgModel] = {
    get() {
      const { level } = this;
      return function(...arguments_) {
        const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
        return createBuilder(this, styler, this[IS_EMPTY]);
      };
    }
  };
}
var proto = Object.defineProperties(() => {
}, {
  ...styles2,
  level: {
    enumerable: true,
    get() {
      return this[GENERATOR].level;
    },
    set(level) {
      this[GENERATOR].level = level;
    }
  }
});
var createStyler = (open, close, parent) => {
  let openAll;
  let closeAll;
  if (parent === void 0) {
    openAll = open;
    closeAll = close;
  } else {
    openAll = parent.openAll + open;
    closeAll = close + parent.closeAll;
  }
  return {
    open,
    close,
    openAll,
    closeAll,
    parent
  };
};
var createBuilder = (self, _styler, _isEmpty) => {
  const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
  Object.setPrototypeOf(builder, proto);
  builder[GENERATOR] = self;
  builder[STYLER] = _styler;
  builder[IS_EMPTY] = _isEmpty;
  return builder;
};
var applyStyle = (self, string) => {
  if (self.level <= 0 || !string) {
    return self[IS_EMPTY] ? "" : string;
  }
  let styler = self[STYLER];
  if (styler === void 0) {
    return string;
  }
  const { openAll, closeAll } = styler;
  if (string.includes("\x1B")) {
    while (styler !== void 0) {
      string = stringReplaceAll(string, styler.close, styler.open);
      styler = styler.parent;
    }
  }
  const lfIndex = string.indexOf("\n");
  if (lfIndex !== -1) {
    string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
  }
  return openAll + string + closeAll;
};
Object.defineProperties(createChalk.prototype, styles2);
var chalk = createChalk();
var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
var source_default = chalk;

// src/server/functionsTypesWorker.ts
var import_collections = require("@mui/toolpad-utils/collections");

// src/server/functionsShared.ts
var ts = __toESM(require("typescript"));
var compilerOptions = {
  noEmit: true,
  target: ts.ScriptTarget.ESNext,
  lib: ["lib.esnext.d.ts"],
  types: ["node"],
  // NOTE: strictNullChecks is essential for the type extraction to work properly. When we decide
  // to support user-defined tsconfig.json, we must make sure this option is enabled.
  strictNullChecks: true,
  module: ts.ModuleKind.CommonJS,
  moduleResolution: ts.ModuleResolutionKind.Bundler,
  esModuleInterop: true,
  allowSyntheticDefaultImports: true
};

// src/server/functionsTypesWorker.ts
var NULL_PROP_VALUE = {
  type: "object",
  schema: { type: "null" },
  default: null
};
function propValueFromJsonSchema(schema) {
  if (!schema) {
    return NULL_PROP_VALUE;
  }
  if (Array.isArray(schema.type)) {
    return propValueFromJsonSchema({
      ...schema,
      type: schema.type[0]
    });
  }
  switch (schema.type) {
    case "integer":
      return { type: "number" };
    case "string": {
      if (schema.enum) {
        return { type: "string", enum: schema.enum.map((value) => String(value)) };
      }
      return { type: "string" };
    }
    case "null":
    case null:
    case void 0:
      return NULL_PROP_VALUE;
    default:
      return { type: schema.type, schema };
  }
}
function formatDiagnostic(diagnostic) {
  const message = ts2.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
  if (diagnostic.file) {
    const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
    return `${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`;
  }
  return message;
}
function hasTypeFlag(type, flag) {
  return (type.getFlags() & flag) !== 0;
}
function asUnionTypes(type) {
  return type.isUnion() ? type.types : [type];
}
function toJsonSchema(tsType, checker, seenTypes) {
  if (seenTypes.has(tsType)) {
    return { const: "[Circular]" };
  }
  seenTypes.add(tsType);
  try {
    if (hasTypeFlag(tsType, ts2.TypeFlags.Undefined) || hasTypeFlag(tsType, ts2.TypeFlags.Void) || hasTypeFlag(tsType, ts2.TypeFlags.VoidLike)) {
      return null;
    }
    if (hasTypeFlag(tsType, ts2.TypeFlags.Null)) {
      return { type: "null" };
    }
    if (tsType === checker.getTrueType()) {
      return { type: "boolean", const: true };
    }
    if (tsType === checker.getFalseType()) {
      return { type: "boolean", const: false };
    }
    if (tsType.isNumberLiteral()) {
      return { type: "number", const: tsType.value };
    }
    if (tsType.isStringLiteral()) {
      return { type: "string", const: tsType.value };
    }
    if (tsType.isUnion()) {
      const anyOf = [];
      const withoutUndefined = tsType.types.filter(
        (type) => !hasTypeFlag(type, ts2.TypeFlags.Undefined)
      );
      if (withoutUndefined.length <= 0) {
        return null;
      }
      if (withoutUndefined.length === 1) {
        return toJsonSchema(withoutUndefined[0], checker, seenTypes);
      }
      for (const type of withoutUndefined) {
        const itemType = toJsonSchema(type, checker, seenTypes);
        if (itemType) {
          anyOf.push(itemType);
        }
      }
      const typeNames = /* @__PURE__ */ new Set();
      const enumValues = /* @__PURE__ */ new Set();
      let hasTrue = false;
      let hasFalse = false;
      let hasOther = false;
      let isEnum = true;
      for (const itemType of anyOf) {
        if (typeof itemType.const !== "undefined") {
          enumValues.add(itemType.const);
        } else {
          isEnum = false;
        }
        if (itemType.const === true) {
          hasTrue = true;
        } else if (itemType.const === false) {
          hasFalse = true;
        } else {
          hasOther = true;
        }
        for (const typeName of (0, import_collections.asArray)(itemType.type)) {
          if (typeName) {
            typeNames.add(typeName);
          }
        }
      }
      if (hasTrue && hasFalse && !hasOther) {
        return { type: "boolean" };
      }
      if (isEnum) {
        let type;
        if (typeNames.size === 1) {
          type = Array.from(typeNames)[0];
        }
        return { type, enum: Array.from(enumValues) };
      }
      if (anyOf.length === 1) {
        return anyOf[0];
      }
      return { anyOf };
    }
    if (hasTypeFlag(tsType, ts2.TypeFlags.BooleanLike) || hasTypeFlag(tsType, ts2.TypeFlags.Boolean) || hasTypeFlag(tsType, ts2.TypeFlags.BooleanLiteral)) {
      return { type: "boolean" };
    }
    if (hasTypeFlag(tsType, ts2.TypeFlags.NumberLike) || hasTypeFlag(tsType, ts2.TypeFlags.Number) || hasTypeFlag(tsType, ts2.TypeFlags.NumberLiteral) || hasTypeFlag(tsType, ts2.TypeFlags.BigIntLike) || hasTypeFlag(tsType, ts2.TypeFlags.BigInt) || hasTypeFlag(tsType, ts2.TypeFlags.BigIntLiteral)) {
      return { type: "number" };
    }
    if (hasTypeFlag(tsType, ts2.TypeFlags.StringLike) || hasTypeFlag(tsType, ts2.TypeFlags.String) || hasTypeFlag(tsType, ts2.TypeFlags.StringLiteral)) {
      return { type: "string" };
    }
    if (hasTypeFlag(tsType, ts2.TypeFlags.Object)) {
      if (checker.isArrayLikeType(tsType)) {
        let items;
        const indexType = tsType.getNumberIndexType();
        if (indexType) {
          items = toJsonSchema(indexType, checker, seenTypes) ?? void 0;
        }
        return {
          type: "array",
          items
        };
      }
      const required = [];
      const properties = Object.fromEntries(
        tsType.getProperties().flatMap((propertySymbol) => {
          const propertyName = propertySymbol.getName();
          const propertyType = checker.getTypeOfSymbol(propertySymbol);
          const isOptional = asUnionTypes(propertyType).some(
            (type) => hasTypeFlag(type, ts2.TypeFlags.Undefined)
          );
          if (!isOptional) {
            required.push(propertyName);
          }
          const propertySchema = toJsonSchema(propertyType, checker, seenTypes);
          return propertySchema ? [[propertyName, propertySchema]] : [];
        })
      );
      return { type: "object", properties, required };
    }
    return {};
  } finally {
    seenTypes.delete(tsType);
  }
}
function getParameters(callSignatures, checker) {
  (0, import_invariant.default)(callSignatures.length > 0, "Expected at least 1 call signature");
  const paramEntries = callSignatures[0].getParameters().map((parameter) => {
    const paramType = checker.getTypeOfSymbolAtLocation(parameter, parameter.valueDeclaration);
    const schema = toJsonSchema(paramType, checker, /* @__PURE__ */ new Set());
    return [
      parameter.getName(),
      {
        ...propValueFromJsonSchema(schema),
        required: !checker.isOptionalParameter(
          parameter.valueDeclaration
        )
      }
    ];
  });
  return paramEntries;
}
function getAwaitedType(type, checker) {
  const awaitedType = type.getNonNullableType();
  const then = awaitedType.getProperty("then");
  if (hasTypeFlag(awaitedType, ts2.TypeFlags.Object) && then) {
    const thenType = checker.getTypeOfSymbolAtLocation(then, then.valueDeclaration);
    for (const thenCallSignature of thenType.getCallSignatures()) {
      const [onfulfilled] = thenCallSignature.getParameters();
      if (onfulfilled) {
        const onfulfilledType = checker.getTypeOfSymbolAtLocation(onfulfilled, onfulfilled.valueDeclaration).getNonNullableType();
        for (const onFulfilledCallSignature of onfulfilledType.getCallSignatures()) {
          const [value] = onFulfilledCallSignature.getParameters();
          if (value) {
            const valueType = checker.getTypeOfSymbolAtLocation(value, value.valueDeclaration);
            return getAwaitedType(valueType, checker);
          }
        }
      }
    }
  }
  return type;
}
function isToolpadCreateFunction(exportType) {
  const properties = exportType.getProperties();
  for (const property of properties) {
    if (ts2.isPropertySignature(property.valueDeclaration)) {
      if (property.valueDeclaration.name.getText() === "[TOOLPAD_FUNCTION]") {
        return true;
      }
    }
  }
  return false;
}
function getCreateFunctionParameters(callSignatures, checker) {
  (0, import_invariant.default)(callSignatures.length > 0, "Expected at least 1 call signature");
  const [callSignature] = callSignatures;
  const [firstParameter] = callSignature.getParameters();
  (0, import_invariant.default)(firstParameter, "Expected at least 1 parameter");
  const firstParameterType = checker.getTypeOfSymbolAtLocation(
    firstParameter,
    firstParameter.valueDeclaration
  );
  const parametersProperty = firstParameterType.getProperty("parameters");
  (0, import_invariant.default)(parametersProperty, "Expected parameters property");
  const parametersPropertyType = checker.getTypeOfSymbolAtLocation(
    parametersProperty,
    parametersProperty.valueDeclaration
  );
  return parametersPropertyType.getProperties().map((property) => {
    const propertyType = checker.getTypeOfSymbol(property);
    const schema = toJsonSchema(propertyType, checker, /* @__PURE__ */ new Set());
    return [
      property.getName(),
      {
        ...propValueFromJsonSchema(schema),
        required: false
      }
    ];
  });
}
function getReturnType(callSignatures, checker) {
  (0, import_invariant.default)(callSignatures.length > 0, "Expected at least 1 call signature");
  const returnType = callSignatures[0].getReturnType();
  const awaitedReturnType = getAwaitedType(returnType, checker);
  const schema = toJsonSchema(awaitedReturnType, checker, /* @__PURE__ */ new Set());
  return {
    schema
  };
}
var createFunctionWarningShown = false;
async function extractTypes({
  resourcesFolder
}) {
  const entryPoints = await (0, import_glob.glob)(path.join(resourcesFolder, "./*.ts"), {
    windowsPathsNoEscape: true
  });
  const program = ts2.createProgram(entryPoints, compilerOptions);
  const checker = program.getTypeChecker();
  const usingCreateFunction = [];
  const files = entryPoints.map((entrypoint) => {
    const sourceFile = program.getSourceFile(entrypoint);
    const relativeEntrypoint = path.relative(resourcesFolder, entrypoint);
    if (!sourceFile) {
      return null;
    }
    const diagnostics = program.getSemanticDiagnostics(sourceFile);
    for (const diagnostic of diagnostics) {
      console.log(`${source_default.blue("info")}  - ${formatDiagnostic(diagnostic)}`);
    }
    const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
    if (!moduleSymbol) {
      return null;
    }
    const handlers = checker.getExportsOfModule(moduleSymbol).map((symbol) => {
      const exportType = checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration);
      const callSignatures = exportType.getCallSignatures();
      if (callSignatures.length <= 0) {
        return null;
      }
      const isCreateFunction = isToolpadCreateFunction(exportType);
      if (isCreateFunction) {
        usingCreateFunction.push(symbol.name);
      }
      return {
        name: symbol.name,
        isCreateFunction,
        parameters: isCreateFunction ? getCreateFunctionParameters(callSignatures, checker) : getParameters(callSignatures, checker),
        returnType: getReturnType(callSignatures, checker)
      };
    }).filter(Boolean);
    return {
      name: relativeEntrypoint,
      errors: diagnostics.filter((diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Error).map((diagnostic) => ({ message: formatDiagnostic(diagnostic) })),
      warnings: diagnostics.filter((diagnostic) => diagnostic.category === ts2.DiagnosticCategory.Warning).map((diagnostic) => ({ message: formatDiagnostic(diagnostic) })),
      handlers
    };
  }).filter(Boolean).sort((a, b) => a.name.localeCompare(b.name));
  if (usingCreateFunction.length > 0 && !createFunctionWarningShown) {
    console.warn(
      `${source_default.yellow("warn")} - ${source_default.bold(usingCreateFunction.length)} function${usingCreateFunction.length === 1 ? " is" : "s are"} using the deprecated ${source_default.red(
        "createFunction"
      )} API. This will be removed from Toolpad in a future release. Please see ${source_default.underline(
        source_default.blue("https://mui.com/toolpad/reference/api/create-function/")
      )} for migration information and updates.`
    );
    createFunctionWarningShown = true;
  }
  return { files };
}
//# sourceMappingURL=functionsTypesWorker.js.map