import CJS_COMPAT_NODE_URL_6jofinbrhmg from 'node:url';
import CJS_COMPAT_NODE_PATH_6jofinbrhmg from 'node:path';
import CJS_COMPAT_NODE_MODULE_6jofinbrhmg from "node:module";

var __filename = CJS_COMPAT_NODE_URL_6jofinbrhmg.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_6jofinbrhmg.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_6jofinbrhmg.createRequire(import.meta.url);

// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  getVirtualModules
} from "./_node-chunks/chunk-XEEHUBKG.js";
import {
  __commonJS,
  __require,
  __toESM
} from "./_node-chunks/chunk-3GAYTYW2.js";

// ../../../node_modules/pretty-hrtime/index.js
var require_pretty_hrtime = __commonJS({
  "../../../node_modules/pretty-hrtime/index.js"(exports, module) {
    "use strict";
    var minimalDesc = ["h", "min", "s", "ms", "\u03BCs", "ns"], verboseDesc = ["hour", "minute", "second", "millisecond", "microsecond", "nanosecond"], convert = [3600, 60, 1, 1e6, 1e3, 1];
    module.exports = function(source, opts) {
      var verbose, precise, i, spot, sourceAtStep, valAtStep, decimals, strAtStep, results, totalSeconds;
      if (verbose = !1, precise = !1, opts && (verbose = opts.verbose || !1, precise = opts.precise || !1), !Array.isArray(source) || source.length !== 2 || typeof source[0] != "number" || typeof source[1] != "number")
        return "";
      for (source[1] < 0 && (totalSeconds = source[0] + source[1] / 1e9, source[0] = parseInt(totalSeconds), source[1] = parseFloat((totalSeconds % 1).toPrecision(9)) * 1e9), results = "", i = 0; i < 6 && (spot = i < 3 ? 0 : 1, sourceAtStep = source[spot], i !== 3 && i !== 0 && (sourceAtStep = sourceAtStep % convert[i - 1]), i === 2 && (sourceAtStep += source[1] / 1e9), valAtStep = sourceAtStep / convert[i], !(valAtStep >= 1 && (verbose && (valAtStep = Math.floor(valAtStep)), precise ? strAtStep = valAtStep.toString() : (decimals = valAtStep >= 10 ? 0 : 2, strAtStep = valAtStep.toFixed(decimals)), strAtStep.indexOf(".") > -1 && strAtStep[strAtStep.length - 1] === "0" && (strAtStep = strAtStep.replace(/\.?0+$/, "")), results && (results += " "), results += strAtStep, verbose ? (results += " " + verboseDesc[i], strAtStep !== "1" && (results += "s")) : results += " " + minimalDesc[i], !verbose))); i++)
        ;
      return results;
    };
  }
});

// ../../../node_modules/totalist/sync/index.js
var require_sync = __commonJS({
  "../../../node_modules/totalist/sync/index.js"(exports) {
    var { join: join2, resolve: resolve2 } = __require("path"), { readdirSync, statSync } = __require("fs");
    function totalist(dir, callback, pre = "") {
      dir = resolve2(".", dir);
      let arr = readdirSync(dir), i = 0, abs, stats;
      for (; i < arr.length; i++)
        abs = join2(dir, arr[i]), stats = statSync(abs), stats.isDirectory() ? totalist(abs, callback, join2(pre, arr[i])) : callback(join2(pre, arr[i]), abs, stats);
    }
    exports.totalist = totalist;
  }
});

// ../../../node_modules/@polka/url/build.js
var require_build = __commonJS({
  "../../../node_modules/@polka/url/build.js"(exports) {
    var qs = __require("querystring");
    function parse2(req) {
      let raw = req.url;
      if (raw == null) return;
      let prev = req._parsedUrl;
      if (prev && prev.raw === raw) return prev;
      let pathname = raw, search = "", query, hash;
      if (raw.length > 1) {
        let idx = raw.indexOf("#", 1);
        idx !== -1 && (hash = raw.substring(idx), pathname = raw.substring(0, idx)), idx = pathname.indexOf("?", 1), idx !== -1 && (search = pathname.substring(idx), pathname = pathname.substring(0, idx), search.length > 1 && (query = qs.parse(search.substring(1))));
      }
      return req._parsedUrl = { pathname, search, query, hash, raw };
    }
    exports.parse = parse2;
  }
});

// ../../../node_modules/mrmime/index.js
var require_mrmime = __commonJS({
  "../../../node_modules/mrmime/index.js"(exports) {
    var mimes = {
      "3g2": "video/3gpp2",
      "3gp": "video/3gpp",
      "3gpp": "video/3gpp",
      "3mf": "model/3mf",
      aac: "audio/aac",
      ac: "application/pkix-attr-cert",
      adp: "audio/adpcm",
      adts: "audio/aac",
      ai: "application/postscript",
      aml: "application/automationml-aml+xml",
      amlx: "application/automationml-amlx+zip",
      amr: "audio/amr",
      apng: "image/apng",
      appcache: "text/cache-manifest",
      appinstaller: "application/appinstaller",
      appx: "application/appx",
      appxbundle: "application/appxbundle",
      asc: "application/pgp-keys",
      atom: "application/atom+xml",
      atomcat: "application/atomcat+xml",
      atomdeleted: "application/atomdeleted+xml",
      atomsvc: "application/atomsvc+xml",
      au: "audio/basic",
      avci: "image/avci",
      avcs: "image/avcs",
      avif: "image/avif",
      aw: "application/applixware",
      bdoc: "application/bdoc",
      bin: "application/octet-stream",
      bmp: "image/bmp",
      bpk: "application/octet-stream",
      btf: "image/prs.btif",
      btif: "image/prs.btif",
      buffer: "application/octet-stream",
      ccxml: "application/ccxml+xml",
      cdfx: "application/cdfx+xml",
      cdmia: "application/cdmi-capability",
      cdmic: "application/cdmi-container",
      cdmid: "application/cdmi-domain",
      cdmio: "application/cdmi-object",
      cdmiq: "application/cdmi-queue",
      cer: "application/pkix-cert",
      cgm: "image/cgm",
      cjs: "application/node",
      class: "application/java-vm",
      coffee: "text/coffeescript",
      conf: "text/plain",
      cpl: "application/cpl+xml",
      cpt: "application/mac-compactpro",
      crl: "application/pkix-crl",
      css: "text/css",
      csv: "text/csv",
      cu: "application/cu-seeme",
      cwl: "application/cwl",
      cww: "application/prs.cww",
      davmount: "application/davmount+xml",
      dbk: "application/docbook+xml",
      deb: "application/octet-stream",
      def: "text/plain",
      deploy: "application/octet-stream",
      dib: "image/bmp",
      "disposition-notification": "message/disposition-notification",
      dist: "application/octet-stream",
      distz: "application/octet-stream",
      dll: "application/octet-stream",
      dmg: "application/octet-stream",
      dms: "application/octet-stream",
      doc: "application/msword",
      dot: "application/msword",
      dpx: "image/dpx",
      drle: "image/dicom-rle",
      dsc: "text/prs.lines.tag",
      dssc: "application/dssc+der",
      dtd: "application/xml-dtd",
      dump: "application/octet-stream",
      dwd: "application/atsc-dwd+xml",
      ear: "application/java-archive",
      ecma: "application/ecmascript",
      elc: "application/octet-stream",
      emf: "image/emf",
      eml: "message/rfc822",
      emma: "application/emma+xml",
      emotionml: "application/emotionml+xml",
      eps: "application/postscript",
      epub: "application/epub+zip",
      exe: "application/octet-stream",
      exi: "application/exi",
      exp: "application/express",
      exr: "image/aces",
      ez: "application/andrew-inset",
      fdf: "application/fdf",
      fdt: "application/fdt+xml",
      fits: "image/fits",
      g3: "image/g3fax",
      gbr: "application/rpki-ghostbusters",
      geojson: "application/geo+json",
      gif: "image/gif",
      glb: "model/gltf-binary",
      gltf: "model/gltf+json",
      gml: "application/gml+xml",
      gpx: "application/gpx+xml",
      gram: "application/srgs",
      grxml: "application/srgs+xml",
      gxf: "application/gxf",
      gz: "application/gzip",
      h261: "video/h261",
      h263: "video/h263",
      h264: "video/h264",
      heic: "image/heic",
      heics: "image/heic-sequence",
      heif: "image/heif",
      heifs: "image/heif-sequence",
      hej2: "image/hej2k",
      held: "application/atsc-held+xml",
      hjson: "application/hjson",
      hlp: "application/winhlp",
      hqx: "application/mac-binhex40",
      hsj2: "image/hsj2",
      htm: "text/html",
      html: "text/html",
      ics: "text/calendar",
      ief: "image/ief",
      ifb: "text/calendar",
      iges: "model/iges",
      igs: "model/iges",
      img: "application/octet-stream",
      in: "text/plain",
      ini: "text/plain",
      ink: "application/inkml+xml",
      inkml: "application/inkml+xml",
      ipfix: "application/ipfix",
      iso: "application/octet-stream",
      its: "application/its+xml",
      jade: "text/jade",
      jar: "application/java-archive",
      jhc: "image/jphc",
      jls: "image/jls",
      jp2: "image/jp2",
      jpe: "image/jpeg",
      jpeg: "image/jpeg",
      jpf: "image/jpx",
      jpg: "image/jpeg",
      jpg2: "image/jp2",
      jpgm: "image/jpm",
      jpgv: "video/jpeg",
      jph: "image/jph",
      jpm: "image/jpm",
      jpx: "image/jpx",
      js: "text/javascript",
      json: "application/json",
      json5: "application/json5",
      jsonld: "application/ld+json",
      jsonml: "application/jsonml+json",
      jsx: "text/jsx",
      jt: "model/jt",
      jxl: "image/jxl",
      jxr: "image/jxr",
      jxra: "image/jxra",
      jxrs: "image/jxrs",
      jxs: "image/jxs",
      jxsc: "image/jxsc",
      jxsi: "image/jxsi",
      jxss: "image/jxss",
      kar: "audio/midi",
      ktx: "image/ktx",
      ktx2: "image/ktx2",
      less: "text/less",
      lgr: "application/lgr+xml",
      list: "text/plain",
      litcoffee: "text/coffeescript",
      log: "text/plain",
      lostxml: "application/lost+xml",
      lrf: "application/octet-stream",
      m1v: "video/mpeg",
      m21: "application/mp21",
      m2a: "audio/mpeg",
      m2t: "video/mp2t",
      m2ts: "video/mp2t",
      m2v: "video/mpeg",
      m3a: "audio/mpeg",
      m4a: "audio/mp4",
      m4p: "application/mp4",
      m4s: "video/iso.segment",
      ma: "application/mathematica",
      mads: "application/mads+xml",
      maei: "application/mmt-aei+xml",
      man: "text/troff",
      manifest: "text/cache-manifest",
      map: "application/json",
      mar: "application/octet-stream",
      markdown: "text/markdown",
      mathml: "application/mathml+xml",
      mb: "application/mathematica",
      mbox: "application/mbox",
      md: "text/markdown",
      mdx: "text/mdx",
      me: "text/troff",
      mesh: "model/mesh",
      meta4: "application/metalink4+xml",
      metalink: "application/metalink+xml",
      mets: "application/mets+xml",
      mft: "application/rpki-manifest",
      mid: "audio/midi",
      midi: "audio/midi",
      mime: "message/rfc822",
      mj2: "video/mj2",
      mjp2: "video/mj2",
      mjs: "text/javascript",
      mml: "text/mathml",
      mods: "application/mods+xml",
      mov: "video/quicktime",
      mp2: "audio/mpeg",
      mp21: "application/mp21",
      mp2a: "audio/mpeg",
      mp3: "audio/mpeg",
      mp4: "video/mp4",
      mp4a: "audio/mp4",
      mp4s: "application/mp4",
      mp4v: "video/mp4",
      mpd: "application/dash+xml",
      mpe: "video/mpeg",
      mpeg: "video/mpeg",
      mpf: "application/media-policy-dataset+xml",
      mpg: "video/mpeg",
      mpg4: "video/mp4",
      mpga: "audio/mpeg",
      mpp: "application/dash-patch+xml",
      mrc: "application/marc",
      mrcx: "application/marcxml+xml",
      ms: "text/troff",
      mscml: "application/mediaservercontrol+xml",
      msh: "model/mesh",
      msi: "application/octet-stream",
      msix: "application/msix",
      msixbundle: "application/msixbundle",
      msm: "application/octet-stream",
      msp: "application/octet-stream",
      mtl: "model/mtl",
      mts: "video/mp2t",
      musd: "application/mmt-usd+xml",
      mxf: "application/mxf",
      mxmf: "audio/mobile-xmf",
      mxml: "application/xv+xml",
      n3: "text/n3",
      nb: "application/mathematica",
      nq: "application/n-quads",
      nt: "application/n-triples",
      obj: "model/obj",
      oda: "application/oda",
      oga: "audio/ogg",
      ogg: "audio/ogg",
      ogv: "video/ogg",
      ogx: "application/ogg",
      omdoc: "application/omdoc+xml",
      onepkg: "application/onenote",
      onetmp: "application/onenote",
      onetoc: "application/onenote",
      onetoc2: "application/onenote",
      opf: "application/oebps-package+xml",
      opus: "audio/ogg",
      otf: "font/otf",
      owl: "application/rdf+xml",
      oxps: "application/oxps",
      p10: "application/pkcs10",
      p7c: "application/pkcs7-mime",
      p7m: "application/pkcs7-mime",
      p7s: "application/pkcs7-signature",
      p8: "application/pkcs8",
      pdf: "application/pdf",
      pfr: "application/font-tdpfr",
      pgp: "application/pgp-encrypted",
      pkg: "application/octet-stream",
      pki: "application/pkixcmp",
      pkipath: "application/pkix-pkipath",
      pls: "application/pls+xml",
      png: "image/png",
      prc: "model/prc",
      prf: "application/pics-rules",
      provx: "application/provenance+xml",
      ps: "application/postscript",
      pskcxml: "application/pskc+xml",
      pti: "image/prs.pti",
      qt: "video/quicktime",
      raml: "application/raml+yaml",
      rapd: "application/route-apd+xml",
      rdf: "application/rdf+xml",
      relo: "application/p2p-overlay+xml",
      rif: "application/reginfo+xml",
      rl: "application/resource-lists+xml",
      rld: "application/resource-lists-diff+xml",
      rmi: "audio/midi",
      rnc: "application/relax-ng-compact-syntax",
      rng: "application/xml",
      roa: "application/rpki-roa",
      roff: "text/troff",
      rq: "application/sparql-query",
      rs: "application/rls-services+xml",
      rsat: "application/atsc-rsat+xml",
      rsd: "application/rsd+xml",
      rsheet: "application/urc-ressheet+xml",
      rss: "application/rss+xml",
      rtf: "text/rtf",
      rtx: "text/richtext",
      rusd: "application/route-usd+xml",
      s3m: "audio/s3m",
      sbml: "application/sbml+xml",
      scq: "application/scvp-cv-request",
      scs: "application/scvp-cv-response",
      sdp: "application/sdp",
      senmlx: "application/senml+xml",
      sensmlx: "application/sensml+xml",
      ser: "application/java-serialized-object",
      setpay: "application/set-payment-initiation",
      setreg: "application/set-registration-initiation",
      sgi: "image/sgi",
      sgm: "text/sgml",
      sgml: "text/sgml",
      shex: "text/shex",
      shf: "application/shf+xml",
      shtml: "text/html",
      sieve: "application/sieve",
      sig: "application/pgp-signature",
      sil: "audio/silk",
      silo: "model/mesh",
      siv: "application/sieve",
      slim: "text/slim",
      slm: "text/slim",
      sls: "application/route-s-tsid+xml",
      smi: "application/smil+xml",
      smil: "application/smil+xml",
      snd: "audio/basic",
      so: "application/octet-stream",
      spdx: "text/spdx",
      spp: "application/scvp-vp-response",
      spq: "application/scvp-vp-request",
      spx: "audio/ogg",
      sql: "application/sql",
      sru: "application/sru+xml",
      srx: "application/sparql-results+xml",
      ssdl: "application/ssdl+xml",
      ssml: "application/ssml+xml",
      stk: "application/hyperstudio",
      stl: "model/stl",
      stpx: "model/step+xml",
      stpxz: "model/step-xml+zip",
      stpz: "model/step+zip",
      styl: "text/stylus",
      stylus: "text/stylus",
      svg: "image/svg+xml",
      svgz: "image/svg+xml",
      swidtag: "application/swid+xml",
      t: "text/troff",
      t38: "image/t38",
      td: "application/urc-targetdesc+xml",
      tei: "application/tei+xml",
      teicorpus: "application/tei+xml",
      text: "text/plain",
      tfi: "application/thraud+xml",
      tfx: "image/tiff-fx",
      tif: "image/tiff",
      tiff: "image/tiff",
      toml: "application/toml",
      tr: "text/troff",
      trig: "application/trig",
      ts: "video/mp2t",
      tsd: "application/timestamped-data",
      tsv: "text/tab-separated-values",
      ttc: "font/collection",
      ttf: "font/ttf",
      ttl: "text/turtle",
      ttml: "application/ttml+xml",
      txt: "text/plain",
      u3d: "model/u3d",
      u8dsn: "message/global-delivery-status",
      u8hdr: "message/global-headers",
      u8mdn: "message/global-disposition-notification",
      u8msg: "message/global",
      ubj: "application/ubjson",
      uri: "text/uri-list",
      uris: "text/uri-list",
      urls: "text/uri-list",
      vcard: "text/vcard",
      vrml: "model/vrml",
      vtt: "text/vtt",
      vxml: "application/voicexml+xml",
      war: "application/java-archive",
      wasm: "application/wasm",
      wav: "audio/wav",
      weba: "audio/webm",
      webm: "video/webm",
      webmanifest: "application/manifest+json",
      webp: "image/webp",
      wgsl: "text/wgsl",
      wgt: "application/widget",
      wif: "application/watcherinfo+xml",
      wmf: "image/wmf",
      woff: "font/woff",
      woff2: "font/woff2",
      wrl: "model/vrml",
      wsdl: "application/wsdl+xml",
      wspolicy: "application/wspolicy+xml",
      x3d: "model/x3d+xml",
      x3db: "model/x3d+fastinfoset",
      x3dbz: "model/x3d+binary",
      x3dv: "model/x3d-vrml",
      x3dvz: "model/x3d+vrml",
      x3dz: "model/x3d+xml",
      xaml: "application/xaml+xml",
      xav: "application/xcap-att+xml",
      xca: "application/xcap-caps+xml",
      xcs: "application/calendar+xml",
      xdf: "application/xcap-diff+xml",
      xdssc: "application/dssc+xml",
      xel: "application/xcap-el+xml",
      xenc: "application/xenc+xml",
      xer: "application/patch-ops-error+xml",
      xfdf: "application/xfdf",
      xht: "application/xhtml+xml",
      xhtml: "application/xhtml+xml",
      xhvml: "application/xv+xml",
      xlf: "application/xliff+xml",
      xm: "audio/xm",
      xml: "text/xml",
      xns: "application/xcap-ns+xml",
      xop: "application/xop+xml",
      xpl: "application/xproc+xml",
      xsd: "application/xml",
      xsf: "application/prs.xsf+xml",
      xsl: "application/xml",
      xslt: "application/xml",
      xspf: "application/xspf+xml",
      xvm: "application/xv+xml",
      xvml: "application/xv+xml",
      yaml: "text/yaml",
      yang: "application/yang",
      yin: "application/yin+xml",
      yml: "text/yaml",
      zip: "application/zip"
    };
    function lookup(extn) {
      let tmp = ("" + extn).trim().toLowerCase(), idx = tmp.lastIndexOf(".");
      return mimes[~idx ? tmp.substring(++idx) : tmp];
    }
    exports.mimes = mimes;
    exports.lookup = lookup;
  }
});

// ../../../node_modules/sirv/build.js
var require_build2 = __commonJS({
  "../../../node_modules/sirv/build.js"(exports, module) {
    var fs = __require("fs"), { join: join2, normalize: normalize2, resolve: resolve2 } = __require("path"), { totalist } = require_sync(), { parse: parse2 } = require_build(), { lookup } = require_mrmime(), noop = () => {
    };
    function isMatch(uri, arr) {
      for (let i = 0; i < arr.length; i++)
        if (arr[i].test(uri)) return !0;
    }
    function toAssume(uri, extns) {
      let i = 0, x, len = uri.length - 1;
      uri.charCodeAt(len) === 47 && (uri = uri.substring(0, len));
      let arr = [], tmp = `${uri}/index`;
      for (; i < extns.length; i++)
        x = extns[i] ? `.${extns[i]}` : "", uri && arr.push(uri + x), arr.push(tmp + x);
      return arr;
    }
    function viaCache(cache, uri, extns) {
      let i = 0, data, arr = toAssume(uri, extns);
      for (; i < arr.length; i++)
        if (data = cache[arr[i]]) return data;
    }
    function viaLocal(dir, isEtag, uri, extns) {
      let i = 0, arr = toAssume(uri, extns), abs, stats, name, headers;
      for (; i < arr.length; i++)
        if (abs = normalize2(join2(dir, name = arr[i])), abs.startsWith(dir) && fs.existsSync(abs)) {
          if (stats = fs.statSync(abs), stats.isDirectory()) continue;
          return headers = toHeaders(name, stats, isEtag), headers["Cache-Control"] = isEtag ? "no-cache" : "no-store", { abs, stats, headers };
        }
    }
    function is404(req, res) {
      return res.statusCode = 404, res.end();
    }
    function send(req, res, file, stats, headers) {
      let code = 200, tmp, opts = {};
      headers = { ...headers };
      for (let key in headers)
        tmp = res.getHeader(key), tmp && (headers[key] = tmp);
      if ((tmp = res.getHeader("content-type")) && (headers["Content-Type"] = tmp), req.headers.range) {
        code = 206;
        let [x, y] = req.headers.range.replace("bytes=", "").split("-"), end = opts.end = parseInt(y, 10) || stats.size - 1, start2 = opts.start = parseInt(x, 10) || 0;
        if (end >= stats.size && (end = stats.size - 1), start2 >= stats.size)
          return res.setHeader("Content-Range", `bytes */${stats.size}`), res.statusCode = 416, res.end();
        headers["Content-Range"] = `bytes ${start2}-${end}/${stats.size}`, headers["Content-Length"] = end - start2 + 1, headers["Accept-Ranges"] = "bytes";
      }
      res.writeHead(code, headers), fs.createReadStream(file, opts).pipe(res);
    }
    var ENCODING = {
      ".br": "br",
      ".gz": "gzip"
    };
    function toHeaders(name, stats, isEtag) {
      let enc = ENCODING[name.slice(-3)], ctype = lookup(name.slice(0, enc && -3)) || "";
      ctype === "text/html" && (ctype += ";charset=utf-8");
      let headers = {
        "Content-Length": stats.size,
        "Content-Type": ctype,
        "Last-Modified": stats.mtime.toUTCString()
      };
      return enc && (headers["Content-Encoding"] = enc), isEtag && (headers.ETag = `W/"${stats.size}-${stats.mtime.getTime()}"`), headers;
    }
    module.exports = function(dir, opts = {}) {
      dir = resolve2(dir || ".");
      let isNotFound = opts.onNoMatch || is404, setHeaders = opts.setHeaders || noop, extensions = opts.extensions || ["html", "htm"], gzips = opts.gzip && extensions.map((x) => `${x}.gz`).concat("gz"), brots = opts.brotli && extensions.map((x) => `${x}.br`).concat("br"), FILES = {}, fallback = "/", isEtag = !!opts.etag, isSPA = !!opts.single;
      if (typeof opts.single == "string") {
        let idx = opts.single.lastIndexOf(".");
        fallback += ~idx ? opts.single.substring(0, idx) : opts.single;
      }
      let ignores = [];
      opts.ignores !== !1 && (ignores.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/), opts.dotfiles ? ignores.push(/\/\.\w/) : ignores.push(/\/\.well-known/), [].concat(opts.ignores || []).forEach((x) => {
        ignores.push(new RegExp(x, "i"));
      }));
      let cc = opts.maxAge != null && `public,max-age=${opts.maxAge}`;
      cc && opts.immutable ? cc += ",immutable" : cc && opts.maxAge === 0 && (cc += ",must-revalidate"), opts.dev || totalist(dir, (name, abs, stats) => {
        if (!/\.well-known[\\+\/]/.test(name)) {
          if (!opts.dotfiles && /(^\.|[\\+|\/+]\.)/.test(name)) return;
        }
        let headers = toHeaders(name, stats, isEtag);
        cc && (headers["Cache-Control"] = cc), FILES["/" + name.normalize().replace(/\\+/g, "/")] = { abs, stats, headers };
      });
      let lookup2 = opts.dev ? viaLocal.bind(0, dir, isEtag) : viaCache.bind(0, FILES);
      return function(req, res, next) {
        let extns = [""], pathname = parse2(req).pathname, val = req.headers["accept-encoding"] || "";
        if (gzips && val.includes("gzip") && extns.unshift(...gzips), brots && /(br|brotli)/i.test(val) && extns.unshift(...brots), extns.push(...extensions), pathname.indexOf("%") !== -1)
          try {
            pathname = decodeURI(pathname);
          } catch {
          }
        let data = lookup2(pathname, extns) || isSPA && !isMatch(pathname, ignores) && lookup2(fallback, extns);
        if (!data) return next ? next() : isNotFound(req, res);
        if (isEtag && req.headers["if-none-match"] === data.headers.ETag)
          return res.writeHead(304), res.end();
        (gzips || brots) && res.setHeader("Vary", "Accept-Encoding"), setHeaders(res, pathname, data.stats), send(req, res, data.abs, data.stats, data.headers);
      };
    };
  }
});

// src/index.ts
import { cp } from "node:fs/promises";
import { fileURLToPath } from "node:url";
import { PREVIEW_BUILDER_PROGRESS } from "storybook/internal/core-events";
import { logger } from "storybook/internal/node-logger";
import {
  WebpackCompilationError,
  WebpackInvocationError,
  WebpackMissingStatsError
} from "storybook/internal/server-errors";
import { checkWebpackVersion } from "@storybook/core-webpack";

// ../../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
  return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
var normalize = function(path2) {
  if (path2.length === 0)
    return ".";
  path2 = normalizeWindowsPath(path2);
  let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
  return path2 = normalizeString(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2);
}, join = function(...arguments_) {
  if (arguments_.length === 0)
    return ".";
  let joined;
  for (let argument of arguments_)
    argument && argument.length > 0 && (joined === void 0 ? joined = argument : joined += `/${argument}`);
  return joined === void 0 ? "." : normalize(joined.replace(/\/\/+/g, "/"));
};
function normalizeString(path2, allowAboveRoot) {
  let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
  for (let index = 0; index <= path2.length; ++index) {
    if (index < path2.length)
      char = path2[index];
    else {
      if (char === "/")
        break;
      char = "/";
    }
    if (char === "/") {
      if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
        if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
          if (res.length > 2) {
            let lastSlashIndex = res.lastIndexOf("/");
            lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
            continue;
          } else if (res.length > 0) {
            res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
            continue;
          }
        }
        allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
      } else
        res.length > 0 ? res += `/${path2.slice(lastSlash + 1, index)}` : res = path2.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
      lastSlash = index, dots = 0;
    } else char === "." && dots !== -1 ? ++dots : dots = -1;
  }
  return res;
}
var isAbsolute = function(p) {
  return _IS_ABSOLUTE_RE.test(p);
};
var _EXTNAME_RE = /.(\.[^./]+)$/, extname = function(p) {
  let match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
  return match && match[1] || "";
};
var dirname = function(p) {
  let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
  return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
};
var basename = function(p, extension) {
  let lastSegment = normalizeWindowsPath(p).split("/").pop();
  return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
}, parse = function(p) {
  let root = normalizeWindowsPath(p).split("/").shift() || "/", base = basename(p), extension = extname(base);
  return {
    root,
    dir: dirname(p),
    base,
    ext: extension,
    name: base.slice(0, base.length - extension.length)
  };
};

// src/index.ts
var import_pretty_hrtime = __toESM(require_pretty_hrtime(), 1), import_sirv = __toESM(require_build2(), 1);
import webpackModule from "webpack";
import webpackDevMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
var { DefinePlugin, IgnorePlugin, ProgressPlugin } = webpackModule, WebpackDefinePlugin = DefinePlugin, WebpackIgnorePlugin = IgnorePlugin, printDuration = (startTime) => (0, import_pretty_hrtime.default)(process.hrtime(startTime)).replace(" ms", " milliseconds").replace(" s", " seconds").replace(" min", " minutes"), corePath = dirname(fileURLToPath(import.meta.resolve("storybook/package.json"))), compilation, reject, executor = {
  get: async (options) => {
    let version = await options.presets.apply("webpackVersion") || "5", webpackInstance = (await options.presets.apply("webpackInstance"))?.default || webpackModule;
    return checkWebpackVersion({ version }, "5", "builder-webpack5"), webpackInstance;
  }
}, getConfig = async (options) => {
  let { presets } = options, typescriptOptions = await presets.apply("typescript", {}, options), frameworkOptions = await presets.apply("frameworkOptions");
  return presets.apply(
    "webpack",
    {},
    {
      ...options,
      typescriptOptions,
      frameworkOptions
    }
  );
}, asyncIterator, bail = async () => {
  if (asyncIterator)
    try {
      await asyncIterator.throw(new Error());
    } catch {
    }
  return reject && reject(), new Promise((res, rej) => {
    if (process && compilation)
      try {
        compilation.close(() => res()), logger.warn("Force closed preview build");
      } catch {
        logger.warn("Unable to close preview build!"), res();
      }
    else
      res();
  });
}, starter = async function* ({
  startTime,
  options,
  router,
  channel
}) {
  let webpackInstance = await executor.get(options);
  yield;
  let config = await getConfig(options);
  if (config.stats === "none" || config.stats === "summary")
    throw new WebpackMissingStatsError();
  yield;
  let compiler = webpackInstance(config);
  if (!compiler)
    throw new WebpackInvocationError({
      // eslint-disable-next-line local-rules/no-uncategorized-errors
      error: new Error("Missing Webpack compiler at runtime!")
    });
  yield;
  let modulesCount = await options.cache?.get("modulesCount", 1e3), totalModules, value = 0;
  new ProgressPlugin({
    handler: (newValue, message, arg3) => {
      value = Math.max(newValue, value);
      let progress = { value, message: message.charAt(0).toUpperCase() + message.slice(1) };
      if (message === "building") {
        let counts = arg3 && arg3.match(/entries (\d+)\/(\d+)/) || [], complete = parseInt(counts[1], 10), total = parseInt(counts[2], 10);
        !Number.isNaN(complete) && !Number.isNaN(total) && (progress.modules = { complete, total }, totalModules = total);
      }
      value === 1 && (options.cache && options.cache.set("modulesCount", totalModules), progress.message || (progress.message = `Completed in ${printDuration(startTime)}.`)), channel.emit(PREVIEW_BUILDER_PROGRESS, progress);
    },
    modulesCount
  }).apply(compiler);
  let middlewareOptions = {
    publicPath: config.output?.publicPath,
    writeToDisk: !0,
    stats: "errors-only"
  };
  compilation = webpackDevMiddleware(compiler, middlewareOptions);
  let previewResolvedDir = join(corePath, "dist/preview");
  router.use(
    "/sb-preview",
    (0, import_sirv.default)(previewResolvedDir, {
      maxAge: 3e5,
      dev: !0,
      immutable: !0
    })
  ), router.use(compilation), router.use(webpackHotMiddleware(compiler, { log: !1 }));
  let stats = await new Promise((res, rej) => {
    compilation?.waitUntilValid(res), reject = rej;
  });
  if (yield, !stats)
    throw new WebpackMissingStatsError();
  let { warnings, errors } = getWebpackStats({ config, stats });
  if (warnings.length > 0 && warnings?.forEach((e) => logger.warn(e.message)), errors.length > 0)
    throw new WebpackCompilationError({ errors });
  return {
    bail,
    stats,
    totalTime: process.hrtime(startTime)
  };
};
function getWebpackStats({ config, stats }) {
  let statsOptions = typeof config.stats == "string" ? config.stats : {
    ...config.stats,
    warnings: !0,
    errors: !0
  }, { warnings = [], errors = [] } = stats?.toJson(statsOptions) || {};
  return {
    warnings,
    errors
  };
}
var builder = async function* ({ startTime, options }) {
  let webpackInstance = await executor.get(options);
  yield;
  let config = await getConfig(options);
  if (config.stats === "none" || config.stats === "summary")
    throw new WebpackMissingStatsError();
  yield;
  let compiler = webpackInstance(config);
  if (!compiler)
    throw new WebpackInvocationError({
      // eslint-disable-next-line local-rules/no-uncategorized-errors
      error: new Error("Missing Webpack compiler at runtime!")
    });
  let webpackCompilation = new Promise((succeed, fail) => {
    compiler.run((error, stats) => {
      if (error) {
        compiler.close(() => fail(new WebpackInvocationError({ error })));
        return;
      }
      if (!stats)
        throw new WebpackMissingStatsError();
      let { warnings, errors } = getWebpackStats({ config, stats });
      if (warnings.length > 0 && warnings?.forEach((e) => logger.warn(e.message)), errors.length > 0) {
        errors.forEach((e) => logger.error(e.message)), compiler.close(() => fail(new WebpackCompilationError({ errors })));
        return;
      }
      compiler.close((closeErr) => closeErr ? fail(new WebpackInvocationError({ error: closeErr })) : succeed(stats));
    });
  }), previewResolvedDir = join(corePath, "dist/preview"), previewDirTarget = join(options.outputDir || "", "sb-preview"), previewFiles = cp(previewResolvedDir, previewDirTarget, {
    filter: (src) => {
      let { ext } = parse(src);
      return ext ? ext === ".js" : !0;
    },
    recursive: !0
  }), [webpackCompilationOutput] = await Promise.all([webpackCompilation, previewFiles]);
  return webpackCompilationOutput;
}, 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 = [
  import.meta.resolve("@storybook/builder-webpack5/presets/preview-preset")
], overridePresets = [
  import.meta.resolve("@storybook/builder-webpack5/presets/custom-webpack-preset")
];
export {
  WebpackDefinePlugin,
  WebpackIgnorePlugin,
  bail,
  build,
  corePresets,
  executor,
  getConfig,
  getVirtualModules,
  overridePresets,
  printDuration,
  start
};
