"use strict";
var We = Object.create;
var A = Object.defineProperty;
var Ge = Object.getOwnPropertyDescriptor;
var ze = Object.getOwnPropertyNames;
var Xe = Object.getPrototypeOf, Ke = Object.prototype.hasOwnProperty;
var f = (s, e) => A(s, "name", { value: e, configurable: !0 });
var Je = (s, e) => () => (e || s((e = { exports: {} }).exports, e), e.exports), Qe = (s, e) => {
  for (var t in e)
    A(s, t, { get: e[t], enumerable: !0 });
}, ce = (s, e, t, r) => {
  if (e && typeof e == "object" || typeof e == "function")
    for (let i of ze(e))
      !Ke.call(s, i) && i !== t && A(s, i, { get: () => e[i], enumerable: !(r = Ge(e, i)) || r.enumerable });
  return s;
};
var z = (s, e, t) => (t = s != null ? We(Xe(s)) : {}, ce(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  e || !s || !s.__esModule ? A(t, "default", { value: s, enumerable: !0 }) : t,
  s
)), He = (s) => ce(A({}, "__esModule", { value: !0 }), s);

// ../node_modules/ts-dedent/dist/index.js
var R = Je(($) => {
  "use strict";
  Object.defineProperty($, "__esModule", { value: !0 });
  $.dedent = void 0;
  function pe(s) {
    for (var e = [], t = 1; t < arguments.length; t++)
      e[t - 1] = arguments[t];
    var r = Array.from(typeof s == "string" ? [s] : s);
    r[r.length - 1] = r[r.length - 1].replace(/\r?\n([\t ]*)$/, "");
    var i = r.reduce(function(a, p) {
      var d = p.match(/\n([\t ]+|(?!\s).)/g);
      return d ? a.concat(d.map(function(g) {
        var x, E;
        return (E = (x = g.match(/[\t ]/g)) === null || x === void 0 ? void 0 : x.length) !== null && E !== void 0 ? E : 0;
      })) : a;
    }, []);
    if (i.length) {
      var o = new RegExp(`
[	 ]{` + Math.min.apply(Math, i) + "}", "g");
      r = r.map(function(a) {
        return a.replace(o, `
`);
      });
    }
    r[0] = r[0].replace(/^\r?\n/, "");
    var l = r[0];
    return e.forEach(function(a, p) {
      var d = l.match(/(?:^|\n)( *)$/), g = d ? d[1] : "", x = a;
      typeof a == "string" && a.includes(`
`) && (x = String(a).split(`
`).map(function(E, b) {
        return b === 0 ? E : "" + g + E;
      }).join(`
`)), l += x + r[p + 1];
    }), l;
  }
  f(pe, "dedent");
  $.dedent = pe;
  $.default = pe;
});

// src/csf-tools/index.ts
var dt = {};
Qe(dt, {
  BadMetaError: () => U,
  ConfigFile: () => Z,
  CsfFile: () => K,
  MixedFactoryError: () => M,
  MultipleMetaError: () => X,
  NoMetaError: () => L,
  babelParse: () => Ae.babelParse,
  babelParseFile: () => ye,
  enrichCsf: () => pt,
  enrichCsfMeta: () => we,
  enrichCsfStory: () => ve,
  extractDescription: () => oe,
  extractSource: () => Fe,
  formatConfig: () => Se,
  formatCsf: () => te,
  getStorySortParameter: () => ct,
  isCsfFactoryPreview: () => at,
  isModuleMock: () => xe,
  isValidPreviewPath: () => ge,
  loadConfig: () => je,
  loadCsf: () => Q,
  printConfig: () => Oe,
  printCsf: () => be,
  readConfig: () => nt,
  readCsf: () => it,
  vitestTransform: () => Ve,
  writeConfig: () => ot,
  writeCsf: () => st
});
module.exports = He(dt);

// src/csf-tools/CsfFile.ts
var J = require("node:fs/promises"), c = require("storybook/internal/babel"), I = require("storybook/internal/csf"), P = z(R(), 1);

// src/csf-tools/findVarInitialization.ts
var w = require("storybook/internal/babel");
var O = /* @__PURE__ */ f((s, e) => {
  let t = null, r = null;
  return e.body.find((i) => (w.types.isVariableDeclaration(i) ? r = i.declarations : w.types.isExportNamedDeclaration(i) && w.types.isVariableDeclaration(
  i.declaration) && (r = i.declaration.declarations), r && r.find((o) => w.types.isVariableDeclarator(o) && w.types.isIdentifier(o.id) && o.
  id.name === s ? (t = o.init, !0) : !1))), t;
}, "findVarInitialization");

// src/csf-tools/CsfFile.ts
var fe = console, Ye = /\/preview(.(js|jsx|mjs|ts|tsx))?$/, ge = /* @__PURE__ */ f((s) => Ye.test(s), "isValidPreviewPath");
function Ze(s) {
  if (c.types.isArrayExpression(s))
    return s.elements.map((e) => {
      if (c.types.isStringLiteral(e))
        return e.value;
      throw new Error(`Expected string literal: ${e}`);
    });
  if (c.types.isStringLiteral(s))
    return new RegExp(s.value);
  if (c.types.isRegExpLiteral(s))
    return new RegExp(s.pattern, s.flags);
  throw new Error(`Unknown include/exclude: ${s}`);
}
f(Ze, "parseIncludeExclude");
function de(s) {
  if (!c.types.isArrayExpression(s))
    throw new Error("CSF: Expected tags array");
  return s.elements.map((e) => {
    if (c.types.isStringLiteral(e))
      return e.value;
    throw new Error("CSF: Expected tag to be string literal");
  });
}
f(de, "parseTags");
var D = /* @__PURE__ */ f((s, e) => {
  let t = "";
  if (s.loc) {
    let { line: r, column: i } = s.loc?.start || {};
    t = `(line ${r}, col ${i})`;
  }
  return `${e || ""} ${t}`.trim();
}, "formatLocation"), xe = /* @__PURE__ */ f((s) => rt.test(s), "isModuleMock"), me = /* @__PURE__ */ f((s, e, t) => {
  let r = s;
  if (c.types.isCallExpression(s)) {
    let { callee: i, arguments: o } = s;
    if (c.types.isProgram(e) && c.types.isMemberExpression(i) && c.types.isIdentifier(i.object) && c.types.isIdentifier(i.property) && i.property.
    name === "bind" && (o.length === 0 || o.length === 1 && c.types.isObjectExpression(o[0]) && o[0].properties.length === 0)) {
      let l = i.object.name, a = O(l, e);
      a && (t._templates[l] = a, r = a);
    }
  }
  return c.types.isArrowFunctionExpression(r) || c.types.isFunctionDeclaration(r) ? r.params.length > 0 : !1;
}, "isArgsStory"), et = /* @__PURE__ */ f((s) => {
  if (c.types.isArrayExpression(s))
    return s.elements.map((e) => {
      if (c.types.isStringLiteral(e))
        return e.value;
      throw new Error(`Expected string literal named export: ${e}`);
    });
  throw new Error(`Expected array of string literals: ${s}`);
}, "parseExportsOrder"), ue = /* @__PURE__ */ f((s, e) => e.reduce(
  (t, r) => {
    let i = s[r];
    return i && (t[r] = i), t;
  },
  {}
), "sortExports"), tt = /* @__PURE__ */ f((s) => {
  if (c.types.isArrowFunctionExpression(s) || c.types.isFunctionDeclaration(s)) {
    let e = s.params;
    if (e.length >= 1) {
      let [t] = e;
      if (c.types.isObjectPattern(t))
        return !!t.properties.find((r) => {
          if (c.types.isObjectProperty(r) && c.types.isIdentifier(r.key))
            return r.key.name === "mount";
        });
    }
  }
  return !1;
}, "hasMount"), rt = /^[.\/#].*\.mock($|\.[^.]*$)/i, L = class extends Error {
  static {
    f(this, "NoMetaError");
  }
  constructor(e, t, r) {
    let i = "".trim();
    super(P.dedent`
      CSF: ${e} ${D(t, r)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, X = class extends Error {
  static {
    f(this, "MultipleMetaError");
  }
  constructor(e, t, r) {
    let i = `${e} ${D(t, r)}`.trim();
    super(P.dedent`
      CSF: ${e} ${D(t, r)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, M = class extends Error {
  static {
    f(this, "MixedFactoryError");
  }
  constructor(e, t, r) {
    let i = `${e} ${D(t, r)}`.trim();
    super(P.dedent`
      CSF: ${e} ${D(t, r)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, U = class extends Error {
  static {
    f(this, "BadMetaError");
  }
  constructor(e, t, r) {
    let i = "".trim();
    super(P.dedent`
      CSF: ${e} ${D(t, r)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, K = class {
  constructor(e, t, r) {
    this._stories = {};
    this._metaAnnotations = {};
    this._storyExports = {};
    this._storyPaths = {};
    this._storyStatements = {};
    this._storyAnnotations = {};
    this._templates = {};
    this._ast = e, this._file = r, this._options = t, this.imports = [];
  }
  static {
    f(this, "CsfFile");
  }
  _parseTitle(e) {
    let t = c.types.isIdentifier(e) ? O(e.name, this._ast.program) : e;
    if (c.types.isStringLiteral(t))
      return t.value;
    if (c.types.isTSSatisfiesExpression(t) && c.types.isStringLiteral(t.expression))
      return t.expression.value;
    throw new Error(P.dedent`
      CSF: unexpected dynamic title ${D(t, this._options.fileName)}

      More info: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#string-literal-titles
    `);
  }
  _parseMeta(e, t) {
    if (this._metaNode)
      throw new X("multiple meta objects", e, this._options.fileName);
    this._metaNode = e;
    let r = {};
    e.properties.forEach((i) => {
      if (c.types.isIdentifier(i.key)) {
        if (this._metaAnnotations[i.key.name] = i.value, i.key.name === "title")
          r.title = this._parseTitle(i.value);
        else if (["includeStories", "excludeStories"].includes(i.key.name))
          r[i.key.name] = Ze(i.value);
        else if (i.key.name === "component") {
          let o = i.value;
          if (c.types.isIdentifier(o)) {
            let a = o.name, p = t.body.find(
              (d) => c.types.isImportDeclaration(d) && d.specifiers.find((g) => g.local.name === a)
            );
            if (p) {
              let { source: d } = p;
              c.types.isStringLiteral(d) && (this._rawComponentPath = d.value);
            }
          }
          let { code: l } = c.recast.print(i.value, {});
          r.component = l;
        } else if (i.key.name === "tags") {
          let o = i.value;
          c.types.isIdentifier(o) && (o = O(o.name, this._ast.program)), r.tags = de(o);
        } else if (i.key.name === "id")
          if (c.types.isStringLiteral(i.value))
            r.id = i.value.value;
          else
            throw new Error(`Unexpected component id: ${i.value}`);
      }
    }), this._meta = r;
  }
  getStoryExport(e) {
    let t = this._storyExports[e];
    if (t = c.types.isVariableDeclarator(t) ? t.init : t, c.types.isCallExpression(t)) {
      let { callee: r, arguments: i } = t;
      if (c.types.isMemberExpression(r) && c.types.isIdentifier(r.object) && c.types.isIdentifier(r.property) && r.property.name === "bind" &&
      (i.length === 0 || i.length === 1 && c.types.isObjectExpression(i[0]) && i[0].properties.length === 0)) {
        let { name: o } = r.object;
        t = this._templates[o];
      }
    }
    return t;
  }
  parse() {
    let e = this;
    if ((0, c.traverse)(this._ast, {
      ExportDefaultDeclaration: {
        enter(r) {
          let { node: i, parent: o } = r, l = c.types.isIdentifier(i.declaration) && c.types.isProgram(o);
          if (e._options.transformInlineMeta && !l && c.types.isExpression(i.declaration)) {
            let d = r.scope.generateUidIdentifier("meta");
            e._metaVariableName = d.name;
            let g = [
              c.types.variableDeclaration("const", [c.types.variableDeclarator(d, i.declaration)]),
              c.types.exportDefaultDeclaration(d)
            ];
            g.forEach((x) => x.loc = r.node.loc), r.replaceWithMultiple(g);
            return;
          }
          let a, p;
          if (l) {
            let d = i.declaration.name;
            e._metaVariableName = d;
            let g = /* @__PURE__ */ f((x) => c.types.isIdentifier(x.id) && x.id.name === d, "isVariableDeclarator");
            e._metaStatement = e._ast.program.body.find(
              (x) => c.types.isVariableDeclaration(x) && x.declarations.find(g)
            ), p = (e?._metaStatement?.declarations || []).find(
              g
            )?.init;
          } else
            e._metaStatement = i, p = i.declaration;
          if (c.types.isObjectExpression(p) ? a = p : (
            // export default { ... } as Meta<...>
            (c.types.isTSAsExpression(p) || c.types.isTSSatisfiesExpression(p)) && c.types.isObjectExpression(p.expression) && (a = p.expression)
          ), a && c.types.isProgram(o) && e._parseMeta(a, o), e._metaStatement && !e._metaNode)
            throw new L(
              "default export must be an object",
              e._metaStatement,
              e._options.fileName
            );
          e._metaPath = r;
        }
      },
      ExportNamedDeclaration: {
        enter(r) {
          let { node: i, parent: o } = r, l;
          c.types.isVariableDeclaration(i.declaration) ? l = i.declaration.declarations.filter((a) => c.types.isVariableDeclarator(a)) : c.types.
          isFunctionDeclaration(i.declaration) && (l = [i.declaration]), l ? l.forEach((a) => {
            if (c.types.isIdentifier(a.id)) {
              let p = !1, { name: d } = a.id;
              if (d === "__namedExportsOrder" && c.types.isVariableDeclarator(a)) {
                e._namedExportsOrder = et(a.init);
                return;
              }
              e._storyExports[d] = a, e._storyPaths[d] = r, e._storyStatements[d] = i;
              let g = (0, I.storyNameFromExport)(d);
              e._storyAnnotations[d] ? fe.warn(
                `Unexpected annotations for "${d}" before story declaration`
              ) : e._storyAnnotations[d] = {};
              let x;
              if (c.types.isVariableDeclarator(a) ? x = c.types.isTSAsExpression(a.init) || c.types.isTSSatisfiesExpression(a.init) ? a.init.
              expression : a.init : x = a, c.types.isCallExpression(x) && c.types.isMemberExpression(x.callee) && c.types.isIdentifier(x.callee.
              property) && x.callee.property.name === "story" && (p = !0, x = x.arguments[0]), e._metaIsFactory && !p)
                throw new M(
                  "expected factory story",
                  x,
                  e._options.fileName
                );
              if (!e._metaIsFactory && p)
                throw e._metaNode ? new M(
                  "expected non-factory story",
                  x,
                  e._options.fileName
                ) : new U(
                  "meta() factory must be imported from .storybook/preview configuration",
                  x,
                  e._options.fileName
                );
              let E = {};
              c.types.isObjectExpression(x) ? (E.__isArgsStory = !0, x.properties.forEach((b) => {
                if (c.types.isIdentifier(b.key)) {
                  if (b.key.name === "render")
                    E.__isArgsStory = me(
                      b.value,
                      o,
                      e
                    );
                  else if (b.key.name === "name" && c.types.isStringLiteral(b.value))
                    g = b.value.value;
                  else if (b.key.name === "storyName" && c.types.isStringLiteral(b.value))
                    fe.warn(
                      `Unexpected usage of "storyName" in "${d}". Please use "name" instead.`
                    );
                  else if (b.key.name === "parameters" && c.types.isObjectExpression(b.value)) {
                    let h = b.value.properties.find(
                      (v) => c.types.isObjectProperty(v) && c.types.isIdentifier(v.key) && v.key.name === "__id"
                    );
                    h && (E.__id = h.value.value);
                  }
                  e._storyAnnotations[d][b.key.name] = b.value;
                }
              })) : E.__isArgsStory = me(x, o, e), e._stories[d] = {
                id: "FIXME",
                name: g,
                parameters: E,
                __stats: {
                  factory: p
                }
              };
            }
          }) : i.specifiers.length > 0 && i.specifiers.forEach((a) => {
            if (c.types.isExportSpecifier(a) && c.types.isIdentifier(a.exported)) {
              let { name: p } = a.exported, { name: d } = a.local, g = c.types.isProgram(o) ? O(a.local.name, o) : a.local;
              if (p === "default") {
                let x;
                c.types.isObjectExpression(g) ? x = g : (
                  // export default { ... } as Meta<...>
                  c.types.isTSAsExpression(g) && c.types.isObjectExpression(g.expression) && (x = g.expression)
                ), x && c.types.isProgram(o) && e._parseMeta(x, o);
              } else
                e._storyAnnotations[p] = {}, e._storyStatements[p] = g, e._storyPaths[p] = r, e._stories[p] = {
                  id: "FIXME",
                  name: p,
                  localName: d,
                  parameters: {},
                  __stats: {}
                };
            }
          });
        }
      },
      ExpressionStatement: {
        enter({ node: r, parent: i }) {
          let { expression: o } = r;
          if (c.types.isProgram(i) && c.types.isAssignmentExpression(o) && c.types.isMemberExpression(o.left) && c.types.isIdentifier(o.left.
          object) && c.types.isIdentifier(o.left.property)) {
            let l = o.left.object.name, a = o.left.property.name, p = o.right;
            if (e._storyAnnotations[l] && (a === "story" && c.types.isObjectExpression(p) ? p.properties.forEach((d) => {
              c.types.isIdentifier(d.key) && (e._storyAnnotations[l][d.key.name] = d.value);
            }) : e._storyAnnotations[l][a] = p), a === "storyName" && c.types.isStringLiteral(p)) {
              let d = p.value, g = e._stories[l];
              if (!g)
                return;
              g.name = d;
            }
          }
        }
      },
      CallExpression: {
        enter(r) {
          let { node: i } = r, { callee: o } = i;
          if (c.types.isIdentifier(o) && o.name === "storiesOf")
            throw new Error(P.dedent`
              Unexpected \`storiesOf\` usage: ${D(i, e._options.fileName)}.

              SB8 does not support \`storiesOf\`. 
            `);
          if (c.types.isMemberExpression(o) && c.types.isIdentifier(o.property) && o.property.name === "meta" && c.types.isIdentifier(o.object) &&
          i.arguments.length > 0) {
            let a = r.scope.getBinding(o.object.name)?.path?.parentPath?.node;
            if (c.types.isImportDeclaration(a))
              if (ge(a.source.value)) {
                let p = i.arguments[0];
                e._metaVariableName = o.property.name, e._metaIsFactory = !0, e._parseMeta(p, e._ast.program);
              } else
                throw new U(
                  "meta() factory must be imported from .storybook/preview configuration",
                  a,
                  e._options.fileName
                );
          }
        }
      },
      ImportDeclaration: {
        enter({ node: r }) {
          let { source: i } = r;
          if (c.types.isStringLiteral(i))
            e.imports.push(i.value);
          else
            throw new Error("CSF: unexpected import source");
        }
      }
    }), !e._meta)
      throw new L("missing default export", e._ast, e._options.fileName);
    let t = Object.entries(e._stories);
    if (e._meta.title = this._options.makeTitle(e._meta?.title), e._metaAnnotations.play && (e._meta.tags = [...e._meta.tags || [], "play-fn"]),
    e._stories = t.reduce(
      (r, [i, o]) => {
        if (!(0, I.isExportStory)(i, e._meta))
          return r;
        let l = o.parameters?.__id ?? (0, I.toId)(e._meta?.id || e._meta?.title, (0, I.storyNameFromExport)(i)), a = { ...o.parameters, __id: l },
        { includeStories: p } = e._meta || {};
        i === "__page" && (t.length === 1 || Array.isArray(p) && p.length === 1) && (a.docsOnly = !0), r[i] = { ...o, id: l, parameters: a };
        let d = e._storyAnnotations[i], { tags: g, play: x } = d;
        if (g) {
          let h = c.types.isIdentifier(g) ? O(g.name, this._ast.program) : g;
          r[i].tags = de(h);
        }
        x && (r[i].tags = [...r[i].tags || [], "play-fn"]);
        let E = r[i].__stats;
        ["play", "render", "loaders", "beforeEach", "globals", "tags"].forEach((h) => {
          E[h] = !!d[h] || !!e._metaAnnotations[h];
        });
        let b = e.getStoryExport(i);
        return E.storyFn = !!(c.types.isArrowFunctionExpression(b) || c.types.isFunctionDeclaration(b)), E.mount = tt(d.play ?? e._metaAnnotations.
        play), E.moduleMock = !!e.imports.find((h) => xe(h)), r;
      },
      {}
    ), Object.keys(e._storyExports).forEach((r) => {
      (0, I.isExportStory)(r, e._meta) || (delete e._storyExports[r], delete e._storyAnnotations[r], delete e._storyStatements[r]);
    }), e._namedExportsOrder) {
      let r = Object.keys(e._storyExports);
      e._storyExports = ue(e._storyExports, e._namedExportsOrder), e._stories = ue(e._stories, e._namedExportsOrder);
      let i = Object.keys(e._storyExports);
      if (r.length !== i.length)
        throw new Error(
          `Missing exports after sort: ${r.filter(
            (o) => !i.includes(o)
          )}`
        );
    }
    return e;
  }
  get meta() {
    return this._meta;
  }
  get stories() {
    return Object.values(this._stories);
  }
  get indexInputs() {
    let { fileName: e } = this._options;
    if (!e)
      throw new Error(
        P.dedent`Cannot automatically create index inputs with CsfFile.indexInputs because the CsfFile instance was created without a the fileName option.
        Either add the fileName option when creating the CsfFile instance, or create the index inputs manually.`
      );
    return Object.entries(this._stories).map(([t, r]) => {
      let i = [...this._meta?.tags ?? [], ...r.tags ?? []];
      return {
        type: "story",
        importPath: e,
        rawComponentPath: this._rawComponentPath,
        exportName: t,
        name: r.name,
        title: this.meta?.title,
        metaId: this.meta?.id,
        tags: i,
        __id: r.id,
        __stats: r.__stats
      };
    });
  }
}, ye = /* @__PURE__ */ f(({
  code: s,
  filename: e = "",
  ast: t
}) => new c.BabelFileClass({ filename: e }, { code: s, ast: t ?? (0, c.babelParse)(s) }), "babelParseFile"), Q = /* @__PURE__ */ f((s, e) => {
  let t = (0, c.babelParse)(s), r = ye({ code: s, filename: e.fileName, ast: t });
  return new K(t, e, r);
}, "loadCsf"), te = /* @__PURE__ */ f((s, e = { sourceMaps: !1 }, t) => {
  let r = (0, c.generate)(s._ast, e, t);
  return e.sourceMaps ? r : r.code;
}, "formatCsf"), be = /* @__PURE__ */ f((s, e = {}) => c.recast.print(s._ast, e), "printCsf"), it = /* @__PURE__ */ f(async (s, e) => {
  let t = (await (0, J.readFile)(s, "utf-8")).toString();
  return Q(t, { ...e, fileName: s });
}, "readCsf"), st = /* @__PURE__ */ f(async (s, e) => {
  if (!(e || s._options.fileName))
    throw new Error("Please specify a fileName for writeCsf");
  await (0, J.writeFile)(e, be(s).code);
}, "writeCsf");

// src/csf-tools/ConfigFile.ts
var ee = require("node:fs/promises"), n = require("storybook/internal/babel"), Ee = z(R(), 1);
var re = console, ie = /* @__PURE__ */ f(({
  expectedType: s,
  foundType: e,
  node: t
}) => Ee.dedent`
      CSF Parsing error: Expected '${s}' but found '${e}' instead in '${t?.type}'.
    `, "getCsfParsingErrorMessage"), C = /* @__PURE__ */ f((s) => n.types.isIdentifier(s.key) ? s.key.name : n.types.isStringLiteral(s.key) ?
s.key.value : null, "propKey"), H = /* @__PURE__ */ f((s) => n.types.isTSAsExpression(s) || n.types.isTSSatisfiesExpression(s) ? H(s.expression) :
s, "unwrap"), he = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0)
    return e;
  if (n.types.isObjectExpression(e)) {
    let [t, ...r] = s, i = e.properties.find((o) => C(o) === t);
    if (i)
      return he(r, i.value);
  }
}, "_getPath"), _e = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0) {
    if (n.types.isObjectExpression(e))
      return e.properties;
    throw new Error("Expected object expression");
  }
  if (n.types.isObjectExpression(e)) {
    let [t, ...r] = s, i = e.properties.find((o) => C(o) === t);
    if (i)
      return r.length === 0 ? e.properties : _e(r, i.value);
  }
}, "_getPathProperties"), Y = /* @__PURE__ */ f((s, e) => {
  let t = null, r = null;
  return e.body.find((i) => (n.types.isVariableDeclaration(i) ? r = i.declarations : n.types.isExportNamedDeclaration(i) && n.types.isVariableDeclaration(
  i.declaration) && (r = i.declaration.declarations), r && r.find((o) => n.types.isVariableDeclarator(o) && n.types.isIdentifier(o.id) && o.
  id.name === s ? (t = o, !0) : !1))), t;
}, "_findVarDeclarator"), F = /* @__PURE__ */ f((s, e) => Y(s, e)?.init, "_findVarInitialization"), B = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0)
    return e;
  let [t, ...r] = s, i = B(r, e);
  return n.types.objectExpression([n.types.objectProperty(n.types.identifier(t), i)]);
}, "_makeObjectExpression"), q = /* @__PURE__ */ f((s, e, t) => {
  let [r, ...i] = s, o = t.properties.find(
    (l) => C(l) === r
  );
  o ? n.types.isObjectExpression(o.value) && i.length > 0 ? q(i, e, o.value) : o.value = B(i, e) : t.properties.push(
    n.types.objectProperty(n.types.identifier(r), B(i, e))
  );
}, "_updateExportNode"), Z = class {
  constructor(e, t, r) {
    this._exports = {};
    // FIXME: this is a hack. this is only used in the case where the user is
    // modifying a named export that's a scalar. The _exports map is not suitable
    // for that. But rather than refactor the whole thing, we just use this as a stopgap.
    this._exportDecls = {};
    this.hasDefaultExport = !1;
    this._ast = e, this._code = t, this.fileName = r;
  }
  static {
    f(this, "ConfigFile");
  }
  _parseExportsObject(e) {
    this._exportsObject = e, e.properties.forEach((t) => {
      let r = C(t);
      if (r) {
        let i = t.value;
        n.types.isIdentifier(i) && (i = F(i.name, this._ast.program)), this._exports[r] = i;
      }
    });
  }
  parse() {
    let e = this;
    return (0, n.traverse)(this._ast, {
      ExportDefaultDeclaration: {
        enter({ node: t, parent: r }) {
          e.hasDefaultExport = !0;
          let i = n.types.isIdentifier(t.declaration) && n.types.isProgram(r) ? F(t.declaration.name, r) : t.declaration;
          i = H(i), n.types.isCallExpression(i) && n.types.isObjectExpression(i.arguments[0]) && (i = i.arguments[0]), n.types.isObjectExpression(
          i) ? e._parseExportsObject(i) : re.warn(
            ie({
              expectedType: "ObjectExpression",
              foundType: i?.type,
              node: i || t.declaration
            })
          );
        }
      },
      ExportNamedDeclaration: {
        enter({ node: t, parent: r }) {
          if (n.types.isVariableDeclaration(t.declaration))
            t.declaration.declarations.forEach((i) => {
              if (n.types.isVariableDeclarator(i) && n.types.isIdentifier(i.id)) {
                let { name: o } = i.id, l = i.init;
                n.types.isIdentifier(l) && (l = F(l.name, r)), e._exports[o] = l, e._exportDecls[o] = i;
              }
            });
          else if (n.types.isFunctionDeclaration(t.declaration)) {
            let i = t.declaration;
            if (n.types.isIdentifier(i.id)) {
              let { name: o } = i.id;
              e._exportDecls[o] = i;
            }
          } else t.specifiers ? t.specifiers.forEach((i) => {
            if (n.types.isExportSpecifier(i) && n.types.isIdentifier(i.local) && n.types.isIdentifier(i.exported)) {
              let { name: o } = i.local, { name: l } = i.exported, a = Y(o, r);
              a && (e._exports[l] = a.init, e._exportDecls[l] = a);
            }
          }) : re.warn(
            ie({
              expectedType: "VariableDeclaration",
              foundType: t.declaration?.type,
              node: t.declaration
            })
          );
        }
      },
      ExpressionStatement: {
        enter({ node: t, parent: r }) {
          if (n.types.isAssignmentExpression(t.expression) && t.expression.operator === "=") {
            let { left: i, right: o } = t.expression;
            if (n.types.isMemberExpression(i) && n.types.isIdentifier(i.object) && i.object.name === "module" && n.types.isIdentifier(i.property) &&
            i.property.name === "exports") {
              let l = o;
              n.types.isIdentifier(o) && (l = F(o.name, r)), l = H(l), n.types.isObjectExpression(l) ? (e._exportsObject = l, l.properties.forEach(
              (a) => {
                let p = C(a);
                if (p) {
                  let d = a.value;
                  n.types.isIdentifier(d) && (d = F(
                    d.name,
                    r
                  )), e._exports[p] = d;
                }
              })) : re.warn(
                ie({
                  expectedType: "ObjectExpression",
                  foundType: l?.type,
                  node: l
                })
              );
            }
          }
        }
      },
      CallExpression: {
        enter: /* @__PURE__ */ f(({ node: t }) => {
          n.types.isIdentifier(t.callee) && t.callee.name === "definePreview" && t.arguments.length === 1 && n.types.isObjectExpression(t.arguments[0]) &&
          e._parseExportsObject(t.arguments[0]);
        }, "enter")
      }
    }), e;
  }
  getFieldNode(e) {
    let [t, ...r] = e, i = this._exports[t];
    if (i)
      return he(r, i);
  }
  getFieldProperties(e) {
    let [t, ...r] = e, i = this._exports[t];
    if (i)
      return _e(r, i);
  }
  getFieldValue(e) {
    let t = this.getFieldNode(e);
    if (t) {
      let { code: r } = (0, n.generate)(t, {});
      return (0, eval)(`(() => (${r}))()`);
    }
  }
  getSafeFieldValue(e) {
    try {
      return this.getFieldValue(e);
    } catch {
    }
  }
  setFieldNode(e, t) {
    let [r, ...i] = e, o = this._exports[r];
    if (this._exportsObject) {
      let p = this._exportsObject.properties.find((d) => C(d) === r);
      if (p && n.types.isIdentifier(p.value)) {
        let d = Y(p.value.name, this._ast.program);
        if (d && n.types.isObjectExpression(d.init)) {
          q(i, t, d.init);
          return;
        }
      }
      q(e, t, this._exportsObject), this._exports[e[0]] = t;
      return;
    }
    if (o && n.types.isObjectExpression(o) && i.length > 0) {
      q(i, t, o);
      return;
    }
    let l = Y(r, this._ast.program);
    if (l && n.types.isObjectExpression(l.init)) {
      q(i, t, l.init);
      return;
    }
    if (o && i.length === 0 && this._exportDecls[e[0]]) {
      let a = this._exportDecls[e[0]];
      n.types.isVariableDeclarator(a) && (a.init = B([], t));
    } else {
      if (this.hasDefaultExport)
        throw new Error(
          `Could not set the "${e.join(
            "."
          )}" field as the default export is not an object in this file.`
        );
      {
        let a = B(i, t), p = n.types.exportNamedDeclaration(
          n.types.variableDeclaration("const", [n.types.variableDeclarator(n.types.identifier(r), a)])
        );
        this._exports[r] = a, this._ast.program.body.push(p);
      }
    }
  }
  /**
   * @example
   *
   * ```ts
   * // 1. { framework: 'framework-name' }
   * // 2. { framework: { name: 'framework-name', options: {} }
   * getNameFromPath(['framework']); // => 'framework-name'
   * ```
   *
   * @returns The name of a node in a given path, supporting the following formats:
   */
  getNameFromPath(e) {
    let t = this.getFieldNode(e);
    if (t)
      return this._getPresetValue(t, "name");
  }
  /**
   * Returns an array of names of a node in a given path, supporting the following formats:
   *
   * @example
   *
   * ```ts
   * const config = {
   *   addons: ['first-addon', { name: 'second-addon', options: {} }],
   * };
   * // => ['first-addon', 'second-addon']
   * getNamesFromPath(['addons']);
   * ```
   */
  getNamesFromPath(e) {
    let t = this.getFieldNode(e);
    if (!t)
      return;
    let r = [];
    return n.types.isArrayExpression(t) && t.elements.forEach((i) => {
      r.push(this._getPresetValue(i, "name"));
    }), r;
  }
  _getPnpWrappedValue(e) {
    if (n.types.isCallExpression(e)) {
      let t = e.arguments[0];
      if (n.types.isStringLiteral(t))
        return t.value;
    }
  }
  /**
   * Given a node and a fallback property, returns a **non-evaluated** string value of the node.
   *
   * 1. `{ node: 'value' }`
   * 2. `{ node: { fallbackProperty: 'value' } }`
   */
  _getPresetValue(e, t) {
    let r;
    if (n.types.isStringLiteral(e) ? r = e.value : n.types.isObjectExpression(e) ? e.properties.forEach((i) => {
      n.types.isObjectProperty(i) && n.types.isIdentifier(i.key) && i.key.name === t && (n.types.isStringLiteral(i.value) ? r = i.value.value :
      r = this._getPnpWrappedValue(i.value)), n.types.isObjectProperty(i) && n.types.isStringLiteral(i.key) && i.key.value === "name" && n.types.
      isStringLiteral(i.value) && (r = i.value.value);
    }) : n.types.isCallExpression(e) && (r = this._getPnpWrappedValue(e)), !r)
      throw new Error(
        `The given node must be a string literal or an object expression with a "${t}" property that is a string literal.`
      );
    return r;
  }
  removeField(e) {
    let t = /* @__PURE__ */ f((i, o) => {
      let l = i.findIndex(
        (a) => n.types.isIdentifier(a.key) && a.key.name === o || n.types.isStringLiteral(a.key) && a.key.value === o
      );
      l >= 0 && i.splice(l, 1);
    }, "removeProperty");
    if (e.length === 1) {
      let i = !1;
      if (this._ast.program.body.forEach((o) => {
        if (n.types.isExportNamedDeclaration(o) && n.types.isVariableDeclaration(o.declaration)) {
          let l = o.declaration.declarations[0];
          n.types.isIdentifier(l.id) && l.id.name === e[0] && (this._ast.program.body.splice(this._ast.program.body.indexOf(o), 1), i = !0);
        }
        if (n.types.isExportDefaultDeclaration(o)) {
          let l = o.declaration;
          if (n.types.isIdentifier(l) && (l = F(l.name, this._ast.program)), l = H(l), n.types.isObjectExpression(l)) {
            let a = l.properties;
            t(a, e[0]), i = !0;
          }
        }
        if (n.types.isExpressionStatement(o) && n.types.isAssignmentExpression(o.expression) && n.types.isMemberExpression(o.expression.left) &&
        n.types.isIdentifier(o.expression.left.object) && o.expression.left.object.name === "module" && n.types.isIdentifier(o.expression.left.
        property) && o.expression.left.property.name === "exports" && n.types.isObjectExpression(o.expression.right)) {
          let l = o.expression.right.properties;
          t(l, e[0]), i = !0;
        }
      }), i)
        return;
    }
    let r = this.getFieldProperties(e);
    if (r) {
      let i = e.at(-1);
      t(r, i);
    }
  }
  appendValueToArray(e, t) {
    let r = this.valueToNode(t);
    r && this.appendNodeToArray(e, r);
  }
  appendNodeToArray(e, t) {
    let r = this.getFieldNode(e);
    if (!r)
      this.setFieldNode(e, n.types.arrayExpression([t]));
    else if (n.types.isArrayExpression(r))
      r.elements.push(t);
    else
      throw new Error(`Expected array at '${e.join(".")}', got '${r.type}'`);
  }
  /**
   * Specialized helper to remove addons or other array entries that can either be strings or
   * objects with a name property.
   */
  removeEntryFromArray(e, t) {
    let r = this.getFieldNode(e);
    if (r)
      if (n.types.isArrayExpression(r)) {
        let i = r.elements.findIndex((o) => n.types.isStringLiteral(o) ? o.value === t : n.types.isObjectExpression(o) ? this._getPresetValue(
        o, "name") === t : this._getPnpWrappedValue(o) === t);
        if (i >= 0)
          r.elements.splice(i, 1);
        else
          throw new Error(`Could not find '${t}' in array at '${e.join(".")}'`);
      } else
        throw new Error(`Expected array at '${e.join(".")}', got '${r.type}'`);
  }
  _inferQuotes() {
    if (!this._quotes) {
      let e = (this._ast.tokens || []).slice(0, 500).reduce(
        (t, r) => (r.type.label === "string" && (t[this._code[r.start]] += 1), t),
        { "'": 0, '"': 0 }
      );
      this._quotes = e["'"] > e['"'] ? "single" : "double";
    }
    return this._quotes;
  }
  valueToNode(e) {
    let t = this._inferQuotes(), r;
    if (t === "single") {
      let { code: i } = (0, n.generate)(n.types.valueToNode(e), { jsescOption: { quotes: t } }), o = (0, n.babelParse)(`const __x = ${i}`);
      (0, n.traverse)(o, {
        VariableDeclaration: {
          enter({ node: l }) {
            l.declarations.length === 1 && n.types.isVariableDeclarator(l.declarations[0]) && n.types.isIdentifier(l.declarations[0].id) && l.
            declarations[0].id.name === "__x" && (r = l.declarations[0].init);
          }
        }
      });
    } else
      r = n.types.valueToNode(e);
    return r;
  }
  setFieldValue(e, t) {
    let r = this.valueToNode(t);
    if (!r)
      throw new Error(`Unexpected value ${JSON.stringify(t)}`);
    this.setFieldNode(e, r);
  }
  getBodyDeclarations() {
    return this._ast.program.body;
  }
  setBodyDeclaration(e) {
    this._ast.program.body.push(e);
  }
  /**
   * Import specifiers for a specific require import
   *
   * @example
   *
   * ```ts
   * // const { foo } = require('bar');
   * setRequireImport(['foo'], 'bar');
   *
   * // const foo = require('bar');
   * setRequireImport('foo', 'bar');
   * ```
   *
   * @param importSpecifiers - The import specifiers to set. If a string is passed in, a default
   *   import will be set. Otherwise, an array of named imports will be set
   * @param fromImport - The module to import from
   */
  setRequireImport(e, t) {
    let r = this._ast.program.body.find(
      (l) => n.types.isVariableDeclaration(l) && l.declarations.length === 1 && n.types.isVariableDeclarator(l.declarations[0]) && n.types.isCallExpression(
      l.declarations[0].init) && n.types.isIdentifier(l.declarations[0].init.callee) && l.declarations[0].init.callee.name === "require" && n.types.
      isStringLiteral(l.declarations[0].init.arguments[0]) && l.declarations[0].init.arguments[0].value === t
    ), i = /* @__PURE__ */ f((l) => n.types.isObjectPattern(r?.declarations[0].id) && r?.declarations[0].id.properties.find(
      (a) => n.types.isObjectProperty(a) && n.types.isIdentifier(a.key) && a.key.name === l
    ), "hasRequireSpecifier"), o = /* @__PURE__ */ f((l, a) => l.declarations.length === 1 && n.types.isVariableDeclarator(l.declarations[0]) &&
    n.types.isIdentifier(l.declarations[0].id) && l.declarations[0].id.name === a, "hasDefaultRequireSpecifier");
    if (typeof e == "string") {
      let l = /* @__PURE__ */ f(() => {
        this._ast.program.body.unshift(
          n.types.variableDeclaration("const", [
            n.types.variableDeclarator(
              n.types.identifier(e),
              n.types.callExpression(n.types.identifier("require"), [n.types.stringLiteral(t)])
            )
          ])
        );
      }, "addDefaultRequireSpecifier");
      r && o(r, e) || l();
    } else r ? e.forEach((l) => {
      i(l) || r.declarations[0].id.properties.push(
        n.types.objectProperty(n.types.identifier(l), n.types.identifier(l), void 0, !0)
      );
    }) : this._ast.program.body.unshift(
      n.types.variableDeclaration("const", [
        n.types.variableDeclarator(
          n.types.objectPattern(
            e.map(
              (l) => n.types.objectProperty(n.types.identifier(l), n.types.identifier(l), void 0, !0)
            )
          ),
          n.types.callExpression(n.types.identifier("require"), [n.types.stringLiteral(t)])
        )
      ])
    );
  }
  /**
   * Set import specifiers for a given import statement.
   *
   * Does not support setting type imports (yet)
   *
   * @example
   *
   * ```ts
   * // import { foo } from 'bar';
   * setImport(['foo'], 'bar');
   *
   * // import foo from 'bar';
   * setImport('foo', 'bar');
   *
   * // import * as foo from 'bar';
   * setImport({ namespace: 'foo' }, 'bar');
   *
   * // import 'bar';
   * setImport(null, 'bar');
   * ```
   *
   * @param importSpecifiers - The import specifiers to set. If a string is passed in, a default
   *   import will be set. Otherwise, an array of named imports will be set
   * @param fromImport - The module to import from
   */
  setImport(e, t) {
    let r = /* @__PURE__ */ f((p) => n.types.importSpecifier(n.types.identifier(p), n.types.identifier(p)), "getNewImportSpecifier"), i = /* @__PURE__ */ f(
    (p, d) => p.specifiers.find(
      (g) => n.types.isImportSpecifier(g) && n.types.isIdentifier(g.imported) && g.imported.name === d
    ), "hasImportSpecifier"), o = /* @__PURE__ */ f((p, d) => p.specifiers.find(
      (g) => n.types.isImportNamespaceSpecifier(g) && n.types.isIdentifier(g.local) && g.local.name === d
    ), "hasNamespaceImportSpecifier"), l = /* @__PURE__ */ f((p, d) => p.specifiers.find(
      (g) => n.types.isImportDefaultSpecifier(g) && n.types.isIdentifier(g.local) && g.local.name === d
    ), "hasDefaultImportSpecifier"), a = this._ast.program.body.find(
      (p) => n.types.isImportDeclaration(p) && p.source.value === t
    );
    e === null ? a || this._ast.program.body.unshift(n.types.importDeclaration([], n.types.stringLiteral(t))) : typeof e == "string" ? a ? l(
    a, e) || a.specifiers.push(
      n.types.importDefaultSpecifier(n.types.identifier(e))
    ) : this._ast.program.body.unshift(
      n.types.importDeclaration(
        [n.types.importDefaultSpecifier(n.types.identifier(e))],
        n.types.stringLiteral(t)
      )
    ) : Array.isArray(e) ? a ? e.forEach((p) => {
      i(a, p) || a.specifiers.push(r(p));
    }) : this._ast.program.body.unshift(
      n.types.importDeclaration(
        e.map(r),
        n.types.stringLiteral(t)
      )
    ) : e.namespace && (a ? o(a, e.namespace) || a.specifiers.push(
      n.types.importNamespaceSpecifier(n.types.identifier(e.namespace))
    ) : this._ast.program.body.unshift(
      n.types.importDeclaration(
        [n.types.importNamespaceSpecifier(n.types.identifier(e.namespace))],
        n.types.stringLiteral(t)
      )
    ));
  }
}, je = /* @__PURE__ */ f((s, e) => {
  let t = (0, n.babelParse)(s);
  return new Z(t, s, e);
}, "loadConfig"), Se = /* @__PURE__ */ f((s) => Oe(s).code, "formatConfig"), Oe = /* @__PURE__ */ f((s, e = {}) => n.recast.print(s._ast, e),
"printConfig"), nt = /* @__PURE__ */ f(async (s) => {
  let e = (await (0, ee.readFile)(s, "utf-8")).toString();
  return je(e, s).parse();
}, "readConfig"), ot = /* @__PURE__ */ f(async (s, e) => {
  let t = e || s.fileName;
  if (!t)
    throw new Error("Please specify a fileName for writeConfig");
  await (0, ee.writeFile)(t, Se(s));
}, "writeConfig"), at = /* @__PURE__ */ f((s) => !!s._ast.program.body.find((t) => n.types.isImportDeclaration(t) && t.source.value.includes(
"@storybook") && t.specifiers.some((r) => n.types.isImportSpecifier(r) && n.types.isIdentifier(r.imported) && r.imported.name === "definePre\
view")), "isCsfFactoryPreview");

// src/csf-tools/getStorySortParameter.ts
var y = require("storybook/internal/babel"), Ie = z(R(), 1);
var lt = console, se = /* @__PURE__ */ f((s, e) => {
  let t;
  return s.properties.forEach((r) => {
    y.types.isIdentifier(r.key) && r.key.name === e && (t = r.value);
  }), t;
}, "getValue"), ne = /* @__PURE__ */ f((s) => {
  let e = W(s);
  if (y.types.isArrayExpression(e))
    return e.elements.map((t) => ne(t));
  if (y.types.isObjectExpression(e))
    return e.properties.reduce((t, r) => (y.types.isIdentifier(r.key) && (t[r.key.name] = ne(r.value)), t), {});
  if (y.types.isLiteral(e))
    return e.value;
  if (y.types.isIdentifier(e))
    return T(e.name, !0);
  throw new Error(`Unknown node type ${e.type}`);
}, "parseValue"), T = /* @__PURE__ */ f((s, e) => {
  let t = Ie.dedent`
    Unexpected '${s}'. Parameter 'options.storySort' should be defined inline e.g.:

    export default {
      parameters: {
        options: {
          storySort: <array | object | function>
        },
      },
    };
  `;
  if (e)
    throw new Error(t);
  lt.info(t);
}, "unsupported"), W = /* @__PURE__ */ f((s) => y.types.isTSAsExpression(s) || y.types.isTSSatisfiesExpression(s) ? s.expression : s, "strip\
TSModifiers"), De = /* @__PURE__ */ f((s) => {
  let e = W(s);
  if (y.types.isObjectExpression(e)) {
    let t = se(e, "options");
    if (t) {
      if (y.types.isObjectExpression(t))
        return se(t, "storySort");
      T("options", !0);
    }
  }
}, "parseParameters"), Pe = /* @__PURE__ */ f((s, e) => {
  let t = W(s);
  if (y.types.isObjectExpression(t)) {
    let r = se(t, "parameters");
    if (y.types.isIdentifier(r) && (r = O(r.name, e)), r)
      return De(r);
  } else
    T("default", !0);
}, "parseDefault"), ct = /* @__PURE__ */ f((s) => {
  if (!s.includes("storySort"))
    return;
  let e, t = (0, y.babelParse)(s);
  if ((0, y.traverse)(t, {
    ExportNamedDeclaration: {
      enter({ node: r }) {
        y.types.isVariableDeclaration(r.declaration) ? r.declaration.declarations.forEach((i) => {
          if (y.types.isVariableDeclarator(i) && y.types.isIdentifier(i.id)) {
            let { name: o } = i.id;
            if (o === "parameters" && i.init) {
              let l = W(i.init);
              e = De(l);
            }
          }
        }) : r.specifiers.forEach((i) => {
          y.types.isIdentifier(i.exported) && i.exported.name === "parameters" && T("parameters", !1);
        });
      }
    },
    ExportDefaultDeclaration: {
      enter({ node: r }) {
        let i = r.declaration;
        y.types.isIdentifier(i) && (i = O(i.name, t.program)), i = W(i), y.types.isCallExpression(i) && y.types.isObjectExpression(i.arguments?.[0]) ?
        e = Pe(i.arguments[0], t.program) : y.types.isObjectExpression(i) ? e = Pe(i, t.program) : T("default", !1);
      }
    }
  }), !!e) {
    if (y.types.isArrowFunctionExpression(e)) {
      let { code: r } = (0, y.generate)(e, {});
      return (0, eval)(r);
    }
    if (y.types.isFunctionExpression(e)) {
      let { code: r } = (0, y.generate)(e, {}), i = e.id?.name, o = `(a, b) => {
      ${r};
      return ${i}(a, b)
    }`;
      return (0, eval)(o);
    }
    return y.types.isLiteral(e) || y.types.isArrayExpression(e) || y.types.isObjectExpression(e) ? ne(e) : T("storySort", !0);
  }
}, "getStorySortParameter");

// src/csf-tools/enrichCsf.ts
var u = require("storybook/internal/babel");
var ve = /* @__PURE__ */ f((s, e, t, r) => {
  let i = e.getStoryExport(t), o = u.types.isCallExpression(i) && u.types.isMemberExpression(i.callee) && u.types.isIdentifier(i.callee.object) &&
  i.callee.object.name === "meta", l = !r?.disableSource && Fe(i), a = !r?.disableDescription && oe(e._storyStatements[t]), p = [], d = o ? u.types.
  memberExpression(u.types.identifier(t), u.types.identifier("input")) : u.types.identifier(t), g = u.types.memberExpression(d, u.types.identifier(
  "parameters"));
  p.push(u.types.spreadElement(g));
  let x = u.types.optionalMemberExpression(
    g,
    u.types.identifier("docs"),
    !1,
    !0
  ), E = [];
  if (l) {
    let b = u.types.optionalMemberExpression(
      x,
      u.types.identifier("source"),
      !1,
      !0
    );
    E.push(
      u.types.objectProperty(
        u.types.identifier("source"),
        u.types.objectExpression([
          u.types.objectProperty(u.types.identifier("originalSource"), u.types.stringLiteral(l)),
          u.types.spreadElement(b)
        ])
      )
    );
  }
  if (a) {
    let b = u.types.optionalMemberExpression(
      x,
      u.types.identifier("description"),
      !1,
      !0
    );
    E.push(
      u.types.objectProperty(
        u.types.identifier("description"),
        u.types.objectExpression([
          u.types.objectProperty(u.types.identifier("story"), u.types.stringLiteral(a)),
          u.types.spreadElement(b)
        ])
      )
    );
  }
  if (E.length > 0) {
    p.push(
      u.types.objectProperty(
        u.types.identifier("docs"),
        u.types.objectExpression([u.types.spreadElement(x), ...E])
      )
    );
    let b = u.types.expressionStatement(
      u.types.assignmentExpression("=", g, u.types.objectExpression(p))
    );
    s._ast.program.body.push(b);
  }
}, "enrichCsfStory"), Ne = /* @__PURE__ */ f((s, e, t) => {
  if (!e.length) {
    s.properties.find(
      (p) => u.types.isObjectProperty(p) && u.types.isIdentifier(p.key) && p.key.name === "component"
    ) || s.properties.unshift(t);
    return;
  }
  let [r, ...i] = e, o = s.properties.find(
    (a) => u.types.isObjectProperty(a) && u.types.isIdentifier(a.key) && a.key.name === r && u.types.isObjectExpression(a.value)
  ), l;
  o ? l = o.value : (l = u.types.objectExpression([]), s.properties.push(u.types.objectProperty(u.types.identifier(r), l))), Ne(l, i, t);
}, "addComponentDescription"), we = /* @__PURE__ */ f((s, e, t) => {
  let r = !t?.disableDescription && oe(e._metaStatement);
  if (r) {
    let i = s._metaNode;
    i && u.types.isObjectExpression(i) && Ne(
      i,
      ["parameters", "docs", "description"],
      u.types.objectProperty(u.types.identifier("component"), u.types.stringLiteral(r))
    );
  }
}, "enrichCsfMeta"), pt = /* @__PURE__ */ f((s, e, t) => {
  we(s, e, t), Object.keys(s._storyExports).forEach((r) => {
    ve(s, e, r, t);
  });
}, "enrichCsf"), Fe = /* @__PURE__ */ f((s) => {
  let e = u.types.isVariableDeclarator(s) ? s.init : s, { code: t } = (0, u.generate)(e, {});
  return t;
}, "extractSource"), oe = /* @__PURE__ */ f((s) => s?.leadingComments ? s.leadingComments.map((t) => t.type === "CommentLine" || !t.value.startsWith(
"*") ? null : t.value.split(`
`).map((r) => r.replace(/^(\s+)?(\*+)?(\s)?/, "")).join(`
`).trim()).filter(Boolean).join(`
`) : "", "extractDescription");

// src/csf-tools/index.ts
var Ae = require("storybook/internal/babel");

// src/csf-tools/vitest-plugin/transformer.ts
var m = require("storybook/internal/babel"), Te = require("storybook/internal/common"), ke = require("storybook/internal/csf"), ae = z(R(), 1);
var Ce = console, ft = /* @__PURE__ */ f((s, e) => !(e.include.length && !e.include.some((t) => s?.includes(t)) || e.exclude.some((t) => s?.
includes(t))), "isValidTest");
async function Ve({
  code: s,
  fileName: e,
  configDir: t,
  stories: r,
  tagsFilter: i,
  previewLevelTags: o = []
}) {
  if (!/\.stor(y|ies)\./.test(e))
    return s;
  let a = Q(s, {
    fileName: e,
    transformInlineMeta: !0,
    makeTitle: /* @__PURE__ */ f((_) => {
      let S = (0, Te.getStoryTitle)({
        storyFilePath: e,
        configDir: t,
        stories: r,
        userTitle: _
      }) || "unknown";
      return S === "unknown" && Ce.warn(
        ae.dedent`
            [Storybook]: Could not calculate story title for "${e}".
            Please make sure that this file matches the globs included in the "stories" field in your Storybook configuration at "${t}".
          `
      ), S;
    }, "makeTitle")
  }).parse(), p = a._ast, d = a._metaVariableName, g = a._metaNode, x = g.properties.find(
    (_) => m.types.isObjectProperty(_) && m.types.isIdentifier(_.key) && _.key.name === "title"
  ), E = m.types.stringLiteral(a._meta?.title || "unknown");
  if (x ? m.types.isObjectProperty(x) && (x.value = E) : g.properties.push(m.types.objectProperty(m.types.identifier("title"), E)), !g || !a.
  _meta)
    throw new Error(
      `The Storybook vitest plugin could not detect the meta (default export) object in the story file. 

Please make sure you have a default export with the meta object. If you are using a different export format that is not supported, please fi\
le an issue with details about your use case.`
    );
  let b = {};
  Object.keys(a._stories).map((_) => {
    let S = (0, ke.combineTags)(
      "test",
      "dev",
      ...o,
      ...a.meta?.tags || [],
      ...a._stories[_].tags || []
    );
    ft(S, i) && (b[_] = a._storyStatements[_]);
  });
  let h = a._file.path.scope.generateUidIdentifier("test"), v = a._file.path.scope.generateUidIdentifier("describe");
  if (Object.keys(b).length === 0) {
    let _ = m.types.expressionStatement(
      m.types.callExpression(m.types.memberExpression(v, m.types.identifier("skip")), [
        m.types.stringLiteral("No valid tests found")
      ])
    );
    p.program.body.push(_);
    let S = [
      m.types.importDeclaration(
        [
          m.types.importSpecifier(h, m.types.identifier("test")),
          m.types.importSpecifier(v, m.types.identifier("describe"))
        ],
        m.types.stringLiteral("vitest")
      )
    ];
    p.program.body.unshift(...S);
  } else {
    let le = function() {
      let j = a._file.path.scope.generateUidIdentifier("isRunningFromThisFile"), N = m.types.memberExpression(
        m.types.callExpression(m.types.memberExpression(_, m.types.identifier("getState")), []),
        m.types.identifier("testPath")
      ), k = m.types.memberExpression(
        m.types.memberExpression(m.types.identifier("globalThis"), m.types.identifier("__vitest_worker__")),
        m.types.identifier("filepath")
      ), V = m.types.logicalExpression(
        "??",
        // TODO: switch order of testPathProperty and filePathProperty when the bug is fixed
        // https://github.com/vitest-dev/vitest/issues/6367 (or probably just use testPathProperty)
        k,
        N
      ), G = m.types.callExpression(
        m.types.memberExpression(
          m.types.memberExpression(
            m.types.memberExpression(m.types.identifier("import"), m.types.identifier("meta")),
            m.types.identifier("url")
          ),
          m.types.identifier("includes")
        ),
        [V]
      );
      return { isRunningFromThisFileDeclaration: m.types.variableDeclaration("const", [
        m.types.variableDeclarator(j, G)
      ]), isRunningFromThisFileId: j };
    };
    var mt = le;
    f(le, "getTestGuardDeclaration");
    let _ = a._file.path.scope.generateUidIdentifier("expect"), S = a._file.path.scope.generateUidIdentifier("testStory"), $e = m.types.identifier(
    JSON.stringify(i.skip)), { isRunningFromThisFileDeclaration: Re, isRunningFromThisFileId: Le } = le();
    p.program.body.push(Re);
    let Me = /* @__PURE__ */ f(({
      localName: j,
      exportName: N,
      testTitle: k,
      node: V
    }) => {
      let G = m.types.expressionStatement(
        m.types.callExpression(h, [
          m.types.stringLiteral(k),
          m.types.callExpression(S, [
            m.types.stringLiteral(N),
            m.types.identifier(j),
            m.types.identifier(d),
            $e
          ])
        ])
      );
      return G.loc = V.loc, G;
    }, "getTestStatementForStory"), Ue = Object.entries(b).map(([j, N]) => {
      if (N === null) {
        Ce.warn(
          ae.dedent`
            [Storybook]: Could not transform "${j}" story into test at "${e}".
            Please make sure to define stories in the same file and not re-export stories coming from other files".
          `
        );
        return;
      }
      let k = a._stories[j].localName ?? j, V = a._stories[j].name ?? j;
      return Me({ testTitle: V, localName: k, exportName: j, node: N });
    }).filter((j) => !!j), qe = m.types.ifStatement(Le, m.types.blockStatement(Ue));
    p.program.body.push(qe);
    let Be = [
      m.types.importDeclaration(
        [
          m.types.importSpecifier(h, m.types.identifier("test")),
          m.types.importSpecifier(_, m.types.identifier("expect"))
        ],
        m.types.stringLiteral("vitest")
      ),
      m.types.importDeclaration(
        [m.types.importSpecifier(S, m.types.identifier("testStory"))],
        m.types.stringLiteral("@storybook/addon-vitest/internal/test-utils")
      )
    ];
    p.program.body.unshift(...Be);
  }
  return te(a, { sourceMaps: !0, sourceFileName: e }, s);
}
f(Ve, "vitestTransform");
