import CJS_COMPAT_NODE_URL_jj04cksboja from 'node:url';
import CJS_COMPAT_NODE_PATH_jj04cksboja from 'node:path';
import CJS_COMPAT_NODE_MODULE_jj04cksboja from "node:module";

var __filename = CJS_COMPAT_NODE_URL_jj04cksboja.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_jj04cksboja.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_jj04cksboja.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  BROWSER_TARGETS,
  NODE_TARGET,
  SUPPORTED_FEATURES
} from "./chunk-UQQ6U5JW.js";
import {
  require_build
} from "./chunk-RLDWXV7X.js";
import {
  resolveModulePath,
  resolvePackageDir
} from "./chunk-3ML5DUTC.js";
import {
  join,
  parse
} from "./chunk-NU5QOZC6.js";
import {
  slash
} from "./chunk-QZCH76UX.js";
import {
  __commonJS,
  __esm,
  __export,
  __name,
  __require,
  __toCommonJS,
  __toESM
} from "./chunk-T7Y6VNG2.js";

// ../node_modules/tslib/tslib.es6.mjs
var tslib_es6_exports = {};
__export(tslib_es6_exports, {
  __addDisposableResource: () => __addDisposableResource,
  __assign: () => __assign,
  __asyncDelegator: () => __asyncDelegator,
  __asyncGenerator: () => __asyncGenerator,
  __asyncValues: () => __asyncValues,
  __await: () => __await,
  __awaiter: () => __awaiter,
  __classPrivateFieldGet: () => __classPrivateFieldGet,
  __classPrivateFieldIn: () => __classPrivateFieldIn,
  __classPrivateFieldSet: () => __classPrivateFieldSet,
  __createBinding: () => __createBinding,
  __decorate: () => __decorate,
  __disposeResources: () => __disposeResources,
  __esDecorate: () => __esDecorate,
  __exportStar: () => __exportStar,
  __extends: () => __extends,
  __generator: () => __generator,
  __importDefault: () => __importDefault,
  __importStar: () => __importStar,
  __makeTemplateObject: () => __makeTemplateObject,
  __metadata: () => __metadata,
  __param: () => __param,
  __propKey: () => __propKey,
  __read: () => __read,
  __rest: () => __rest,
  __rewriteRelativeImportExtension: () => __rewriteRelativeImportExtension,
  __runInitializers: () => __runInitializers,
  __setFunctionName: () => __setFunctionName,
  __spread: () => __spread,
  __spreadArray: () => __spreadArray,
  __spreadArrays: () => __spreadArrays,
  __values: () => __values,
  default: () => tslib_es6_default
});
function __extends(d, b) {
  if (typeof b !== "function" && b !== null)
    throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  extendStatics(d, b);
  function __() {
    this.constructor = d;
  }
  __name(__, "__");
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
    t[p] = s[p];
  if (s != null && typeof Object.getOwnPropertySymbols === "function")
    for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
      if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
        t[p[i]] = s[p[i]];
    }
  return t;
}
function __decorate(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
}
function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
  function accept(f) {
    if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
    return f;
  }
  __name(accept, "accept");
  var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
  var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
  var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
  var _, done = false;
  for (var i = decorators.length - 1; i >= 0; i--) {
    var context = {};
    for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
    for (var p in contextIn.access) context.access[p] = contextIn.access[p];
    context.addInitializer = function(f) {
      if (done) throw new TypeError("Cannot add initializers after decoration has completed");
      extraInitializers.push(accept(f || null));
    };
    var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
    if (kind === "accessor") {
      if (result === void 0) continue;
      if (result === null || typeof result !== "object") throw new TypeError("Object expected");
      if (_ = accept(result.get)) descriptor.get = _;
      if (_ = accept(result.set)) descriptor.set = _;
      if (_ = accept(result.init)) initializers.unshift(_);
    } else if (_ = accept(result)) {
      if (kind === "field") initializers.unshift(_);
      else descriptor[key] = _;
    }
  }
  if (target) Object.defineProperty(target, contextIn.name, descriptor);
  done = true;
}
function __runInitializers(thisArg, initializers, value) {
  var useValue = arguments.length > 2;
  for (var i = 0; i < initializers.length; i++) {
    value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
  }
  return useValue ? value : void 0;
}
function __propKey(x) {
  return typeof x === "symbol" ? x : "".concat(x);
}
function __setFunctionName(f, name, prefix) {
  if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
  return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
}
function __metadata(metadataKey, metadataValue) {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  __name(adopt, "adopt");
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    __name(fulfilled, "fulfilled");
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    __name(rejected, "rejected");
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    __name(step, "step");
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: /* @__PURE__ */ __name(function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, "sent"), trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() {
    return this;
  }), g;
  function verb(n) {
    return function(v) {
      return step([n, v]);
    };
  }
  __name(verb, "verb");
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    while (g && (g = 0, op[0] && (_ = 0)), _) try {
      if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
      if (y = 0, t) op = [op[0] & 2, t.value];
      switch (op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          _.label++;
          return { value: op[1], done: false };
        case 5:
          _.label++;
          y = op[1];
          op = [0];
          continue;
        case 7:
          op = _.ops.pop();
          _.trys.pop();
          continue;
        default:
          if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
            _ = 0;
            continue;
          }
          if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
            _.label = op[1];
            break;
          }
          if (op[0] === 6 && _.label < t[1]) {
            _.label = t[1];
            t = op;
            break;
          }
          if (t && _.label < t[2]) {
            _.label = t[2];
            _.ops.push(op);
            break;
          }
          if (t[2]) _.ops.pop();
          _.trys.pop();
          continue;
      }
      op = body.call(thisArg, _);
    } catch (e) {
      op = [6, e];
      y = 0;
    } finally {
      f = t = 0;
    }
    if (op[0] & 5) throw op[1];
    return { value: op[0] ? op[1] : void 0, done: true };
  }
  __name(step, "step");
}
function __exportStar(m, o) {
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
}
function __values(o) {
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
  if (m) return m.call(o);
  if (o && typeof o.length === "number") return {
    next: /* @__PURE__ */ __name(function() {
      if (o && i >= o.length) o = void 0;
      return { value: o && o[i++], done: !o };
    }, "next")
  };
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
  var m = typeof Symbol === "function" && o[Symbol.iterator];
  if (!m) return o;
  var i = m.call(o), r, ar = [], e;
  try {
    while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      if (r && !r.done && (m = i["return"])) m.call(i);
    } finally {
      if (e) throw e.error;
    }
  }
  return ar;
}
function __spread() {
  for (var ar = [], i = 0; i < arguments.length; i++)
    ar = ar.concat(__read(arguments[i]));
  return ar;
}
function __spreadArrays() {
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
    for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
      r[k] = a[j];
  return r;
}
function __spreadArray(to, from, pack) {
  if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
    if (ar || !(i in from)) {
      if (!ar) ar = Array.prototype.slice.call(from, 0, i);
      ar[i] = from[i];
    }
  }
  return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
  return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var g = generator.apply(thisArg, _arguments || []), i, q = [];
  return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function() {
    return this;
  }, i;
  function awaitReturn(f) {
    return function(v) {
      return Promise.resolve(v).then(f, reject);
    };
  }
  __name(awaitReturn, "awaitReturn");
  function verb(n, f) {
    if (g[n]) {
      i[n] = function(v) {
        return new Promise(function(a, b) {
          q.push([n, v, a, b]) > 1 || resume(n, v);
        });
      };
      if (f) i[n] = f(i[n]);
    }
  }
  __name(verb, "verb");
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  __name(resume, "resume");
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  __name(step, "step");
  function fulfill(value) {
    resume("next", value);
  }
  __name(fulfill, "fulfill");
  function reject(value) {
    resume("throw", value);
  }
  __name(reject, "reject");
  function settle(f, v) {
    if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
  }
  __name(settle, "settle");
}
function __asyncDelegator(o) {
  var i, p;
  return i = {}, verb("next"), verb("throw", function(e) {
    throw e;
  }), verb("return"), i[Symbol.iterator] = function() {
    return this;
  }, i;
  function verb(n, f) {
    i[n] = o[n] ? function(v) {
      return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v;
    } : f;
  }
  __name(verb, "verb");
}
function __asyncValues(o) {
  if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
  var m = o[Symbol.asyncIterator], i;
  return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
    return this;
  }, i);
  function verb(n) {
    i[n] = o[n] && function(v) {
      return new Promise(function(resolve, reject) {
        v = o[n](v), settle(resolve, reject, v.done, v.value);
      });
    };
  }
  __name(verb, "verb");
  function settle(resolve, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve({ value: v2, done: d });
    }, reject);
  }
  __name(settle, "settle");
}
function __makeTemplateObject(cooked, raw) {
  if (Object.defineProperty) {
    Object.defineProperty(cooked, "raw", { value: raw });
  } else {
    cooked.raw = raw;
  }
  return cooked;
}
function __importStar(mod) {
  if (mod && mod.__esModule) return mod;
  var result = {};
  if (mod != null) {
    for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  }
  __setModuleDefault(result, mod);
  return result;
}
function __importDefault(mod) {
  return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
}
function __classPrivateFieldSet(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
}
function __classPrivateFieldIn(state, receiver) {
  if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object");
  return typeof state === "function" ? receiver === state : state.has(receiver);
}
function __addDisposableResource(env, value, async) {
  if (value !== null && value !== void 0) {
    if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
    var dispose, inner;
    if (async) {
      if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
      dispose = value[Symbol.asyncDispose];
    }
    if (dispose === void 0) {
      if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
      dispose = value[Symbol.dispose];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
    if (inner) dispose = /* @__PURE__ */ __name(function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    }, "dispose");
    env.stack.push({ value, dispose, async });
  } else if (async) {
    env.stack.push({ async: true });
  }
  return value;
}
function __disposeResources(env) {
  function fail(e) {
    env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
    env.hasError = true;
  }
  __name(fail, "fail");
  var r, s = 0;
  function next() {
    while (r = env.stack.pop()) {
      try {
        if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
        if (r.dispose) {
          var result = r.dispose.call(r.value);
          if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
            fail(e);
            return next();
          });
        } else s |= 1;
      } catch (e) {
        fail(e);
      }
    }
    if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
    if (env.hasError) throw env.error;
  }
  __name(next, "next");
  return next();
}
function __rewriteRelativeImportExtension(path, preserveJsx) {
  if (typeof path === "string" && /^\.\.?\//.test(path)) {
    return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function(m, tsx, d, ext, cm) {
      return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : d + ext + "." + cm.toLowerCase() + "js";
    });
  }
  return path;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default;
var init_tslib_es6 = __esm({
  "../node_modules/tslib/tslib.es6.mjs"() {
    extendStatics = /* @__PURE__ */ __name(function(d, b) {
      extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
      };
      return extendStatics(d, b);
    }, "extendStatics");
    __name(__extends, "__extends");
    __assign = /* @__PURE__ */ __name(function() {
      __assign = Object.assign || /* @__PURE__ */ __name(function __assign2(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
      }, "__assign");
      return __assign.apply(this, arguments);
    }, "__assign");
    __name(__rest, "__rest");
    __name(__decorate, "__decorate");
    __name(__param, "__param");
    __name(__esDecorate, "__esDecorate");
    __name(__runInitializers, "__runInitializers");
    __name(__propKey, "__propKey");
    __name(__setFunctionName, "__setFunctionName");
    __name(__metadata, "__metadata");
    __name(__awaiter, "__awaiter");
    __name(__generator, "__generator");
    __createBinding = Object.create ? function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      var desc = Object.getOwnPropertyDescriptor(m, k);
      if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
        desc = { enumerable: true, get: /* @__PURE__ */ __name(function() {
          return m[k];
        }, "get") };
      }
      Object.defineProperty(o, k2, desc);
    } : function(o, m, k, k2) {
      if (k2 === void 0) k2 = k;
      o[k2] = m[k];
    };
    __name(__exportStar, "__exportStar");
    __name(__values, "__values");
    __name(__read, "__read");
    __name(__spread, "__spread");
    __name(__spreadArrays, "__spreadArrays");
    __name(__spreadArray, "__spreadArray");
    __name(__await, "__await");
    __name(__asyncGenerator, "__asyncGenerator");
    __name(__asyncDelegator, "__asyncDelegator");
    __name(__asyncValues, "__asyncValues");
    __name(__makeTemplateObject, "__makeTemplateObject");
    __setModuleDefault = Object.create ? function(o, v) {
      Object.defineProperty(o, "default", { enumerable: true, value: v });
    } : function(o, v) {
      o["default"] = v;
    };
    ownKeys = /* @__PURE__ */ __name(function(o) {
      ownKeys = Object.getOwnPropertyNames || function(o2) {
        var ar = [];
        for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
        return ar;
      };
      return ownKeys(o);
    }, "ownKeys");
    __name(__importStar, "__importStar");
    __name(__importDefault, "__importDefault");
    __name(__classPrivateFieldGet, "__classPrivateFieldGet");
    __name(__classPrivateFieldSet, "__classPrivateFieldSet");
    __name(__classPrivateFieldIn, "__classPrivateFieldIn");
    __name(__addDisposableResource, "__addDisposableResource");
    _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
      var e = new Error(message);
      return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };
    __name(__disposeResources, "__disposeResources");
    __name(__rewriteRelativeImportExtension, "__rewriteRelativeImportExtension");
    tslib_es6_default = {
      __extends,
      __assign,
      __rest,
      __decorate,
      __param,
      __esDecorate,
      __runInitializers,
      __propKey,
      __setFunctionName,
      __metadata,
      __awaiter,
      __generator,
      __createBinding,
      __exportStar,
      __values,
      __read,
      __spread,
      __spreadArrays,
      __spreadArray,
      __await,
      __asyncGenerator,
      __asyncDelegator,
      __asyncValues,
      __makeTemplateObject,
      __importStar,
      __importDefault,
      __classPrivateFieldGet,
      __classPrivateFieldSet,
      __classPrivateFieldIn,
      __addDisposableResource,
      __disposeResources,
      __rewriteRelativeImportExtension
    };
  }
});

// ../node_modules/@yarnpkg/esbuild-plugin-pnp/lib/index.js
var require_lib = __commonJS({
  "../node_modules/@yarnpkg/esbuild-plugin-pnp/lib/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.pnpPlugin = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
    var fs = tslib_1.__importStar(__require("fs"));
    var path_1 = tslib_1.__importDefault(__require("path"));
    var matchAll = /()/;
    var defaultExtensions = [`.tsx`, `.ts`, `.jsx`, `.mjs`, `.cjs`, `.js`, `.css`, `.json`];
    function parseExternals(externals) {
      return externals.map((external) => {
        const wildcardIdx = external.indexOf(`*`);
        if (wildcardIdx !== -1)
          return { prefix: external.slice(0, wildcardIdx), suffix: external.slice(wildcardIdx + 1) };
        return external;
      });
    }
    __name(parseExternals, "parseExternals");
    function isExternal(path, externals) {
      for (const external of externals) {
        if (typeof external === `object`) {
          if (path.length >= external.prefix.length + external.suffix.length && path.startsWith(external.prefix) && path.endsWith(external.suffix)) {
            return true;
          }
        } else {
          if (path === external)
            return true;
          if (!external.startsWith(`/`) && !external.startsWith(`./`) && !external.startsWith(`../`) && external !== `.` && external !== `..`) {
            if (path.startsWith(`${external}/`)) {
              return true;
            }
          }
        }
      }
      return false;
    }
    __name(isExternal, "isExternal");
    async function defaultOnLoad(args) {
      return {
        contents: await fs.promises.readFile(args.path),
        loader: `default`,
        // For regular imports in the `file` namespace, resolveDir is the directory the
        // file being resolved lives in. For all other virtual modules, this defaults to
        // empty string: ""
        // A sensible value for pnp imports is the same as the `file` namespace, as pnp
        // still resolves to files on disk (in the cache).
        resolveDir: path_1.default.dirname(args.path)
      };
    }
    __name(defaultOnLoad, "defaultOnLoad");
    async function defaultOnResolve(args, { resolvedPath, error, watchFiles }) {
      const problems = error ? [{ text: error.message }] : [];
      let mergeWith;
      switch (args.kind) {
        case `require-call`:
        case `require-resolve`:
        case `dynamic-import`:
          {
            mergeWith = { warnings: problems };
          }
          break;
        default:
          {
            mergeWith = { errors: problems };
          }
          break;
      }
      if (resolvedPath !== null) {
        return { namespace: `pnp`, path: resolvedPath, watchFiles };
      } else {
        return { external: true, ...mergeWith, watchFiles };
      }
    }
    __name(defaultOnResolve, "defaultOnResolve");
    function pnpPlugin2({ baseDir = process.cwd(), extensions = defaultExtensions, filter = matchAll, onResolve = defaultOnResolve, onLoad = defaultOnLoad } = {}) {
      return {
        name: `@yarnpkg/esbuild-plugin-pnp`,
        setup(build2) {
          var _a, _b;
          const { findPnpApi } = __require("module");
          if (typeof findPnpApi === `undefined`)
            return;
          const externals = parseExternals((_a = build2.initialOptions.external) !== null && _a !== void 0 ? _a : []);
          const platform = (_b = build2.initialOptions.platform) !== null && _b !== void 0 ? _b : `browser`;
          const isPlatformNode = platform === `node`;
          const conditionsDefault = new Set(build2.initialOptions.conditions);
          conditionsDefault.add(`default`);
          if (platform === `browser` || platform === `node`)
            conditionsDefault.add(platform);
          const conditionsImport = new Set(conditionsDefault);
          conditionsImport.add(`import`);
          const conditionsRequire = new Set(conditionsDefault);
          conditionsRequire.add(`require`);
          build2.onResolve({ filter }, (args) => {
            var _a2, _b2;
            if (isExternal(args.path, externals))
              return { external: true };
            let conditions = conditionsDefault;
            if (args.kind === `dynamic-import` || args.kind === `import-statement`)
              conditions = conditionsImport;
            else if (args.kind === `require-call` || args.kind === `require-resolve`)
              conditions = conditionsRequire;
            const effectiveImporter = args.resolveDir ? `${args.resolveDir}/` : args.importer ? args.importer : `${baseDir}/`;
            const pnpApi = findPnpApi(effectiveImporter);
            if (!pnpApi)
              return void 0;
            let path = null;
            let error;
            try {
              path = pnpApi.resolveRequest(args.path, effectiveImporter, {
                conditions,
                considerBuiltins: isPlatformNode,
                extensions
              });
            } catch (e) {
              error = e;
            }
            const watchFiles = [pnpApi.resolveRequest(`pnpapi`, null)];
            if (path) {
              const locator = pnpApi.findPackageLocator(path);
              if (locator) {
                const info = pnpApi.getPackageInformation(locator);
                if ((info === null || info === void 0 ? void 0 : info.linkType) === `SOFT`) {
                  watchFiles.push((_b2 = (_a2 = pnpApi.resolveVirtual) === null || _a2 === void 0 ? void 0 : _a2.call(pnpApi, path)) !== null && _b2 !== void 0 ? _b2 : path);
                }
              }
            }
            return onResolve(args, { resolvedPath: path, error, watchFiles });
          });
          if (build2.onLoad !== null) {
            build2.onLoad({ filter }, onLoad);
          }
        }
      };
    }
    __name(pnpPlugin2, "pnpPlugin");
    exports.pnpPlugin = pnpPlugin2;
  }
});

// ../node_modules/ejs/lib/utils.js
var require_utils = __commonJS({
  "../node_modules/ejs/lib/utils.js"(exports) {
    "use strict";
    var regExpChars = /[|\\{}()[\]^$+*?.]/g;
    var hasOwnProperty = Object.prototype.hasOwnProperty;
    var hasOwn = /* @__PURE__ */ __name(function(obj, key) {
      return hasOwnProperty.apply(obj, [key]);
    }, "hasOwn");
    exports.escapeRegExpChars = function(string) {
      if (!string) {
        return "";
      }
      return String(string).replace(regExpChars, "\\$&");
    };
    var _ENCODE_HTML_RULES = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&#34;",
      "'": "&#39;"
    };
    var _MATCH_HTML = /[&<>'"]/g;
    function encode_char(c) {
      return _ENCODE_HTML_RULES[c] || c;
    }
    __name(encode_char, "encode_char");
    var escapeFuncStr = `var _ENCODE_HTML_RULES = {
      "&": "&amp;"
    , "<": "&lt;"
    , ">": "&gt;"
    , '"': "&#34;"
    , "'": "&#39;"
    }
  , _MATCH_HTML = /[&<>'"]/g;
function encode_char(c) {
  return _ENCODE_HTML_RULES[c] || c;
};
`;
    exports.escapeXML = function(markup) {
      return markup == void 0 ? "" : String(markup).replace(_MATCH_HTML, encode_char);
    };
    function escapeXMLToString() {
      return Function.prototype.toString.call(this) + ";\n" + escapeFuncStr;
    }
    __name(escapeXMLToString, "escapeXMLToString");
    try {
      if (typeof Object.defineProperty === "function") {
        Object.defineProperty(exports.escapeXML, "toString", { value: escapeXMLToString });
      } else {
        exports.escapeXML.toString = escapeXMLToString;
      }
    } catch (err) {
      console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)");
    }
    exports.shallowCopy = function(to, from) {
      from = from || {};
      if (to !== null && to !== void 0) {
        for (var p in from) {
          if (!hasOwn(from, p)) {
            continue;
          }
          if (p === "__proto__" || p === "constructor") {
            continue;
          }
          to[p] = from[p];
        }
      }
      return to;
    };
    exports.shallowCopyFromList = function(to, from, list) {
      list = list || [];
      from = from || {};
      if (to !== null && to !== void 0) {
        for (var i = 0; i < list.length; i++) {
          var p = list[i];
          if (typeof from[p] != "undefined") {
            if (!hasOwn(from, p)) {
              continue;
            }
            if (p === "__proto__" || p === "constructor") {
              continue;
            }
            to[p] = from[p];
          }
        }
      }
      return to;
    };
    exports.cache = {
      _data: {},
      set: /* @__PURE__ */ __name(function(key, val) {
        this._data[key] = val;
      }, "set"),
      get: /* @__PURE__ */ __name(function(key) {
        return this._data[key];
      }, "get"),
      remove: /* @__PURE__ */ __name(function(key) {
        delete this._data[key];
      }, "remove"),
      reset: /* @__PURE__ */ __name(function() {
        this._data = {};
      }, "reset")
    };
    exports.hyphenToCamel = function(str) {
      return str.replace(/-[a-z]/g, function(match) {
        return match[1].toUpperCase();
      });
    };
    exports.createNullProtoObjWherePossible = function() {
      if (typeof Object.create == "function") {
        return function() {
          return /* @__PURE__ */ Object.create(null);
        };
      }
      if (!({ __proto__: null } instanceof Object)) {
        return function() {
          return { __proto__: null };
        };
      }
      return function() {
        return {};
      };
    }();
    exports.hasOwnOnlyObject = function(obj) {
      var o = exports.createNullProtoObjWherePossible();
      for (var p in obj) {
        if (hasOwn(obj, p)) {
          o[p] = obj[p];
        }
      }
      return o;
    };
  }
});

// ../node_modules/ejs/package.json
var require_package = __commonJS({
  "../node_modules/ejs/package.json"(exports, module) {
    module.exports = {
      name: "ejs",
      description: "Embedded JavaScript templates",
      keywords: [
        "template",
        "engine",
        "ejs"
      ],
      version: "3.1.10",
      author: "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
      license: "Apache-2.0",
      bin: {
        ejs: "./bin/cli.js"
      },
      main: "./lib/ejs.js",
      jsdelivr: "ejs.min.js",
      unpkg: "ejs.min.js",
      repository: {
        type: "git",
        url: "git://github.com/mde/ejs.git"
      },
      bugs: "https://github.com/mde/ejs/issues",
      homepage: "https://github.com/mde/ejs",
      dependencies: {
        jake: "^10.8.5"
      },
      devDependencies: {
        browserify: "^16.5.1",
        eslint: "^6.8.0",
        "git-directory-deploy": "^1.5.1",
        jsdoc: "^4.0.2",
        "lru-cache": "^4.0.1",
        mocha: "^10.2.0",
        "uglify-js": "^3.3.16"
      },
      engines: {
        node: ">=0.10.0"
      },
      scripts: {
        test: "npx jake test"
      }
    };
  }
});

// ../node_modules/ejs/lib/ejs.js
var require_ejs = __commonJS({
  "../node_modules/ejs/lib/ejs.js"(exports) {
    "use strict";
    var fs = __require("fs");
    var path = __require("path");
    var utils = require_utils();
    var scopeOptionWarned = false;
    var _VERSION_STRING = require_package().version;
    var _DEFAULT_OPEN_DELIMITER = "<";
    var _DEFAULT_CLOSE_DELIMITER = ">";
    var _DEFAULT_DELIMITER = "%";
    var _DEFAULT_LOCALS_NAME = "locals";
    var _NAME = "ejs";
    var _REGEX_STRING = "(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";
    var _OPTS_PASSABLE_WITH_DATA = [
      "delimiter",
      "scope",
      "context",
      "debug",
      "compileDebug",
      "client",
      "_with",
      "rmWhitespace",
      "strict",
      "filename",
      "async"
    ];
    var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat("cache");
    var _BOM = /^\uFEFF/;
    var _JS_IDENTIFIER = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/;
    exports.cache = utils.cache;
    exports.fileLoader = fs.readFileSync;
    exports.localsName = _DEFAULT_LOCALS_NAME;
    exports.promiseImpl = new Function("return this;")().Promise;
    exports.resolveInclude = function(name, filename, isDir) {
      var dirname3 = path.dirname;
      var extname = path.extname;
      var resolve = path.resolve;
      var includePath = resolve(isDir ? filename : dirname3(filename), name);
      var ext = extname(name);
      if (!ext) {
        includePath += ".ejs";
      }
      return includePath;
    };
    function resolvePaths(name, paths) {
      var filePath;
      if (paths.some(function(v) {
        filePath = exports.resolveInclude(name, v, true);
        return fs.existsSync(filePath);
      })) {
        return filePath;
      }
    }
    __name(resolvePaths, "resolvePaths");
    function getIncludePath(path2, options) {
      var includePath;
      var filePath;
      var views = options.views;
      var match = /^[A-Za-z]+:\\|^\//.exec(path2);
      if (match && match.length) {
        path2 = path2.replace(/^\/*/, "");
        if (Array.isArray(options.root)) {
          includePath = resolvePaths(path2, options.root);
        } else {
          includePath = exports.resolveInclude(path2, options.root || "/", true);
        }
      } else {
        if (options.filename) {
          filePath = exports.resolveInclude(path2, options.filename);
          if (fs.existsSync(filePath)) {
            includePath = filePath;
          }
        }
        if (!includePath && Array.isArray(views)) {
          includePath = resolvePaths(path2, views);
        }
        if (!includePath && typeof options.includer !== "function") {
          throw new Error('Could not find the include file "' + options.escapeFunction(path2) + '"');
        }
      }
      return includePath;
    }
    __name(getIncludePath, "getIncludePath");
    function handleCache(options, template) {
      var func;
      var filename = options.filename;
      var hasTemplate = arguments.length > 1;
      if (options.cache) {
        if (!filename) {
          throw new Error("cache option requires a filename");
        }
        func = exports.cache.get(filename);
        if (func) {
          return func;
        }
        if (!hasTemplate) {
          template = fileLoader(filename).toString().replace(_BOM, "");
        }
      } else if (!hasTemplate) {
        if (!filename) {
          throw new Error("Internal EJS error: no file name or template provided");
        }
        template = fileLoader(filename).toString().replace(_BOM, "");
      }
      func = exports.compile(template, options);
      if (options.cache) {
        exports.cache.set(filename, func);
      }
      return func;
    }
    __name(handleCache, "handleCache");
    function tryHandleCache(options, data, cb) {
      var result;
      if (!cb) {
        if (typeof exports.promiseImpl == "function") {
          return new exports.promiseImpl(function(resolve, reject) {
            try {
              result = handleCache(options)(data);
              resolve(result);
            } catch (err) {
              reject(err);
            }
          });
        } else {
          throw new Error("Please provide a callback function");
        }
      } else {
        try {
          result = handleCache(options)(data);
        } catch (err) {
          return cb(err);
        }
        cb(null, result);
      }
    }
    __name(tryHandleCache, "tryHandleCache");
    function fileLoader(filePath) {
      return exports.fileLoader(filePath);
    }
    __name(fileLoader, "fileLoader");
    function includeFile(path2, options) {
      var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
      opts.filename = getIncludePath(path2, opts);
      if (typeof options.includer === "function") {
        var includerResult = options.includer(path2, opts.filename);
        if (includerResult) {
          if (includerResult.filename) {
            opts.filename = includerResult.filename;
          }
          if (includerResult.template) {
            return handleCache(opts, includerResult.template);
          }
        }
      }
      return handleCache(opts);
    }
    __name(includeFile, "includeFile");
    function rethrow(err, str, flnm, lineno, esc) {
      var lines = str.split("\n");
      var start2 = Math.max(lineno - 3, 0);
      var end = Math.min(lines.length, lineno + 3);
      var filename = esc(flnm);
      var context = lines.slice(start2, end).map(function(line, i) {
        var curr = i + start2 + 1;
        return (curr == lineno ? " >> " : "    ") + curr + "| " + line;
      }).join("\n");
      err.path = filename;
      err.message = (filename || "ejs") + ":" + lineno + "\n" + context + "\n\n" + err.message;
      throw err;
    }
    __name(rethrow, "rethrow");
    function stripSemi(str) {
      return str.replace(/;(\s*$)/, "$1");
    }
    __name(stripSemi, "stripSemi");
    exports.compile = /* @__PURE__ */ __name(function compile(template, opts) {
      var templ;
      if (opts && opts.scope) {
        if (!scopeOptionWarned) {
          console.warn("`scope` option is deprecated and will be removed in EJS 3");
          scopeOptionWarned = true;
        }
        if (!opts.context) {
          opts.context = opts.scope;
        }
        delete opts.scope;
      }
      templ = new Template(template, opts);
      return templ.compile();
    }, "compile");
    exports.render = function(template, d, o) {
      var data = d || utils.createNullProtoObjWherePossible();
      var opts = o || utils.createNullProtoObjWherePossible();
      if (arguments.length == 2) {
        utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
      }
      return handleCache(opts, template)(data);
    };
    exports.renderFile = function() {
      var args = Array.prototype.slice.call(arguments);
      var filename = args.shift();
      var cb;
      var opts = { filename };
      var data;
      var viewOpts;
      if (typeof arguments[arguments.length - 1] == "function") {
        cb = args.pop();
      }
      if (args.length) {
        data = args.shift();
        if (args.length) {
          utils.shallowCopy(opts, args.pop());
        } else {
          if (data.settings) {
            if (data.settings.views) {
              opts.views = data.settings.views;
            }
            if (data.settings["view cache"]) {
              opts.cache = true;
            }
            viewOpts = data.settings["view options"];
            if (viewOpts) {
              utils.shallowCopy(opts, viewOpts);
            }
          }
          utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
        }
        opts.filename = filename;
      } else {
        data = utils.createNullProtoObjWherePossible();
      }
      return tryHandleCache(opts, data, cb);
    };
    exports.Template = Template;
    exports.clearCache = function() {
      exports.cache.reset();
    };
    function Template(text, optsParam) {
      var opts = utils.hasOwnOnlyObject(optsParam);
      var options = utils.createNullProtoObjWherePossible();
      this.templateText = text;
      this.mode = null;
      this.truncate = false;
      this.currentLine = 1;
      this.source = "";
      options.client = opts.client || false;
      options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
      options.compileDebug = opts.compileDebug !== false;
      options.debug = !!opts.debug;
      options.filename = opts.filename;
      options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
      options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
      options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
      options.strict = opts.strict || false;
      options.context = opts.context;
      options.cache = opts.cache || false;
      options.rmWhitespace = opts.rmWhitespace;
      options.root = opts.root;
      options.includer = opts.includer;
      options.outputFunctionName = opts.outputFunctionName;
      options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
      options.views = opts.views;
      options.async = opts.async;
      options.destructuredLocals = opts.destructuredLocals;
      options.legacyInclude = typeof opts.legacyInclude != "undefined" ? !!opts.legacyInclude : true;
      if (options.strict) {
        options._with = false;
      } else {
        options._with = typeof opts._with != "undefined" ? opts._with : true;
      }
      this.opts = options;
      this.regex = this.createRegex();
    }
    __name(Template, "Template");
    Template.modes = {
      EVAL: "eval",
      ESCAPED: "escaped",
      RAW: "raw",
      COMMENT: "comment",
      LITERAL: "literal"
    };
    Template.prototype = {
      createRegex: /* @__PURE__ */ __name(function() {
        var str = _REGEX_STRING;
        var delim = utils.escapeRegExpChars(this.opts.delimiter);
        var open = utils.escapeRegExpChars(this.opts.openDelimiter);
        var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
        str = str.replace(/%/g, delim).replace(/</g, open).replace(/>/g, close);
        return new RegExp(str);
      }, "createRegex"),
      compile: /* @__PURE__ */ __name(function() {
        var src;
        var fn;
        var opts = this.opts;
        var prepended = "";
        var appended = "";
        var escapeFn = opts.escapeFunction;
        var ctor;
        var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : "undefined";
        if (!this.source) {
          this.generateSource();
          prepended += '  var __output = "";\n  function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
          if (opts.outputFunctionName) {
            if (!_JS_IDENTIFIER.test(opts.outputFunctionName)) {
              throw new Error("outputFunctionName is not a valid JS identifier.");
            }
            prepended += "  var " + opts.outputFunctionName + " = __append;\n";
          }
          if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName)) {
            throw new Error("localsName is not a valid JS identifier.");
          }
          if (opts.destructuredLocals && opts.destructuredLocals.length) {
            var destructuring = "  var __locals = (" + opts.localsName + " || {}),\n";
            for (var i = 0; i < opts.destructuredLocals.length; i++) {
              var name = opts.destructuredLocals[i];
              if (!_JS_IDENTIFIER.test(name)) {
                throw new Error("destructuredLocals[" + i + "] is not a valid JS identifier.");
              }
              if (i > 0) {
                destructuring += ",\n  ";
              }
              destructuring += name + " = __locals." + name;
            }
            prepended += destructuring + ";\n";
          }
          if (opts._with !== false) {
            prepended += "  with (" + opts.localsName + " || {}) {\n";
            appended += "  }\n";
          }
          appended += "  return __output;\n";
          this.source = prepended + this.source + appended;
        }
        if (opts.compileDebug) {
          src = "var __line = 1\n  , __lines = " + JSON.stringify(this.templateText) + "\n  , __filename = " + sanitizedFilename + ";\ntry {\n" + this.source + "} catch (e) {\n  rethrow(e, __lines, __filename, __line, escapeFn);\n}\n";
        } else {
          src = this.source;
        }
        if (opts.client) {
          src = "escapeFn = escapeFn || " + escapeFn.toString() + ";\n" + src;
          if (opts.compileDebug) {
            src = "rethrow = rethrow || " + rethrow.toString() + ";\n" + src;
          }
        }
        if (opts.strict) {
          src = '"use strict";\n' + src;
        }
        if (opts.debug) {
          console.log(src);
        }
        if (opts.compileDebug && opts.filename) {
          src = src + "\n//# sourceURL=" + sanitizedFilename + "\n";
        }
        try {
          if (opts.async) {
            try {
              ctor = new Function("return (async function(){}).constructor;")();
            } catch (e) {
              if (e instanceof SyntaxError) {
                throw new Error("This environment does not support async/await");
              } else {
                throw e;
              }
            }
          } else {
            ctor = Function;
          }
          fn = new ctor(opts.localsName + ", escapeFn, include, rethrow", src);
        } catch (e) {
          if (e instanceof SyntaxError) {
            if (opts.filename) {
              e.message += " in " + opts.filename;
            }
            e.message += " while compiling ejs\n\n";
            e.message += "If the above error is not helpful, you may want to try EJS-Lint:\n";
            e.message += "https://github.com/RyanZim/EJS-Lint";
            if (!opts.async) {
              e.message += "\n";
              e.message += "Or, if you meant to create an async function, pass `async: true` as an option.";
            }
          }
          throw e;
        }
        var returnedFn = opts.client ? fn : /* @__PURE__ */ __name(function anonymous(data) {
          var include = /* @__PURE__ */ __name(function(path2, includeData) {
            var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
            if (includeData) {
              d = utils.shallowCopy(d, includeData);
            }
            return includeFile(path2, opts)(d);
          }, "include");
          return fn.apply(
            opts.context,
            [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]
          );
        }, "anonymous");
        if (opts.filename && typeof Object.defineProperty === "function") {
          var filename = opts.filename;
          var basename2 = path.basename(filename, path.extname(filename));
          try {
            Object.defineProperty(returnedFn, "name", {
              value: basename2,
              writable: false,
              enumerable: false,
              configurable: true
            });
          } catch (e) {
          }
        }
        return returnedFn;
      }, "compile"),
      generateSource: /* @__PURE__ */ __name(function() {
        var opts = this.opts;
        if (opts.rmWhitespace) {
          this.templateText = this.templateText.replace(/[\r\n]+/g, "\n").replace(/^\s+|\s+$/gm, "");
        }
        this.templateText = this.templateText.replace(/[ \t]*<%_/gm, "<%_").replace(/_%>[ \t]*/gm, "_%>");
        var self = this;
        var matches = this.parseTemplateText();
        var d = this.opts.delimiter;
        var o = this.opts.openDelimiter;
        var c = this.opts.closeDelimiter;
        if (matches && matches.length) {
          matches.forEach(function(line, index) {
            var closing;
            if (line.indexOf(o + d) === 0 && line.indexOf(o + d + d) !== 0) {
              closing = matches[index + 2];
              if (!(closing == d + c || closing == "-" + d + c || closing == "_" + d + c)) {
                throw new Error('Could not find matching close tag for "' + line + '".');
              }
            }
            self.scanLine(line);
          });
        }
      }, "generateSource"),
      parseTemplateText: /* @__PURE__ */ __name(function() {
        var str = this.templateText;
        var pat = this.regex;
        var result = pat.exec(str);
        var arr = [];
        var firstPos;
        while (result) {
          firstPos = result.index;
          if (firstPos !== 0) {
            arr.push(str.substring(0, firstPos));
            str = str.slice(firstPos);
          }
          arr.push(result[0]);
          str = str.slice(result[0].length);
          result = pat.exec(str);
        }
        if (str) {
          arr.push(str);
        }
        return arr;
      }, "parseTemplateText"),
      _addOutput: /* @__PURE__ */ __name(function(line) {
        if (this.truncate) {
          line = line.replace(/^(?:\r\n|\r|\n)/, "");
          this.truncate = false;
        }
        if (!line) {
          return line;
        }
        line = line.replace(/\\/g, "\\\\");
        line = line.replace(/\n/g, "\\n");
        line = line.replace(/\r/g, "\\r");
        line = line.replace(/"/g, '\\"');
        this.source += '    ; __append("' + line + '")\n';
      }, "_addOutput"),
      scanLine: /* @__PURE__ */ __name(function(line) {
        var self = this;
        var d = this.opts.delimiter;
        var o = this.opts.openDelimiter;
        var c = this.opts.closeDelimiter;
        var newLineCount = 0;
        newLineCount = line.split("\n").length - 1;
        switch (line) {
          case o + d:
          case o + d + "_":
            this.mode = Template.modes.EVAL;
            break;
          case o + d + "=":
            this.mode = Template.modes.ESCAPED;
            break;
          case o + d + "-":
            this.mode = Template.modes.RAW;
            break;
          case o + d + "#":
            this.mode = Template.modes.COMMENT;
            break;
          case o + d + d:
            this.mode = Template.modes.LITERAL;
            this.source += '    ; __append("' + line.replace(o + d + d, o + d) + '")\n';
            break;
          case d + d + c:
            this.mode = Template.modes.LITERAL;
            this.source += '    ; __append("' + line.replace(d + d + c, d + c) + '")\n';
            break;
          case d + c:
          case "-" + d + c:
          case "_" + d + c:
            if (this.mode == Template.modes.LITERAL) {
              this._addOutput(line);
            }
            this.mode = null;
            this.truncate = line.indexOf("-") === 0 || line.indexOf("_") === 0;
            break;
          default:
            if (this.mode) {
              switch (this.mode) {
                case Template.modes.EVAL:
                case Template.modes.ESCAPED:
                case Template.modes.RAW:
                  if (line.lastIndexOf("//") > line.lastIndexOf("\n")) {
                    line += "\n";
                  }
              }
              switch (this.mode) {
                // Just executing code
                case Template.modes.EVAL:
                  this.source += "    ; " + line + "\n";
                  break;
                // Exec, esc, and output
                case Template.modes.ESCAPED:
                  this.source += "    ; __append(escapeFn(" + stripSemi(line) + "))\n";
                  break;
                // Exec and output
                case Template.modes.RAW:
                  this.source += "    ; __append(" + stripSemi(line) + ")\n";
                  break;
                case Template.modes.COMMENT:
                  break;
                // Literal <%% mode, append as raw output
                case Template.modes.LITERAL:
                  this._addOutput(line);
                  break;
              }
            } else {
              this._addOutput(line);
            }
        }
        if (self.opts.compileDebug && newLineCount) {
          this.currentLine += newLineCount;
          this.source += "    ; __line = " + this.currentLine + "\n";
        }
      }, "scanLine")
    };
    exports.escapeXML = utils.escapeXML;
    exports.__express = exports.renderFile;
    exports.VERSION = _VERSION_STRING;
    exports.name = _NAME;
    if (typeof window != "undefined") {
      window.ejs = exports;
    }
  }
});

// src/builder-manager/index.ts
import { cp, rm, writeFile as writeFile3 } from "node:fs/promises";
import { stringifyProcessEnvs } from "storybook/internal/common";
import { logger } from "storybook/internal/node-logger";

// ../node_modules/@fal-works/esbuild-plugin-global-externals/lib/module-info.js
var normalizeModuleInfo = /* @__PURE__ */ __name((value) => {
  const {
    type = "esm",
    varName,
    namedExports = null,
    defaultExport = true
  } = typeof value === "string" ? { varName: value } : value;
  return { type, varName, namedExports, defaultExport };
}, "normalizeModuleInfo");

// ../node_modules/@fal-works/esbuild-plugin-global-externals/lib/on-load.js
var createCjsContents = /* @__PURE__ */ __name((variableName) => `module.exports = ${variableName};`, "createCjsContents");
var createEsmContents = /* @__PURE__ */ __name((variableName, namedExports, defaultExport) => {
  const codeElements = defaultExport ? [`export default ${variableName};`] : [];
  if (namedExports && namedExports.length) {
    const exportNames = [...new Set(namedExports)].join(", ");
    codeElements.push(`const { ${exportNames} } = ${variableName};`);
    codeElements.push(`export { ${exportNames} };`);
  }
  return codeElements.join("\n");
}, "createEsmContents");
var createContents = /* @__PURE__ */ __name((moduleInfo) => {
  const { type, varName, namedExports, defaultExport } = moduleInfo;
  switch (type) {
    case "esm":
      return createEsmContents(varName, namedExports, defaultExport);
    case "cjs":
      return createCjsContents(varName);
  }
}, "createContents");

// ../node_modules/@fal-works/esbuild-plugin-global-externals/lib/with-reg-exp.js
var PLUGIN_NAME = "global-externals";
var globalExternalsWithRegExp = /* @__PURE__ */ __name((globals) => {
  const { modulePathFilter, getModuleInfo } = globals;
  return {
    name: PLUGIN_NAME,
    setup(build2) {
      build2.onResolve({ filter: modulePathFilter }, (args) => ({
        path: args.path,
        namespace: PLUGIN_NAME
      }));
      build2.onLoad({ filter: /.*/, namespace: PLUGIN_NAME }, (args) => {
        const modulePath = args.path;
        const moduleInfo = normalizeModuleInfo(getModuleInfo(modulePath));
        return { contents: createContents(moduleInfo) };
      });
    }
  };
}, "globalExternalsWithRegExp");

// ../node_modules/@fal-works/esbuild-plugin-global-externals/lib/with-object.js
var globalExternals = /* @__PURE__ */ __name((globals) => {
  const normalizedGlobals = {
    modulePathFilter: new RegExp(`^(?:${Object.keys(globals).join("|")})$`),
    getModuleInfo: /* @__PURE__ */ __name((modulePath) => globals[modulePath], "getModuleInfo")
  };
  return globalExternalsWithRegExp(normalizedGlobals);
}, "globalExternals");

// src/builder-manager/index.ts
var import_esbuild_plugin_pnp = __toESM(require_lib(), 1);
var import_sirv = __toESM(require_build(), 1);

// src/manager/globals/exports.ts
var exports_default = {
  react: [
    "Children",
    "Component",
    "Fragment",
    "Profiler",
    "PureComponent",
    "StrictMode",
    "Suspense",
    "__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED",
    "act",
    "cloneElement",
    "createContext",
    "createElement",
    "createFactory",
    "createRef",
    "forwardRef",
    "isValidElement",
    "lazy",
    "memo",
    "startTransition",
    "unstable_act",
    "useCallback",
    "useContext",
    "useDebugValue",
    "useDeferredValue",
    "useEffect",
    "useId",
    "useImperativeHandle",
    "useInsertionEffect",
    "useLayoutEffect",
    "useMemo",
    "useReducer",
    "useRef",
    "useState",
    "useSyncExternalStore",
    "useTransition",
    "version"
  ],
  "react-dom": [
    "__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED",
    "createPortal",
    "createRoot",
    "findDOMNode",
    "flushSync",
    "hydrate",
    "hydrateRoot",
    "render",
    "unmountComponentAtNode",
    "unstable_batchedUpdates",
    "unstable_renderSubtreeIntoContainer",
    "version"
  ],
  "react-dom/client": ["createRoot", "hydrateRoot"],
  "@storybook/icons": [
    "AccessibilityAltIcon",
    "AccessibilityIcon",
    "AccessibilityIgnoredIcon",
    "AddIcon",
    "AdminIcon",
    "AlertAltIcon",
    "AlertIcon",
    "AlignLeftIcon",
    "AlignRightIcon",
    "AppleIcon",
    "ArrowBottomLeftIcon",
    "ArrowBottomRightIcon",
    "ArrowDownIcon",
    "ArrowLeftIcon",
    "ArrowRightIcon",
    "ArrowSolidDownIcon",
    "ArrowSolidLeftIcon",
    "ArrowSolidRightIcon",
    "ArrowSolidUpIcon",
    "ArrowTopLeftIcon",
    "ArrowTopRightIcon",
    "ArrowUpIcon",
    "AzureDevOpsIcon",
    "BackIcon",
    "BasketIcon",
    "BatchAcceptIcon",
    "BatchDenyIcon",
    "BeakerIcon",
    "BellIcon",
    "BitbucketIcon",
    "BoldIcon",
    "BookIcon",
    "BookmarkHollowIcon",
    "BookmarkIcon",
    "BottomBarIcon",
    "BottomBarToggleIcon",
    "BoxIcon",
    "BranchIcon",
    "BrowserIcon",
    "BugIcon",
    "ButtonIcon",
    "CPUIcon",
    "CalendarIcon",
    "CameraIcon",
    "CameraStabilizeIcon",
    "CategoryIcon",
    "CertificateIcon",
    "ChangedIcon",
    "ChatIcon",
    "CheckIcon",
    "ChevronDownIcon",
    "ChevronLeftIcon",
    "ChevronRightIcon",
    "ChevronSmallDownIcon",
    "ChevronSmallLeftIcon",
    "ChevronSmallRightIcon",
    "ChevronSmallUpIcon",
    "ChevronUpIcon",
    "ChromaticIcon",
    "ChromeIcon",
    "CircleHollowIcon",
    "CircleIcon",
    "ClearIcon",
    "CloseAltIcon",
    "CloseIcon",
    "CloudHollowIcon",
    "CloudIcon",
    "CogIcon",
    "CollapseIcon",
    "CommandIcon",
    "CommentAddIcon",
    "CommentIcon",
    "CommentsIcon",
    "CommitIcon",
    "CompassIcon",
    "ComponentDrivenIcon",
    "ComponentIcon",
    "ContrastIcon",
    "ContrastIgnoredIcon",
    "ControlsIcon",
    "CopyIcon",
    "CreditIcon",
    "CrossIcon",
    "DashboardIcon",
    "DatabaseIcon",
    "DeleteIcon",
    "DiamondIcon",
    "DirectionIcon",
    "DiscordIcon",
    "DocChartIcon",
    "DocListIcon",
    "DocumentIcon",
    "DownloadIcon",
    "DragIcon",
    "EditIcon",
    "EditorIcon",
    "EllipsisIcon",
    "EmailIcon",
    "ExpandAltIcon",
    "ExpandIcon",
    "EyeCloseIcon",
    "EyeIcon",
    "FaceHappyIcon",
    "FaceNeutralIcon",
    "FaceSadIcon",
    "FacebookIcon",
    "FailedIcon",
    "FastForwardIcon",
    "FigmaIcon",
    "FilterIcon",
    "FlagIcon",
    "FolderIcon",
    "FormIcon",
    "GDriveIcon",
    "GiftIcon",
    "GithubIcon",
    "GitlabIcon",
    "GlobeIcon",
    "GoogleIcon",
    "GraphBarIcon",
    "GraphLineIcon",
    "GraphqlIcon",
    "GridAltIcon",
    "GridIcon",
    "GrowIcon",
    "HeartHollowIcon",
    "HeartIcon",
    "HomeIcon",
    "HourglassIcon",
    "InfoIcon",
    "ItalicIcon",
    "JumpToIcon",
    "KeyIcon",
    "LightningIcon",
    "LightningOffIcon",
    "LinkBrokenIcon",
    "LinkIcon",
    "LinkedinIcon",
    "LinuxIcon",
    "ListOrderedIcon",
    "ListUnorderedIcon",
    "LocationIcon",
    "LockIcon",
    "MarkdownIcon",
    "MarkupIcon",
    "MediumIcon",
    "MemoryIcon",
    "MenuIcon",
    "MergeIcon",
    "MirrorIcon",
    "MobileIcon",
    "MoonIcon",
    "NutIcon",
    "OutboxIcon",
    "OutlineIcon",
    "PaintBrushAltIcon",
    "PaintBrushIcon",
    "PaperClipIcon",
    "ParagraphIcon",
    "PassedIcon",
    "PhoneIcon",
    "PhotoDragIcon",
    "PhotoIcon",
    "PhotoStabilizeIcon",
    "PinAltIcon",
    "PinIcon",
    "PlayAllHollowIcon",
    "PlayBackIcon",
    "PlayHollowIcon",
    "PlayIcon",
    "PlayNextIcon",
    "PlusIcon",
    "PointerDefaultIcon",
    "PointerHandIcon",
    "PowerIcon",
    "PrintIcon",
    "ProceedIcon",
    "ProfileIcon",
    "PullRequestIcon",
    "QuestionIcon",
    "RSSIcon",
    "RedirectIcon",
    "ReduxIcon",
    "RefreshIcon",
    "ReplyIcon",
    "RepoIcon",
    "RequestChangeIcon",
    "RewindIcon",
    "RulerIcon",
    "SaveIcon",
    "SearchIcon",
    "ShareAltIcon",
    "ShareIcon",
    "ShieldIcon",
    "SideBySideIcon",
    "SidebarAltIcon",
    "SidebarAltToggleIcon",
    "SidebarIcon",
    "SidebarToggleIcon",
    "SortDownIcon",
    "SortUpIcon",
    "SpeakerIcon",
    "StackedIcon",
    "StarHollowIcon",
    "StarIcon",
    "StatusFailIcon",
    "StatusIcon",
    "StatusPassIcon",
    "StatusWarnIcon",
    "StickerIcon",
    "StopAltHollowIcon",
    "StopAltIcon",
    "StopIcon",
    "StorybookIcon",
    "StructureIcon",
    "SubtractIcon",
    "SunIcon",
    "SupportIcon",
    "SweepIcon",
    "SwitchAltIcon",
    "SyncIcon",
    "TabletIcon",
    "ThumbsUpIcon",
    "TimeIcon",
    "TimerIcon",
    "TransferIcon",
    "TrashIcon",
    "TwitterIcon",
    "TypeIcon",
    "UbuntuIcon",
    "UndoIcon",
    "UnfoldIcon",
    "UnlockIcon",
    "UnpinIcon",
    "UploadIcon",
    "UserAddIcon",
    "UserAltIcon",
    "UserIcon",
    "UsersIcon",
    "VSCodeIcon",
    "VerifiedIcon",
    "VideoIcon",
    "WandIcon",
    "WatchIcon",
    "WindowsIcon",
    "WrenchIcon",
    "XIcon",
    "YoutubeIcon",
    "ZoomIcon",
    "ZoomOutIcon",
    "ZoomResetIcon",
    "iconList"
  ],
  "storybook/manager-api": [
    "ActiveTabs",
    "Consumer",
    "ManagerContext",
    "Provider",
    "RequestResponseError",
    "addons",
    "combineParameters",
    "controlOrMetaKey",
    "controlOrMetaSymbol",
    "eventMatchesShortcut",
    "eventToShortcut",
    "experimental_MockUniversalStore",
    "experimental_UniversalStore",
    "experimental_getStatusStore",
    "experimental_getTestProviderStore",
    "experimental_requestResponse",
    "experimental_useStatusStore",
    "experimental_useTestProviderStore",
    "experimental_useUniversalStore",
    "internal_fullStatusStore",
    "internal_fullTestProviderStore",
    "internal_universalStatusStore",
    "internal_universalTestProviderStore",
    "isMacLike",
    "isShortcutTaken",
    "keyToSymbol",
    "merge",
    "mockChannel",
    "optionOrAltSymbol",
    "shortcutMatchesShortcut",
    "shortcutToHumanString",
    "types",
    "useAddonState",
    "useArgTypes",
    "useArgs",
    "useChannel",
    "useGlobalTypes",
    "useGlobals",
    "useParameter",
    "useSharedState",
    "useStoryPrepared",
    "useStorybookApi",
    "useStorybookState"
  ],
  "storybook/theming": [
    "CacheProvider",
    "ClassNames",
    "Global",
    "ThemeProvider",
    "background",
    "color",
    "convert",
    "create",
    "createCache",
    "createGlobal",
    "createReset",
    "css",
    "darken",
    "ensure",
    "getPreferredColorScheme",
    "ignoreSsrWarning",
    "isPropValid",
    "jsx",
    "keyframes",
    "lighten",
    "styled",
    "themes",
    "typography",
    "useTheme",
    "withTheme"
  ],
  "storybook/theming/create": ["create", "themes"],
  "storybook/test": [
    "buildQueries",
    "clearAllMocks",
    "configure",
    "createEvent",
    "expect",
    "findAllByAltText",
    "findAllByDisplayValue",
    "findAllByLabelText",
    "findAllByPlaceholderText",
    "findAllByRole",
    "findAllByTestId",
    "findAllByText",
    "findAllByTitle",
    "findByAltText",
    "findByDisplayValue",
    "findByLabelText",
    "findByPlaceholderText",
    "findByRole",
    "findByTestId",
    "findByText",
    "findByTitle",
    "fireEvent",
    "fn",
    "getAllByAltText",
    "getAllByDisplayValue",
    "getAllByLabelText",
    "getAllByPlaceholderText",
    "getAllByRole",
    "getAllByTestId",
    "getAllByText",
    "getAllByTitle",
    "getByAltText",
    "getByDisplayValue",
    "getByLabelText",
    "getByPlaceholderText",
    "getByRole",
    "getByTestId",
    "getByText",
    "getByTitle",
    "getConfig",
    "getDefaultNormalizer",
    "getElementError",
    "getNodeText",
    "getQueriesForElement",
    "getRoles",
    "getSuggestedQuery",
    "isInaccessible",
    "isMockFunction",
    "logDOM",
    "logRoles",
    "mocked",
    "mocks",
    "onMockCall",
    "prettyDOM",
    "prettyFormat",
    "queries",
    "queryAllByAltText",
    "queryAllByAttribute",
    "queryAllByDisplayValue",
    "queryAllByLabelText",
    "queryAllByPlaceholderText",
    "queryAllByRole",
    "queryAllByTestId",
    "queryAllByText",
    "queryAllByTitle",
    "queryByAltText",
    "queryByAttribute",
    "queryByDisplayValue",
    "queryByLabelText",
    "queryByPlaceholderText",
    "queryByRole",
    "queryByTestId",
    "queryByText",
    "queryByTitle",
    "queryHelpers",
    "resetAllMocks",
    "restoreAllMocks",
    "sb",
    "screen",
    "spyOn",
    "uninstrumentedUserEvent",
    "userEvent",
    "waitFor",
    "waitForElementToBeRemoved",
    "within"
  ],
  "storybook/internal/channels": [
    "Channel",
    "HEARTBEAT_INTERVAL",
    "HEARTBEAT_MAX_LATENCY",
    "PostMessageTransport",
    "WebsocketTransport",
    "createBrowserChannel"
  ],
  "storybook/internal/client-logger": ["deprecate", "logger", "once", "pretty"],
  "storybook/internal/components": [
    "A",
    "ActionBar",
    "AddonPanel",
    "Badge",
    "Bar",
    "Blockquote",
    "Button",
    "Card",
    "ClipboardCode",
    "Code",
    "Collapsible",
    "DL",
    "Div",
    "DocumentWrapper",
    "EmptyTabContent",
    "ErrorFormatter",
    "FlexBar",
    "FocusProxy",
    "Form",
    "H1",
    "H2",
    "H3",
    "H4",
    "H5",
    "H6",
    "HR",
    "IconButton",
    "Img",
    "LI",
    "Link",
    "ListItem",
    "Listbox",
    "ListboxAction",
    "ListboxButton",
    "ListboxItem",
    "ListboxText",
    "Loader",
    "Modal",
    "OL",
    "P",
    "Placeholder",
    "Pre",
    "ProgressSpinner",
    "ResetWrapper",
    "ScrollArea",
    "Separator",
    "Spaced",
    "Span",
    "StorybookIcon",
    "StorybookLogo",
    "SyntaxHighlighter",
    "TT",
    "TabBar",
    "TabButton",
    "TabWrapper",
    "Table",
    "Tabs",
    "TabsState",
    "TooltipLinkList",
    "TooltipMessage",
    "TooltipNote",
    "UL",
    "WithTooltip",
    "WithTooltipPure",
    "Zoom",
    "codeCommon",
    "components",
    "createCopyToClipboardFunction",
    "getStoryHref",
    "interleaveSeparators",
    "nameSpaceClassNames",
    "resetComponents",
    "withReset"
  ],
  "storybook/internal/core-events": [
    "ARGTYPES_INFO_REQUEST",
    "ARGTYPES_INFO_RESPONSE",
    "CHANNEL_CREATED",
    "CHANNEL_WS_DISCONNECT",
    "CONFIG_ERROR",
    "CREATE_NEW_STORYFILE_REQUEST",
    "CREATE_NEW_STORYFILE_RESPONSE",
    "CURRENT_STORY_WAS_SET",
    "DOCS_PREPARED",
    "DOCS_RENDERED",
    "FILE_COMPONENT_SEARCH_REQUEST",
    "FILE_COMPONENT_SEARCH_RESPONSE",
    "FORCE_REMOUNT",
    "FORCE_RE_RENDER",
    "GLOBALS_UPDATED",
    "NAVIGATE_URL",
    "OPEN_IN_EDITOR_REQUEST",
    "OPEN_IN_EDITOR_RESPONSE",
    "PLAY_FUNCTION_THREW_EXCEPTION",
    "PRELOAD_ENTRIES",
    "PREVIEW_BUILDER_PROGRESS",
    "PREVIEW_INITIALIZED",
    "PREVIEW_KEYDOWN",
    "REGISTER_SUBSCRIPTION",
    "REQUEST_WHATS_NEW_DATA",
    "RESET_STORY_ARGS",
    "RESULT_WHATS_NEW_DATA",
    "SAVE_STORY_REQUEST",
    "SAVE_STORY_RESPONSE",
    "SELECT_STORY",
    "SET_CONFIG",
    "SET_CURRENT_STORY",
    "SET_FILTER",
    "SET_GLOBALS",
    "SET_INDEX",
    "SET_STORIES",
    "SET_WHATS_NEW_CACHE",
    "SHARED_STATE_CHANGED",
    "SHARED_STATE_SET",
    "STORIES_COLLAPSE_ALL",
    "STORIES_EXPAND_ALL",
    "STORY_ARGS_UPDATED",
    "STORY_CHANGED",
    "STORY_ERRORED",
    "STORY_FINISHED",
    "STORY_HOT_UPDATED",
    "STORY_INDEX_INVALIDATED",
    "STORY_MISSING",
    "STORY_PREPARED",
    "STORY_RENDERED",
    "STORY_RENDER_PHASE_CHANGED",
    "STORY_SPECIFIED",
    "STORY_THREW_EXCEPTION",
    "STORY_UNCHANGED",
    "TELEMETRY_ERROR",
    "TOGGLE_WHATS_NEW_NOTIFICATIONS",
    "UNHANDLED_ERRORS_WHILE_PLAYING",
    "UPDATE_GLOBALS",
    "UPDATE_QUERY_PARAMS",
    "UPDATE_STORY_ARGS"
  ],
  "storybook/internal/manager-errors": [
    "Category",
    "ProviderDoesNotExtendBaseProviderError",
    "StatusTypeIdMismatchError",
    "UncaughtManagerError"
  ],
  "storybook/internal/router": [
    "BaseLocationProvider",
    "DEEPLY_EQUAL",
    "Link",
    "Location",
    "LocationProvider",
    "Match",
    "Route",
    "buildArgsParam",
    "deepDiff",
    "getMatch",
    "parsePath",
    "queryFromLocation",
    "stringifyQuery",
    "useNavigate"
  ],
  "storybook/internal/types": ["Addon_TypesEnum"]
};

// src/manager/globals/globals.ts
var globalsNameReferenceMap = {
  react: "__REACT__",
  "react-dom": "__REACT_DOM__",
  "react-dom/client": "__REACT_DOM_CLIENT__",
  "@storybook/icons": "__STORYBOOK_ICONS__",
  "storybook/manager-api": "__STORYBOOK_API__",
  "storybook/test": "__STORYBOOK_TEST__",
  "storybook/theming": "__STORYBOOK_THEMING__",
  "storybook/theming/create": "__STORYBOOK_THEMING_CREATE__",
  "storybook/internal/channels": "__STORYBOOK_CHANNELS__",
  "storybook/internal/client-logger": "__STORYBOOK_CLIENT_LOGGER__",
  "storybook/internal/components": "__STORYBOOK_COMPONENTS__",
  "storybook/internal/core-events": "__STORYBOOK_CORE_EVENTS__",
  "storybook/internal/manager-errors": "__STORYBOOK_CORE_EVENTS_MANAGER_ERRORS__",
  "storybook/internal/router": "__STORYBOOK_ROUTER__",
  "storybook/internal/types": "__STORYBOOK_TYPES__"
};
var globalPackages = Object.keys(globalsNameReferenceMap);

// src/manager/globals/globals-module-info.ts
var duplicatedKeys = [
  "storybook/theming",
  "storybook/theming/create",
  "storybook/manager-api",
  "storybook/test",
  "storybook/actions",
  "storybook/highlight",
  "storybook/viewport"
];
var globalsModuleInfoMap = globalPackages.reduce(
  (acc, key) => {
    acc[key] = {
      type: "esm",
      varName: globalsNameReferenceMap[key],
      namedExports: exports_default[key],
      defaultExport: true
    };
    if (duplicatedKeys.includes(key)) {
      acc[key.replace("storybook", "storybook/internal")] = {
        type: "esm",
        varName: globalsNameReferenceMap[key],
        namedExports: exports_default[key],
        defaultExport: true
      };
    }
    return acc;
  },
  {}
);

// src/builder-manager/utils/data.ts
import { basename } from "node:path";
import { getRefs } from "storybook/internal/common";

// src/builder-manager/utils/template.ts
var import_ejs = __toESM(require_ejs(), 1);
import { readFile } from "node:fs/promises";
var getTemplatePath = /* @__PURE__ */ __name((template) => {
  return join(resolvePackageDir("storybook"), "assets/server", template);
}, "getTemplatePath");
var readTemplate = /* @__PURE__ */ __name(async (template) => {
  const path = getTemplatePath(template);
  return readFile(path, { encoding: "utf8" });
}, "readTemplate");
var renderHTML = /* @__PURE__ */ __name(async (template, title, favicon, customHead, cssFiles, jsFiles, features, refs, logLevel, docsOptions, tagsOptions, { versionCheck, previewUrl, configType, ignorePreview }, globals) => {
  const titleRef = await title;
  const templateRef = await template;
  const stringifiedGlobals = Object.entries(globals).reduce(
    (transformed, [key, value]) => ({ ...transformed, [key]: JSON.stringify(value) }),
    {}
  );
  return (0, import_ejs.render)(templateRef, {
    title: titleRef ? `${titleRef} - Storybook` : "Storybook",
    files: { js: jsFiles, css: cssFiles },
    favicon: await favicon,
    globals: {
      FEATURES: JSON.stringify(await features, null, 2),
      REFS: JSON.stringify(await refs, null, 2),
      LOGLEVEL: JSON.stringify(await logLevel, null, 2),
      DOCS_OPTIONS: JSON.stringify(await docsOptions, null, 2),
      CONFIG_TYPE: JSON.stringify(await configType, null, 2),
      // These two need to be double stringified because the UI expects a string
      VERSIONCHECK: JSON.stringify(JSON.stringify(versionCheck), null, 2),
      PREVIEW_URL: JSON.stringify(previewUrl, null, 2),
      // global preview URL
      TAGS_OPTIONS: JSON.stringify(await tagsOptions, null, 2),
      ...stringifiedGlobals
    },
    head: await customHead || "",
    ignorePreview
  });
}, "renderHTML");

// src/builder-manager/utils/data.ts
var getData = /* @__PURE__ */ __name(async (options) => {
  const refs = getRefs(options);
  const favicon = options.presets.apply("favicon").then((p) => basename(p));
  const features = options.presets.apply("features");
  const logLevel = options.presets.apply("logLevel");
  const title = options.presets.apply("title");
  const docsOptions = options.presets.apply("docs", {});
  const tagsOptions = options.presets.apply("tags", {});
  const template = readTemplate("template.ejs");
  const customHead = options.presets.apply("managerHead");
  const [instance, config] = await Promise.all([
    //
    executor.get(),
    getConfig(options)
  ]);
  return {
    refs,
    features,
    title,
    docsOptions,
    template,
    customHead,
    instance,
    config,
    logLevel,
    favicon,
    tagsOptions
  };
}, "getData");

// src/builder-manager/utils/files.ts
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join as join2, normalize, relative } from "node:path";
async function readOrderedFiles(addonsDir, outputFiles) {
  const files = await Promise.all(
    outputFiles?.map(async (file) => {
      const { location, url } = sanitizePath(file, addonsDir);
      if (!existsSync(location)) {
        const directory = dirname(location);
        await mkdir(directory, { recursive: true });
      }
      await writeFile(location, file.contents);
      return url;
    }) || []
  );
  const jsFiles = files.filter((file) => file.endsWith(".js"));
  const cssFiles = files.filter((file) => file.endsWith(".css"));
  return { cssFiles, jsFiles };
}
__name(readOrderedFiles, "readOrderedFiles");
function sanitizePath(file, addonsDir) {
  const filePath = relative(addonsDir, file.path);
  const location = normalize(join2(addonsDir, filePath));
  const url = `./sb-addons/${slash(filePath).split("/").map(encodeURIComponent).join("/")}`;
  return { location, url };
}
__name(sanitizePath, "sanitizePath");

// src/builder-manager/utils/framework.ts
import { sep } from "node:path";
import {
  extractProperRendererNameFromFramework,
  getFrameworkName
} from "storybook/internal/common";
var pluckNameFromConfigProperty = /* @__PURE__ */ __name((property) => {
  if (!property) {
    return void 0;
  }
  return typeof property === "string" ? property : property.name;
}, "pluckNameFromConfigProperty");
var normalizePath = /* @__PURE__ */ __name((packagePath) => packagePath.replaceAll(sep, "/"), "normalizePath");
var pluckStorybookPackageFromPath = /* @__PURE__ */ __name((packagePath) => normalizePath(packagePath).match(/(@storybook\/.*)$/)?.[1], "pluckStorybookPackageFromPath");
var pluckThirdPartyPackageFromPath = /* @__PURE__ */ __name((packagePath) => normalizePath(packagePath).split("node_modules/")[1] ?? packagePath, "pluckThirdPartyPackageFromPath");
var buildFrameworkGlobalsFromOptions = /* @__PURE__ */ __name(async (options) => {
  const globals = {};
  const { builder: builder2 } = await options.presets.apply("core");
  const frameworkName = await getFrameworkName(options);
  const rendererName = await extractProperRendererNameFromFramework(frameworkName);
  if (rendererName) {
    globals.STORYBOOK_RENDERER = await extractProperRendererNameFromFramework(frameworkName) ?? void 0;
  }
  const resolvedPreviewBuilder = pluckNameFromConfigProperty(builder2);
  if (resolvedPreviewBuilder) {
    globals.STORYBOOK_BUILDER = pluckStorybookPackageFromPath(resolvedPreviewBuilder) ?? pluckThirdPartyPackageFromPath(resolvedPreviewBuilder);
  }
  const framework = pluckNameFromConfigProperty(await options.presets.apply("framework"));
  if (framework) {
    globals.STORYBOOK_FRAMEWORK = framework;
  }
  if (options.networkAddress) {
    globals.STORYBOOK_NETWORK_ADDRESS = options.networkAddress;
  }
  return globals;
}, "buildFrameworkGlobalsFromOptions");

// src/builder-manager/utils/managerEntries.ts
import { existsSync as existsSync2 } from "node:fs";
import { mkdir as mkdir2, writeFile as writeFile2 } from "node:fs/promises";
import { dirname as dirname2, join as join3, parse as parse2, relative as relative2, sep as sep2 } from "node:path";
import { resolvePathInStorybookCache } from "storybook/internal/common";
var sanitizeBase = /* @__PURE__ */ __name((path) => {
  return path.replaceAll(".", "").replaceAll("@", "").replaceAll(sep2, "-").replaceAll("/", "-").replaceAll(new RegExp(/^(-)+/g), "");
}, "sanitizeBase");
var sanitizeFinal = /* @__PURE__ */ __name((path) => {
  const sections = path.split(/-?node_modules-?/);
  return sections[sections.length - 1].replaceAll("storybook-addon-", "").replaceAll("dist-", "");
}, "sanitizeFinal");
async function wrapManagerEntries(entrypoints, uniqueId) {
  return Promise.all(
    entrypoints.map(async (entry, i) => {
      const { name, dir } = parse2(entry);
      const cacheLocation = resolvePathInStorybookCache("sb-manager", uniqueId);
      if (!cacheLocation) {
        throw new Error("Could not create/find cache directory");
      }
      const base = relative2(process.cwd(), dir);
      const location = join3(
        cacheLocation,
        sanitizeFinal(join3(`${sanitizeBase(base)}-${i}`, `${sanitizeBase(name)}-bundle.js`))
      );
      if (!existsSync2(location)) {
        const directory = dirname2(location);
        await mkdir2(directory, { recursive: true });
      }
      await writeFile2(location, `import '${slash(entry).replaceAll(/'/g, "\\'")}';`);
      return location;
    })
  );
}
__name(wrapManagerEntries, "wrapManagerEntries");

// src/builder-manager/index.ts
var CORE_DIR_ORIGIN = join(resolvePackageDir("storybook"), "dist/manager");
var isRootPath = /^\/($|\?)/;
var compilation;
var asyncIterator;
var getConfig = /* @__PURE__ */ __name(async (options) => {
  const [managerEntriesFromPresets, envs] = await Promise.all([
    options.presets.apply("managerEntries", []),
    options.presets.apply("env")
  ]);
  const tsconfigPath = getTemplatePath("addon.tsconfig.json");
  let configDirManagerEntry;
  try {
    configDirManagerEntry = resolveModulePath("./manager", {
      from: options.configDir,
      extensions: [".js", ".mjs", ".jsx", ".ts", ".mts", ".tsx"]
    });
  } catch (e) {
  }
  const entryPoints = configDirManagerEntry ? [...managerEntriesFromPresets, configDirManagerEntry] : managerEntriesFromPresets;
  return {
    entryPoints: await wrapManagerEntries(entryPoints, options.cacheKey),
    outdir: join(options.outputDir || "./", "sb-addons"),
    format: "iife",
    write: false,
    ignoreAnnotations: true,
    resolveExtensions: [".ts", ".tsx", ".mjs", ".js", ".jsx"],
    outExtension: { ".js": ".js" },
    loader: {
      ".js": "jsx",
      // media
      ".png": "dataurl",
      ".gif": "dataurl",
      ".jpg": "dataurl",
      ".jpeg": "dataurl",
      ".svg": "dataurl",
      ".webp": "dataurl",
      ".webm": "dataurl",
      ".mp3": "dataurl",
      // modern fonts
      ".woff2": "dataurl",
      // legacy font formats
      ".woff": "dataurl",
      ".eot": "dataurl",
      ".ttf": "dataurl"
    },
    target: BROWSER_TARGETS,
    supported: SUPPORTED_FEATURES,
    platform: "browser",
    bundle: true,
    minify: false,
    minifyWhitespace: false,
    minifyIdentifiers: false,
    minifySyntax: true,
    metafile: false,
    // turn this on to assist with debugging the bundling of managerEntries
    // treeShaking: true,
    sourcemap: false,
    conditions: ["browser", "module", "default"],
    jsxFactory: "React.createElement",
    jsxFragment: "React.Fragment",
    jsx: "transform",
    jsxImportSource: "react",
    tsconfig: tsconfigPath,
    legalComments: "external",
    plugins: [globalExternals(globalsModuleInfoMap), (0, import_esbuild_plugin_pnp.pnpPlugin)()],
    banner: {
      js: "try{"
    },
    footer: {
      js: '}catch(e){ console.error("[Storybook] One of your manager-entries failed: " + import.meta.url, e); }'
    },
    define: {
      "process.env": JSON.stringify(envs),
      ...stringifyProcessEnvs(envs),
      global: "window",
      module: "{}"
    }
  };
}, "getConfig");
var executor = {
  get: /* @__PURE__ */ __name(async () => {
    const { build: build2 } = await import("esbuild");
    return build2;
  }, "get")
};
var starter = /* @__PURE__ */ __name(async function* starterGeneratorFn({
  startTime,
  options,
  router
}) {
  if (!options.quiet) {
    logger.info("=> Starting manager..");
  }
  const {
    config,
    favicon,
    customHead,
    features,
    instance,
    refs,
    template,
    title,
    logLevel,
    docsOptions,
    tagsOptions
  } = await getData(options);
  yield;
  const addonsDir = config.outdir;
  await rm(addonsDir, { recursive: true, force: true });
  yield;
  compilation = await instance({
    ...config
  });
  yield;
  router.use(
    "/sb-addons",
    (0, import_sirv.default)(addonsDir, {
      maxAge: 3e5,
      dev: true,
      immutable: true
    })
  );
  router.use(
    "/sb-manager",
    (0, import_sirv.default)(CORE_DIR_ORIGIN, {
      maxAge: 3e5,
      dev: true,
      immutable: true
    })
  );
  const { cssFiles, jsFiles } = await readOrderedFiles(addonsDir, compilation?.outputFiles);
  if (compilation.metafile && options.outputDir) {
    await writeFile3(
      join(options.outputDir, "metafile.json"),
      JSON.stringify(compilation.metafile, null, 2)
    );
  }
  const globals = await buildFrameworkGlobalsFromOptions(options);
  yield;
  const html = await renderHTML(
    template,
    title,
    favicon,
    customHead,
    cssFiles,
    jsFiles,
    features,
    refs,
    logLevel,
    docsOptions,
    tagsOptions,
    options,
    globals
  );
  yield;
  router.use("/", ({ url }, res, next) => {
    if (url && isRootPath.test(url)) {
      res.statusCode = 200;
      res.setHeader("Content-Type", "text/html");
      res.write(html);
      res.end();
    } else {
      next();
    }
  });
  router.use(`/index.html`, (req, res) => {
    res.statusCode = 200;
    res.setHeader("Content-Type", "text/html");
    res.write(html);
    res.end();
  });
  return {
    bail,
    stats: {
      toJson: /* @__PURE__ */ __name(() => ({}), "toJson")
    },
    totalTime: process.hrtime(startTime)
  };
}, "starterGeneratorFn");
var builder = /* @__PURE__ */ __name(async function* builderGeneratorFn({ startTime, options }) {
  if (!options.outputDir) {
    throw new Error("outputDir is required");
  }
  logger.info("=> Building manager..");
  const {
    config,
    customHead,
    favicon,
    features,
    instance,
    refs,
    template,
    title,
    logLevel,
    docsOptions,
    tagsOptions
  } = await getData(options);
  yield;
  const addonsDir = config.outdir;
  const coreDirTarget = join(options.outputDir, `sb-manager`);
  compilation = await instance({
    ...config,
    minify: true
  });
  yield;
  const managerFiles = cp(CORE_DIR_ORIGIN, coreDirTarget, {
    filter: /* @__PURE__ */ __name((src) => {
      const { ext } = parse(src);
      if (ext) {
        return ext === ".js";
      }
      return true;
    }, "filter"),
    recursive: true
  });
  const { cssFiles, jsFiles } = await readOrderedFiles(addonsDir, compilation?.outputFiles);
  const globals = await buildFrameworkGlobalsFromOptions(options);
  yield;
  const html = await renderHTML(
    template,
    title,
    favicon,
    customHead,
    cssFiles,
    jsFiles,
    features,
    refs,
    logLevel,
    docsOptions,
    tagsOptions,
    options,
    globals
  );
  await Promise.all([writeFile3(join(options.outputDir, "index.html"), html), managerFiles]);
  logger.trace({ message: "=> Manager built", time: process.hrtime(startTime) });
  return {
    toJson: /* @__PURE__ */ __name(() => ({}), "toJson")
  };
}, "builderGeneratorFn");
var bail = /* @__PURE__ */ __name(async () => {
  if (asyncIterator) {
    try {
      await asyncIterator.throw(new Error());
    } catch (e) {
    }
  }
}, "bail");
var start = /* @__PURE__ */ __name(async (options) => {
  asyncIterator = starter(options);
  let result;
  do {
    result = await asyncIterator.next();
  } while (!result.done);
  return result.value;
}, "start");
var build = /* @__PURE__ */ __name(async (options) => {
  asyncIterator = builder(options);
  let result;
  do {
    result = await asyncIterator.next();
  } while (!result.done);
  return result.value;
}, "build");
var corePresets = [];
var overridePresets = [];
export {
  BROWSER_TARGETS,
  NODE_TARGET,
  bail,
  build,
  corePresets,
  executor,
  getConfig,
  overridePresets,
  start
};
