import ESM_COMPAT_Module from "node:module";
import { fileURLToPath as ESM_COMPAT_fileURLToPath } from 'node:url';
import { dirname as ESM_COMPAT_dirname } from 'node:path';
const __filename = ESM_COMPAT_fileURLToPath(import.meta.url);
const __dirname = ESM_COMPAT_dirname(__filename);
const require = ESM_COMPAT_Module.createRequire(import.meta.url);
var ke = Object.create;
var X = Object.defineProperty;
var Ve = Object.getOwnPropertyDescriptor;
var Ae = Object.getOwnPropertyNames;
var $e = Object.getPrototypeOf, Re = Object.prototype.hasOwnProperty;
var f = (s, e) => X(s, "name", { value: e, configurable: !0 });
var Le = (s, e) => () => (e || s((e = { exports: {} }).exports, e), e.exports);
var Me = (s, e, i, t) => {
  if (e && typeof e == "object" || typeof e == "function")
    for (let r of Ae(e))
      !Re.call(s, r) && r !== i && X(s, r, { get: () => e[r], enumerable: !(t = Ve(e, r)) || t.enumerable });
  return s;
};
var U = (s, e, i) => (i = s != null ? ke($e(s)) : {}, Me(
  // 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 ? X(i, "default", { value: s, enumerable: !0 }) : i,
  s
));

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

// src/csf-tools/CsfFile.ts
var P = U(V(), 1);
import { readFile as Ue, writeFile as qe } from "node:fs/promises";
import {
  BabelFileClass as Be,
  babelParse as fe,
  generate as We,
  recast as de,
  types as c,
  traverse as Ge
} from "storybook/internal/babel";
import { isExportStory as ne, storyNameFromExport as oe, toId as ze } from "storybook/internal/csf";

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

// src/csf-tools/CsfFile.ts
var ae = console, Xe = /\/preview(.(js|jsx|mjs|ts|tsx))?$/, Ke = /* @__PURE__ */ f((s) => Xe.test(s), "isValidPreviewPath");
function Je(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(Je, "parseIncludeExclude");
function le(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(le, "parseTags");
var I = /* @__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"), Qe = /* @__PURE__ */ f((s) => Ze.test(s), "isModuleMock"), ce = /* @__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 l = r.object.name, a = O(l, e);
      a && (i._templates[l] = a, t = a);
    }
  }
  return c.isArrowFunctionExpression(t) || c.isFunctionDeclaration(t) ? t.params.length > 0 : !1;
}, "isArgsStory"), He = /* @__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"), pe = /* @__PURE__ */ f((s, e) => e.reduce(
  (i, t) => {
    let r = s[t];
    return r && (i[t] = r), i;
  },
  {}
), "sortExports"), Ye = /* @__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"), Ze = /^[.\/#].*\.mock($|\.[^.]*$)/i, q = class extends Error {
  static {
    f(this, "NoMetaError");
  }
  constructor(e, i, t) {
    let r = "".trim();
    super(P.dedent`
      CSF: ${e} ${I(i, t)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, K = class extends Error {
  static {
    f(this, "MultipleMetaError");
  }
  constructor(e, i, t) {
    let r = `${e} ${I(i, t)}`.trim();
    super(P.dedent`
      CSF: ${e} ${I(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, "MixedFactoryError");
  }
  constructor(e, i, t) {
    let r = `${e} ${I(i, t)}`.trim();
    super(P.dedent`
      CSF: ${e} ${I(i, t)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, W = class extends Error {
  static {
    f(this, "BadMetaError");
  }
  constructor(e, i, t) {
    let r = "".trim();
    super(P.dedent`
      CSF: ${e} ${I(i, t)}
      
      More info: https://storybook.js.org/docs/writing-stories#default-export
    `), this.name = this.constructor.name;
  }
}, J = 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) ? O(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(P.dedent`
      CSF: unexpected dynamic title ${I(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 K("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] = Je(r.value);
        else if (r.key.name === "component") {
          let o = r.value;
          if (c.isIdentifier(o)) {
            let a = o.name, p = i.body.find(
              (d) => c.isImportDeclaration(d) && d.specifiers.find((g) => g.local.name === a)
            );
            if (p) {
              let { source: d } = p;
              c.isStringLiteral(d) && (this._rawComponentPath = d.value);
            }
          }
          let { code: l } = de.print(r.value, {});
          t.component = l;
        } else if (r.key.name === "tags") {
          let o = r.value;
          c.isIdentifier(o) && (o = O(o.name, this._ast.program)), t.tags = le(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 (Ge(this._ast, {
      ExportDefaultDeclaration: {
        enter(t) {
          let { node: r, parent: o } = t, l = c.isIdentifier(r.declaration) && c.isProgram(o);
          if (e._options.transformInlineMeta && !l && c.isExpression(r.declaration)) {
            let d = t.scope.generateUidIdentifier("meta");
            e._metaVariableName = d.name;
            let g = [
              c.variableDeclaration("const", [c.variableDeclarator(d, r.declaration)]),
              c.exportDefaultDeclaration(d)
            ];
            g.forEach((x) => x.loc = t.node.loc), t.replaceWithMultiple(g);
            return;
          }
          let a, p;
          if (l) {
            let d = r.declaration.name;
            e._metaVariableName = d;
            let g = /* @__PURE__ */ f((x) => c.isIdentifier(x.id) && x.id.name === d, "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) ? a = p : (
            // export default { ... } as Meta<...>
            (c.isTSAsExpression(p) || c.isTSSatisfiesExpression(p)) && c.isObjectExpression(p.expression) && (a = p.expression)
          ), a && c.isProgram(o) && e._parseMeta(a, o), e._metaStatement && !e._metaNode)
            throw new q(
              "default export must be an object",
              e._metaStatement,
              e._options.fileName
            );
          e._metaPath = t;
        }
      },
      ExportNamedDeclaration: {
        enter(t) {
          let { node: r, parent: o } = t, l;
          c.isVariableDeclaration(r.declaration) ? l = r.declaration.declarations.filter((a) => c.isVariableDeclarator(a)) : c.isFunctionDeclaration(
          r.declaration) && (l = [r.declaration]), l ? l.forEach((a) => {
            if (c.isIdentifier(a.id)) {
              let p = !1, { name: d } = a.id;
              if (d === "__namedExportsOrder" && c.isVariableDeclarator(a)) {
                e._namedExportsOrder = He(a.init);
                return;
              }
              e._storyExports[d] = a, e._storyPaths[d] = t, e._storyStatements[d] = r;
              let g = oe(d);
              e._storyAnnotations[d] ? ae.warn(
                `Unexpected annotations for "${d}" before story declaration`
              ) : e._storyAnnotations[d] = {};
              let x;
              if (c.isVariableDeclarator(a) ? x = c.isTSAsExpression(a.init) || c.isTSSatisfiesExpression(a.init) ? a.init.expression : a.init :
              x = a, c.isCallExpression(x) && c.isMemberExpression(x.callee) && c.isIdentifier(x.callee.property) && x.callee.property.name ===
              "story" && (p = !0, x = x.arguments[0]), e._metaIsFactory && !p)
                throw new B(
                  "expected factory story",
                  x,
                  e._options.fileName
                );
              if (!e._metaIsFactory && p)
                throw e._metaNode ? new B(
                  "expected non-factory story",
                  x,
                  e._options.fileName
                ) : new W(
                  "meta() factory must be imported from .storybook/preview configuration",
                  x,
                  e._options.fileName
                );
              let b = {};
              c.isObjectExpression(x) ? (b.__isArgsStory = !0, x.properties.forEach((y) => {
                if (c.isIdentifier(y.key)) {
                  if (y.key.name === "render")
                    b.__isArgsStory = ce(
                      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))
                    ae.warn(
                      `Unexpected usage of "storyName" in "${d}". Please use "name" instead.`
                    );
                  else if (y.key.name === "parameters" && c.isObjectExpression(y.value)) {
                    let h = y.value.properties.find(
                      (D) => c.isObjectProperty(D) && c.isIdentifier(D.key) && D.key.name === "__id"
                    );
                    h && (b.__id = h.value.value);
                  }
                  e._storyAnnotations[d][y.key.name] = y.value;
                }
              })) : b.__isArgsStory = ce(x, o, e), e._stories[d] = {
                id: "FIXME",
                name: g,
                parameters: b,
                __stats: {
                  factory: p
                }
              };
            }
          }) : r.specifiers.length > 0 && r.specifiers.forEach((a) => {
            if (c.isExportSpecifier(a) && c.isIdentifier(a.exported)) {
              let { name: p } = a.exported, { name: d } = a.local, g = c.isProgram(o) ? O(a.local.name, o) : a.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
                e._storyAnnotations[p] = {}, e._storyStatements[p] = g, e._storyPaths[p] = t, e._stories[p] = {
                  id: "FIXME",
                  name: p,
                  localName: d,
                  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 l = o.left.object.name, a = o.left.property.name, p = o.right;
            if (e._storyAnnotations[l] && (a === "story" && c.isObjectExpression(p) ? p.properties.forEach((d) => {
              c.isIdentifier(d.key) && (e._storyAnnotations[l][d.key.name] = d.value);
            }) : e._storyAnnotations[l][a] = p), a === "storyName" && c.isStringLiteral(p)) {
              let d = p.value, g = e._stories[l];
              if (!g)
                return;
              g.name = d;
            }
          }
        }
      },
      CallExpression: {
        enter(t) {
          let { node: r } = t, { callee: o } = r;
          if (c.isIdentifier(o) && o.name === "storiesOf")
            throw new Error(P.dedent`
              Unexpected \`storiesOf\` usage: ${I(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 a = t.scope.getBinding(o.object.name)?.path?.parentPath?.node;
            if (c.isImportDeclaration(a))
              if (Ke(a.source.value)) {
                let p = r.arguments[0];
                e._metaVariableName = o.property.name, e._metaIsFactory = !0, e._parseMeta(p, e._ast.program);
              } else
                throw new W(
                  "meta() factory must be imported from .storybook/preview configuration",
                  a,
                  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 q("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 (!ne(r, e._meta))
          return t;
        let l = o.parameters?.__id ?? ze(e._meta?.id || e._meta?.title, oe(r)), a = { ...o.parameters, __id: l }, { includeStories: p } = e.
        _meta || {};
        r === "__page" && (i.length === 1 || Array.isArray(p) && p.length === 1) && (a.docsOnly = !0), t[r] = { ...o, id: l, parameters: a };
        let d = e._storyAnnotations[r], { tags: g, play: x } = d;
        if (g) {
          let h = c.isIdentifier(g) ? O(g.name, this._ast.program) : g;
          t[r].tags = le(h);
        }
        x && (t[r].tags = [...t[r].tags || [], "play-fn"]);
        let b = t[r].__stats;
        ["play", "render", "loaders", "beforeEach", "globals", "tags"].forEach((h) => {
          b[h] = !!d[h] || !!e._metaAnnotations[h];
        });
        let y = e.getStoryExport(r);
        return b.storyFn = !!(c.isArrowFunctionExpression(y) || c.isFunctionDeclaration(y)), b.mount = Ye(d.play ?? e._metaAnnotations.play),
        b.moduleMock = !!e.imports.find((h) => Qe(h)), t;
      },
      {}
    ), Object.keys(e._storyExports).forEach((t) => {
      ne(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 = pe(e._storyExports, e._namedExportsOrder), e._stories = pe(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(
        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(([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
      };
    });
  }
}, et = /* @__PURE__ */ f(({
  code: s,
  filename: e = "",
  ast: i
}) => new Be({ filename: e }, { code: s, ast: i ?? fe(s) }), "babelParseFile"), Q = /* @__PURE__ */ f((s, e) => {
  let i = fe(s), t = et({ code: s, filename: e.fileName, ast: i });
  return new J(i, e, t);
}, "loadCsf"), me = /* @__PURE__ */ f((s, e = { sourceMaps: !1 }, i) => {
  let t = We(s._ast, e, i);
  return e.sourceMaps ? t : t.code;
}, "formatCsf"), tt = /* @__PURE__ */ f((s, e = {}) => de.print(s._ast, e), "printCsf"), Ft = /* @__PURE__ */ f(async (s, e) => {
  let i = (await Ue(s, "utf-8")).toString();
  return Q(i, { ...e, fileName: s });
}, "readCsf"), Ct = /* @__PURE__ */ f(async (s, e) => {
  if (!(e || s._options.fileName))
    throw new Error("Please specify a fileName for writeCsf");
  await qe(e, tt(s).code);
}, "writeCsf");

// src/csf-tools/ConfigFile.ts
var ye = U(V(), 1);
import { readFile as rt, writeFile as it } from "node:fs/promises";
import {
  babelParse as xe,
  generate as ue,
  recast as st,
  types as n,
  traverse as ge
} from "storybook/internal/babel";
var H = console, Y = /* @__PURE__ */ f(({
  expectedType: s,
  foundType: e,
  node: i
}) => ye.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"), G = /* @__PURE__ */ f((s) => n.isTSAsExpression(s) || n.isTSSatisfiesExpression(s) ? G(s.expression) : s, "unwrap"), be = /* @__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 be(t, r.value);
  }
}, "_getPath"), Ee = /* @__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 : Ee(t, r.value);
  }
}, "_getPathProperties"), z = /* @__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"), N = /* @__PURE__ */ f((s, e) => z(s, e)?.init, "_findVarInitialization"), R = /* @__PURE__ */ f((s, e) => {
  if (s.length === 0)
    return e;
  let [i, ...t] = s, r = R(t, e);
  return n.objectExpression([n.objectProperty(n.identifier(i), r)]);
}, "_makeObjectExpression"), $ = /* @__PURE__ */ f((s, e, i) => {
  let [t, ...r] = s, o = i.properties.find(
    (l) => w(l) === t
  );
  o ? n.isObjectExpression(o.value) && r.length > 0 ? $(r, e, o.value) : o.value = R(r, e) : i.properties.push(
    n.objectProperty(n.identifier(t), R(r, e))
  );
}, "_updateExportNode"), Z = 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 = N(r.name, this._ast.program)), this._exports[t] = r;
      }
    });
  }
  parse() {
    let e = this;
    return ge(this._ast, {
      ExportDefaultDeclaration: {
        enter({ node: i, parent: t }) {
          e.hasDefaultExport = !0;
          let r = n.isIdentifier(i.declaration) && n.isProgram(t) ? N(i.declaration.name, t) : i.declaration;
          r = G(r), n.isCallExpression(r) && n.isObjectExpression(r.arguments[0]) && (r = r.arguments[0]), n.isObjectExpression(r) ? e._parseExportsObject(
          r) : H.warn(
            Y({
              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, l = r.init;
                n.isIdentifier(l) && (l = N(l.name, t)), e._exports[o] = l, 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: l } = r.exported, a = z(o, t);
              a && (e._exports[l] = a.init, e._exportDecls[l] = a);
            }
          }) : H.warn(
            Y({
              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 l = o;
              n.isIdentifier(o) && (l = N(o.name, t)), l = G(l), n.isObjectExpression(l) ? (e._exportsObject = l, l.properties.forEach((a) => {
                let p = w(a);
                if (p) {
                  let d = a.value;
                  n.isIdentifier(d) && (d = N(
                    d.name,
                    t
                  )), e._exports[p] = d;
                }
              })) : H.warn(
                Y({
                  expectedType: "ObjectExpression",
                  foundType: l?.type,
                  node: l
                })
              );
            }
          }
        }
      },
      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 be(t, r);
  }
  getFieldProperties(e) {
    let [i, ...t] = e, r = this._exports[i];
    if (r)
      return Ee(t, r);
  }
  getFieldValue(e) {
    let i = this.getFieldNode(e);
    if (i) {
      let { code: t } = ue(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((d) => w(d) === t);
      if (p && n.isIdentifier(p.value)) {
        let d = z(p.value.name, this._ast.program);
        if (d && n.isObjectExpression(d.init)) {
          $(r, i, d.init);
          return;
        }
      }
      $(e, i, this._exportsObject), this._exports[e[0]] = i;
      return;
    }
    if (o && n.isObjectExpression(o) && r.length > 0) {
      $(r, i, o);
      return;
    }
    let l = z(t, this._ast.program);
    if (l && n.isObjectExpression(l.init)) {
      $(r, i, l.init);
      return;
    }
    if (o && r.length === 0 && this._exportDecls[e[0]]) {
      let a = this._exportDecls[e[0]];
      n.isVariableDeclarator(a) && (a.init = R([], 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 a = R(r, i), p = n.exportNamedDeclaration(
          n.variableDeclaration("const", [n.variableDeclarator(n.identifier(t), a)])
        );
        this._exports[t] = 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 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 l = r.findIndex(
        (a) => n.isIdentifier(a.key) && a.key.name === o || n.isStringLiteral(a.key) && a.key.value === o
      );
      l >= 0 && r.splice(l, 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 l = o.declaration.declarations[0];
          n.isIdentifier(l.id) && l.id.name === e[0] && (this._ast.program.body.splice(this._ast.program.body.indexOf(o), 1), r = !0);
        }
        if (n.isExportDefaultDeclaration(o)) {
          let l = o.declaration;
          if (n.isIdentifier(l) && (l = N(l.name, this._ast.program)), l = G(l), n.isObjectExpression(l)) {
            let a = l.properties;
            i(a, 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 l = o.expression.right.properties;
          i(l, 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 } = ue(n.valueToNode(e), { jsescOption: { quotes: i } }), o = xe(`const __x = ${r}`);
      ge(o, {
        VariableDeclaration: {
          enter({ node: l }) {
            l.declarations.length === 1 && n.isVariableDeclarator(l.declarations[0]) && n.isIdentifier(l.declarations[0].id) && l.declarations[0].
            id.name === "__x" && (t = l.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(
      (l) => n.isVariableDeclaration(l) && l.declarations.length === 1 && n.isVariableDeclarator(l.declarations[0]) && n.isCallExpression(l.
      declarations[0].init) && n.isIdentifier(l.declarations[0].init.callee) && l.declarations[0].init.callee.name === "require" && n.isStringLiteral(
      l.declarations[0].init.arguments[0]) && l.declarations[0].init.arguments[0].value === i
    ), r = /* @__PURE__ */ f((l) => n.isObjectPattern(t?.declarations[0].id) && t?.declarations[0].id.properties.find(
      (a) => n.isObjectProperty(a) && n.isIdentifier(a.key) && a.key.name === l
    ), "hasRequireSpecifier"), o = /* @__PURE__ */ f((l, a) => l.declarations.length === 1 && n.isVariableDeclarator(l.declarations[0]) && n.
    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.variableDeclaration("const", [
            n.variableDeclarator(
              n.identifier(e),
              n.callExpression(n.identifier("require"), [n.stringLiteral(i)])
            )
          ])
        );
      }, "addDefaultRequireSpecifier");
      t && o(t, e) || l();
    } else t ? e.forEach((l) => {
      r(l) || t.declarations[0].id.properties.push(
        n.objectProperty(n.identifier(l), n.identifier(l), void 0, !0)
      );
    }) : this._ast.program.body.unshift(
      n.variableDeclaration("const", [
        n.variableDeclarator(
          n.objectPattern(
            e.map(
              (l) => n.objectProperty(n.identifier(l), n.identifier(l), 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 = /* @__PURE__ */ f((p) => n.importSpecifier(n.identifier(p), n.identifier(p)), "getNewImportSpecifier"), r = /* @__PURE__ */ f((p, d) => p.
    specifiers.find(
      (g) => n.isImportSpecifier(g) && n.isIdentifier(g.imported) && g.imported.name === d
    ), "hasImportSpecifier"), o = /* @__PURE__ */ f((p, d) => p.specifiers.find(
      (g) => n.isImportNamespaceSpecifier(g) && n.isIdentifier(g.local) && g.local.name === d
    ), "hasNamespaceImportSpecifier"), l = /* @__PURE__ */ f((p, d) => p.specifiers.find(
      (g) => n.isImportDefaultSpecifier(g) && n.isIdentifier(g.local) && g.local.name === d
    ), "hasDefaultImportSpecifier"), a = this._ast.program.body.find(
      (p) => n.isImportDeclaration(p) && p.source.value === i
    );
    e === null ? a || this._ast.program.body.unshift(n.importDeclaration([], n.stringLiteral(i))) : typeof e == "string" ? a ? l(a, e) || a.
    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) ? a ? e.forEach((p) => {
      r(a, p) || a.specifiers.push(t(p));
    }) : this._ast.program.body.unshift(
      n.importDeclaration(
        e.map(t),
        n.stringLiteral(i)
      )
    ) : e.namespace && (a ? o(a, e.namespace) || a.specifiers.push(
      n.importNamespaceSpecifier(n.identifier(e.namespace))
    ) : this._ast.program.body.unshift(
      n.importDeclaration(
        [n.importNamespaceSpecifier(n.identifier(e.namespace))],
        n.stringLiteral(i)
      )
    ));
  }
}, nt = /* @__PURE__ */ f((s, e) => {
  let i = xe(s);
  return new Z(i, s, e);
}, "loadConfig"), ot = /* @__PURE__ */ f((s) => at(s).code, "formatConfig"), at = /* @__PURE__ */ f((s, e = {}) => st.print(s._ast, e), "pri\
ntConfig"), $t = /* @__PURE__ */ f(async (s) => {
  let e = (await rt(s, "utf-8")).toString();
  return nt(e, s).parse();
}, "readConfig"), Rt = /* @__PURE__ */ f(async (s, e) => {
  let i = e || s.fileName;
  if (!i)
    throw new Error("Please specify a fileName for writeConfig");
  await it(i, ot(s));
}, "writeConfig"), Lt = /* @__PURE__ */ f((s) => !!s._ast.program.body.find((i) => n.isImportDeclaration(i) && i.source.value.includes("@sto\
rybook") && i.specifiers.some((t) => n.isImportSpecifier(t) && n.isIdentifier(t.imported) && t.imported.name === "definePreview")), "isCsfFa\
ctoryPreview");

// src/csf-tools/getStorySortParameter.ts
var je = U(V(), 1);
import { babelParse as lt, generate as he, types as E, traverse as ct } from "storybook/internal/babel";
var pt = console, ee = /* @__PURE__ */ f((s, e) => {
  let i;
  return s.properties.forEach((t) => {
    E.isIdentifier(t.key) && t.key.name === e && (i = t.value);
  }), i;
}, "getValue"), te = /* @__PURE__ */ f((s) => {
  let e = L(s);
  if (E.isArrayExpression(e))
    return e.elements.map((i) => te(i));
  if (E.isObjectExpression(e))
    return e.properties.reduce((i, t) => (E.isIdentifier(t.key) && (i[t.key.name] = te(t.value)), i), {});
  if (E.isLiteral(e))
    return e.value;
  if (E.isIdentifier(e))
    return F(e.name, !0);
  throw new Error(`Unknown node type ${e.type}`);
}, "parseValue"), F = /* @__PURE__ */ f((s, e) => {
  let i = je.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);
  pt.info(i);
}, "unsupported"), L = /* @__PURE__ */ f((s) => E.isTSAsExpression(s) || E.isTSSatisfiesExpression(s) ? s.expression : s, "stripTSModifiers"),
Se = /* @__PURE__ */ f((s) => {
  let e = L(s);
  if (E.isObjectExpression(e)) {
    let i = ee(e, "options");
    if (i) {
      if (E.isObjectExpression(i))
        return ee(i, "storySort");
      F("options", !0);
    }
  }
}, "parseParameters"), _e = /* @__PURE__ */ f((s, e) => {
  let i = L(s);
  if (E.isObjectExpression(i)) {
    let t = ee(i, "parameters");
    if (E.isIdentifier(t) && (t = O(t.name, e)), t)
      return Se(t);
  } else
    F("default", !0);
}, "parseDefault"), Wt = /* @__PURE__ */ f((s) => {
  if (!s.includes("storySort"))
    return;
  let e, i = lt(s);
  if (ct(i, {
    ExportNamedDeclaration: {
      enter({ node: t }) {
        E.isVariableDeclaration(t.declaration) ? t.declaration.declarations.forEach((r) => {
          if (E.isVariableDeclarator(r) && E.isIdentifier(r.id)) {
            let { name: o } = r.id;
            if (o === "parameters" && r.init) {
              let l = L(r.init);
              e = Se(l);
            }
          }
        }) : t.specifiers.forEach((r) => {
          E.isIdentifier(r.exported) && r.exported.name === "parameters" && F("parameters", !1);
        });
      }
    },
    ExportDefaultDeclaration: {
      enter({ node: t }) {
        let r = t.declaration;
        E.isIdentifier(r) && (r = O(r.name, i.program)), r = L(r), E.isCallExpression(r) && E.isObjectExpression(r.arguments?.[0]) ? e = _e(
        r.arguments[0], i.program) : E.isObjectExpression(r) ? e = _e(r, i.program) : F("default", !1);
      }
    }
  }), !!e) {
    if (E.isArrowFunctionExpression(e)) {
      let { code: t } = he(e, {});
      return (0, eval)(t);
    }
    if (E.isFunctionExpression(e)) {
      let { code: t } = he(e, {}), r = e.id?.name, o = `(a, b) => {
      ${t};
      return ${r}(a, b)
    }`;
      return (0, eval)(o);
    }
    return E.isLiteral(e) || E.isArrayExpression(e) || E.isObjectExpression(e) ? te(e) : F("storySort", !0);
  }
}, "getStorySortParameter");

// src/csf-tools/enrichCsf.ts
import { generate as ft, types as u } from "storybook/internal/babel";
var dt = /* @__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", l = !t?.disableSource && ut(r), a = !t?.disableDescription && Pe(e._storyStatements[i]), p = [], d = o ? u.memberExpression(
  u.identifier(i), u.identifier("input")) : u.identifier(i), g = u.memberExpression(d, u.identifier("parameters"));
  p.push(u.spreadElement(g));
  let x = u.optionalMemberExpression(
    g,
    u.identifier("docs"),
    !1,
    !0
  ), b = [];
  if (l) {
    let y = u.optionalMemberExpression(
      x,
      u.identifier("source"),
      !1,
      !0
    );
    b.push(
      u.objectProperty(
        u.identifier("source"),
        u.objectExpression([
          u.objectProperty(u.identifier("originalSource"), u.stringLiteral(l)),
          u.spreadElement(y)
        ])
      )
    );
  }
  if (a) {
    let y = u.optionalMemberExpression(
      x,
      u.identifier("description"),
      !1,
      !0
    );
    b.push(
      u.objectProperty(
        u.identifier("description"),
        u.objectExpression([
          u.objectProperty(u.identifier("story"), u.stringLiteral(a)),
          u.spreadElement(y)
        ])
      )
    );
  }
  if (b.length > 0) {
    p.push(
      u.objectProperty(
        u.identifier("docs"),
        u.objectExpression([u.spreadElement(x), ...b])
      )
    );
    let y = u.expressionStatement(
      u.assignmentExpression("=", g, u.objectExpression(p))
    );
    s._ast.program.body.push(y);
  }
}, "enrichCsfStory"), Oe = /* @__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(
    (a) => u.isObjectProperty(a) && u.isIdentifier(a.key) && a.key.name === t && u.isObjectExpression(a.value)
  ), l;
  o ? l = o.value : (l = u.objectExpression([]), s.properties.push(u.objectProperty(u.identifier(t), l))), Oe(l, r, i);
}, "addComponentDescription"), mt = /* @__PURE__ */ f((s, e, i) => {
  let t = !i?.disableDescription && Pe(e._metaStatement);
  if (t) {
    let r = s._metaNode;
    r && u.isObjectExpression(r) && Oe(
      r,
      ["parameters", "docs", "description"],
      u.objectProperty(u.identifier("component"), u.stringLiteral(t))
    );
  }
}, "enrichCsfMeta"), Kt = /* @__PURE__ */ f((s, e, i) => {
  mt(s, e, i), Object.keys(s._storyExports).forEach((t) => {
    dt(s, e, t, i);
  });
}, "enrichCsf"), ut = /* @__PURE__ */ f((s) => {
  let e = u.isVariableDeclarator(s) ? s.init : s, { code: i } = ft(e, {});
  return i;
}, "extractSource"), Pe = /* @__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 cr } from "storybook/internal/babel";

// src/csf-tools/vitest-plugin/transformer.ts
var re = U(V(), 1);
import { types as m } from "storybook/internal/babel";
import { getStoryTitle as gt } from "storybook/internal/common";
import { combineTags as xt } from "storybook/internal/csf";
var Ie = console, yt = /* @__PURE__ */ f((s, e) => !(e.include.length && !e.include.some((i) => s?.includes(i)) || e.exclude.some((i) => s?.
includes(i))), "isValidTest");
async function bt({
  code: s,
  fileName: e,
  configDir: i,
  stories: t,
  tagsFilter: r,
  previewLevelTags: o = []
}) {
  if (!/\.stor(y|ies)\./.test(e))
    return s;
  let a = Q(s, {
    fileName: e,
    transformInlineMeta: !0,
    makeTitle: /* @__PURE__ */ f((_) => {
      let S = gt({
        storyFilePath: e,
        configDir: i,
        stories: t,
        userTitle: _
      }) || "unknown";
      return S === "unknown" && Ie.warn(
        re.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 = a._ast, d = a._metaVariableName, g = a._metaNode, x = g.properties.find(
    (_) => m.isObjectProperty(_) && m.isIdentifier(_.key) && _.key.name === "title"
  ), b = m.stringLiteral(a._meta?.title || "unknown");
  if (x ? m.isObjectProperty(x) && (x.value = b) : g.properties.push(m.objectProperty(m.identifier("title"), b)), !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 y = {};
  Object.keys(a._stories).map((_) => {
    let S = xt(
      "test",
      "dev",
      ...o,
      ...a.meta?.tags || [],
      ...a._stories[_].tags || []
    );
    yt(S, r) && (y[_] = a._storyStatements[_]);
  });
  let h = a._file.path.scope.generateUidIdentifier("test"), D = a._file.path.scope.generateUidIdentifier("describe");
  if (Object.keys(y).length === 0) {
    let _ = m.expressionStatement(
      m.callExpression(m.memberExpression(D, m.identifier("skip")), [
        m.stringLiteral("No valid tests found")
      ])
    );
    p.program.body.push(_);
    let S = [
      m.importDeclaration(
        [
          m.importSpecifier(h, m.identifier("test")),
          m.importSpecifier(D, m.identifier("describe"))
        ],
        m.stringLiteral("vitest")
      )
    ];
    p.program.body.unshift(...S);
  } else {
    let ie = function() {
      let j = a._file.path.scope.generateUidIdentifier("isRunningFromThisFile"), v = m.memberExpression(
        m.callExpression(m.memberExpression(_, m.identifier("getState")), []),
        m.identifier("testPath")
      ), C = m.memberExpression(
        m.memberExpression(m.identifier("globalThis"), m.identifier("__vitest_worker__")),
        m.identifier("filepath")
      ), T = m.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,
        v
      ), M = m.callExpression(
        m.memberExpression(
          m.memberExpression(
            m.memberExpression(m.identifier("import"), m.identifier("meta")),
            m.identifier("url")
          ),
          m.identifier("includes")
        ),
        [T]
      );
      return { isRunningFromThisFileDeclaration: m.variableDeclaration("const", [
        m.variableDeclarator(j, M)
      ]), isRunningFromThisFileId: j };
    };
    var Et = ie;
    f(ie, "getTestGuardDeclaration");
    let _ = a._file.path.scope.generateUidIdentifier("expect"), S = a._file.path.scope.generateUidIdentifier("testStory"), De = m.identifier(
    JSON.stringify(r.skip)), { isRunningFromThisFileDeclaration: ve, isRunningFromThisFileId: Ne } = ie();
    p.program.body.push(ve);
    let we = /* @__PURE__ */ f(({
      localName: j,
      exportName: v,
      testTitle: C,
      node: T
    }) => {
      let M = m.expressionStatement(
        m.callExpression(h, [
          m.stringLiteral(C),
          m.callExpression(S, [
            m.stringLiteral(v),
            m.identifier(j),
            m.identifier(d),
            De
          ])
        ])
      );
      return M.loc = T.loc, M;
    }, "getTestStatementForStory"), Fe = Object.entries(y).map(([j, v]) => {
      if (v === null) {
        Ie.warn(
          re.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 = a._stories[j].localName ?? j, T = a._stories[j].name ?? j;
      return we({ testTitle: T, localName: C, exportName: j, node: v });
    }).filter((j) => !!j), Ce = m.ifStatement(Ne, m.blockStatement(Fe));
    p.program.body.push(Ce);
    let Te = [
      m.importDeclaration(
        [
          m.importSpecifier(h, m.identifier("test")),
          m.importSpecifier(_, m.identifier("expect"))
        ],
        m.stringLiteral("vitest")
      ),
      m.importDeclaration(
        [m.importSpecifier(S, m.identifier("testStory"))],
        m.stringLiteral("@storybook/addon-vitest/internal/test-utils")
      )
    ];
    p.program.body.unshift(...Te);
  }
  return me(a, { sourceMaps: !0, sourceFileName: e }, s);
}
f(bt, "vitestTransform");
export {
  W as BadMetaError,
  Z as ConfigFile,
  J as CsfFile,
  B as MixedFactoryError,
  K as MultipleMetaError,
  q as NoMetaError,
  cr as babelParse,
  et as babelParseFile,
  Kt as enrichCsf,
  mt as enrichCsfMeta,
  dt as enrichCsfStory,
  Pe as extractDescription,
  ut as extractSource,
  ot as formatConfig,
  me as formatCsf,
  Wt as getStorySortParameter,
  Lt as isCsfFactoryPreview,
  Qe as isModuleMock,
  Ke as isValidPreviewPath,
  nt as loadConfig,
  Q as loadCsf,
  at as printConfig,
  tt as printCsf,
  $t as readConfig,
  Ft as readCsf,
  bt as vitestTransform,
  Rt as writeConfig,
  Ct as writeCsf
};
