import CJS_COMPAT_NODE_URL from 'node:url';
import CJS_COMPAT_NODE_PATH from 'node:path';
import CJS_COMPAT_NODE_MODULE from "node:module";

const __filename = CJS_COMPAT_NODE_URL.fileURLToPath(import.meta.url);
const __dirname = CJS_COMPAT_NODE_PATH.dirname(__filename);
const require = CJS_COMPAT_NODE_MODULE.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
  a as M
} from "./chunk-5G5PMXGR.js";
import {
  a as f,
  f as L
} from "./chunk-HRN2KQZP.js";

// src/csf-tools/CsfFile.ts
var O = L(M(), 1);
import { readFile as Fe, writeFile as Ce } from "node:fs/promises";
import {
  BabelFileClass as Te,
  babelParse as le,
  generate as ke,
  recast as ce,
  types as c,
  traverse as Ve
} from "storybook/internal/babel";
import { isExportStory as re, storyNameFromExport as ie, toId as Ae } from "storybook/internal/csf";
import { logger as se } from "storybook/internal/node-logger";

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

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

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

              SB8 does not support \`storiesOf\`. 
            `);
          if (c.isMemberExpression(o) && c.isIdentifier(o.property) && o.property.name === "meta" && c.isIdentifier(o.object) && r.arguments.length > 0) {
            let l = t.scope.getBinding(o.object.name)?.path?.parentPath?.node;
            if (c.isImportDeclaration(l))
              if (Re(l.source.value)) {
                let p = r.arguments[0];
                e._metaVariableName = o.property.name, e._metaIsFactory = !0, e._parseMeta(p, e._ast.program);
              } else
                throw new B(
                  "meta() factory must be imported from .storybook/preview configuration",
                  l,
                  e._options.fileName
                );
          }
        }
      },
      ImportDeclaration: {
        enter({ node: t }) {
          let { source: r } = t;
          if (c.isStringLiteral(r))
            e.imports.push(r.value);
          else
            throw new Error("CSF: unexpected import source");
        }
      }
    }), !e._meta)
      throw new U("missing default export", e._ast, e._options.fileName);
    let i = 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 = i.reduce(
      (t, [r, o]) => {
        if (!re(r, e._meta))
          return t;
        let a = o.parameters?.__id ?? Ae(e._meta?.id || e._meta?.title, ie(r)), l = { ...o.parameters, __id: a }, { includeStories: p } = e._meta || {};
        r === "__page" && (i.length === 1 || Array.isArray(p) && p.length === 1) && (l.docsOnly = !0), t[r] = { ...o, id: a, parameters: l };
        let m = e._storyAnnotations[r], { tags: g, play: x } = m;
        if (g) {
          let h = c.isIdentifier(g) ? P(g.name, this._ast.program) : g;
          t[r].tags = ne(h);
        }
        x && (t[r].tags = [...t[r].tags || [], "play-fn"]);
        let E = t[r].__stats;
        ["play", "render", "loaders", "beforeEach", "globals", "tags"].forEach((h) => {
          E[h] = !!m[h] || !!e._metaAnnotations[h];
        });
        let y = e.getStoryExport(r);
        return E.storyFn = !!(c.isArrowFunctionExpression(y) || c.isFunctionDeclaration(y)), E.mount = qe(m.play ?? e._metaAnnotations.play), E.moduleMock = !!e.imports.find((h) => Me(h)), t;
      },
      {}
    ), Object.keys(e._storyExports).forEach((t) => {
      re(t, e._meta) || (delete e._storyExports[t], delete e._storyAnnotations[t], delete e._storyStatements[t]);
    }), e._namedExportsOrder) {
      let t = Object.keys(e._storyExports);
      e._storyExports = ae(e._storyExports, e._namedExportsOrder), e._stories = ae(e._stories, e._namedExportsOrder);
      let r = Object.keys(e._storyExports);
      if (t.length !== r.length)
        throw new Error(
          `Missing exports after sort: ${t.filter(
            (o) => !r.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(
        O.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(([i, t]) => {
      let r = [...this._meta?.tags ?? [], ...t.tags ?? []];
      return {
        type: "story",
        importPath: e,
        rawComponentPath: this._rawComponentPath,
        exportName: i,
        name: t.name,
        title: this.meta?.title,
        metaId: this.meta?.id,
        tags: r,
        __id: t.id,
        __stats: t.__stats
      };
    });
  }
}, We = /* @__PURE__ */ f(({
  code: s,
  filename: e = "",
  ast: i
}) => new Te({ filename: e }, { code: s, ast: i ?? le(s) }), "babelParseFile"), K = /* @__PURE__ */ f((s, e) => {
  let i = le(s), t = We({ code: s, filename: e.fileName, ast: i });
  return new X(i, e, t);
}, "loadCsf"), pe = /* @__PURE__ */ f((s, e = { sourceMaps: !1 }, i) => {
  let t = ke(s._ast, e, i);
  return e.sourceMaps ? t : t.code;
}, "formatCsf"), Ge = /* @__PURE__ */ f((s, e = {}) => ce.print(s._ast, e), "printCsf"), Et = /* @__PURE__ */ f(async (s, e) => {
  let i = (await Fe(s, "utf-8")).toString();
  return K(i, { ...e, fileName: s });
}, "readCsf"), ht = /* @__PURE__ */ f(async (s, e) => {
  if (!(e || s._options.fileName))
    throw new Error("Please specify a fileName for writeCsf");
  await Ce(e, Ge(s).code);
}, "writeCsf");

// src/csf-tools/ConfigFile.ts
var ue = L(M(), 1);
import { readFile as ze, writeFile as Xe } from "node:fs/promises";
import {
  babelParse as me,
  generate as fe,
  recast as Ke,
  types as n,
  traverse as de
} from "storybook/internal/babel";
import { logger as J } from "storybook/internal/node-logger";
var Q = /* @__PURE__ */ f(({
  expectedType: s,
  foundType: e,
  node: i
}) => ue.dedent`
      CSF Parsing error: Expected '${s}' but found '${e}' instead in '${i?.type}'.
    `, "getCsfParsingErrorMessage"), w = /* @__PURE__ */ f((s) => n.isIdentifier(s.key) ? s.key.name : n.isStringLiteral(s.key) ? s.key.value : null, "propKey"), W = /* @__PURE__ */ f((s) => n.isTSAsExpression(s) || n.isTSSatisfiesExpression(s) ? W(s.expression) : s, "unwrap"), ge = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0)
    return e;
  if (n.isObjectExpression(e)) {
    let [i, ...t] = s, r = e.properties.find((o) => w(o) === i);
    if (r)
      return ge(t, r.value);
  }
}, "_getPath"), xe = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0) {
    if (n.isObjectExpression(e))
      return e.properties;
    throw new Error("Expected object expression");
  }
  if (n.isObjectExpression(e)) {
    let [i, ...t] = s, r = e.properties.find((o) => w(o) === i);
    if (r)
      return t.length === 0 ? e.properties : xe(t, r.value);
  }
}, "_getPathProperties"), G = /* @__PURE__ */ f((s, e) => {
  let i = null, t = null;
  return e.body.find((r) => (n.isVariableDeclaration(r) ? t = r.declarations : n.isExportNamedDeclaration(r) && n.isVariableDeclaration(r.declaration) && (t = r.declaration.declarations), t && t.find((o) => n.isVariableDeclarator(o) && n.isIdentifier(o.id) && o.id.name === s ? (i = o, !0) : !1))), i;
}, "_findVarDeclarator"), v = /* @__PURE__ */ f((s, e) => G(s, e)?.init, "_findVarInitialization"), A = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0)
    return e;
  let [i, ...t] = s, r = A(t, e);
  return n.objectExpression([n.objectProperty(n.identifier(i), r)]);
}, "_makeObjectExpression"), V = /* @__PURE__ */ f((s, e, i) => {
  let [t, ...r] = s, o = i.properties.find(
    (a) => w(a) === t
  );
  o ? n.isObjectExpression(o.value) && r.length > 0 ? V(r, e, o.value) : o.value = A(r, e) : i.properties.push(
    n.objectProperty(n.identifier(t), A(r, e))
  );
}, "_updateExportNode"), H = class {
  constructor(e, i, t) {
    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 = i, this.fileName = t;
  }
  static {
    f(this, "ConfigFile");
  }
  _parseExportsObject(e) {
    this._exportsObject = e, e.properties.forEach((i) => {
      let t = w(i);
      if (t) {
        let r = i.value;
        n.isIdentifier(r) && (r = v(r.name, this._ast.program)), this._exports[t] = r;
      }
    });
  }
  parse() {
    let e = this;
    return de(this._ast, {
      ExportDefaultDeclaration: {
        enter({ node: i, parent: t }) {
          e.hasDefaultExport = !0;
          let r = n.isIdentifier(i.declaration) && n.isProgram(t) ? v(i.declaration.name, t) : i.declaration;
          r = W(r), n.isCallExpression(r) && n.isObjectExpression(r.arguments[0]) && (r = r.arguments[0]), n.isObjectExpression(r) ? e._parseExportsObject(r) : J.warn(
            Q({
              expectedType: "ObjectExpression",
              foundType: r?.type,
              node: r || i.declaration
            })
          );
        }
      },
      ExportNamedDeclaration: {
        enter({ node: i, parent: t }) {
          if (n.isVariableDeclaration(i.declaration))
            i.declaration.declarations.forEach((r) => {
              if (n.isVariableDeclarator(r) && n.isIdentifier(r.id)) {
                let { name: o } = r.id, a = r.init;
                n.isIdentifier(a) && (a = v(a.name, t)), e._exports[o] = a, e._exportDecls[o] = r;
              }
            });
          else if (n.isFunctionDeclaration(i.declaration)) {
            let r = i.declaration;
            if (n.isIdentifier(r.id)) {
              let { name: o } = r.id;
              e._exportDecls[o] = r;
            }
          } else i.specifiers ? i.specifiers.forEach((r) => {
            if (n.isExportSpecifier(r) && n.isIdentifier(r.local) && n.isIdentifier(r.exported)) {
              let { name: o } = r.local, { name: a } = r.exported, l = G(o, t);
              l && (e._exports[a] = l.init, e._exportDecls[a] = l);
            }
          }) : J.warn(
            Q({
              expectedType: "VariableDeclaration",
              foundType: i.declaration?.type,
              node: i.declaration
            })
          );
        }
      },
      ExpressionStatement: {
        enter({ node: i, parent: t }) {
          if (n.isAssignmentExpression(i.expression) && i.expression.operator === "=") {
            let { left: r, right: o } = i.expression;
            if (n.isMemberExpression(r) && n.isIdentifier(r.object) && r.object.name === "module" && n.isIdentifier(r.property) && r.property.name === "exports") {
              let a = o;
              n.isIdentifier(o) && (a = v(o.name, t)), a = W(a), n.isObjectExpression(a) ? (e._exportsObject = a, a.properties.forEach((l) => {
                let p = w(l);
                if (p) {
                  let m = l.value;
                  n.isIdentifier(m) && (m = v(
                    m.name,
                    t
                  )), e._exports[p] = m;
                }
              })) : J.warn(
                Q({
                  expectedType: "ObjectExpression",
                  foundType: a?.type,
                  node: a
                })
              );
            }
          }
        }
      },
      CallExpression: {
        enter: /* @__PURE__ */ f(({ node: i }) => {
          n.isIdentifier(i.callee) && i.callee.name === "definePreview" && i.arguments.length === 1 && n.isObjectExpression(i.arguments[0]) && e._parseExportsObject(i.arguments[0]);
        }, "enter")
      }
    }), e;
  }
  getFieldNode(e) {
    let [i, ...t] = e, r = this._exports[i];
    if (r)
      return ge(t, r);
  }
  getFieldProperties(e) {
    let [i, ...t] = e, r = this._exports[i];
    if (r)
      return xe(t, r);
  }
  getFieldValue(e) {
    let i = this.getFieldNode(e);
    if (i) {
      let { code: t } = fe(i, {});
      return (0, eval)(`(() => (${t}))()`);
    }
  }
  getSafeFieldValue(e) {
    try {
      return this.getFieldValue(e);
    } catch {
    }
  }
  setFieldNode(e, i) {
    let [t, ...r] = e, o = this._exports[t];
    if (this._exportsObject) {
      let p = this._exportsObject.properties.find((m) => w(m) === t);
      if (p && n.isIdentifier(p.value)) {
        let m = G(p.value.name, this._ast.program);
        if (m && n.isObjectExpression(m.init)) {
          V(r, i, m.init);
          return;
        }
      }
      V(e, i, this._exportsObject), this._exports[e[0]] = i;
      return;
    }
    if (o && n.isObjectExpression(o) && r.length > 0) {
      V(r, i, o);
      return;
    }
    let a = G(t, this._ast.program);
    if (a && n.isObjectExpression(a.init)) {
      V(r, i, a.init);
      return;
    }
    if (o && r.length === 0 && this._exportDecls[e[0]]) {
      let l = this._exportDecls[e[0]];
      n.isVariableDeclarator(l) && (l.init = A([], i));
    } 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 l = A(r, i), p = n.exportNamedDeclaration(
          n.variableDeclaration("const", [n.variableDeclarator(n.identifier(t), l)])
        );
        this._exports[t] = l, 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 i = this.getFieldNode(e);
    if (i)
      return this._getPresetValue(i, "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 i = this.getFieldNode(e);
    if (!i)
      return;
    let t = [];
    return n.isArrayExpression(i) && i.elements.forEach((r) => {
      t.push(this._getPresetValue(r, "name"));
    }), t;
  }
  _getPnpWrappedValue(e) {
    if (n.isCallExpression(e)) {
      let i = e.arguments[0];
      if (n.isStringLiteral(i))
        return i.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, i) {
    let t;
    if (n.isStringLiteral(e) ? t = e.value : n.isObjectExpression(e) ? e.properties.forEach((r) => {
      n.isObjectProperty(r) && n.isIdentifier(r.key) && r.key.name === i && (n.isStringLiteral(r.value) ? t = r.value.value : t = this._getPnpWrappedValue(r.value)), n.isObjectProperty(r) && n.isStringLiteral(r.key) && r.key.value === "name" && n.isStringLiteral(r.value) && (t = r.value.value);
    }) : n.isCallExpression(e) && (t = this._getPnpWrappedValue(e)), !t)
      throw new Error(
        `The given node must be a string literal or an object expression with a "${i}" property that is a string literal.`
      );
    return t;
  }
  removeField(e) {
    let i = /* @__PURE__ */ f((r, o) => {
      let a = r.findIndex(
        (l) => n.isIdentifier(l.key) && l.key.name === o || n.isStringLiteral(l.key) && l.key.value === o
      );
      a >= 0 && r.splice(a, 1);
    }, "removeProperty");
    if (e.length === 1) {
      let r = !1;
      if (this._ast.program.body.forEach((o) => {
        if (n.isExportNamedDeclaration(o) && n.isVariableDeclaration(o.declaration)) {
          let a = o.declaration.declarations[0];
          n.isIdentifier(a.id) && a.id.name === e[0] && (this._ast.program.body.splice(this._ast.program.body.indexOf(o), 1), r = !0);
        }
        if (n.isExportDefaultDeclaration(o)) {
          let a = o.declaration;
          if (n.isIdentifier(a) && (a = v(a.name, this._ast.program)), a = W(a), n.isObjectExpression(a)) {
            let l = a.properties;
            i(l, e[0]), r = !0;
          }
        }
        if (n.isExpressionStatement(o) && n.isAssignmentExpression(o.expression) && n.isMemberExpression(o.expression.left) && n.isIdentifier(o.expression.left.object) && o.expression.left.object.name === "module" && n.isIdentifier(o.expression.left.property) && o.expression.left.property.name === "exports" && n.isObjectExpression(o.expression.right)) {
          let a = o.expression.right.properties;
          i(a, e[0]), r = !0;
        }
      }), r)
        return;
    }
    let t = this.getFieldProperties(e);
    if (t) {
      let r = e.at(-1);
      i(t, r);
    }
  }
  appendValueToArray(e, i) {
    let t = this.valueToNode(i);
    t && this.appendNodeToArray(e, t);
  }
  appendNodeToArray(e, i) {
    let t = this.getFieldNode(e);
    if (!t)
      this.setFieldNode(e, n.arrayExpression([i]));
    else if (n.isArrayExpression(t))
      t.elements.push(i);
    else
      throw new Error(`Expected array at '${e.join(".")}', got '${t.type}'`);
  }
  /**
   * Specialized helper to remove addons or other array entries that can either be strings or
   * objects with a name property.
   */
  removeEntryFromArray(e, i) {
    let t = this.getFieldNode(e);
    if (t)
      if (n.isArrayExpression(t)) {
        let r = t.elements.findIndex((o) => n.isStringLiteral(o) ? o.value === i : n.isObjectExpression(o) ? this._getPresetValue(o, "name") === i : this._getPnpWrappedValue(o) === i);
        if (r >= 0)
          t.elements.splice(r, 1);
        else
          throw new Error(`Could not find '${i}' in array at '${e.join(".")}'`);
      } else
        throw new Error(`Expected array at '${e.join(".")}', got '${t.type}'`);
  }
  _inferQuotes() {
    if (!this._quotes) {
      let e = (this._ast.tokens || []).slice(0, 500).reduce(
        (i, t) => (t.type.label === "string" && (i[this._code[t.start]] += 1), i),
        { "'": 0, '"': 0 }
      );
      this._quotes = e["'"] > e['"'] ? "single" : "double";
    }
    return this._quotes;
  }
  valueToNode(e) {
    let i = this._inferQuotes(), t;
    if (i === "single") {
      let { code: r } = fe(n.valueToNode(e), { jsescOption: { quotes: i } }), o = me(`const __x = ${r}`);
      de(o, {
        VariableDeclaration: {
          enter({ node: a }) {
            a.declarations.length === 1 && n.isVariableDeclarator(a.declarations[0]) && n.isIdentifier(a.declarations[0].id) && a.declarations[0].id.name === "__x" && (t = a.declarations[0].init);
          }
        }
      });
    } else
      t = n.valueToNode(e);
    return t;
  }
  setFieldValue(e, i) {
    let t = this.valueToNode(i);
    if (!t)
      throw new Error(`Unexpected value ${JSON.stringify(i)}`);
    this.setFieldNode(e, t);
  }
  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, i) {
    let t = this._ast.program.body.find((a) => {
      let l = n.isVariableDeclaration(a) && a.declarations.length === 1 && n.isVariableDeclarator(a.declarations[0]) && n.isCallExpression(a.declarations[0].init) && n.isIdentifier(a.declarations[0].init.callee) && a.declarations[0].init.callee.name === "require" && n.isStringLiteral(a.declarations[0].init.arguments[0]) && (a.declarations[0].init.arguments[0].value === i || a.declarations[0].init.arguments[0].value === i.split("node:")[1]);
      return l && (i = a.declarations[0].init.arguments[0].value), l;
    }), r = /* @__PURE__ */ f((a) => n.isObjectPattern(t?.declarations[0].id) && t?.declarations[0].id.properties.find(
      (l) => n.isObjectProperty(l) && n.isIdentifier(l.key) && l.key.name === a
    ), "hasRequireSpecifier"), o = /* @__PURE__ */ f((a, l) => a.declarations.length === 1 && n.isVariableDeclarator(a.declarations[0]) && n.isIdentifier(a.declarations[0].id) && a.declarations[0].id.name === l, "hasDefaultRequireSpecifier");
    if (typeof e == "string") {
      let a = /* @__PURE__ */ f(() => {
        this._ast.program.body.unshift(
          n.variableDeclaration("const", [
            n.variableDeclarator(
              n.identifier(e),
              n.callExpression(n.identifier("require"), [n.stringLiteral(i)])
            )
          ])
        );
      }, "addDefaultRequireSpecifier");
      t && o(t, e) || a();
    } else t ? e.forEach((a) => {
      r(a) || t.declarations[0].id.properties.push(
        n.objectProperty(n.identifier(a), n.identifier(a), void 0, !0)
      );
    }) : this._ast.program.body.unshift(
      n.variableDeclaration("const", [
        n.variableDeclarator(
          n.objectPattern(
            e.map(
              (a) => n.objectProperty(n.identifier(a), n.identifier(a), void 0, !0)
            )
          ),
          n.callExpression(n.identifier("require"), [n.stringLiteral(i)])
        )
      ])
    );
  }
  /**
   * 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, i) {
    let t = this._ast.program.body.find((p) => {
      let m = n.isImportDeclaration(p) && (p.source.value === i || p.source.value === i.split("node:")[1]);
      return m && (i = p.source.value), m;
    }), r = /* @__PURE__ */ f((p) => n.importSpecifier(n.identifier(p), n.identifier(p)), "getNewImportSpecifier"), o = /* @__PURE__ */ f((p, m) => p.specifiers.find(
      (g) => n.isImportSpecifier(g) && n.isIdentifier(g.imported) && g.imported.name === m
    ), "hasImportSpecifier"), a = /* @__PURE__ */ f((p, m) => p.specifiers.find(
      (g) => n.isImportNamespaceSpecifier(g) && n.isIdentifier(g.local) && g.local.name === m
    ), "hasNamespaceImportSpecifier");
    e === null ? t || this._ast.program.body.unshift(n.importDeclaration([], n.stringLiteral(i))) : typeof e == "string" ? t ? (/* @__PURE__ */ f((p, m) => p.specifiers.find(
      (g) => n.isImportDefaultSpecifier(g) && n.isIdentifier(g.local) && g.local.name === m
    ), "hasDefaultImportSpecifier"))(t, e) || t.specifiers.push(
      n.importDefaultSpecifier(n.identifier(e))
    ) : this._ast.program.body.unshift(
      n.importDeclaration(
        [n.importDefaultSpecifier(n.identifier(e))],
        n.stringLiteral(i)
      )
    ) : Array.isArray(e) ? t ? e.forEach((p) => {
      o(t, p) || t.specifiers.push(r(p));
    }) : this._ast.program.body.unshift(
      n.importDeclaration(
        e.map(r),
        n.stringLiteral(i)
      )
    ) : e.namespace && (t ? a(t, e.namespace) || t.specifiers.push(
      n.importNamespaceSpecifier(n.identifier(e.namespace))
    ) : this._ast.program.body.unshift(
      n.importDeclaration(
        [n.importNamespaceSpecifier(n.identifier(e.namespace))],
        n.stringLiteral(i)
      )
    ));
  }
}, Je = /* @__PURE__ */ f((s, e) => {
  let i = me(s);
  return new H(i, s, e);
}, "loadConfig"), Qe = /* @__PURE__ */ f((s) => He(s).code, "formatConfig"), He = /* @__PURE__ */ f((s, e = {}) => Ke.print(s._ast, e), "printConfig"), Dt = /* @__PURE__ */ f(async (s) => {
  let e = (await ze(s, "utf-8")).toString();
  return Je(e, s).parse();
}, "readConfig"), It = /* @__PURE__ */ f(async (s, e) => {
  let i = e || s.fileName;
  if (!i)
    throw new Error("Please specify a fileName for writeConfig");
  await Xe(i, Qe(s));
}, "writeConfig"), Nt = /* @__PURE__ */ f((s) => !!s._ast.program.body.find((i) => n.isImportDeclaration(i) && i.source.value.includes("@storybook") && i.specifiers.some((t) => n.isImportSpecifier(t) && n.isIdentifier(t.imported) && t.imported.name === "definePreview")), "isCsfFactoryPreview");

// src/csf-tools/getStorySortParameter.ts
var Ee = L(M(), 1);
import { babelParse as Ye, generate as ye, types as b, traverse as Ze } from "storybook/internal/babel";
import { logger as et } from "storybook/internal/node-logger";
var Y = /* @__PURE__ */ f((s, e) => {
  let i;
  return s.properties.forEach((t) => {
    b.isIdentifier(t.key) && t.key.name === e && (i = t.value);
  }), i;
}, "getValue"), Z = /* @__PURE__ */ f((s) => {
  let e = $(s);
  if (b.isArrayExpression(e))
    return e.elements.map((i) => Z(i));
  if (b.isObjectExpression(e))
    return e.properties.reduce((i, t) => (b.isIdentifier(t.key) && (i[t.key.name] = Z(t.value)), i), {});
  if (b.isLiteral(e))
    return e.value;
  if (b.isIdentifier(e))
    return F(e.name, !0);
  throw new Error(`Unknown node type ${e.type}`);
}, "parseValue"), F = /* @__PURE__ */ f((s, e) => {
  let i = Ee.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(i);
  et.log(i);
}, "unsupported"), $ = /* @__PURE__ */ f((s) => b.isTSAsExpression(s) || b.isTSSatisfiesExpression(s) ? s.expression : s, "stripTSModifiers"), he = /* @__PURE__ */ f((s) => {
  let e = $(s);
  if (b.isObjectExpression(e)) {
    let i = Y(e, "options");
    if (i) {
      if (b.isObjectExpression(i))
        return Y(i, "storySort");
      F("options", !0);
    }
  }
}, "parseParameters"), be = /* @__PURE__ */ f((s, e) => {
  let i = $(s);
  if (b.isObjectExpression(i)) {
    let t = Y(i, "parameters");
    if (b.isIdentifier(t) && (t = P(t.name, e)), t)
      return he(t);
  } else
    F("default", !0);
}, "parseDefault"), kt = /* @__PURE__ */ f((s) => {
  if (!s.includes("storySort"))
    return;
  let e, i = Ye(s);
  if (Ze(i, {
    ExportNamedDeclaration: {
      enter({ node: t }) {
        b.isVariableDeclaration(t.declaration) ? t.declaration.declarations.forEach((r) => {
          if (b.isVariableDeclarator(r) && b.isIdentifier(r.id)) {
            let { name: o } = r.id;
            if (o === "parameters" && r.init) {
              let a = $(r.init);
              e = he(a);
            }
          }
        }) : t.specifiers.forEach((r) => {
          b.isIdentifier(r.exported) && r.exported.name === "parameters" && F("parameters", !1);
        });
      }
    },
    ExportDefaultDeclaration: {
      enter({ node: t }) {
        let r = t.declaration;
        b.isIdentifier(r) && (r = P(r.name, i.program)), r = $(r), b.isCallExpression(r) && b.isObjectExpression(r.arguments?.[0]) ? e = be(r.arguments[0], i.program) : b.isObjectExpression(r) ? e = be(r, i.program) : F("default", !1);
      }
    }
  }), !!e) {
    if (b.isArrowFunctionExpression(e)) {
      let { code: t } = ye(e, {});
      return (0, eval)(t);
    }
    if (b.isFunctionExpression(e)) {
      let { code: t } = ye(e, {}), r = e.id?.name, o = `(a, b) => {
      ${t};
      return ${r}(a, b)
    }`;
      return (0, eval)(o);
    }
    return b.isLiteral(e) || b.isArrayExpression(e) || b.isObjectExpression(e) ? Z(e) : F("storySort", !0);
  }
}, "getStorySortParameter");

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

// src/csf-tools/index.ts
import { babelParse as er } from "storybook/internal/babel";

// src/csf-tools/vitest-plugin/transformer.ts
var ee = L(M(), 1);
import { types as d } from "storybook/internal/babel";
import { getStoryTitle as nt } from "storybook/internal/common";
import { combineTags as ot } from "storybook/internal/csf";
import { logger as Se } from "storybook/internal/node-logger";
var at = /* @__PURE__ */ f((s, e) => !(e.include.length && !e.include.some((i) => s?.includes(i)) || e.exclude.some((i) => s?.includes(i))), "isValidTest");
async function lt({
  code: s,
  fileName: e,
  configDir: i,
  stories: t,
  tagsFilter: r,
  previewLevelTags: o = []
}) {
  if (!/\.stor(y|ies)\./.test(e))
    return s;
  let l = K(s, {
    fileName: e,
    transformInlineMeta: !0,
    makeTitle: /* @__PURE__ */ f((_) => {
      let S = nt({
        storyFilePath: e,
        configDir: i,
        stories: t,
        userTitle: _
      }) || "unknown";
      return S === "unknown" && Se.warn(
        ee.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 "${i}".
          `
      ), S;
    }, "makeTitle")
  }).parse(), p = l._ast, m = l._metaVariableName, g = l._metaNode, x = g.properties.find(
    (_) => d.isObjectProperty(_) && d.isIdentifier(_.key) && _.key.name === "title"
  ), E = d.stringLiteral(l._meta?.title || "unknown");
  if (x ? d.isObjectProperty(x) && (x.value = E) : g.properties.push(d.objectProperty(d.identifier("title"), E)), !g || !l._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 file an issue with details about your use case.`
    );
  let y = {};
  Object.keys(l._stories).map((_) => {
    let S = ot(
      "test",
      "dev",
      ...o,
      ...l.meta?.tags || [],
      ...l._stories[_].tags || []
    );
    at(S, r) && (y[_] = l._storyStatements[_]);
  });
  let h = l._file.path.scope.generateUidIdentifier("test"), I = l._file.path.scope.generateUidIdentifier("describe");
  if (Object.keys(y).length === 0) {
    let _ = d.expressionStatement(
      d.callExpression(d.memberExpression(I, d.identifier("skip")), [
        d.stringLiteral("No valid tests found")
      ])
    );
    p.program.body.push(_);
    let S = [
      d.importDeclaration(
        [
          d.importSpecifier(h, d.identifier("test")),
          d.importSpecifier(I, d.identifier("describe"))
        ],
        d.stringLiteral("vitest")
      )
    ];
    p.program.body.unshift(...S);
  } else {
    let te = function() {
      let j = l._file.path.scope.generateUidIdentifier("isRunningFromThisFile"), N = d.memberExpression(
        d.callExpression(d.memberExpression(_, d.identifier("getState")), []),
        d.identifier("testPath")
      ), C = d.memberExpression(
        d.memberExpression(d.identifier("globalThis"), d.identifier("__vitest_worker__")),
        d.identifier("filepath")
      ), T = d.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)
        C,
        N
      ), R = d.callExpression(
        d.memberExpression(
          d.callExpression(d.identifier("convertToFilePath"), [
            d.memberExpression(
              d.memberExpression(d.identifier("import"), d.identifier("meta")),
              d.identifier("url")
            )
          ]),
          d.identifier("includes")
        ),
        [T]
      );
      return { isRunningFromThisFileDeclaration: d.variableDeclaration("const", [
        d.variableDeclarator(j, R)
      ]), isRunningFromThisFileId: j };
    };
    var ct = te;
    f(te, "getTestGuardDeclaration");
    let _ = l._file.path.scope.generateUidIdentifier("expect"), S = l._file.path.scope.generateUidIdentifier("testStory"), Pe = d.identifier(JSON.stringify(r.skip)), { isRunningFromThisFileDeclaration: Oe, isRunningFromThisFileId: De } = te();
    p.program.body.push(Oe);
    let Ie = /* @__PURE__ */ f(({
      localName: j,
      exportName: N,
      testTitle: C,
      node: T
    }) => {
      let R = d.expressionStatement(
        d.callExpression(h, [
          d.stringLiteral(C),
          d.callExpression(S, [
            d.stringLiteral(N),
            d.identifier(j),
            d.identifier(m),
            Pe
          ])
        ])
      );
      return R.loc = T.loc, R;
    }, "getTestStatementForStory"), Ne = Object.entries(y).map(([j, N]) => {
      if (N === null) {
        Se.warn(
          ee.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 C = l._stories[j].localName ?? j, T = l._stories[j].name ?? j;
      return Ie({ testTitle: T, localName: C, exportName: j, node: N });
    }).filter((j) => !!j), ve = d.ifStatement(De, d.blockStatement(Ne));
    p.program.body.push(ve);
    let we = [
      d.importDeclaration(
        [
          d.importSpecifier(h, d.identifier("test")),
          d.importSpecifier(_, d.identifier("expect"))
        ],
        d.stringLiteral("vitest")
      ),
      d.importDeclaration(
        [
          d.importSpecifier(S, d.identifier("testStory")),
          d.importSpecifier(d.identifier("convertToFilePath"), d.identifier("convertToFilePath"))
        ],
        d.stringLiteral("@storybook/addon-vitest/internal/test-utils")
      )
    ];
    p.program.body.unshift(...we);
  }
  return pe(l, { sourceMaps: !0, sourceFileName: e }, s);
}
f(lt, "vitestTransform");

export {
  Re as a,
  Me as b,
  U as c,
  z as d,
  q as e,
  B as f,
  X as g,
  We as h,
  K as i,
  pe as j,
  Ge as k,
  Et as l,
  ht as m,
  H as n,
  Je as o,
  Qe as p,
  He as q,
  Dt as r,
  It as s,
  Nt as t,
  kt as u,
  rt as v,
  it as w,
  Rt as x,
  st as y,
  je as z,
  lt as A,
  er as B
};
