import CJS_COMPAT_NODE_URL_fkaa0x0zihe from 'node:url';
import CJS_COMPAT_NODE_PATH_fkaa0x0zihe from 'node:path';
import CJS_COMPAT_NODE_MODULE_fkaa0x0zihe from "node:module";

var __filename = CJS_COMPAT_NODE_URL_fkaa0x0zihe.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_fkaa0x0zihe.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_fkaa0x0zihe.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  BROWSER_TARGETS,
  NODE_TARGET,
  SUPPORTED_FEATURES
} from "./chunk-WAIN5JNB.js";
import {
  require_build
} from "./chunk-DNQSVAYP.js";
import {
  resolveModulePath,
  resolvePackageDir
} from "./chunk-IZCZHPXK.js";
import {
  join,
  parse
} from "./chunk-QUBI53SI.js";
import {
  slash
} from "./chunk-CLXX6SQC.js";
import {
  __commonJS,
  __esm,
  __export,
  __require,
  __toCommonJS,
  __toESM
} from "./chunk-4ILNNMLG.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;
  }
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
  var t = {};
  for (var p in s) 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++)
      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--) (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;
  }
  for (var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value", target = !descriptorIn && ctor ? contextIn.static ? ctor : ctor.prototype : null, descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}), _, done = !1, 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");
      (_ = accept(result.get)) && (descriptor.get = _), (_ = accept(result.set)) && (descriptor.set = _), (_ = accept(result.init)) && initializers.unshift(_);
    } else (_ = accept(result)) && (kind === "field" ? initializers.unshift(_) : descriptor[key] = _);
  }
  target && Object.defineProperty(target, contextIn.name, descriptor), done = !0;
}
function __runInitializers(thisArg, initializers, value) {
  for (var useValue = arguments.length > 2, 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) {
  return typeof name == "symbol" && (name = name.description ? "[".concat(name.description, "]") : ""), Object.defineProperty(f, "name", { configurable: !0, 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);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator.throw(value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
}
function __generator(thisArg, body) {
  var _ = { label: 0, sent: function() {
    if (t[0] & 1) throw t[1];
    return t[1];
  }, 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]);
    };
  }
  function step(op) {
    if (f) throw new TypeError("Generator is already executing.");
    for (; 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;
      switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
        case 0:
        case 1:
          t = op;
          break;
        case 4:
          return _.label++, { value: op[1], done: !1 };
        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;
          }
          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: !0 };
  }
}
function __exportStar(m, o) {
  for (var p in m) 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: function() {
      return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
    }
  };
  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 {
    for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; ) ar.push(r.value);
  } catch (error) {
    e = { error };
  } finally {
    try {
      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++)
    (ar || !(i in from)) && (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);
    };
  }
  function verb(n, f) {
    g[n] && (i[n] = function(v) {
      return new Promise(function(a, b) {
        q.push([n, v, a, b]) > 1 || resume(n, v);
      });
    }, f && (i[n] = f(i[n])));
  }
  function resume(n, v) {
    try {
      step(g[n](v));
    } catch (e) {
      settle(q[0][3], e);
    }
  }
  function step(r) {
    r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
  }
  function fulfill(value) {
    resume("next", value);
  }
  function reject(value) {
    resume("throw", value);
  }
  function settle(f, v) {
    f(v), q.shift(), q.length && resume(q[0][0], q[0][1]);
  }
}
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: !1 } : f ? f(v) : v;
    } : f;
  }
}
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);
      });
    };
  }
  function settle(resolve, reject, d, v) {
    Promise.resolve(v).then(function(v2) {
      resolve({ value: v2, done: d });
    }, reject);
  }
}
function __makeTemplateObject(cooked, raw) {
  return Object.defineProperty ? Object.defineProperty(cooked, "raw", { value: raw }) : cooked.raw = raw, 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++) k[i] !== "default" && __createBinding(result, mod, k[i]);
  return __setModuleDefault(result, mod), 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) {
    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], async && (inner = dispose);
    }
    if (typeof dispose != "function") throw new TypeError("Object not disposable.");
    inner && (dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    }), env.stack.push({ value, dispose, async });
  } else async && env.stack.push({ async: !0 });
  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 = !0;
  }
  var r, s = 0;
  function next() {
    for (; 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) {
            return fail(e), 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;
  }
  return next();
}
function __rewriteRelativeImportExtension(path, preserveJsx) {
  return typeof path == "string" && /^\.\.?\//.test(path) ? 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";
  }) : path;
}
var extendStatics, __assign, __createBinding, __setModuleDefault, ownKeys, _SuppressedError, tslib_es6_default, init_tslib_es6 = __esm({
  "../node_modules/tslib/tslib.es6.mjs"() {
    extendStatics = function(d, b) {
      return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
        d2.__proto__ = b2;
      } || function(d2, b2) {
        for (var p in b2) Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
      }, extendStatics(d, b);
    };
    __assign = function() {
      return __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
          s = arguments[i];
          for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]);
        }
        return t;
      }, __assign.apply(this, arguments);
    };
    __createBinding = Object.create ? (function(o, m, k, k2) {
      k2 === void 0 && (k2 = k);
      var desc = Object.getOwnPropertyDescriptor(m, k);
      (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) && (desc = { enumerable: !0, get: function() {
        return m[k];
      } }), Object.defineProperty(o, k2, desc);
    }) : (function(o, m, k, k2) {
      k2 === void 0 && (k2 = k), o[k2] = m[k];
    });
    __setModuleDefault = Object.create ? (function(o, v) {
      Object.defineProperty(o, "default", { enumerable: !0, value: v });
    }) : function(o, v) {
      o.default = v;
    }, ownKeys = function(o) {
      return ownKeys = Object.getOwnPropertyNames || function(o2) {
        var ar = [];
        for (var k in o2) Object.prototype.hasOwnProperty.call(o2, k) && (ar[ar.length] = k);
        return ar;
      }, ownKeys(o);
    };
    _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;
    };
    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: !0 });
    exports.pnpPlugin = void 0;
    var tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports)), fs = tslib_1.__importStar(__require("fs")), path_1 = tslib_1.__importDefault(__require("path")), matchAll = /()/, defaultExtensions = [".tsx", ".ts", ".jsx", ".mjs", ".cjs", ".js", ".css", ".json"];
    function parseExternals(externals) {
      return externals.map((external) => {
        let wildcardIdx = external.indexOf("*");
        return wildcardIdx !== -1 ? { prefix: external.slice(0, wildcardIdx), suffix: external.slice(wildcardIdx + 1) } : external;
      });
    }
    function isExternal(path, externals) {
      for (let 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 !0;
        } else if (path === external || !external.startsWith("/") && !external.startsWith("./") && !external.startsWith("../") && external !== "." && external !== ".." && path.startsWith(`${external}/`))
          return !0;
      return !1;
    }
    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)
      };
    }
    async function defaultOnResolve(args, { resolvedPath, error, watchFiles }) {
      let problems = error ? [{ text: error.message }] : [], mergeWith;
      switch (args.kind) {
        case "require-call":
        case "require-resolve":
        case "dynamic-import":
          mergeWith = { warnings: problems };
          break;
        default:
          mergeWith = { errors: problems };
          break;
      }
      return resolvedPath !== null ? { namespace: "pnp", path: resolvedPath, watchFiles } : { external: !0, ...mergeWith, watchFiles };
    }
    function pnpPlugin2({ baseDir = process.cwd(), extensions = defaultExtensions, filter = matchAll, onResolve = defaultOnResolve, onLoad = defaultOnLoad } = {}) {
      return {
        name: "@yarnpkg/esbuild-plugin-pnp",
        setup(build2) {
          var _a, _b;
          let { findPnpApi } = __require("module");
          if (typeof findPnpApi > "u")
            return;
          let externals = parseExternals((_a = build2.initialOptions.external) !== null && _a !== void 0 ? _a : []), platform = (_b = build2.initialOptions.platform) !== null && _b !== void 0 ? _b : "browser", isPlatformNode = platform === "node", conditionsDefault = new Set(build2.initialOptions.conditions);
          conditionsDefault.add("default"), (platform === "browser" || platform === "node") && conditionsDefault.add(platform);
          let conditionsImport = new Set(conditionsDefault);
          conditionsImport.add("import");
          let conditionsRequire = new Set(conditionsDefault);
          conditionsRequire.add("require"), build2.onResolve({ filter }, (args) => {
            var _a2, _b2;
            if (isExternal(args.path, externals))
              return { external: !0 };
            let conditions = conditionsDefault;
            args.kind === "dynamic-import" || args.kind === "import-statement" ? conditions = conditionsImport : (args.kind === "require-call" || args.kind === "require-resolve") && (conditions = conditionsRequire);
            let effectiveImporter = args.resolveDir ? `${args.resolveDir}/` : args.importer ? args.importer : `${baseDir}/`, pnpApi = findPnpApi(effectiveImporter);
            if (!pnpApi)
              return;
            let path = null, error;
            try {
              path = pnpApi.resolveRequest(args.path, effectiveImporter, {
                conditions,
                considerBuiltins: isPlatformNode,
                extensions
              });
            } catch (e) {
              error = e;
            }
            let watchFiles = [pnpApi.resolveRequest("pnpapi", null)];
            if (path) {
              let locator = pnpApi.findPackageLocator(path);
              if (locator) {
                let info = pnpApi.getPackageInformation(locator);
                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 });
          }), build2.onLoad !== null && build2.onLoad({ filter }, onLoad);
        }
      };
    }
    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, hasOwnProperty = Object.prototype.hasOwnProperty, hasOwn = function(obj, key) {
      return hasOwnProperty.apply(obj, [key]);
    };
    exports.escapeRegExpChars = function(string) {
      return string ? String(string).replace(regExpChars, "\\$&") : "";
    };
    var _ENCODE_HTML_RULES = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&#34;",
      "'": "&#39;"
    }, _MATCH_HTML = /[&<>'"]/g;
    function encode_char(c) {
      return _ENCODE_HTML_RULES[c] || c;
    }
    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 == null ? "" : String(markup).replace(_MATCH_HTML, encode_char);
    };
    function escapeXMLToString() {
      return Function.prototype.toString.call(this) + `;
` + escapeFuncStr;
    }
    try {
      typeof Object.defineProperty == "function" ? Object.defineProperty(exports.escapeXML, "toString", { value: escapeXMLToString }) : exports.escapeXML.toString = escapeXMLToString;
    } catch {
      console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)");
    }
    exports.shallowCopy = function(to, from) {
      if (from = from || {}, to != null)
        for (var p in from)
          hasOwn(from, p) && (p === "__proto__" || p === "constructor" || (to[p] = from[p]));
      return to;
    };
    exports.shallowCopyFromList = function(to, from, list) {
      if (list = list || [], from = from || {}, to != null)
        for (var i = 0; i < list.length; i++) {
          var p = list[i];
          if (typeof from[p] < "u") {
            if (!hasOwn(from, p) || p === "__proto__" || p === "constructor")
              continue;
            to[p] = from[p];
          }
        }
      return to;
    };
    exports.cache = {
      _data: {},
      set: function(key, val) {
        this._data[key] = val;
      },
      get: function(key) {
        return this._data[key];
      },
      remove: function(key) {
        delete this._data[key];
      },
      reset: function() {
        this._data = {};
      }
    };
    exports.hyphenToCamel = function(str) {
      return str.replace(/-[a-z]/g, function(match) {
        return match[1].toUpperCase();
      });
    };
    exports.createNullProtoObjWherePossible = (function() {
      return typeof Object.create == "function" ? function() {
        return /* @__PURE__ */ Object.create(null);
      } : { __proto__: null } instanceof Object ? function() {
        return {};
      } : function() {
        return { __proto__: null };
      };
    })();
    exports.hasOwnOnlyObject = function(obj) {
      var o = exports.createNullProtoObjWherePossible();
      for (var p in obj)
        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"), path = __require("path"), utils = require_utils(), scopeOptionWarned = !1, _VERSION_STRING = require_package().version, _DEFAULT_OPEN_DELIMITER = "<", _DEFAULT_CLOSE_DELIMITER = ">", _DEFAULT_DELIMITER = "%", _DEFAULT_LOCALS_NAME = "locals", _NAME = "ejs", _REGEX_STRING = "(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)", _OPTS_PASSABLE_WITH_DATA = [
      "delimiter",
      "scope",
      "context",
      "debug",
      "compileDebug",
      "client",
      "_with",
      "rmWhitespace",
      "strict",
      "filename",
      "async"
    ], _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat("cache"), _BOM = /^\uFEFF/, _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, extname = path.extname, resolve = path.resolve, includePath = resolve(isDir ? filename : dirname3(filename), name), ext = extname(name);
      return ext || (includePath += ".ejs"), includePath;
    };
    function resolvePaths(name, paths) {
      var filePath;
      if (paths.some(function(v) {
        return filePath = exports.resolveInclude(name, v, !0), fs.existsSync(filePath);
      }))
        return filePath;
    }
    function getIncludePath(path2, options) {
      var includePath, filePath, views = options.views, match = /^[A-Za-z]+:\\|^\//.exec(path2);
      if (match && match.length)
        path2 = path2.replace(/^\/*/, ""), Array.isArray(options.root) ? includePath = resolvePaths(path2, options.root) : includePath = exports.resolveInclude(path2, options.root || "/", !0);
      else if (options.filename && (filePath = exports.resolveInclude(path2, options.filename), fs.existsSync(filePath) && (includePath = filePath)), !includePath && Array.isArray(views) && (includePath = resolvePaths(path2, views)), !includePath && typeof options.includer != "function")
        throw new Error('Could not find the include file "' + options.escapeFunction(path2) + '"');
      return includePath;
    }
    function handleCache(options, template) {
      var func, filename = options.filename, hasTemplate = arguments.length > 1;
      if (options.cache) {
        if (!filename)
          throw new Error("cache option requires a filename");
        if (func = exports.cache.get(filename), func)
          return func;
        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, "");
      }
      return func = exports.compile(template, options), options.cache && exports.cache.set(filename, func), func;
    }
    function tryHandleCache(options, data, cb) {
      var result;
      if (cb) {
        try {
          result = handleCache(options)(data);
        } catch (err) {
          return cb(err);
        }
        cb(null, result);
      } else {
        if (typeof exports.promiseImpl == "function")
          return new exports.promiseImpl(function(resolve, reject) {
            try {
              result = handleCache(options)(data), resolve(result);
            } catch (err) {
              reject(err);
            }
          });
        throw new Error("Please provide a callback function");
      }
    }
    function fileLoader(filePath) {
      return exports.fileLoader(filePath);
    }
    function includeFile(path2, options) {
      var opts = utils.shallowCopy(utils.createNullProtoObjWherePossible(), options);
      if (opts.filename = getIncludePath(path2, opts), typeof options.includer == "function") {
        var includerResult = options.includer(path2, opts.filename);
        if (includerResult && (includerResult.filename && (opts.filename = includerResult.filename), includerResult.template))
          return handleCache(opts, includerResult.template);
      }
      return handleCache(opts);
    }
    function rethrow(err, str, flnm, lineno, esc) {
      var lines = str.split(`
`), start2 = Math.max(lineno - 3, 0), end = Math.min(lines.length, lineno + 3), filename = esc(flnm), context = lines.slice(start2, end).map(function(line, i) {
        var curr = i + start2 + 1;
        return (curr == lineno ? " >> " : "    ") + curr + "| " + line;
      }).join(`
`);
      throw err.path = filename, err.message = (filename || "ejs") + ":" + lineno + `
` + context + `

` + err.message, err;
    }
    function stripSemi(str) {
      return str.replace(/;(\s*$)/, "$1");
    }
    exports.compile = function(template, opts) {
      var templ;
      return opts && opts.scope && (scopeOptionWarned || (console.warn("`scope` option is deprecated and will be removed in EJS 3"), scopeOptionWarned = !0), opts.context || (opts.context = opts.scope), delete opts.scope), templ = new Template(template, opts), templ.compile();
    };
    exports.render = function(template, d, o) {
      var data = d || utils.createNullProtoObjWherePossible(), opts = o || utils.createNullProtoObjWherePossible();
      return arguments.length == 2 && utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA), handleCache(opts, template)(data);
    };
    exports.renderFile = function() {
      var args = Array.prototype.slice.call(arguments), filename = args.shift(), cb, opts = { filename }, data, viewOpts;
      return typeof arguments[arguments.length - 1] == "function" && (cb = args.pop()), args.length ? (data = args.shift(), args.length ? utils.shallowCopy(opts, args.pop()) : (data.settings && (data.settings.views && (opts.views = data.settings.views), data.settings["view cache"] && (opts.cache = !0), viewOpts = data.settings["view options"], viewOpts && utils.shallowCopy(opts, viewOpts)), utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS)), opts.filename = filename) : data = utils.createNullProtoObjWherePossible(), tryHandleCache(opts, data, cb);
    };
    exports.Template = Template;
    exports.clearCache = function() {
      exports.cache.reset();
    };
    function Template(text, optsParam) {
      var opts = utils.hasOwnOnlyObject(optsParam), options = utils.createNullProtoObjWherePossible();
      this.templateText = text, this.mode = null, this.truncate = !1, this.currentLine = 1, this.source = "", options.client = opts.client || !1, options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML, options.compileDebug = opts.compileDebug !== !1, 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 || !1, options.context = opts.context, options.cache = opts.cache || !1, 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 < "u" ? !!opts.legacyInclude : !0, options.strict ? options._with = !1 : options._with = typeof opts._with < "u" ? opts._with : !0, this.opts = options, this.regex = this.createRegex();
    }
    Template.modes = {
      EVAL: "eval",
      ESCAPED: "escaped",
      RAW: "raw",
      COMMENT: "comment",
      LITERAL: "literal"
    };
    Template.prototype = {
      createRegex: function() {
        var str = _REGEX_STRING, delim = utils.escapeRegExpChars(this.opts.delimiter), open = utils.escapeRegExpChars(this.opts.openDelimiter), close = utils.escapeRegExpChars(this.opts.closeDelimiter);
        return str = str.replace(/%/g, delim).replace(/</g, open).replace(/>/g, close), new RegExp(str);
      },
      compile: function() {
        var src, fn, opts = this.opts, prepended = "", appended = "", escapeFn = opts.escapeFunction, ctor, sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : "undefined";
        if (!this.source) {
          if (this.generateSource(), prepended += `  var __output = "";
  function __append(s) { if (s !== undefined && s !== null) __output += s }
`, opts.outputFunctionName) {
            if (!_JS_IDENTIFIER.test(opts.outputFunctionName))
              throw new Error("outputFunctionName is not a valid JS identifier.");
            prepended += "  var " + opts.outputFunctionName + ` = __append;
`;
          }
          if (opts.localsName && !_JS_IDENTIFIER.test(opts.localsName))
            throw new Error("localsName is not a valid JS identifier.");
          if (opts.destructuredLocals && opts.destructuredLocals.length) {
            for (var destructuring = "  var __locals = (" + opts.localsName + ` || {}),
`, 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.");
              i > 0 && (destructuring += `,
  `), destructuring += name + " = __locals." + name;
            }
            prepended += destructuring + `;
`;
          }
          opts._with !== !1 && (prepended += "  with (" + opts.localsName + ` || {}) {
`, appended += `  }
`), appended += `  return __output;
`, this.source = prepended + this.source + appended;
        }
        opts.compileDebug ? src = `var __line = 1
  , __lines = ` + JSON.stringify(this.templateText) + `
  , __filename = ` + sanitizedFilename + `;
try {
` + this.source + `} catch (e) {
  rethrow(e, __lines, __filename, __line, escapeFn);
}
` : src = this.source, opts.client && (src = "escapeFn = escapeFn || " + escapeFn.toString() + `;
` + src, opts.compileDebug && (src = "rethrow = rethrow || " + rethrow.toString() + `;
` + src)), opts.strict && (src = `"use strict";
` + src), opts.debug && console.log(src), opts.compileDebug && opts.filename && (src = src + `
//# sourceURL=` + sanitizedFilename + `
`);
        try {
          if (opts.async)
            try {
              ctor = new Function("return (async function(){}).constructor;")();
            } catch (e) {
              throw e instanceof SyntaxError ? new Error("This environment does not support async/await") : e;
            }
          else
            ctor = Function;
          fn = new ctor(opts.localsName + ", escapeFn, include, rethrow", src);
        } catch (e) {
          throw e instanceof SyntaxError && (opts.filename && (e.message += " in " + opts.filename), e.message += ` while compiling ejs

`, e.message += `If the above error is not helpful, you may want to try EJS-Lint:
`, e.message += "https://github.com/RyanZim/EJS-Lint", opts.async || (e.message += `
`, e.message += "Or, if you meant to create an async function, pass `async: true` as an option.")), e;
        }
        var returnedFn = opts.client ? fn : function(data) {
          var include = function(path2, includeData) {
            var d = utils.shallowCopy(utils.createNullProtoObjWherePossible(), data);
            return includeData && (d = utils.shallowCopy(d, includeData)), includeFile(path2, opts)(d);
          };
          return fn.apply(
            opts.context,
            [data || utils.createNullProtoObjWherePossible(), escapeFn, include, rethrow]
          );
        };
        if (opts.filename && typeof Object.defineProperty == "function") {
          var filename = opts.filename, basename2 = path.basename(filename, path.extname(filename));
          try {
            Object.defineProperty(returnedFn, "name", {
              value: basename2,
              writable: !1,
              enumerable: !1,
              configurable: !0
            });
          } catch {
          }
        }
        return returnedFn;
      },
      generateSource: function() {
        var opts = this.opts;
        opts.rmWhitespace && (this.templateText = this.templateText.replace(/[\r\n]+/g, `
`).replace(/^\s+|\s+$/gm, "")), this.templateText = this.templateText.replace(/[ \t]*<%_/gm, "<%_").replace(/_%>[ \t]*/gm, "_%>");
        var self = this, matches = this.parseTemplateText(), d = this.opts.delimiter, o = this.opts.openDelimiter, c = this.opts.closeDelimiter;
        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], !(closing == d + c || closing == "-" + d + c || closing == "_" + d + c)))
            throw new Error('Could not find matching close tag for "' + line + '".');
          self.scanLine(line);
        });
      },
      parseTemplateText: function() {
        for (var str = this.templateText, pat = this.regex, result = pat.exec(str), arr = [], firstPos; result; )
          firstPos = result.index, 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);
        return str && arr.push(str), arr;
      },
      _addOutput: function(line) {
        if (this.truncate && (line = line.replace(/^(?:\r\n|\r|\n)/, ""), this.truncate = !1), !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 + `")
`;
      },
      scanLine: function(line) {
        var self = this, d = this.opts.delimiter, o = this.opts.openDelimiter, c = this.opts.closeDelimiter, newLineCount = 0;
        switch (newLineCount = line.split(`
`).length - 1, 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) + `")
`;
            break;
          case d + d + c:
            this.mode = Template.modes.LITERAL, this.source += '    ; __append("' + line.replace(d + d + c, d + c) + `")
`;
            break;
          case d + c:
          case "-" + d + c:
          case "_" + d + c:
            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:
                  line.lastIndexOf("//") > line.lastIndexOf(`
`) && (line += `
`);
              }
              switch (this.mode) {
                // Just executing code
                case Template.modes.EVAL:
                  this.source += "    ; " + line + `
`;
                  break;
                // Exec, esc, and output
                case Template.modes.ESCAPED:
                  this.source += "    ; __append(escapeFn(" + stripSemi(line) + `))
`;
                  break;
                // Exec and output
                case Template.modes.RAW:
                  this.source += "    ; __append(" + stripSemi(line) + `)
`;
                  break;
                case Template.modes.COMMENT:
                  break;
                // Literal <%% mode, append as raw output
                case Template.modes.LITERAL:
                  this._addOutput(line);
                  break;
              }
            } else
              this._addOutput(line);
        }
        self.opts.compileDebug && newLineCount && (this.currentLine += newLineCount, this.source += "    ; __line = " + this.currentLine + `
`);
      }
    };
    exports.escapeXML = utils.escapeXML;
    exports.__express = exports.renderFile;
    exports.VERSION = _VERSION_STRING;
    exports.name = _NAME;
    typeof window < "u" && (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 = (value) => {
  let {
    type = "esm",
    varName,
    namedExports = null,
    defaultExport = !0
  } = typeof value == "string" ? { varName: value } : value;
  return { type, varName, namedExports, defaultExport };
};

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

// ../node_modules/@fal-works/esbuild-plugin-global-externals/lib/with-reg-exp.js
var PLUGIN_NAME = "global-externals", globalExternalsWithRegExp = (globals) => {
  let { 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) => {
        let modulePath = args.path, moduleInfo = normalizeModuleInfo(getModuleInfo(modulePath));
        return { contents: createContents(moduleInfo) };
      });
    }
  };
};

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

// 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_checklistStore",
    "internal_fullStatusStore",
    "internal_fullTestProviderStore",
    "internal_universalChecklistStore",
    "internal_universalStatusStore",
    "internal_universalTestProviderStore",
    "isMacLike",
    "isShortcutTaken",
    "keyToSymbol",
    "merge",
    "mockChannel",
    "optionOrAltSymbol",
    "shortcutMatchesShortcut",
    "shortcutToAriaKeyshortcuts",
    "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",
    "AbstractToolbar",
    "ActionBar",
    "AddonPanel",
    "Badge",
    "Bar",
    "Blockquote",
    "Button",
    "Card",
    "ClipboardCode",
    "Code",
    "Collapsible",
    "DL",
    "Div",
    "DocumentWrapper",
    "EmptyTabContent",
    "ErrorFormatter",
    "FlexBar",
    "Form",
    "H1",
    "H2",
    "H3",
    "H4",
    "H5",
    "H6",
    "HR",
    "IconButton",
    "Img",
    "LI",
    "Link",
    "ListItem",
    "Listbox",
    "Loader",
    "Modal",
    "ModalDecorator",
    "OL",
    "P",
    "Placeholder",
    "Popover",
    "PopoverProvider",
    "Pre",
    "ProgressSpinner",
    "ResetWrapper",
    "ScrollArea",
    "Select",
    "Separator",
    "Spaced",
    "Span",
    "StatelessTab",
    "StatelessTabList",
    "StatelessTabPanel",
    "StatelessTabsView",
    "StorybookIcon",
    "StorybookLogo",
    "SyntaxHighlighter",
    "TT",
    "TabBar",
    "TabButton",
    "TabList",
    "TabPanel",
    "TabWrapper",
    "Table",
    "Tabs",
    "TabsState",
    "TabsView",
    "ToggleButton",
    "Toolbar",
    "Tooltip",
    "TooltipLinkList",
    "TooltipMessage",
    "TooltipNote",
    "TooltipProvider",
    "UL",
    "WithTooltip",
    "WithTooltipPure",
    "Zoom",
    "codeCommon",
    "components",
    "convertToReactAriaPlacement",
    "createCopyToClipboardFunction",
    "getStoryHref",
    "interleaveSeparators",
    "nameSpaceClassNames",
    "resetComponents",
    "useTabsState",
    "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__"
}, 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"
], globalsModuleInfoMap = globalPackages.reduce(
  (acc, key) => (acc[key] = {
    type: "esm",
    varName: globalsNameReferenceMap[key],
    namedExports: exports_default[key],
    defaultExport: !0
  }, duplicatedKeys.includes(key) && (acc[key.replace("storybook", "storybook/internal")] = {
    type: "esm",
    varName: globalsNameReferenceMap[key],
    namedExports: exports_default[key],
    defaultExport: !0
  }), 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 = (template) => join(resolvePackageDir("storybook"), "assets/server", template), readTemplate = async (template) => {
  let path = getTemplatePath(template);
  return readFile(path, { encoding: "utf8" });
};
var renderHTML = async (template, title, favicon, customHead, cssFiles, jsFiles, features, refs, logLevel, docsOptions, tagsOptions, { versionCheck, previewUrl, configType, ignorePreview }, globals) => {
  let titleRef = await title, templateRef = await template, 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
  });
};

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

// 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) {
  let files = await Promise.all(
    outputFiles?.map(async (file) => {
      let { location, url } = sanitizePath(file, addonsDir);
      if (!existsSync(location)) {
        let directory = dirname(location);
        await mkdir(directory, { recursive: !0 });
      }
      return await writeFile(location, file.contents), url;
    }) || []
  ), jsFiles = files.filter((file) => file.endsWith(".js"));
  return { cssFiles: files.filter((file) => file.endsWith(".css")), jsFiles };
}
function sanitizePath(file, addonsDir) {
  let filePath = relative(addonsDir, file.path), location = normalize(join2(addonsDir, filePath)), url = `./sb-addons/${slash(filePath).split("/").map(encodeURIComponent).join("/")}`;
  return { location, url };
}

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

// 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 = (path) => path.replaceAll(".", "").replaceAll("@", "").replaceAll(sep2, "-").replaceAll("/", "-").replaceAll(new RegExp(/^(-)+/g), ""), sanitizeFinal = (path) => {
  let sections = path.split(/-?node_modules-?/);
  return sections[sections.length - 1].replaceAll("storybook-addon-", "").replaceAll("dist-", "");
};
async function wrapManagerEntries(entrypoints, uniqueId) {
  return Promise.all(
    entrypoints.map(async (entry, i) => {
      let { name, dir } = parse2(entry), cacheLocation = resolvePathInStorybookCache("sb-manager", uniqueId);
      if (!cacheLocation)
        throw new Error("Could not create/find cache directory");
      let base = relative2(process.cwd(), dir), location = join3(
        cacheLocation,
        sanitizeFinal(join3(`${sanitizeBase(base)}-${i}`, `${sanitizeBase(name)}-bundle.js`))
      );
      if (!existsSync2(location)) {
        let directory = dirname2(location);
        await mkdir2(directory, { recursive: !0 });
      }
      return await writeFile2(location, `import '${slash(entry).replaceAll(/'/g, "\\'")}';`), location;
    })
  );
}

// src/builder-manager/index.ts
var CORE_DIR_ORIGIN = join(resolvePackageDir("storybook"), "dist/manager"), isRootPath = /^\/($|\?)/, compilation, asyncIterator, getConfig = async (options) => {
  let [managerEntriesFromPresets, envs] = await Promise.all([
    options.presets.apply("managerEntries", []),
    options.presets.apply("env")
  ]), tsconfigPath = getTemplatePath("addon.tsconfig.json"), configDirManagerEntry;
  try {
    configDirManagerEntry = resolveModulePath("./manager", {
      from: options.configDir,
      extensions: [".js", ".mjs", ".jsx", ".ts", ".mts", ".tsx"]
    });
  } catch {
  }
  let entryPoints = configDirManagerEntry ? [...managerEntriesFromPresets, configDirManagerEntry] : managerEntriesFromPresets;
  return {
    entryPoints: await wrapManagerEntries(entryPoints, options.cacheKey),
    outdir: join(options.outputDir || "./", "sb-addons"),
    format: "iife",
    write: !1,
    ignoreAnnotations: !0,
    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: !0,
    minify: !1,
    minifyWhitespace: !1,
    minifyIdentifiers: !1,
    minifySyntax: !0,
    metafile: !1,
    // turn this on to assist with debugging the bundling of managerEntries
    // treeShaking: true,
    sourcemap: !1,
    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: "{}"
    }
  };
}, executor = {
  get: async () => {
    let { build: build2 } = await import("esbuild");
    return build2;
  }
}, starter = async function* ({
  startTime,
  options,
  router
}) {
  options.quiet || logger.info("=> Starting manager..");
  let {
    config,
    favicon,
    customHead,
    features,
    instance,
    refs,
    template,
    title,
    logLevel,
    docsOptions,
    tagsOptions
  } = await getData(options);
  yield;
  let addonsDir = config.outdir;
  await rm(addonsDir, { recursive: !0, force: !0 }), yield, compilation = await instance({
    ...config
  }), yield, router.use(
    "/sb-addons",
    (0, import_sirv.default)(addonsDir, {
      maxAge: 3e5,
      dev: !0,
      immutable: !0
    })
  ), router.use(
    "/sb-manager",
    (0, import_sirv.default)(CORE_DIR_ORIGIN, {
      maxAge: 3e5,
      dev: !0,
      immutable: !0
    })
  );
  let { cssFiles, jsFiles } = await readOrderedFiles(addonsDir, compilation?.outputFiles);
  compilation.metafile && options.outputDir && await writeFile3(
    join(options.outputDir, "metafile.json"),
    JSON.stringify(compilation.metafile, null, 2)
  );
  let globals = await buildFrameworkGlobalsFromOptions(options);
  yield;
  let html = await renderHTML(
    template,
    title,
    favicon,
    customHead,
    cssFiles,
    jsFiles,
    features,
    refs,
    logLevel,
    docsOptions,
    tagsOptions,
    options,
    globals
  );
  return yield, router.use("/", ({ url }, res, next) => {
    url && isRootPath.test(url) ? (res.statusCode = 200, res.setHeader("Content-Type", "text/html"), res.write(html), res.end()) : next();
  }), router.use("/index.html", (req, res) => {
    res.statusCode = 200, res.setHeader("Content-Type", "text/html"), res.write(html), res.end();
  }), {
    bail,
    stats: {
      toJson: () => ({})
    },
    totalTime: process.hrtime(startTime)
  };
}, builder = async function* ({ startTime, options }) {
  if (!options.outputDir)
    throw new Error("outputDir is required");
  logger.info("=> Building manager..");
  let {
    config,
    customHead,
    favicon,
    features,
    instance,
    refs,
    template,
    title,
    logLevel,
    docsOptions,
    tagsOptions
  } = await getData(options);
  yield;
  let addonsDir = config.outdir, coreDirTarget = join(options.outputDir, "sb-manager");
  compilation = await instance({
    ...config,
    minify: !0
  }), yield;
  let managerFiles = cp(CORE_DIR_ORIGIN, coreDirTarget, {
    filter: (src) => {
      let { ext } = parse(src);
      return ext ? ext === ".js" : !0;
    },
    recursive: !0
  }), { cssFiles, jsFiles } = await readOrderedFiles(addonsDir, compilation?.outputFiles), globals = await buildFrameworkGlobalsFromOptions(options);
  yield;
  let html = await renderHTML(
    template,
    title,
    favicon,
    customHead,
    cssFiles,
    jsFiles,
    features,
    refs,
    logLevel,
    docsOptions,
    tagsOptions,
    options,
    globals
  );
  return await Promise.all([writeFile3(join(options.outputDir, "index.html"), html), managerFiles]), logger.trace({ message: "=> Manager built", time: process.hrtime(startTime) }), {
    toJson: () => ({})
  };
}, bail = async () => {
  if (asyncIterator)
    try {
      await asyncIterator.throw(new Error());
    } catch {
    }
}, start = async (options) => {
  asyncIterator = starter(options);
  let result;
  do
    result = await asyncIterator.next();
  while (!result.done);
  return result.value;
}, build = async (options) => {
  asyncIterator = builder(options);
  let result;
  do
    result = await asyncIterator.next();
  while (!result.done);
  return result.value;
}, corePresets = [], overridePresets = [];
export {
  BROWSER_TARGETS,
  NODE_TARGET,
  bail,
  build,
  corePresets,
  executor,
  getConfig,
  overridePresets,
  start
};
