@storybook/react 11.0.0-beta.1 → 11.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/_browser-chunks/{chunk-2TQVKMJE.js → chunk-EA5DV32Q.js} +36 -1
  2. package/dist/_browser-chunks/{chunk-6MBKXM7O.js → chunk-U7XUEUFQ.js} +2 -2
  3. package/dist/_browser-chunks/{chunk-LGSTPTL6.js → chunk-WWHCZJWM.js} +10 -9
  4. package/dist/_node-chunks/{chunk-37XDLJI5.js → chunk-2DNUEB5U.js} +18 -17
  5. package/dist/_node-chunks/{chunk-RVHW3VEA.js → chunk-ASUAJQT5.js} +6 -6
  6. package/dist/_node-chunks/{chunk-FCIBS77S.js → chunk-BWU7O3KC.js} +7 -7
  7. package/dist/_node-chunks/{chunk-IYZUDUNZ.js → chunk-DW2HJ23M.js} +7 -7
  8. package/dist/_node-chunks/{chunk-U53ZMSA3.js → chunk-PXKXGEPO.js} +1716 -515
  9. package/dist/_node-chunks/{chunk-YNIH7TZQ.js → chunk-QRCEILHM.js} +8 -8
  10. package/dist/_node-chunks/chunk-TP7UUO2M.js +18 -0
  11. package/dist/_node-chunks/{chunk-GQOGANUK.js → chunk-VQBUQHU3.js} +11 -13
  12. package/dist/_node-chunks/{chunk-PPFRYFMF.js → chunk-XIFLZILW.js} +16 -8
  13. package/dist/_node-chunks/{chunk-FUHORIY7.js → chunk-XQPV7U3R.js} +9 -9
  14. package/dist/_node-chunks/{extractArgTypesFromComponentFile-EQEZZAHL.js → extractArgTypesFromComponentFile-PKEIPQGN.js} +17 -15
  15. package/dist/_node-chunks/{extractReactDocgenInfo-COAPYCG6.js → extractReactDocgenInfo-J6CKNSQN.js} +11 -11
  16. package/dist/_node-chunks/{extractReactTypescriptDocgenInfo-7FFDIBEA.js → extractReactTypescriptDocgenInfo-AJTC3KA3.js} +9 -9
  17. package/dist/_node-chunks/reactDocgen-YAGNM6ZQ.js +26 -0
  18. package/dist/builder-docgen.d.ts +2 -2
  19. package/dist/builder-docgen.js +9 -8
  20. package/dist/docgen/docgen-worker.js +22 -18
  21. package/dist/entry-preview-argtypes.js +1 -1
  22. package/dist/entry-preview-docs.js +1 -1
  23. package/dist/index.js +3 -3
  24. package/dist/preset.js +35 -25
  25. package/dist/preview.js +3 -3
  26. package/package.json +5 -3
  27. package/dist/_node-chunks/reactDocgen-6ZJPM2YE.js +0 -26
@@ -1,14 +1,17 @@
1
- import CJS_COMPAT_NODE_URL_19uq4gz0tcr from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_19uq4gz0tcr from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_19uq4gz0tcr from "node:module";
1
+ import CJS_COMPAT_NODE_URL_0pbco1v5vos from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_0pbco1v5vos from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_0pbco1v5vos from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_19uq4gz0tcr.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_19uq4gz0tcr.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_19uq4gz0tcr.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_0pbco1v5vos.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_0pbco1v5vos.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_0pbco1v5vos.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
+ import {
13
+ REACT_DOCGEN_TYPESCRIPT_APIS
14
+ } from "./chunk-TP7UUO2M.js";
12
15
  import {
13
16
  asyncCache,
14
17
  cached,
@@ -20,11 +23,11 @@ import {
20
23
  groupByToMap,
21
24
  invariant,
22
25
  matchPath
23
- } from "./chunk-IYZUDUNZ.js";
26
+ } from "./chunk-DW2HJ23M.js";
24
27
  import {
25
28
  __commonJS,
26
29
  __toESM
27
- } from "./chunk-RVHW3VEA.js";
30
+ } from "./chunk-ASUAJQT5.js";
28
31
 
29
32
  // ../../../node_modules/@volar/source-map/lib/binarySearch.js
30
33
  var require_binarySearch = __commonJS({
@@ -1571,7 +1574,7 @@ var require_proxyLanguageService = __commonJS({
1571
1574
  };
1572
1575
  }
1573
1576
  function getEncodedSemanticClassifications(language, getEncodedSemanticClassifications2) {
1574
- return (filePath, span, format2) => {
1577
+ return (filePath, span, format3) => {
1575
1578
  let fileName = filePath.replace(windowsPathReg, "/"), [serviceScript, targetScript, sourceScript] = (0, utils_1.getServiceScript)(language, fileName);
1576
1579
  if (targetScript?.associatedOnly)
1577
1580
  return {
@@ -1585,7 +1588,7 @@ var require_proxyLanguageService = __commonJS({
1585
1588
  spans: [],
1586
1589
  endOfLineState: 0
1587
1590
  };
1588
- let mappingOffset = (0, transform_1.getMappingOffset)(language, serviceScript), start = mapped.start + mappingOffset, end = mapped.end + mappingOffset, result = getEncodedSemanticClassifications2(targetScript.id, { start, length: end - start }, format2), spans = [];
1591
+ let mappingOffset = (0, transform_1.getMappingOffset)(language, serviceScript), start = mapped.start + mappingOffset, end = mapped.end + mappingOffset, result = getEncodedSemanticClassifications2(targetScript.id, { start, length: end - start }, format3), spans = [];
1589
1592
  for (let i = 0; i < result.spans.length; i += 3)
1590
1593
  for (let [_, sourceStart, sourceEnd] of (0, transform_1.toSourceRanges)(sourceScript, language, serviceScript, result.spans[i], result.spans[i] + result.spans[i + 1], !1, language_core_1.isSemanticTokensEnabled)) {
1591
1594
  spans.push(sourceStart, sourceEnd - sourceStart, result.spans[i + 2]);
@@ -1593,7 +1596,7 @@ var require_proxyLanguageService = __commonJS({
1593
1596
  }
1594
1597
  return result.spans = spans, result;
1595
1598
  } else
1596
- return getEncodedSemanticClassifications2(fileName, span, format2);
1599
+ return getEncodedSemanticClassifications2(fileName, span, format3);
1597
1600
  };
1598
1601
  }
1599
1602
  function getSyntacticDiagnostics(language, languageService, getSyntacticDiagnostics2) {
@@ -1841,23 +1844,23 @@ var require_path_browserify = __commonJS({
1841
1844
  }
1842
1845
  return res;
1843
1846
  }
1844
- function _format(sep2, pathObject) {
1847
+ function _format(sep3, pathObject) {
1845
1848
  var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || "");
1846
- return dir ? dir === pathObject.root ? dir + base : dir + sep2 + base : base;
1849
+ return dir ? dir === pathObject.root ? dir + base : dir + sep3 + base : base;
1847
1850
  }
1848
- var posix2 = {
1851
+ var posix3 = {
1849
1852
  // path.resolve([from ...], to)
1850
1853
  resolve: function() {
1851
- for (var resolvedPath = "", resolvedAbsolute = !1, cwd2, i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1854
+ for (var resolvedPath = "", resolvedAbsolute = !1, cwd3, i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
1852
1855
  var path2;
1853
- i >= 0 ? path2 = arguments[i] : (cwd2 === void 0 && (cwd2 = process.cwd()), path2 = cwd2), assertPath(path2), path2.length !== 0 && (resolvedPath = path2 + "/" + resolvedPath, resolvedAbsolute = path2.charCodeAt(0) === 47);
1856
+ i >= 0 ? path2 = arguments[i] : (cwd3 === void 0 && (cwd3 = process.cwd()), path2 = cwd3), assertPath(path2), path2.length !== 0 && (resolvedPath = path2 + "/" + resolvedPath, resolvedAbsolute = path2.charCodeAt(0) === 47);
1854
1857
  }
1855
1858
  return resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute ? resolvedPath.length > 0 ? "/" + resolvedPath : "/" : resolvedPath.length > 0 ? resolvedPath : ".";
1856
1859
  },
1857
1860
  normalize: function(path2) {
1858
1861
  if (assertPath(path2), path2.length === 0) return ".";
1859
- var isAbsolute2 = path2.charCodeAt(0) === 47, trailingSeparator = path2.charCodeAt(path2.length - 1) === 47;
1860
- return path2 = normalizeStringPosix(path2, !isAbsolute2), path2.length === 0 && !isAbsolute2 && (path2 = "."), path2.length > 0 && trailingSeparator && (path2 += "/"), isAbsolute2 ? "/" + path2 : path2;
1862
+ var isAbsolute3 = path2.charCodeAt(0) === 47, trailingSeparator = path2.charCodeAt(path2.length - 1) === 47;
1863
+ return path2 = normalizeStringPosix(path2, !isAbsolute3), path2.length === 0 && !isAbsolute3 && (path2 = "."), path2.length > 0 && trailingSeparator && (path2 += "/"), isAbsolute3 ? "/" + path2 : path2;
1861
1864
  },
1862
1865
  isAbsolute: function(path2) {
1863
1866
  return assertPath(path2), path2.length > 0 && path2.charCodeAt(0) === 47;
@@ -1869,10 +1872,10 @@ var require_path_browserify = __commonJS({
1869
1872
  var arg = arguments[i];
1870
1873
  assertPath(arg), arg.length > 0 && (joined === void 0 ? joined = arg : joined += "/" + arg);
1871
1874
  }
1872
- return joined === void 0 ? "." : posix2.normalize(joined);
1875
+ return joined === void 0 ? "." : posix3.normalize(joined);
1873
1876
  },
1874
1877
  relative: function(from, to) {
1875
- if (assertPath(from), assertPath(to), from === to || (from = posix2.resolve(from), to = posix2.resolve(to), from === to)) return "";
1878
+ if (assertPath(from), assertPath(to), from === to || (from = posix3.resolve(from), to = posix3.resolve(to), from === to)) return "";
1876
1879
  for (var fromStart = 1; fromStart < from.length && from.charCodeAt(fromStart) === 47; ++fromStart)
1877
1880
  ;
1878
1881
  for (var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1; toStart < to.length && to.charCodeAt(toStart) === 47; ++toStart)
@@ -1967,8 +1970,8 @@ var require_path_browserify = __commonJS({
1967
1970
  assertPath(path2);
1968
1971
  var ret = { root: "", dir: "", base: "", ext: "", name: "" };
1969
1972
  if (path2.length === 0) return ret;
1970
- var code = path2.charCodeAt(0), isAbsolute2 = code === 47, start;
1971
- isAbsolute2 ? (ret.root = "/", start = 1) : start = 0;
1973
+ var code = path2.charCodeAt(0), isAbsolute3 = code === 47, start;
1974
+ isAbsolute3 ? (ret.root = "/", start = 1) : start = 0;
1972
1975
  for (var startDot = -1, startPart = 0, end = -1, matchedSlash = !0, i = path2.length - 1, preDotState = 0; i >= start; --i) {
1973
1976
  if (code = path2.charCodeAt(i), code === 47) {
1974
1977
  if (!matchedSlash) {
@@ -1981,15 +1984,15 @@ var require_path_browserify = __commonJS({
1981
1984
  }
1982
1985
  return startDot === -1 || end === -1 || // We saw a non-dot character immediately before the dot
1983
1986
  preDotState === 0 || // The (right-most) trimmed path component is exactly '..'
1984
- preDotState === 1 && startDot === end - 1 && startDot === startPart + 1 ? end !== -1 && (startPart === 0 && isAbsolute2 ? ret.base = ret.name = path2.slice(1, end) : ret.base = ret.name = path2.slice(startPart, end)) : (startPart === 0 && isAbsolute2 ? (ret.name = path2.slice(1, startDot), ret.base = path2.slice(1, end)) : (ret.name = path2.slice(startPart, startDot), ret.base = path2.slice(startPart, end)), ret.ext = path2.slice(startDot, end)), startPart > 0 ? ret.dir = path2.slice(0, startPart - 1) : isAbsolute2 && (ret.dir = "/"), ret;
1987
+ preDotState === 1 && startDot === end - 1 && startDot === startPart + 1 ? end !== -1 && (startPart === 0 && isAbsolute3 ? ret.base = ret.name = path2.slice(1, end) : ret.base = ret.name = path2.slice(startPart, end)) : (startPart === 0 && isAbsolute3 ? (ret.name = path2.slice(1, startDot), ret.base = path2.slice(1, end)) : (ret.name = path2.slice(startPart, startDot), ret.base = path2.slice(startPart, end)), ret.ext = path2.slice(startDot, end)), startPart > 0 ? ret.dir = path2.slice(0, startPart - 1) : isAbsolute3 && (ret.dir = "/"), ret;
1985
1988
  },
1986
1989
  sep: "/",
1987
1990
  delimiter: ":",
1988
1991
  win32: null,
1989
1992
  posix: null
1990
1993
  };
1991
- posix2.posix = posix2;
1992
- module.exports = posix2;
1994
+ posix3.posix = posix3;
1995
+ module.exports = posix3;
1993
1996
  }
1994
1997
  });
1995
1998
 
@@ -3325,213 +3328,1315 @@ var require_typescript = __commonJS({
3325
3328
  }
3326
3329
  });
3327
3330
 
3328
- // src/componentManifest/componentMeta/ComponentMetaManager.ts
3331
+ // ../../lib/component-meta-typescript/dist/_node-chunks/chunk-3F3YNNK2.js
3332
+ import CJS_COMPAT_NODE_URL_6lg7c74mo83 from "node:url";
3333
+ import CJS_COMPAT_NODE_PATH_6lg7c74mo83 from "node:path";
3334
+ import CJS_COMPAT_NODE_MODULE_6lg7c74mo83 from "node:module";
3335
+ import { pathToFileURL } from "node:url";
3329
3336
  import {
3330
- ComponentMetaManager as BaseComponentMetaManager,
3331
- parseTsconfigCommandLine
3332
- } from "storybook/internal/component-meta";
3333
- import { logger } from "storybook/internal/node-logger";
3334
-
3335
- // src/componentManifest/componentMeta/ComponentMetaProject.ts
3336
- var import_language_core = __toESM(require_language_core(), 1), import_typescript = __toESM(require_typescript(), 1);
3337
+ getTypeScriptDocgenApi,
3338
+ isModuleNotFoundError,
3339
+ isTypeScriptUsableForDocgen,
3340
+ readTypeScriptPackageForDocgen
3341
+ } from "storybook/internal/common";
3337
3342
  import {
3338
- ProgramBackedProject,
3339
- ProjectFileTracker
3340
- } from "storybook/internal/component-meta";
3341
- import * as path from "path";
3342
-
3343
- // src/componentManifest/componentMeta/componentMetaExtractor.ts
3344
- import { extractComponentJsDocInfo } from "storybook/internal/component-meta";
3345
- var LARGE_SOURCE_THRESHOLD = 30, MAX_UNWRAP_DEPTH = 5, MAX_SERIALIZATION_DEPTH = 5;
3346
- function isLiteralType(type) {
3347
- return type.isStringLiteral() || type.isNumberLiteral();
3348
- }
3349
- function isUnionType(type) {
3350
- return type.isUnion();
3351
- }
3352
- function isWrappedExpression(typescript, expression) {
3353
- return typescript.isParenthesizedExpression(expression) || typescript.isAsExpression(expression) || typescript.isNonNullExpression(expression) || (typescript.isSatisfiesExpression?.(expression) ?? !1);
3354
- }
3355
- function resolveAliasedSymbol(typescript, checker, symbol) {
3356
- return symbol.flags & typescript.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
3357
- }
3358
- function getSymbolContextNode(symbol) {
3359
- return symbol.valueDeclaration ?? symbol.getDeclarations()?.[0];
3360
- }
3361
- function resolveComponentSymbolFromNode(typescript, checker, node) {
3362
- if (!node)
3363
- return;
3364
- let symbol = checker.getSymbolAtLocation(node);
3365
- return symbol ? resolveComponentSymbol(typescript, checker, symbol, node) : void 0;
3366
- }
3367
- function resolveComponentSymbol(typescript, checker, symbol, contextNode, depth = 0) {
3368
- let resolved = resolveAliasedSymbol(typescript, checker, symbol);
3369
- if (depth > MAX_UNWRAP_DEPTH)
3370
- return resolved;
3371
- let declarationForPromotion = getSymbolContextNode(resolved);
3372
- if (declarationForPromotion && (typescript.isArrowFunction(declarationForPromotion) || typescript.isFunctionExpression(declarationForPromotion)) && declarationForPromotion.parent && typescript.isVariableDeclaration(declarationForPromotion.parent) && typescript.isIdentifier(declarationForPromotion.parent.name)) {
3373
- let variableSymbol = checker.getSymbolAtLocation(declarationForPromotion.parent.name);
3374
- variableSymbol && (resolved = resolveAliasedSymbol(typescript, checker, variableSymbol));
3375
- }
3376
- let declaration = getSymbolContextNode(resolved);
3377
- if (declaration) {
3378
- if (typescript.isShorthandPropertyAssignment(declaration)) {
3379
- let valueSymbol = checker.getShorthandAssignmentValueSymbol(declaration);
3380
- if (valueSymbol)
3381
- return resolveComponentSymbol(
3382
- typescript,
3383
- checker,
3384
- valueSymbol,
3385
- declaration.name,
3386
- depth + 1
3387
- );
3388
- }
3389
- if (typescript.isPropertyAssignment(declaration)) {
3390
- let next = resolveComponentSymbolFromNode(typescript, checker, declaration.initializer);
3391
- if (next)
3392
- return next;
3393
- }
3394
- if (typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken) {
3395
- let next = resolveComponentSymbolFromNode(typescript, checker, declaration.right);
3396
- if (next)
3397
- return next;
3398
- }
3399
- }
3400
- let typeSymbol = (!!(resolved.flags & typescript.SymbolFlags.Property) || declaration !== void 0 && (typescript.isPropertyAssignment(declaration) || typescript.isShorthandPropertyAssignment(declaration) || typescript.isPropertySignature(declaration) || typescript.isPropertyDeclaration(declaration) || typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken)) && checker.getTypeOfSymbolAtLocation(resolved, contextNode).getSymbol?.();
3401
- if (typeSymbol) {
3402
- let resolvedTypeSymbol = resolveAliasedSymbol(typescript, checker, typeSymbol), typeDeclaration = getSymbolContextNode(resolvedTypeSymbol);
3403
- if (resolvedTypeSymbol !== resolved && typeDeclaration)
3404
- return resolveComponentSymbol(
3405
- typescript,
3406
- checker,
3407
- resolvedTypeSymbol,
3408
- typeDeclaration,
3409
- depth + 1
3410
- );
3411
- }
3412
- return resolved;
3413
- }
3414
- function findImportSymbolInStoryFile(typescript, checker, storySourceFile, componentRef) {
3415
- let importSpecifier = componentRef.importId, importName = componentRef.importName, memberAccess = componentRef.member;
3416
- if (importSpecifier)
3417
- for (let stmt of storySourceFile.statements) {
3418
- if (!typescript.isImportDeclaration(stmt))
3419
- continue;
3420
- let moduleSpec = stmt.moduleSpecifier;
3421
- if (!typescript.isStringLiteral(moduleSpec) || moduleSpec.text !== importSpecifier)
3422
- continue;
3423
- let clause = stmt.importClause;
3424
- if (!clause)
3425
- continue;
3426
- let importSymbol;
3427
- if (importName === "default") {
3428
- if (clause.name && (importSymbol = checker.getSymbolAtLocation(clause.name)), !importSymbol && clause.namedBindings && typescript.isNamedImports(clause.namedBindings)) {
3429
- for (let spec of clause.namedBindings.elements)
3430
- if ((spec.propertyName ?? spec.name).text === "default") {
3431
- importSymbol = checker.getSymbolAtLocation(spec.name);
3432
- break;
3433
- }
3434
- }
3435
- } else if (clause.namedBindings && typescript.isNamedImports(clause.namedBindings)) {
3436
- for (let spec of clause.namedBindings.elements)
3437
- if ((spec.propertyName ?? spec.name).text === importName) {
3438
- importSymbol = checker.getSymbolAtLocation(spec.name);
3439
- break;
3440
- }
3343
+ TypeScriptMissingForDocgenError,
3344
+ TypeScriptWithoutCompilerApiError
3345
+ } from "storybook/internal/server-errors";
3346
+ var __filename = CJS_COMPAT_NODE_URL_6lg7c74mo83.fileURLToPath(import.meta.url), __dirname = CJS_COMPAT_NODE_PATH_6lg7c74mo83.dirname(__filename), require2 = CJS_COMPAT_NODE_MODULE_6lg7c74mo83.createRequire(import.meta.url), _lazyMatch = () => {
3347
+ var __lib__ = (() => {
3348
+ var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
3349
+ for (var n in e) m(r, n, { get: e[n], enumerable: !0 });
3350
+ }, H = (r, e, n, a) => {
3351
+ if (e && typeof e == "object" || typeof e == "function") for (let t of G(e)) !T.call(r, t) && t !== n && m(r, t, { get: () => e[t], enumerable: !(a = V(e, t)) || a.enumerable });
3352
+ return r;
3353
+ }, J = (r) => H(m({}, "__esModule", { value: !0 }), r), w = {};
3354
+ q(w, { default: () => re });
3355
+ var A = (r) => Array.isArray(r), d = (r) => typeof r == "function", Q = (r) => r.length === 0, W = (r) => typeof r == "number", K = (r) => typeof r == "object" && r !== null, X = (r) => r instanceof RegExp, b = (r) => typeof r == "string", h = (r) => r === void 0, Y = (r) => {
3356
+ let e = /* @__PURE__ */ new Map();
3357
+ return (n) => {
3358
+ let a = e.get(n);
3359
+ if (a) return a;
3360
+ let t = r(n);
3361
+ return e.set(n, t), t;
3362
+ };
3363
+ }, rr = (r, e, n = {}) => {
3364
+ let a = { cache: {}, input: r, index: 0, indexMax: 0, options: n, output: [] };
3365
+ if (v(e)(a) && a.index === r.length) return a.output;
3366
+ throw new Error(`Failed to parse at index ${a.indexMax}`);
3367
+ }, i = (r, e) => A(r) ? er(r, e) : b(r) ? ar(r, e) : nr(r, e), er = (r, e) => {
3368
+ let n = {};
3369
+ for (let a of r) {
3370
+ if (a.length !== 1) throw new Error(`Invalid character: "${a}"`);
3371
+ let t = a.charCodeAt(0);
3372
+ n[t] = !0;
3441
3373
  }
3442
- if (!importSymbol && memberAccess && clause.namedBindings && typescript.isNamespaceImport(clause.namedBindings) && (importSymbol = checker.getSymbolAtLocation(clause.namedBindings.name)), importSymbol)
3443
- return importSymbol;
3444
- }
3445
- }
3446
- function metaComponentMatchesRef(typescript, checker, storySourceFile, componentRef, metaComponentInitializer) {
3447
- let refSymbol = findImportSymbolInStoryFile(typescript, checker, storySourceFile, componentRef), metaSymbol = resolveComponentSymbolFromNode(typescript, checker, metaComponentInitializer);
3448
- if (refSymbol && metaSymbol && !componentRef.member)
3449
- return resolveAliasedSymbol(typescript, checker, refSymbol) === resolveAliasedSymbol(typescript, checker, metaSymbol);
3450
- if (typescript.isIdentifier(metaComponentInitializer))
3451
- return componentRef.componentName === metaComponentInitializer.text;
3452
- if (typescript.isPropertyAccessExpression(metaComponentInitializer) && typescript.isIdentifier(metaComponentInitializer.expression)) {
3453
- let metaName = `${metaComponentInitializer.expression.text}.${metaComponentInitializer.name.text}`;
3454
- return componentRef.componentName === metaName;
3455
- }
3456
- return !1;
3457
- }
3458
- function resolvePropsFromStoryFile(typescript, checker, storySourceFile, componentRef) {
3459
- let memberAccess = componentRef.member, importSymbol = findImportSymbolInStoryFile(
3460
- typescript,
3461
- checker,
3462
- storySourceFile,
3463
- componentRef
3464
- );
3465
- if (!importSymbol)
3466
- return;
3467
- let result;
3468
- function extractPropsFromJsx(node) {
3469
- let sig = checker.getResolvedSignature(node);
3470
- if (!sig)
3471
- return;
3472
- let params = sig.getParameters();
3473
- return params.length === 0 ? checker.getTypeFromTypeNode(typescript.factory.createTypeLiteralNode([])) : checker.getTypeOfSymbolAtLocation(params[0], node);
3474
- }
3475
- function visit(node) {
3476
- if (!result) {
3477
- if (typescript.isJsxSelfClosingElement(node) || typescript.isJsxOpeningElement(node)) {
3478
- let tagName = node.tagName;
3479
- if (memberAccess) {
3480
- if (typescript.isPropertyAccessExpression(tagName) && tagName.name.text === memberAccess) {
3481
- let leftSym = checker.getSymbolAtLocation(tagName.expression);
3482
- if (leftSym && importSymbol && leftSym === importSymbol) {
3483
- let propsType = extractPropsFromJsx(node);
3484
- if (propsType) {
3485
- let memberSymbol = checker.getSymbolAtLocation(tagName.name) ?? checker.getTypeAtLocation(tagName.expression).getProperty(tagName.name.text) ?? resolveComponentSymbolFromNode(typescript, checker, tagName);
3486
- result = {
3487
- componentRef,
3488
- propsType,
3489
- symbol: memberSymbol ? resolveComponentSymbol(typescript, checker, memberSymbol, tagName.name) : resolveAliasedSymbol(typescript, checker, importSymbol)
3490
- };
3491
- return;
3492
- }
3493
- }
3374
+ return (a) => {
3375
+ let t = a.index, o = a.input;
3376
+ for (; a.index < o.length && o.charCodeAt(a.index) in n; ) a.index += 1;
3377
+ let u = a.index;
3378
+ if (u > t) {
3379
+ if (!h(e) && !a.options.silent) {
3380
+ let s = a.input.slice(t, u), c = d(e) ? e(s, o, String(t)) : e;
3381
+ h(c) || a.output.push(c);
3494
3382
  }
3495
- } else if (typescript.isIdentifier(tagName)) {
3496
- let sym = checker.getSymbolAtLocation(tagName);
3497
- if (sym && importSymbol && sym === importSymbol) {
3498
- let propsType = extractPropsFromJsx(node);
3499
- if (propsType) {
3500
- result = {
3501
- componentRef,
3502
- propsType,
3503
- symbol: resolveAliasedSymbol(typescript, checker, sym)
3504
- };
3505
- return;
3506
- }
3383
+ a.indexMax = Math.max(a.indexMax, a.index);
3384
+ }
3385
+ return !0;
3386
+ };
3387
+ }, nr = (r, e) => {
3388
+ let n = r.source, a = r.flags.replace(/y|$/, "y"), t = new RegExp(n, a);
3389
+ return g((o) => {
3390
+ t.lastIndex = o.index;
3391
+ let u = t.exec(o.input);
3392
+ if (u) {
3393
+ if (!h(e) && !o.options.silent) {
3394
+ let s = d(e) ? e(...u, o.input, String(o.index)) : e;
3395
+ h(s) || o.output.push(s);
3507
3396
  }
3397
+ return o.index += u[0].length, o.indexMax = Math.max(o.indexMax, o.index), !0;
3398
+ } else return !1;
3399
+ });
3400
+ }, ar = (r, e) => (n) => {
3401
+ if (n.input.startsWith(r, n.index)) {
3402
+ if (!h(e) && !n.options.silent) {
3403
+ let t = d(e) ? e(r, n.input, String(n.index)) : e;
3404
+ h(t) || n.output.push(t);
3508
3405
  }
3509
- }
3510
- typescript.forEachChild(node, visit);
3511
- }
3512
- }
3513
- return visit(storySourceFile), result;
3514
- }
3515
- function resolvePropsFromComponentType(typescript, checker, componentType) {
3516
- let callSigs = componentType.getCallSignatures();
3517
- if (callSigs.length > 0) {
3518
- let sig = callSigs[0];
3519
- if (sig.parameters.length === 0)
3520
- return checker.getVoidType();
3521
- let propsType = checker.getTypeOfSymbol(sig.parameters[0]);
3522
- if (!(propsType.flags & typescript.TypeFlags.Any))
3523
- return propsType;
3524
- }
3525
- let ctorSigs = componentType.getConstructSignatures();
3526
- for (let sig of ctorSigs) {
3527
- let propsSym = sig.getReturnType().getProperty("props");
3528
- if (propsSym) {
3529
- let propsType = checker.getTypeOfSymbol(propsSym);
3530
- if (!(propsType.flags & typescript.TypeFlags.Any))
3531
- return propsType;
3532
- }
3533
- }
3534
- }
3406
+ return n.index += r.length, n.indexMax = Math.max(n.indexMax, n.index), !0;
3407
+ } else return !1;
3408
+ }, C = (r, e, n, a) => {
3409
+ let t = v(r);
3410
+ return g(_(M((o) => {
3411
+ let u = 0;
3412
+ for (; u < n; ) {
3413
+ let s = o.index;
3414
+ if (!t(o) || (u += 1, o.index === s)) break;
3415
+ }
3416
+ return u >= e;
3417
+ })));
3418
+ }, tr = (r, e) => C(r, 0, 1), f = (r, e) => C(r, 0, 1 / 0), x = (r, e) => {
3419
+ let n = r.map(v);
3420
+ return g(_(M((a) => {
3421
+ for (let t = 0, o = n.length; t < o; t++) if (!n[t](a)) return !1;
3422
+ return !0;
3423
+ })));
3424
+ }, l = (r, e) => {
3425
+ let n = r.map(v);
3426
+ return g(_((a) => {
3427
+ for (let t = 0, o = n.length; t < o; t++) if (n[t](a)) return !0;
3428
+ return !1;
3429
+ }));
3430
+ }, M = (r, e = !1) => {
3431
+ let n = v(r);
3432
+ return (a) => {
3433
+ let t = a.index, o = a.output.length, u = n(a);
3434
+ return (!u || e) && (a.index = t, a.output.length !== o && (a.output.length = o)), u;
3435
+ };
3436
+ }, _ = (r, e) => v(r), g = /* @__PURE__ */ (() => {
3437
+ let r = 0;
3438
+ return (e) => {
3439
+ let n = v(e), a = r += 1;
3440
+ return (t) => {
3441
+ var o;
3442
+ if (t.options.memoization === !1) return n(t);
3443
+ let u = t.index, s = (o = t.cache)[a] || (o[a] = /* @__PURE__ */ new Map()), c = s.get(u);
3444
+ if (c === !1) return !1;
3445
+ if (W(c)) return t.index = c, !0;
3446
+ if (c) return t.index = c.index, c.output?.length && t.output.push(...c.output), !0;
3447
+ {
3448
+ let Z = t.output.length;
3449
+ if (n(t)) {
3450
+ let D = t.index, U = t.output.length;
3451
+ if (U > Z) {
3452
+ let ee = t.output.slice(Z, U);
3453
+ s.set(u, { index: D, output: ee });
3454
+ } else s.set(u, D);
3455
+ return !0;
3456
+ } else return s.set(u, !1), !1;
3457
+ }
3458
+ };
3459
+ };
3460
+ })(), E = (r) => {
3461
+ let e;
3462
+ return (n) => (e || (e = v(r())), e(n));
3463
+ }, v = Y((r) => {
3464
+ if (d(r)) return Q(r) ? E(r) : r;
3465
+ if (b(r) || X(r)) return i(r);
3466
+ if (A(r)) return x(r);
3467
+ if (K(r)) return l(Object.values(r));
3468
+ throw new Error("Invalid rule");
3469
+ }), P = "abcdefghijklmnopqrstuvwxyz", ir = (r) => {
3470
+ let e = "";
3471
+ for (; r > 0; ) {
3472
+ let n = (r - 1) % 26;
3473
+ e = P[n] + e, r = Math.floor((r - 1) / 26);
3474
+ }
3475
+ return e;
3476
+ }, O = (r) => {
3477
+ let e = 0;
3478
+ for (let n = 0, a = r.length; n < a; n++) e = e * 26 + P.indexOf(r[n]) + 1;
3479
+ return e;
3480
+ }, S = (r, e) => {
3481
+ if (e < r) return S(e, r);
3482
+ let n = [];
3483
+ for (; r <= e; ) n.push(r++);
3484
+ return n;
3485
+ }, or = (r, e, n) => S(r, e).map((a) => String(a).padStart(n, "0")), R = (r, e) => S(O(r), O(e)).map(ir), p = (r) => r, z = (r) => ur((e) => rr(e, r, { memoization: !1 }).join("")), ur = (r) => {
3486
+ let e = {};
3487
+ return (n) => e[n] ?? (e[n] = r(n));
3488
+ }, sr = i(/^\*\*\/\*$/, ".*"), cr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]+)$/, (r, e, n) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}`), lr = i(/^\*\*\/(\*)?([ a-zA-Z0-9._-]*)\{([ a-zA-Z0-9._-]+(?:,[ a-zA-Z0-9._-]+)*)\}$/, (r, e, n, a) => `.*${e ? "" : "(?:^|/)"}${n.replaceAll(".", "\\.")}(?:${a.replaceAll(",", "|").replaceAll(".", "\\.")})`), y = i(/\\./, p), pr = i(/[$.*+?^(){}[\]\|]/, (r) => `\\${r}`), vr = i(/./, p), hr = i(/^(?:!!)*!(.*)$/, (r, e) => `(?!^${L(e)}$).*?`), dr = i(/^(!!)+/, ""), fr = l([hr, dr]), xr = i(/\/(\*\*\/)+/, "(?:/.+/|/)"), gr = i(/^(\*\*\/)+/, "(?:^|.*/)"), mr = i(/\/(\*\*)$/, "(?:/.*|$)"), _r = i(/\*\*/, ".*"), j = l([xr, gr, mr, _r]), Sr = i(/\*\/(?!\*\*\/)/, "[^/]*/"), yr = i(/\*/, "[^/]*"), N = l([Sr, yr]), k = i("?", "[^/]"), $r = i("[", p), wr = i("]", p), Ar = i(/[!^]/, "^/"), br = i(/[a-z]-[a-z]|[0-9]-[0-9]/i, p), Cr = i(/[$.*+?^(){}[\|]/, (r) => `\\${r}`), Mr = i(/[^\]]/, p), Er = l([y, Cr, br, Mr]), B = x([$r, tr(Ar), f(Er), wr]), Pr = i("{", "(?:"), Or = i("}", ")"), Rr = i(/(\d+)\.\.(\d+)/, (r, e, n) => or(+e, +n, Math.min(e.length, n.length)).join("|")), zr = i(/([a-z]+)\.\.([a-z]+)/, (r, e, n) => R(e, n).join("|")), jr = i(/([A-Z]+)\.\.([A-Z]+)/, (r, e, n) => R(e.toLowerCase(), n.toLowerCase()).join("|").toUpperCase()), Nr = l([Rr, zr, jr]), I = x([Pr, Nr, Or]), kr = i("{", "(?:"), Br = i("}", ")"), Ir = i(",", "|"), Fr = i(/[$.*+?^(){[\]\|]/, (r) => `\\${r}`), Lr = i(/[^}]/, p), Zr = E(() => F), Dr = l([j, N, k, B, I, Zr, y, Fr, Ir, Lr]), F = x([kr, f(Dr), Br]), Ur = f(l([sr, cr, lr, fr, j, N, k, B, I, F, y, pr, vr])), Vr = Ur, Gr = z(Vr), L = Gr, Tr = i(/\\./, p), qr = i(/./, p), Hr = i(/\*\*\*+/, "*"), Jr = i(/([^/{[(!])\*\*/, (r, e) => `${e}*`), Qr = i(/(^|.)\*\*(?=[^*/)\]}])/, (r, e) => `${e}*`), Wr = f(l([Tr, Hr, Jr, Qr, qr])), Kr = Wr, Xr = z(Kr), Yr = Xr, $ = (r, e) => {
3489
+ let n = Array.isArray(r) ? r : [r];
3490
+ if (!n.length) return !1;
3491
+ let a = n.map($.compile), t = n.every((s) => /(\/(?:\*\*)?|\[\/\])$/.test(s)), o = e.replace(/[\\\/]+/g, "/").replace(/\/$/, t ? "/" : "");
3492
+ return a.some((s) => s.test(o));
3493
+ };
3494
+ $.compile = (r) => new RegExp(`^${L(Yr(r))}$`, "s");
3495
+ var re = $;
3496
+ return J(w);
3497
+ })();
3498
+ return __lib__.default || __lib__;
3499
+ }, _match, zeptomatch = (path2, pattern) => (_match || (_match = _lazyMatch(), _lazyMatch = null), _match(path2, pattern)), _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
3500
+ function normalizeWindowsPath(input = "") {
3501
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
3502
+ }
3503
+ var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/, _EXTNAME_RE = /.(\.[^./]+|\.)$/, _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/, sep = "/", normalize = function(path2) {
3504
+ if (path2.length === 0)
3505
+ return ".";
3506
+ path2 = normalizeWindowsPath(path2);
3507
+ let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
3508
+ return path2 = normalizeString(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2);
3509
+ }, join = function(...segments) {
3510
+ let path2 = "";
3511
+ for (let seg of segments)
3512
+ if (seg)
3513
+ if (path2.length > 0) {
3514
+ let pathTrailing = path2[path2.length - 1] === "/", segLeading = seg[0] === "/";
3515
+ pathTrailing && segLeading ? path2 += seg.slice(1) : path2 += pathTrailing || segLeading ? seg : `/${seg}`;
3516
+ } else
3517
+ path2 += seg;
3518
+ return normalize(path2);
3519
+ };
3520
+ function cwd() {
3521
+ return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
3522
+ }
3523
+ var resolve = function(...arguments_) {
3524
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
3525
+ let resolvedPath = "", resolvedAbsolute = !1;
3526
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
3527
+ let path2 = index >= 0 ? arguments_[index] : cwd();
3528
+ !path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path2));
3529
+ }
3530
+ return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
3531
+ };
3532
+ function normalizeString(path2, allowAboveRoot) {
3533
+ let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
3534
+ for (let index = 0; index <= path2.length; ++index) {
3535
+ if (index < path2.length)
3536
+ char = path2[index];
3537
+ else {
3538
+ if (char === "/")
3539
+ break;
3540
+ char = "/";
3541
+ }
3542
+ if (char === "/") {
3543
+ if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
3544
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
3545
+ if (res.length > 2) {
3546
+ let lastSlashIndex = res.lastIndexOf("/");
3547
+ lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
3548
+ continue;
3549
+ } else if (res.length > 0) {
3550
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
3551
+ continue;
3552
+ }
3553
+ }
3554
+ allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
3555
+ } else
3556
+ res.length > 0 ? res += `/${path2.slice(lastSlash + 1, index)}` : res = path2.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
3557
+ lastSlash = index, dots = 0;
3558
+ } else char === "." && dots !== -1 ? ++dots : dots = -1;
3559
+ }
3560
+ return res;
3561
+ }
3562
+ var isAbsolute = function(p) {
3563
+ return _IS_ABSOLUTE_RE.test(p);
3564
+ }, toNamespacedPath = function(p) {
3565
+ return normalizeWindowsPath(p);
3566
+ }, extname = function(p) {
3567
+ if (p === "..") return "";
3568
+ let match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
3569
+ return match && match[1] || "";
3570
+ }, relative = function(from, to) {
3571
+ let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
3572
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
3573
+ return _to.join("/");
3574
+ let _fromCopy = [..._from];
3575
+ for (let segment of _fromCopy) {
3576
+ if (_to[0] !== segment)
3577
+ break;
3578
+ _from.shift(), _to.shift();
3579
+ }
3580
+ return [..._from.map(() => ".."), ..._to].join("/");
3581
+ }, dirname = function(p) {
3582
+ let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
3583
+ return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
3584
+ }, format = function(p) {
3585
+ let ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "", segments = [p.root, p.dir, p.base ?? (p.name ?? "") + ext].filter(
3586
+ Boolean
3587
+ );
3588
+ return normalizeWindowsPath(
3589
+ p.root ? resolve(...segments) : segments.join("/")
3590
+ );
3591
+ }, basename = function(p, extension) {
3592
+ let segments = normalizeWindowsPath(p).split("/"), lastSegment = "";
3593
+ for (let i = segments.length - 1; i >= 0; i--) {
3594
+ let val = segments[i];
3595
+ if (val) {
3596
+ lastSegment = val;
3597
+ break;
3598
+ }
3599
+ }
3600
+ return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
3601
+ }, parse = function(p) {
3602
+ let root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "", base = basename(p), extension = extname(base);
3603
+ return {
3604
+ root,
3605
+ dir: dirname(p),
3606
+ base,
3607
+ ext: extension,
3608
+ name: base.slice(0, base.length - extension.length)
3609
+ };
3610
+ }, matchesGlob = (path2, pattern) => zeptomatch(pattern, normalize(path2)), _path = {
3611
+ __proto__: null,
3612
+ basename,
3613
+ dirname,
3614
+ extname,
3615
+ format,
3616
+ isAbsolute,
3617
+ join,
3618
+ matchesGlob,
3619
+ normalize,
3620
+ normalizeString,
3621
+ parse,
3622
+ relative,
3623
+ resolve,
3624
+ sep,
3625
+ toNamespacedPath
3626
+ }, delimiter = globalThis.process?.platform === "win32" ? ";" : ":", _platforms = { posix: void 0, win32: void 0 }, mix = (del = delimiter) => new Proxy(_path, {
3627
+ get(_, prop) {
3628
+ return prop === "delimiter" ? del : prop === "posix" ? posix : prop === "win32" ? win32 : _platforms[prop] || _path[prop];
3629
+ }
3630
+ }), posix = mix(":"), win32 = mix(";"), DOCGEN_APIS = ["compiler", "native"], NATIVE_ENTRY_POINTS = { sync: "./sync", ast: "./ast", factory: "./ast/factory" };
3631
+ async function loadNativeTypeScriptModules(importEntry) {
3632
+ let [sync, ast, factory] = await Promise.all(
3633
+ Object.values(NATIVE_ENTRY_POINTS).map((subpath) => importEntry(subpath))
3634
+ );
3635
+ return { sync, ast, factory };
3636
+ }
3637
+ async function loadTypeScriptForDocgen(importEntry, specifier) {
3638
+ let typescript;
3639
+ try {
3640
+ let imported = await importEntry(".");
3641
+ typescript = imported.default ?? imported;
3642
+ } catch (cause) {
3643
+ throw isModuleNotFoundError(cause) ? new TypeScriptMissingForDocgenError({ cause, apis: DOCGEN_APIS }) : cause;
3644
+ }
3645
+ let { version } = typescript;
3646
+ if (!isTypeScriptUsableForDocgen(version, DOCGEN_APIS))
3647
+ throw new TypeScriptWithoutCompilerApiError({ version, apis: DOCGEN_APIS, specifier });
3648
+ return getTypeScriptDocgenApi(version) === "native" ? { api: "native", typescript: await loadNativeTypeScriptModules(importEntry) } : { api: "compiler", typescript };
3649
+ }
3650
+ var importPackageEntry = ({ version, packageDir, main, exports }, subpath) => {
3651
+ let entry = exports ? exports[subpath] : subpath === "." ? main ?? "index.js" : void 0;
3652
+ if (typeof entry != "string")
3653
+ throw new Error(
3654
+ `TypeScript ${version} at ${packageDir} has no "${subpath}" entry point that Storybook can import`
3655
+ );
3656
+ return import(pathToFileURL(join(packageDir, entry)).href);
3657
+ };
3658
+ function loadDocgenTypeScript(typeScriptSpecifier) {
3659
+ if (typeScriptSpecifier) {
3660
+ let typeScriptPackage = readTypeScriptPackageForDocgen(typeScriptSpecifier, DOCGEN_APIS);
3661
+ return loadTypeScriptForDocgen(
3662
+ (subpath) => importPackageEntry(typeScriptPackage, subpath),
3663
+ typeScriptSpecifier.specifier
3664
+ );
3665
+ }
3666
+ return loadTypeScriptForDocgen((subpath) => import(`typescript${subpath.slice(1)}`));
3667
+ }
3668
+
3669
+ // ../../lib/component-meta-typescript/dist/index.js
3670
+ import CJS_COMPAT_NODE_URL_6lg7c74mo832 from "node:url";
3671
+ import CJS_COMPAT_NODE_PATH_6lg7c74mo832 from "node:path";
3672
+ import CJS_COMPAT_NODE_MODULE_6lg7c74mo832 from "node:module";
3673
+ import { existsSync, readFileSync, statSync } from "node:fs";
3674
+ import {
3675
+ filterSourceFilePaths
3676
+ } from "storybook/internal/component-meta";
3677
+ import { statSync as statSync2 } from "node:fs";
3678
+ import { logger } from "storybook/internal/node-logger";
3679
+ var __filename2 = CJS_COMPAT_NODE_URL_6lg7c74mo832.fileURLToPath(import.meta.url), __dirname2 = CJS_COMPAT_NODE_PATH_6lg7c74mo832.dirname(__filename2), require3 = CJS_COMPAT_NODE_MODULE_6lg7c74mo832.createRequire(import.meta.url), DOCGEN_NODE_GUARDS = [
3680
+ "isArrayLiteralExpression",
3681
+ "isArrayTypeNode",
3682
+ "isArrowFunction",
3683
+ "isAsExpression",
3684
+ "isAwaitExpression",
3685
+ "isBigIntLiteral",
3686
+ "isBinaryExpression",
3687
+ "isBindingElement",
3688
+ "isBlock",
3689
+ "isCallExpression",
3690
+ "isClassDeclaration",
3691
+ "isClassLike",
3692
+ "isComputedPropertyName",
3693
+ "isConditionalExpression",
3694
+ "isConstructorDeclaration",
3695
+ "isConstructorTypeNode",
3696
+ "isEnumDeclaration",
3697
+ "isEnumMember",
3698
+ "isExportAssignment",
3699
+ "isExportDeclaration",
3700
+ "isExpressionStatement",
3701
+ "isExpressionWithTypeArguments",
3702
+ "isFunctionDeclaration",
3703
+ "isFunctionExpression",
3704
+ "isFunctionTypeNode",
3705
+ "isGetAccessor",
3706
+ "isGetAccessorDeclaration",
3707
+ "isIdentifier",
3708
+ "isImportDeclaration",
3709
+ "isImportSpecifier",
3710
+ "isIndexedAccessTypeNode",
3711
+ "isInterfaceDeclaration",
3712
+ "isIntersectionTypeNode",
3713
+ "isJSDoc",
3714
+ "isJSDocSeeTag",
3715
+ "isJsxOpeningElement",
3716
+ "isJsxSelfClosingElement",
3717
+ "isLiteralTypeNode",
3718
+ "isMethodDeclaration",
3719
+ "isNamedExports",
3720
+ "isNamedImports",
3721
+ "isNamespaceImport",
3722
+ "isNewExpression",
3723
+ "isNoSubstitutionTemplateLiteral",
3724
+ "isNonNullExpression",
3725
+ "isNumericLiteral",
3726
+ "isObjectBindingPattern",
3727
+ "isObjectLiteralExpression",
3728
+ "isOmittedExpression",
3729
+ "isParameter",
3730
+ "isParenthesizedExpression",
3731
+ "isParenthesizedTypeNode",
3732
+ "isPrefixUnaryExpression",
3733
+ "isPropertyAccessExpression",
3734
+ "isPropertyAssignment",
3735
+ "isPropertyDeclaration",
3736
+ "isPropertySignature",
3737
+ "isQualifiedName",
3738
+ "isSatisfiesExpression",
3739
+ "isSetAccessor",
3740
+ "isSetAccessorDeclaration",
3741
+ "isShorthandPropertyAssignment",
3742
+ "isSourceFile",
3743
+ "isSpreadAssignment",
3744
+ "isSpreadElement",
3745
+ "isStringLiteral",
3746
+ "isStringLiteralLike",
3747
+ "isTupleTypeNode",
3748
+ "isTypeAliasDeclaration",
3749
+ "isTypeAssertionExpression",
3750
+ "isTypeLiteralNode",
3751
+ "isTypeOperatorNode",
3752
+ "isTypeParameterDeclaration",
3753
+ "isTypeReferenceNode",
3754
+ "isUnionTypeNode",
3755
+ "isVariableDeclaration",
3756
+ "isVariableStatement"
3757
+ ], compilerNodeAccessors = {
3758
+ getTypeParameterDefault: (node) => node.default,
3759
+ hasQuestionToken: (member) => "questionToken" in member && member.questionToken !== void 0,
3760
+ getSeeTagReference: (tag) => tag.name,
3761
+ getJSDocStart: (jsDoc) => jsDoc.pos,
3762
+ getJSDocTagCommentStart: (tag) => (typeof tag.comment == "string" ? tag.getChildren().at(-1)?.end : tag.comment?.pos) ?? tag.tagName.end
3763
+ };
3764
+ function createCompilerDocgenTypeScript(typescript) {
3765
+ let members = {
3766
+ ...compilerNodeAccessors,
3767
+ printNode: (node, visit) => {
3768
+ let result = typescript.transform(node, [
3769
+ (context) => (root) => {
3770
+ let visitChildren = (child) => typescript.visitEachChild(
3771
+ child,
3772
+ (grandchild) => visit(grandchild, visitChildren),
3773
+ context
3774
+ );
3775
+ return visit(root, visitChildren);
3776
+ }
3777
+ ]);
3778
+ try {
3779
+ return typescript.createPrinter({ removeComments: !0 }).printNode(typescript.EmitHint.Unspecified, result.transformed[0], node.getSourceFile());
3780
+ } finally {
3781
+ result.dispose();
3782
+ }
3783
+ },
3784
+ createSourceFile: (fileName, text) => typescript.createSourceFile(fileName, text, typescript.ScriptTarget.Latest, !0),
3785
+ getEmptyObjectType: (checker) => checker.getTypeFromTypeNode(typescript.factory.createTypeLiteralNode([]))
3786
+ };
3787
+ return Object.create(
3788
+ typescript,
3789
+ Object.fromEntries(Object.entries(members).map(([name, value]) => [name, { value }]))
3790
+ );
3791
+ }
3792
+ var getOrCompute = (map, key, compute) => {
3793
+ let value = map.get(key);
3794
+ return value === void 0 && !map.has(key) && (value = compute(), map.set(key, value)), value;
3795
+ }, CallCache = class {
3796
+ constructor() {
3797
+ this.methods = /* @__PURE__ */ new Map();
3798
+ }
3799
+ answer(method, args, ask) {
3800
+ let level = getOrCompute(this.methods, method, () => ({}));
3801
+ for (let arg of args)
3802
+ level = arg !== null && typeof arg == "object" ? getOrCompute(level.objects ??= /* @__PURE__ */ new WeakMap(), arg, () => ({})) : getOrCompute(level.values ??= /* @__PURE__ */ new Map(), arg, () => ({}));
3803
+ return level.answered || (level.answer = ask(), level.answered = !0), level.answer;
3804
+ }
3805
+ }, textPart = (text) => ({
3806
+ kind: "text",
3807
+ text
3808
+ }), SymbolFacade = class {
3809
+ constructor(native, facades) {
3810
+ this.native = native, this.facades = facades;
3811
+ }
3812
+ get name() {
3813
+ return this.native.name;
3814
+ }
3815
+ get escapedName() {
3816
+ return this.native.escapedName;
3817
+ }
3818
+ get flags() {
3819
+ return this.native.flags;
3820
+ }
3821
+ getFlags() {
3822
+ return this.flags;
3823
+ }
3824
+ getName() {
3825
+ return this.native.name;
3826
+ }
3827
+ get valueDeclaration() {
3828
+ return this.resolvedValueDeclaration === void 0 && (this.resolvedValueDeclaration = this.native.valueDeclaration?.resolve() ?? null), this.resolvedValueDeclaration ?? void 0;
3829
+ }
3830
+ get declarations() {
3831
+ return this.getDeclarations();
3832
+ }
3833
+ getDeclarations() {
3834
+ return this.resolvedDeclarations ??= this.native.declarations.flatMap((handle) => {
3835
+ let node = handle.resolve();
3836
+ return node ? [node] : [];
3837
+ }), this.resolvedDeclarations;
3838
+ }
3839
+ getDocumentationComment() {
3840
+ let text = this.facades.documentationComment(this.native);
3841
+ return text ? [textPart(text)] : [];
3842
+ }
3843
+ getJsDocTags() {
3844
+ return this.facades.jsDocTags(this.native).map(({ name, text }) => ({
3845
+ name,
3846
+ text: text === void 0 ? void 0 : [textPart(text)]
3847
+ }));
3848
+ }
3849
+ }, TypeFacade = class {
3850
+ constructor(native, facades) {
3851
+ this.native = native, this.facades = facades;
3852
+ }
3853
+ get flags() {
3854
+ return this.native.flags;
3855
+ }
3856
+ getFlags() {
3857
+ return this.flags;
3858
+ }
3859
+ get symbol() {
3860
+ return this.getSymbol();
3861
+ }
3862
+ get aliasSymbol() {
3863
+ return this.facades.symbol(this.native.getAliasSymbol());
3864
+ }
3865
+ get objectFlags() {
3866
+ return this.native.objectFlags;
3867
+ }
3868
+ getSymbol() {
3869
+ return this.facades.symbol(this.native.getSymbol());
3870
+ }
3871
+ get value() {
3872
+ return this.native.value;
3873
+ }
3874
+ get types() {
3875
+ return this.facades.memberTypes(this.native).map((type) => this.facades.type(type));
3876
+ }
3877
+ isUnion() {
3878
+ return this.native.isUnionType();
3879
+ }
3880
+ isClassOrInterface() {
3881
+ return this.native.isClassOrInterface();
3882
+ }
3883
+ isIntersection() {
3884
+ return this.native.isIntersectionType();
3885
+ }
3886
+ isStringLiteral() {
3887
+ return this.native.isStringLiteralType();
3888
+ }
3889
+ isNumberLiteral() {
3890
+ return this.native.isNumberLiteralType();
3891
+ }
3892
+ getProperty(name) {
3893
+ return this.facades.symbol(this.native.getProperty(name));
3894
+ }
3895
+ getProperties() {
3896
+ return this.properties ??= this.facades.symbols(this.native.getProperties()), this.properties;
3897
+ }
3898
+ getApparentProperties() {
3899
+ return this.apparentProperties ??= this.facades.symbols(this.native.getApparentProperties()), this.apparentProperties;
3900
+ }
3901
+ getCallSignatures() {
3902
+ return this.facades.callSignatures(this.native).map((signature) => this.facades.signature(signature));
3903
+ }
3904
+ getConstructSignatures() {
3905
+ return this.constructSignatures ??= this.native.getConstructSignatures().map((signature) => this.facades.signature(signature)), this.constructSignatures;
3906
+ }
3907
+ getConstraint() {
3908
+ return this.facades.type(this.facades.checker.getBaseConstraintOfType(this.native));
3909
+ }
3910
+ }, SignatureFacade = class {
3911
+ constructor(native, facades) {
3912
+ this.native = native, this.facades = facades;
3913
+ }
3914
+ get parameters() {
3915
+ return this.getParameters();
3916
+ }
3917
+ get declaration() {
3918
+ return this.native.declaration?.resolve();
3919
+ }
3920
+ getParameters() {
3921
+ return this.resolvedParameters ??= this.native.getParameters().map((symbol) => this.facades.symbol(symbol)), this.resolvedParameters;
3922
+ }
3923
+ getReturnType() {
3924
+ return this.facades.type(this.facades.returnType(this.native));
3925
+ }
3926
+ }, EmptyObjectTypeFacade = class {
3927
+ constructor() {
3928
+ this.native = void 0, this.flags = 0, this.getFlags = () => 0, this.getSymbol = () => {
3929
+ }, this.types = [], this.isUnion = () => !1, this.isIntersection = () => !1, this.isStringLiteral = () => !1, this.isNumberLiteral = () => !1, this.getProperty = () => {
3930
+ }, this.getProperties = () => [], this.getApparentProperties = () => [], this.getCallSignatures = () => [], this.getConstructSignatures = () => [], this.getConstraint = () => {
3931
+ };
3932
+ }
3933
+ }, CACHED_QUERIES = [
3934
+ "getAliasedSymbol",
3935
+ "getBaseTypeOfLiteralType",
3936
+ "getBaseTypes",
3937
+ "getDeclaredTypeOfSymbol",
3938
+ "getExportsOfModule",
3939
+ "getMergedSymbol",
3940
+ "getPropertyOfType",
3941
+ "getResolvedSignature",
3942
+ "getShorthandAssignmentValueSymbol",
3943
+ "getSignatureFromDeclaration",
3944
+ "getSymbolAtLocation",
3945
+ "getTypeArguments",
3946
+ "getTypeAtLocation",
3947
+ "getTypeOfSymbol",
3948
+ "resolveName"
3949
+ ];
3950
+ function createDocgenChecker(facades) {
3951
+ let { checker } = facades, calls = new CallCache(), unwrapSymbol = (symbol) => symbol.native, unwrapType = (type) => type.native, unwrapNativeType = (type) => {
3952
+ let native = unwrapType(type);
3953
+ if (!native)
3954
+ throw new Error("The checker cannot take the empty object type here");
3955
+ return native;
3956
+ }, asNode = (node) => node, docgenChecker = {
3957
+ getAliasedSymbol: (symbol) => facades.symbol(checker.getAliasedSymbol(unwrapSymbol(symbol))),
3958
+ getBaseTypeOfLiteralType: (type) => facades.type(checker.getBaseTypeOfLiteralType(unwrapNativeType(type))),
3959
+ getBaseTypes: (type) => checker.getBaseTypes(unwrapNativeType(type)).map((base) => facades.type(base)),
3960
+ getDeclaredTypeOfSymbol: (symbol) => facades.type(checker.getDeclaredTypeOfSymbol(unwrapSymbol(symbol))),
3961
+ getExportsOfModule: (symbol) => checker.getExportsOfModule(unwrapSymbol(symbol)).map((exported) => facades.symbol(exported)),
3962
+ getMergedSymbol: (symbol) => facades.symbol(checker.getMergedSymbol(unwrapSymbol(symbol))),
3963
+ getPropertyOfType: (type, name) => {
3964
+ let native = unwrapType(type);
3965
+ return native && facades.symbol(checker.getPropertyOfType(native, name));
3966
+ },
3967
+ getResolvedSignature: (node) => facades.signature(checker.getResolvedSignature(asNode(node))),
3968
+ getShorthandAssignmentValueSymbol: (node) => node ? facades.symbol(checker.getShorthandAssignmentValueSymbol(asNode(node))) : void 0,
3969
+ getSignatureFromDeclaration: (node) => {
3970
+ let signature = checker.getSignatureFromDeclaration(asNode(node));
3971
+ return signature && facades.signature(signature);
3972
+ },
3973
+ getSymbolAtLocation: (node) => facades.symbol(checker.getSymbolAtLocation(asNode(node))),
3974
+ getTypeArguments: (type) => checker.getTypeArguments(unwrapNativeType(type)).map((argument) => facades.type(argument)),
3975
+ getTypeAtLocation: (node) => facades.type(checker.getTypeAtLocation(asNode(node))),
3976
+ getTypeOfSymbol: (symbol) => facades.type(checker.getTypeOfSymbol(unwrapSymbol(symbol))),
3977
+ getTypeOfSymbolAtLocation: (symbol, node) => facades.type(facades.typeOfSymbolAtLocation(unwrapSymbol(symbol), asNode(node))),
3978
+ getVoidType: () => facades.type(checker.getVoidType()),
3979
+ // The native API takes `meaning` before `location`.
3980
+ resolveName: (name, location, meaning, excludeGlobals) => facades.symbol(
3981
+ checker.resolveName(name, meaning, location && asNode(location), excludeGlobals)
3982
+ ),
3983
+ typeToString: (type, enclosingDeclaration, flags) => {
3984
+ let native = unwrapType(type);
3985
+ return native ? enclosingDeclaration === void 0 && flags === void 0 ? facades.typeToString(native) : calls.answer(
3986
+ "typeToString",
3987
+ [native, enclosingDeclaration, flags],
3988
+ () => checker.typeToString(
3989
+ native,
3990
+ enclosingDeclaration && asNode(enclosingDeclaration),
3991
+ flags
3992
+ )
3993
+ ) : "{}";
3994
+ }
3995
+ };
3996
+ for (let method of CACHED_QUERIES) {
3997
+ let ask = docgenChecker[method];
3998
+ docgenChecker[method] = (...args) => calls.answer(method, args, () => ask(...args));
3999
+ }
4000
+ return docgenChecker;
4001
+ }
4002
+ var NATIVE_FACADES = /* @__PURE__ */ Symbol("nativeFacades"), NativeFacades = class {
4003
+ constructor(project, typescript) {
4004
+ this.project = project, this.typescript = typescript, this.symbolFacades = /* @__PURE__ */ new WeakMap(), this.typeFacades = /* @__PURE__ */ new WeakMap(), this.signatureFacades = /* @__PURE__ */ new WeakMap(), this.emptyObjectType = new EmptyObjectTypeFacade(), this.groupOf = /* @__PURE__ */ new WeakMap(), this.tags = /* @__PURE__ */ new WeakMap(), this.docs = /* @__PURE__ */ new WeakMap(), this.typeAtLocation = /* @__PURE__ */ new WeakMap(), this.typeText = /* @__PURE__ */ new WeakMap(), this.members = /* @__PURE__ */ new WeakMap(), this.typesAtDeclarationFetched = /* @__PURE__ */ new WeakSet(), this.callSignaturesOf = /* @__PURE__ */ new WeakMap(), this.returnTypeOf = /* @__PURE__ */ new WeakMap(), this.checker = project.checker;
4005
+ }
4006
+ static of(checker) {
4007
+ let facades = checker[NATIVE_FACADES];
4008
+ if (!facades)
4009
+ throw new Error("The checker was not created by NativeFacades.createChecker");
4010
+ return facades;
4011
+ }
4012
+ createChecker() {
4013
+ return this.docgenChecker || (this.docgenChecker = createDocgenChecker(this), Object.defineProperty(this.docgenChecker, NATIVE_FACADES, { value: this })), this.docgenChecker;
4014
+ }
4015
+ symbol(native) {
4016
+ return native ? getOrCompute(
4017
+ this.symbolFacades,
4018
+ native,
4019
+ () => new SymbolFacade(native, this)
4020
+ ) : void 0;
4021
+ }
4022
+ symbols(natives) {
4023
+ return this.prefetchDocs(natives), natives.map((native) => this.symbol(native));
4024
+ }
4025
+ type(native) {
4026
+ return native ? getOrCompute(
4027
+ this.typeFacades,
4028
+ native,
4029
+ () => new TypeFacade(native, this)
4030
+ ) : void 0;
4031
+ }
4032
+ signature(native) {
4033
+ return getOrCompute(
4034
+ this.signatureFacades,
4035
+ native,
4036
+ () => new SignatureFacade(native, this)
4037
+ );
4038
+ }
4039
+ getEmptyObjectType() {
4040
+ return this.emptyObjectType;
4041
+ }
4042
+ jsDocTags(symbol) {
4043
+ return getOrCompute(this.tags, symbol, () => this.checker.getJsDocTagsOfSymbol(symbol));
4044
+ }
4045
+ documentationComment(symbol) {
4046
+ return getOrCompute(
4047
+ this.docs,
4048
+ symbol,
4049
+ () => this.checker.getDocumentationCommentOfSymbol(symbol)
4050
+ );
4051
+ }
4052
+ memberTypes(type) {
4053
+ return getOrCompute(
4054
+ this.members,
4055
+ type,
4056
+ () => type.isUnionType() || type.isIntersectionType() ? type.getTypes() : []
4057
+ );
4058
+ }
4059
+ typeToString(type) {
4060
+ return getOrCompute(this.typeText, type, () => this.checker.typeToString(type));
4061
+ }
4062
+ callSignatures(type) {
4063
+ return getOrCompute(this.callSignaturesOf, type, () => type.getCallSignatures());
4064
+ }
4065
+ returnType(signature) {
4066
+ return getOrCompute(this.returnTypeOf, signature, () => signature.getReturnType());
4067
+ }
4068
+ typeOfSymbolAtLocation(symbol, location) {
4069
+ let byLocation = this.typesAt(location), cached2 = byLocation.get(symbol);
4070
+ if (cached2)
4071
+ return cached2;
4072
+ let group = this.groupOf.get(symbol);
4073
+ return group && group.length > 1 && (this.isDeclarationOf(symbol, location) ? this.prefetchTypesAtDeclarations(group) : this.prefetchTypes(
4074
+ group.filter((member) => !byLocation.has(member)),
4075
+ location,
4076
+ byLocation
4077
+ )), getOrCompute(
4078
+ byLocation,
4079
+ symbol,
4080
+ () => this.checker.getTypeOfSymbolAtLocation(symbol, location)
4081
+ );
4082
+ }
4083
+ typesAt(location) {
4084
+ return getOrCompute(this.typeAtLocation, location, () => /* @__PURE__ */ new Map());
4085
+ }
4086
+ isDeclarationOf(symbol, location) {
4087
+ return !!this.symbol(symbol).getDeclarations()?.includes(location);
4088
+ }
4089
+ prefetchDocs(symbols) {
4090
+ let missing = symbols.filter((symbol) => !this.docs.has(symbol));
4091
+ for (let symbol of symbols)
4092
+ this.groupOf.set(symbol, symbols);
4093
+ if (missing.length < 2)
4094
+ return;
4095
+ let { checker } = this, [docs, tags] = this.typescript.batch(
4096
+ missing.map((symbol) => checker.getDocumentationCommentOfSymbol.gen(symbol)),
4097
+ missing.map((symbol) => checker.getJsDocTagsOfSymbol.gen(symbol))
4098
+ );
4099
+ missing.forEach((symbol, index) => {
4100
+ this.docs.set(symbol, docs[index]), this.tags.set(symbol, tags[index]);
4101
+ });
4102
+ }
4103
+ prefetchTypes(symbols, location, byLocation) {
4104
+ if (symbols.length < 2)
4105
+ return;
4106
+ let { checker } = this, [types] = this.typescript.batch(
4107
+ symbols.map((symbol) => checker.getTypeOfSymbolAtLocation.gen(symbol, location))
4108
+ );
4109
+ symbols.forEach((symbol, index) => byLocation.set(symbol, types[index])), this.prefetchTexts(types);
4110
+ }
4111
+ prefetchTypesAtDeclarations(symbols) {
4112
+ let located = symbols.flatMap((symbol) => {
4113
+ if (this.typesAtDeclarationFetched.has(symbol))
4114
+ return [];
4115
+ this.typesAtDeclarationFetched.add(symbol);
4116
+ let declaration = this.symbol(symbol).getDeclarations()?.[0];
4117
+ return declaration ? [{ symbol, location: declaration }] : [];
4118
+ });
4119
+ if (located.length < 2)
4120
+ return;
4121
+ let { checker } = this, [types] = this.typescript.batch(
4122
+ located.map(({ symbol, location }) => checker.getTypeOfSymbolAtLocation.gen(symbol, location))
4123
+ );
4124
+ located.forEach(
4125
+ ({ symbol, location }, index) => this.typesAt(location).set(symbol, types[index])
4126
+ ), this.prefetchTexts(types), this.prefetchSignatures(types);
4127
+ }
4128
+ prefetchSignatures(types) {
4129
+ let objects = [...new Set(types)].filter(
4130
+ (type) => type.flags & this.typescript.TypeFlags.Object && !this.callSignaturesOf.has(type)
4131
+ );
4132
+ if (objects.length < 2)
4133
+ return;
4134
+ let [signatureLists] = this.typescript.batch(
4135
+ objects.map((type) => type.getCallSignatures.gen())
4136
+ );
4137
+ objects.forEach((type, index) => this.callSignaturesOf.set(type, signatureLists[index]));
4138
+ let signatures = signatureLists.flat().filter((signature) => !this.returnTypeOf.has(signature)), [returnTypes] = this.typescript.batch(
4139
+ signatures.map((signature) => signature.getReturnType.gen())
4140
+ );
4141
+ signatures.forEach((signature, index) => this.returnTypeOf.set(signature, returnTypes[index]));
4142
+ }
4143
+ prefetchTexts(types) {
4144
+ let { checker } = this, untexted = [...new Set(types)].filter((type) => !this.typeText.has(type)), unions = untexted.filter(
4145
+ (type) => (type.isUnionType() || type.isIntersectionType()) && !this.members.has(type)
4146
+ ), [texts, members] = this.typescript.batch(
4147
+ untexted.map((type) => checker.typeToString.gen(type)),
4148
+ unions.map((type) => type.getTypes.gen())
4149
+ );
4150
+ untexted.forEach((type, index) => this.typeText.set(type, texts[index])), unions.forEach((type, index) => this.members.set(type, members[index] ?? []));
4151
+ }
4152
+ }, NATIVE_GUARD_NAMES = {
4153
+ isGetAccessor: "isGetAccessorDeclaration",
4154
+ isParameter: "isParameterDeclaration",
4155
+ isPropertySignature: "isPropertySignatureDeclaration",
4156
+ isSetAccessor: "isSetAccessorDeclaration",
4157
+ isTypeAssertionExpression: "isTypeAssertion"
4158
+ }, composedGuards = (ast) => ({
4159
+ isClassLike: (node) => ast.isClassDeclaration(node) || ast.isClassExpression(node),
4160
+ isStringLiteralLike: (node) => ast.isStringLiteral(node) || ast.isNoSubstitutionTemplateLiteral(node)
4161
+ }), nativeNodeAccessors = (ast) => ({
4162
+ getTypeParameterDefault: (node) => node.defaultType,
4163
+ hasQuestionToken: (member) => member.postfixToken?.kind === ast.SyntaxKind.QuestionToken,
4164
+ getSeeTagReference: (tag) => tag.nameExpression,
4165
+ // A JSDoc node starts at the trivia before it, comments included.
4166
+ getJSDocStart: (jsDoc) => {
4167
+ let sourceText = jsDoc.getSourceFile().text, at = jsDoc.pos;
4168
+ for (; at < sourceText.length && !sourceText.startsWith("/**", at); )
4169
+ if (sourceText.startsWith("//", at)) {
4170
+ let lineEnd = sourceText.indexOf(`
4171
+ `, at);
4172
+ at = lineEnd < 0 ? sourceText.length : lineEnd + 1;
4173
+ } else if (sourceText.startsWith("/*", at)) {
4174
+ let close = sourceText.indexOf("*/", at + 2);
4175
+ at = close < 0 ? sourceText.length : close + 2;
4176
+ } else
4177
+ at += 1;
4178
+ return at;
4179
+ },
4180
+ getJSDocTagCommentStart: (tag) => {
4181
+ let comment = tag.comment, commentStart = typeof comment == "string" ? tag.end : comment.pos, end = tag.tagName.end, afterPart = (part) => {
4182
+ part.end <= commentStart && (end = Math.max(end, part.end));
4183
+ };
4184
+ return tag.forEachChild(afterPart, (parts) => parts.forEach(afterPart)), end;
4185
+ }
4186
+ });
4187
+ function createNativeSystem() {
4188
+ return {
4189
+ fileExists: (path2) => {
4190
+ try {
4191
+ return statSync(path2).isFile();
4192
+ } catch {
4193
+ return !1;
4194
+ }
4195
+ },
4196
+ directoryExists: (path2) => {
4197
+ try {
4198
+ return statSync(path2).isDirectory();
4199
+ } catch {
4200
+ return !1;
4201
+ }
4202
+ },
4203
+ readFile: (path2) => {
4204
+ try {
4205
+ return readFileSync(path2, "utf-8");
4206
+ } catch {
4207
+ return;
4208
+ }
4209
+ },
4210
+ useCaseSensitiveFileNames: isCaseSensitiveFileSystem()
4211
+ };
4212
+ }
4213
+ var isCaseSensitiveFileSystem = () => !existsSync(withSwappedCase(process.execPath)), withSwappedCase = (path2) => path2.replace(/\w/g, (character) => {
4214
+ let upper = character.toUpperCase();
4215
+ return character === upper ? character.toLowerCase() : upper;
4216
+ });
4217
+ function createNativeDocgenTypeScript({ sync, ast, factory }, api) {
4218
+ let leases = [], asNode = (node) => node, composed = composedGuards(ast);
4219
+ return {
4220
+ ...Object.fromEntries(
4221
+ DOCGEN_NODE_GUARDS.map((name) => {
4222
+ let guard = composed[name] ?? ast[NATIVE_GUARD_NAMES[name] ?? name];
4223
+ if (typeof guard != "function")
4224
+ throw new Error(`typescript/ast has no node guard for ${name}`);
4225
+ return [name, (node) => guard(asNode(node))];
4226
+ })
4227
+ ),
4228
+ ...nativeNodeAccessors(ast),
4229
+ JsxEmit: sync.JsxEmit,
4230
+ ModuleKind: sync.ModuleKind,
4231
+ ModuleResolutionKind: sync.ModuleResolutionKind,
4232
+ ObjectFlags: sync.ObjectFlags,
4233
+ ScriptTarget: ast.ScriptTarget,
4234
+ SymbolFlags: sync.SymbolFlags,
4235
+ SyntaxKind: ast.SyntaxKind,
4236
+ TypeFlags: sync.TypeFlags,
4237
+ TypeFormatFlags: sync.TypeFormatFlags,
4238
+ factory: {
4239
+ createLiteralTypeNode: (literal) => factory.createLiteralTypeNode(asNode(literal)),
4240
+ createStringLiteral: (text) => factory.createStringLiteral(text, ast.TokenFlags.None)
4241
+ },
4242
+ sys: createNativeSystem(),
4243
+ canHaveDecorators: (node) => "modifiers" in node,
4244
+ canHaveModifiers: (node) => "modifiers" in node,
4245
+ getDecorators: (node) => node.modifiers?.filter(
4246
+ (modifier) => ast.isDecorator(asNode(modifier))
4247
+ ),
4248
+ getJSDocCommentsAndTags: (node) => ast.getJSDocCommentsAndTags(asNode(node)),
4249
+ getJSDocTags: (node) => ast.getJSDocTags(asNode(node)),
4250
+ getLineAndCharacterOfPosition: (sourceFile, position) => sourceFile.getLineAndCharacterOfPosition(position),
4251
+ printNode: (node, visit) => {
4252
+ let visitChildren = (child) => ast.visitEachChild(
4253
+ asNode(child),
4254
+ (grandchild) => asNode(visit(grandchild, visitChildren))
4255
+ );
4256
+ return api.printer.printNode(asNode(visit(node, visitChildren)));
4257
+ },
4258
+ getModifiers: (node) => node.modifiers?.filter(
4259
+ (modifier) => ast.isModifier(asNode(modifier))
4260
+ ),
4261
+ createSourceFile: (fileName, text) => {
4262
+ let lease = api.createSourceFile(fileName, text);
4263
+ return leases.push(lease), lease.sourceFile;
4264
+ },
4265
+ releaseSourceFiles: () => {
4266
+ for (let lease of leases)
4267
+ lease.dispose();
4268
+ leases = [];
4269
+ },
4270
+ batch: (first, second = []) => {
4271
+ if (first.length === 0 && second.length === 0)
4272
+ return [[], []];
4273
+ let [a, b] = api.batch(
4274
+ sync.all(...first),
4275
+ sync.all(...second)
4276
+ );
4277
+ return [a, b];
4278
+ },
4279
+ displayPartsToString: (parts) => (parts ?? []).map((part) => part.text).join(""),
4280
+ forEachChild: ((node, visitor, visitArray) => asNode(node).forEachChild(
4281
+ visitor,
4282
+ visitArray
4283
+ )),
4284
+ getEmptyObjectType: (checker) => NativeFacades.of(checker).getEmptyObjectType()
4285
+ };
4286
+ }
4287
+ var NativeProject = class {
4288
+ constructor(api, typescript, commandLine, configFileName, getCommandLineFn) {
4289
+ this.api = api, this.typescript = typescript, this.commandLine = commandLine, this.configFileName = configFileName, this.getCommandLineFn = getCommandLineFn, this.fileMtimes = /* @__PURE__ */ new Map(), this.createdAt = Date.now(), this.disposed = !1, this.rootFiles = new Set(commandLine.fileNames), this.snapshot = api.createSnapshot({
4290
+ createPrograms: [this.programParams(this.rootFiles, commandLine)]
4291
+ });
4292
+ let program = this.snapshot.operation.createdPrograms?.[0];
4293
+ if (!program)
4294
+ throw this.snapshot.dispose(), new Error(`TypeScript created no program for ${configFileName ?? "inferred files"}`);
4295
+ this.project = program.getProject();
4296
+ }
4297
+ getCommandLine() {
4298
+ return this.commandLine;
4299
+ }
4300
+ hasSourceFile(fileName) {
4301
+ return this.project.program.getSourceFile(fileName) !== void 0;
4302
+ }
4303
+ getSourceFilePaths() {
4304
+ return filterSourceFilePaths(this.project.program.getSourceFileNames());
4305
+ }
4306
+ getSourceFile(fileName) {
4307
+ return this.project.program.getSourceFile(fileName);
4308
+ }
4309
+ ensureFiles(fileNames) {
4310
+ let missing = fileNames.filter(
4311
+ (fileName) => !this.rootFiles.has(fileName) && !this.hasSourceFile(fileName)
4312
+ );
4313
+ if (missing.length === 0)
4314
+ return;
4315
+ let rootFiles = /* @__PURE__ */ new Set([...this.rootFiles, ...missing]);
4316
+ this.replaceSnapshot(
4317
+ this.snapshot.update({
4318
+ reconfigurePrograms: [this.reconfigureParams(rootFiles, this.commandLine)]
4319
+ })
4320
+ ), this.rootFiles = rootFiles;
4321
+ }
4322
+ onFilesChanged(changes) {
4323
+ if (!this.disposed)
4324
+ try {
4325
+ this.applyFileChanges(changes) && this.afterFilesChanged();
4326
+ } catch (error) {
4327
+ logger.debug(`[component-meta] Ignoring file changes for ${this.configFileName}: ${error}`);
4328
+ }
4329
+ }
4330
+ afterFilesChanged() {
4331
+ }
4332
+ dispose() {
4333
+ this.disposed || (this.disposed = !0, this.moduleResolver?.dispose(), this.snapshot.dispose());
4334
+ }
4335
+ ensureFresh(fileNames) {
4336
+ let changed = [], mtimes = /* @__PURE__ */ new Map();
4337
+ for (let fileName of new Set(fileNames)) {
4338
+ let mtime = modifiedTime(fileName);
4339
+ (this.fileMtimes.has(fileName) ? this.fileMtimes.get(fileName) !== mtime : mtime !== void 0 && mtime > this.createdAt) && changed.push(fileName), mtimes.set(fileName, mtime);
4340
+ }
4341
+ changed.length > 0 && this.replaceSnapshot(
4342
+ this.snapshot.update({ fileNotifications: { changed }, ensurePrograms: !0 })
4343
+ );
4344
+ for (let [fileName, mtime] of mtimes)
4345
+ this.fileMtimes.set(fileName, mtime);
4346
+ return changed.length > 0;
4347
+ }
4348
+ getChecker() {
4349
+ return this.facades ??= new NativeFacades(this.project, this.typescript), this.facades.createChecker();
4350
+ }
4351
+ resolveModule(importId, fromFile) {
4352
+ return this.getModuleResolver().resolveModuleName(importId, dirname(fromFile), void 0, {
4353
+ snapshot: this.snapshot
4354
+ }).resolvedModule?.resolvedFileName;
4355
+ }
4356
+ applyFileChanges(changes) {
4357
+ let byType = (type) => changes.filter((change) => change.type === type).map((change) => change.filePath), created = byType("created"), deleted = byType("deleted"), changed = byType("changed"), known = changes.some((change) => this.hasSourceFile(change.filePath)), commandLine = this.commandLine, rootFiles = this.rootFiles;
4358
+ if ((created.length > 0 || deleted.length > 0) && this.getCommandLineFn) {
4359
+ commandLine = this.getCommandLineFn(), rootFiles = /* @__PURE__ */ new Set([...this.rootFiles, ...commandLine.fileNames]);
4360
+ for (let fileName of deleted)
4361
+ rootFiles.delete(fileName);
4362
+ }
4363
+ let rootsChanged = rootFiles.size !== this.rootFiles.size || [...rootFiles].some((fileName) => !this.rootFiles.has(fileName)), reachesProgram = known || rootsChanged || created.length > 0;
4364
+ if (reachesProgram) {
4365
+ this.replaceSnapshot(
4366
+ this.snapshot.update({
4367
+ fileNotifications: { changed, created, deleted },
4368
+ reconfigurePrograms: rootsChanged ? [this.reconfigureParams(rootFiles, commandLine)] : void 0,
4369
+ ensurePrograms: !0
4370
+ })
4371
+ );
4372
+ for (let fileName of [...changed, ...created])
4373
+ this.fileMtimes.set(fileName, modifiedTime(fileName));
4374
+ for (let fileName of deleted)
4375
+ this.fileMtimes.delete(fileName);
4376
+ }
4377
+ return commandLine !== this.commandLine && (this.commandLine = commandLine, this.rootFiles = rootFiles, this.moduleResolver?.dispose(), this.moduleResolver = void 0), reachesProgram;
4378
+ }
4379
+ programParams(rootFiles, commandLine) {
4380
+ let options = {
4381
+ projectReferences: commandLine.projectReferences?.map(({ path: path2 }) => ({ path: path2 }))
4382
+ };
4383
+ return { rootFiles: [...rootFiles], compilerOptions: commandLine.options, options };
4384
+ }
4385
+ reconfigureParams(rootFiles, commandLine) {
4386
+ return { id: this.project.id, ...this.programParams(rootFiles, commandLine) };
4387
+ }
4388
+ getModuleResolver() {
4389
+ return this.moduleResolver ??= this.api.createModuleResolver(this.commandLine.options), this.moduleResolver;
4390
+ }
4391
+ replaceSnapshot(next) {
4392
+ let project = next.getProgram(this.project.id)?.getProject();
4393
+ if (!project)
4394
+ throw next.dispose(), new Error(
4395
+ `TypeScript dropped the program of ${this.configFileName ?? "inferred files"}`
4396
+ );
4397
+ let previous = this.snapshot;
4398
+ this.snapshot = next, this.project = project, this.facades = void 0, previous.dispose();
4399
+ }
4400
+ }, modifiedTime = (fileName) => {
4401
+ try {
4402
+ return statSync2(fileName).mtimeMs;
4403
+ } catch {
4404
+ return;
4405
+ }
4406
+ };
4407
+ function createNativeBackend(modules, ProjectClass, inferredOptions) {
4408
+ let api = new modules.sync.API({ cwd: process.cwd() }), typescript = createNativeDocgenTypeScript(modules, api);
4409
+ return {
4410
+ fileSystem: typescript,
4411
+ factory: {
4412
+ parseCommandLine: (tsconfig) => {
4413
+ let { fileNames, options, projectReferences } = api.parseConfigFile(tsconfig);
4414
+ return {
4415
+ fileNames: [...fileNames],
4416
+ options,
4417
+ projectReferences
4418
+ };
4419
+ },
4420
+ createConfiguredProject: (commandLine, tsconfig, getCommandLine) => new ProjectClass(api, typescript, commandLine, tsconfig, getCommandLine),
4421
+ createInferredProject: () => new ProjectClass(api, typescript, { fileNames: [], options: inferredOptions }, void 0),
4422
+ dispose: () => api.close()
4423
+ }
4424
+ };
4425
+ }
4426
+ function createComponentMetaBackend(loaded, create) {
4427
+ return loaded.api === "native" ? create.native(loaded.typescript) : create.compiler(loaded.typescript);
4428
+ }
4429
+
4430
+ // src/componentManifest/componentMeta/ComponentMetaManager.ts
4431
+ import {
4432
+ ComponentMetaManager as BaseComponentMetaManager,
4433
+ parseTsconfigCommandLine
4434
+ } from "storybook/internal/component-meta";
4435
+ import { logger as logger3 } from "storybook/internal/node-logger";
4436
+
4437
+ // src/componentManifest/componentMeta/ComponentMetaProject.ts
4438
+ var import_language_core = __toESM(require_language_core(), 1), import_typescript = __toESM(require_typescript(), 1);
4439
+ import {
4440
+ ProgramBackedProject,
4441
+ ProjectFileTracker
4442
+ } from "storybook/internal/component-meta";
4443
+ import * as path from "path";
4444
+
4445
+ // src/componentManifest/componentMeta/extract-entries.ts
4446
+ import { logger as logger2 } from "storybook/internal/node-logger";
4447
+
4448
+ // src/componentManifest/componentMeta/componentMetaExtractor.ts
4449
+ import { extractComponentJsDocInfo } from "storybook/internal/component-meta";
4450
+ var LARGE_SOURCE_THRESHOLD = 30, MAX_UNWRAP_DEPTH = 5, MAX_SERIALIZATION_DEPTH = 5;
4451
+ function isLiteralType(type) {
4452
+ return type.isStringLiteral() || type.isNumberLiteral();
4453
+ }
4454
+ function isUnionType(type) {
4455
+ return type.isUnion();
4456
+ }
4457
+ function isWrappedExpression(typescript, expression) {
4458
+ return typescript.isParenthesizedExpression(expression) || typescript.isAsExpression(expression) || typescript.isNonNullExpression(expression) || (typescript.isSatisfiesExpression?.(expression) ?? !1);
4459
+ }
4460
+ function resolveAliasedSymbol(typescript, checker, symbol) {
4461
+ return symbol.flags & typescript.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
4462
+ }
4463
+ function getSymbolContextNode(symbol) {
4464
+ return symbol.valueDeclaration ?? symbol.getDeclarations()?.[0];
4465
+ }
4466
+ function resolveComponentSymbolFromNode(typescript, checker, node) {
4467
+ if (!node)
4468
+ return;
4469
+ let symbol = checker.getSymbolAtLocation(node);
4470
+ return symbol ? resolveComponentSymbol(typescript, checker, symbol, node) : void 0;
4471
+ }
4472
+ function resolveComponentSymbol(typescript, checker, symbol, contextNode, depth = 0) {
4473
+ let resolved = resolveAliasedSymbol(typescript, checker, symbol);
4474
+ if (depth > MAX_UNWRAP_DEPTH)
4475
+ return resolved;
4476
+ let declarationForPromotion = getSymbolContextNode(resolved);
4477
+ if (declarationForPromotion && (typescript.isArrowFunction(declarationForPromotion) || typescript.isFunctionExpression(declarationForPromotion)) && declarationForPromotion.parent && typescript.isVariableDeclaration(declarationForPromotion.parent) && typescript.isIdentifier(declarationForPromotion.parent.name)) {
4478
+ let variableSymbol = checker.getSymbolAtLocation(declarationForPromotion.parent.name);
4479
+ variableSymbol && (resolved = resolveAliasedSymbol(typescript, checker, variableSymbol));
4480
+ }
4481
+ let declaration = getSymbolContextNode(resolved);
4482
+ if (declaration) {
4483
+ if (typescript.isShorthandPropertyAssignment(declaration)) {
4484
+ let valueSymbol = checker.getShorthandAssignmentValueSymbol(declaration);
4485
+ if (valueSymbol)
4486
+ return resolveComponentSymbol(
4487
+ typescript,
4488
+ checker,
4489
+ valueSymbol,
4490
+ declaration.name,
4491
+ depth + 1
4492
+ );
4493
+ }
4494
+ if (typescript.isPropertyAssignment(declaration)) {
4495
+ let next = resolveComponentSymbolFromNode(typescript, checker, declaration.initializer);
4496
+ if (next)
4497
+ return next;
4498
+ }
4499
+ if (typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken) {
4500
+ let next = resolveComponentSymbolFromNode(typescript, checker, declaration.right);
4501
+ if (next)
4502
+ return next;
4503
+ }
4504
+ }
4505
+ let typeSymbol = (!!(resolved.flags & typescript.SymbolFlags.Property) || declaration !== void 0 && (typescript.isPropertyAssignment(declaration) || typescript.isShorthandPropertyAssignment(declaration) || typescript.isPropertySignature(declaration) || typescript.isPropertyDeclaration(declaration) || typescript.isBinaryExpression(declaration) && declaration.operatorToken.kind === typescript.SyntaxKind.EqualsToken)) && checker.getTypeOfSymbolAtLocation(resolved, contextNode).getSymbol?.();
4506
+ if (typeSymbol) {
4507
+ let resolvedTypeSymbol = resolveAliasedSymbol(typescript, checker, typeSymbol), typeDeclaration = getSymbolContextNode(resolvedTypeSymbol);
4508
+ if (resolvedTypeSymbol !== resolved && typeDeclaration)
4509
+ return resolveComponentSymbol(
4510
+ typescript,
4511
+ checker,
4512
+ resolvedTypeSymbol,
4513
+ typeDeclaration,
4514
+ depth + 1
4515
+ );
4516
+ }
4517
+ return resolved;
4518
+ }
4519
+ function findImportSymbolInStoryFile(typescript, checker, storySourceFile, componentRef) {
4520
+ let importSpecifier = componentRef.importId, importName = componentRef.importName, memberAccess = componentRef.member;
4521
+ if (importSpecifier)
4522
+ for (let stmt of storySourceFile.statements) {
4523
+ if (!typescript.isImportDeclaration(stmt))
4524
+ continue;
4525
+ let moduleSpec = stmt.moduleSpecifier;
4526
+ if (!typescript.isStringLiteral(moduleSpec) || moduleSpec.text !== importSpecifier)
4527
+ continue;
4528
+ let clause = stmt.importClause;
4529
+ if (!clause)
4530
+ continue;
4531
+ let importSymbol;
4532
+ if (importName === "default") {
4533
+ if (clause.name && (importSymbol = checker.getSymbolAtLocation(clause.name)), !importSymbol && clause.namedBindings && typescript.isNamedImports(clause.namedBindings)) {
4534
+ for (let spec of clause.namedBindings.elements)
4535
+ if ((spec.propertyName ?? spec.name).text === "default") {
4536
+ importSymbol = checker.getSymbolAtLocation(spec.name);
4537
+ break;
4538
+ }
4539
+ }
4540
+ } else if (clause.namedBindings && typescript.isNamedImports(clause.namedBindings)) {
4541
+ for (let spec of clause.namedBindings.elements)
4542
+ if ((spec.propertyName ?? spec.name).text === importName) {
4543
+ importSymbol = checker.getSymbolAtLocation(spec.name);
4544
+ break;
4545
+ }
4546
+ }
4547
+ if (!importSymbol && memberAccess && clause.namedBindings && typescript.isNamespaceImport(clause.namedBindings) && (importSymbol = checker.getSymbolAtLocation(clause.namedBindings.name)), importSymbol)
4548
+ return importSymbol;
4549
+ }
4550
+ }
4551
+ function metaComponentMatchesRef(typescript, checker, storySourceFile, componentRef, metaComponentInitializer) {
4552
+ let refSymbol = findImportSymbolInStoryFile(typescript, checker, storySourceFile, componentRef), metaSymbol = resolveComponentSymbolFromNode(typescript, checker, metaComponentInitializer);
4553
+ if (refSymbol && metaSymbol && !componentRef.member)
4554
+ return resolveAliasedSymbol(typescript, checker, refSymbol) === resolveAliasedSymbol(typescript, checker, metaSymbol);
4555
+ if (typescript.isIdentifier(metaComponentInitializer))
4556
+ return componentRef.componentName === metaComponentInitializer.text;
4557
+ if (typescript.isPropertyAccessExpression(metaComponentInitializer) && typescript.isIdentifier(metaComponentInitializer.expression)) {
4558
+ let metaName = `${metaComponentInitializer.expression.text}.${metaComponentInitializer.name.text}`;
4559
+ return componentRef.componentName === metaName;
4560
+ }
4561
+ return !1;
4562
+ }
4563
+ function resolvePropsFromStoryFile(typescript, checker, storySourceFile, componentRef) {
4564
+ let memberAccess = componentRef.member, importSymbol = findImportSymbolInStoryFile(
4565
+ typescript,
4566
+ checker,
4567
+ storySourceFile,
4568
+ componentRef
4569
+ );
4570
+ if (!importSymbol)
4571
+ return;
4572
+ let result;
4573
+ function extractPropsFromJsx(node) {
4574
+ let sig = checker.getResolvedSignature(node);
4575
+ if (!sig)
4576
+ return;
4577
+ let params = sig.getParameters();
4578
+ return params.length === 0 ? typescript.getEmptyObjectType(checker) : checker.getTypeOfSymbolAtLocation(params[0], node);
4579
+ }
4580
+ function visit(node) {
4581
+ if (!result) {
4582
+ if (typescript.isJsxSelfClosingElement(node) || typescript.isJsxOpeningElement(node)) {
4583
+ let tagName = node.tagName;
4584
+ if (memberAccess) {
4585
+ if (typescript.isPropertyAccessExpression(tagName) && tagName.name.text === memberAccess) {
4586
+ let leftSym = checker.getSymbolAtLocation(tagName.expression);
4587
+ if (leftSym && importSymbol && leftSym === importSymbol) {
4588
+ let propsType = extractPropsFromJsx(node);
4589
+ if (propsType) {
4590
+ let memberSymbol = checker.getSymbolAtLocation(tagName.name) ?? checker.getTypeAtLocation(tagName.expression).getProperty(tagName.name.text) ?? resolveComponentSymbolFromNode(typescript, checker, tagName);
4591
+ result = {
4592
+ componentRef,
4593
+ propsType,
4594
+ symbol: memberSymbol ? resolveComponentSymbol(typescript, checker, memberSymbol, tagName.name) : resolveAliasedSymbol(typescript, checker, importSymbol)
4595
+ };
4596
+ return;
4597
+ }
4598
+ }
4599
+ }
4600
+ } else if (typescript.isIdentifier(tagName)) {
4601
+ let sym = checker.getSymbolAtLocation(tagName);
4602
+ if (sym && importSymbol && sym === importSymbol) {
4603
+ let propsType = extractPropsFromJsx(node);
4604
+ if (propsType) {
4605
+ result = {
4606
+ componentRef,
4607
+ propsType,
4608
+ symbol: resolveAliasedSymbol(typescript, checker, sym)
4609
+ };
4610
+ return;
4611
+ }
4612
+ }
4613
+ }
4614
+ }
4615
+ typescript.forEachChild(node, visit);
4616
+ }
4617
+ }
4618
+ return visit(storySourceFile), result;
4619
+ }
4620
+ function resolvePropsFromComponentType(typescript, checker, componentType) {
4621
+ let callSigs = componentType.getCallSignatures();
4622
+ if (callSigs.length > 0) {
4623
+ let sig = callSigs[0];
4624
+ if (sig.parameters.length === 0)
4625
+ return checker.getVoidType();
4626
+ let propsType = checker.getTypeOfSymbol(sig.parameters[0]);
4627
+ if (!(propsType.flags & typescript.TypeFlags.Any))
4628
+ return propsType;
4629
+ }
4630
+ let ctorSigs = componentType.getConstructSignatures();
4631
+ for (let sig of ctorSigs) {
4632
+ let propsSym = sig.getReturnType().getProperty("props");
4633
+ if (propsSym) {
4634
+ let propsType = checker.getTypeOfSymbol(propsSym);
4635
+ if (!(propsType.flags & typescript.TypeFlags.Any))
4636
+ return propsType;
4637
+ }
4638
+ }
4639
+ }
3535
4640
  function resolvePropsFromComponentExport(typescript, checker, componentSourceFile, componentRef) {
3536
4641
  let moduleSymbol = checker.getSymbolAtLocation(componentSourceFile);
3537
4642
  if (!moduleSymbol)
@@ -3816,7 +4921,9 @@ function getJSDocDefault(typescript, prop, checker) {
3816
4921
  return typescript.displayPartsToString(tag.text) || void 0;
3817
4922
  }
3818
4923
  function extractPropItem(typescript, checker, prop, contextNode, defaultsMap, typeOverride) {
3819
- let isRequired = !!!(prop.flags & typescript.SymbolFlags.Optional), propType = typeOverride ?? checker.getTypeOfSymbolAtLocation(prop, contextNode), type = serializeType(typescript, checker, propType, isRequired), description = typescript.displayPartsToString(prop.getDocumentationComment(checker)), parent = getParentType(typescript, prop), declarations = getAllDeclarationParents(typescript, prop), propName = prop.getName(), destructuringDefault = defaultsMap?.get(propName), jsDocDefault = getJSDocDefault(typescript, prop, checker), defaultStr = destructuringDefault ?? jsDocDefault;
4924
+ let isRequired = !!!(prop.flags & typescript.SymbolFlags.Optional), propType = typeOverride ?? checker.getTypeOfSymbolAtLocation(prop, contextNode), type = serializeType(typescript, checker, propType, isRequired), description = typescript.displayPartsToString(
4925
+ prop.getDocumentationComment(checker)
4926
+ ), parent = getParentType(typescript, prop), declarations = getAllDeclarationParents(typescript, prop), propName = prop.getName(), destructuringDefault = defaultsMap?.get(propName), jsDocDefault = getJSDocDefault(typescript, prop, checker), defaultStr = destructuringDefault ?? jsDocDefault;
3820
4927
  return {
3821
4928
  name: propName,
3822
4929
  required: isRequired,
@@ -3938,13 +5045,7 @@ function extractDefaultsFromSourceFile(typescript, filePath, {
3938
5045
  let defaults = /* @__PURE__ */ new Map(), content = typescript.sys.readFile(filePath);
3939
5046
  if (!content)
3940
5047
  return defaults;
3941
- let sf = typescript.createSourceFile(
3942
- filePath,
3943
- content,
3944
- typescript.ScriptTarget.Latest,
3945
- /* setParentNodes */
3946
- !0
3947
- ), varMap = /* @__PURE__ */ new Map();
5048
+ let sf = typescript.createSourceFile(filePath, content), varMap = /* @__PURE__ */ new Map();
3948
5049
  for (let stmt of sf.statements) {
3949
5050
  if (typescript.isVariableStatement(stmt))
3950
5051
  for (let decl of stmt.declarationList.declarations)
@@ -4037,6 +5138,90 @@ function hasExportModifier(typescript, node) {
4037
5138
  return typescript.canHaveModifiers(node) && typescript.getModifiers(node)?.some((m) => m.kind === typescript.SyntaxKind.ExportKeyword) === !0;
4038
5139
  }
4039
5140
 
5141
+ // src/componentManifest/componentMeta/extract-entries.ts
5142
+ var isDeclarationFile = (fileName) => fileName.endsWith(".d.ts") || fileName.endsWith(".d.mts") || fileName.endsWith(".d.cts");
5143
+ function extractEntries({ typescript, checker, program, resolveModule }, entries) {
5144
+ let serializationContextByComponentPath = /* @__PURE__ */ new Map();
5145
+ for (let entry of entries)
5146
+ try {
5147
+ let storySourceFile = program.getSourceFile(entry.storyPath), entryComponent = entry.component, componentPath = entryComponent?.path, exportName = entryComponent?.importName;
5148
+ if (!storySourceFile || !componentPath || !exportName || !entryComponent)
5149
+ continue;
5150
+ let importId = entryComponent.importId, isPackageImport = importId && !importId.startsWith("."), componentSourceFile = program.getSourceFile(
5151
+ isPackageImport && resolveModule(importId, entry.storyPath) || componentPath
5152
+ );
5153
+ if (!componentSourceFile)
5154
+ continue;
5155
+ let resolvedComponent;
5156
+ if (importId && (resolvedComponent = resolvePropsFromStoryFile(
5157
+ typescript,
5158
+ checker,
5159
+ storySourceFile,
5160
+ entryComponent
5161
+ )), resolvedComponent || (resolvedComponent = resolveFromMetaComponent(
5162
+ typescript,
5163
+ checker,
5164
+ storySourceFile,
5165
+ entryComponent
5166
+ )), resolvedComponent || (resolvedComponent = resolvePropsFromComponentExport(
5167
+ typescript,
5168
+ checker,
5169
+ componentSourceFile,
5170
+ entryComponent
5171
+ )), !resolvedComponent)
5172
+ continue;
5173
+ let serializationContext = serializationContextByComponentPath.get(componentPath);
5174
+ serializationContext === void 0 && (serializationContext = {
5175
+ sourceFile: componentSourceFile,
5176
+ defaultsSourcePath: isDeclarationFile(componentSourceFile.fileName) ? componentPath : void 0
5177
+ }, serializationContextByComponentPath.set(componentPath, serializationContext));
5178
+ let doc = serializeComponentDoc(typescript, checker, {
5179
+ sourceFile: serializationContext.sourceFile,
5180
+ resolvedComponent,
5181
+ defaultsSourcePath: serializationContext.defaultsSourcePath
5182
+ });
5183
+ doc && (entryComponent.reactComponentMeta = doc, entryComponent.componentJsDocTags = doc.jsDocTags, entryComponent.importOverride = entryComponent.componentJsDocTags?.import?.[0]?.trim());
5184
+ } catch (error) {
5185
+ logger2.debug(`[reactComponentMeta] Extraction failed for ${entry.storyPath}: ${error}`);
5186
+ continue;
5187
+ }
5188
+ }
5189
+ function resolveFromMetaComponent(typescript, checker, storySourceFile, componentRef) {
5190
+ let { member: memberAccess } = componentRef, moduleSymbol = checker.getSymbolAtLocation(storySourceFile);
5191
+ if (!moduleSymbol)
5192
+ return;
5193
+ let defaultExport = checker.getExportsOfModule(moduleSymbol).find((e) => e.getName() === "default");
5194
+ if (!defaultExport)
5195
+ return;
5196
+ let componentProp = checker.getTypeOfSymbol(defaultExport).getProperty("component");
5197
+ if (!componentProp?.valueDeclaration || !typescript.isPropertyAssignment(componentProp.valueDeclaration))
5198
+ return;
5199
+ let metaComponentInitializer = componentProp.valueDeclaration.initializer;
5200
+ if (!metaComponentInitializer || !metaComponentMatchesRef(
5201
+ typescript,
5202
+ checker,
5203
+ storySourceFile,
5204
+ componentRef,
5205
+ metaComponentInitializer
5206
+ ))
5207
+ return;
5208
+ let componentType = checker.getTypeOfSymbol(componentProp), selectedSymbol = checker.getSymbolAtLocation(metaComponentInitializer);
5209
+ if (memberAccess) {
5210
+ let prop = componentType.getProperty(memberAccess);
5211
+ if (prop)
5212
+ componentType = checker.getTypeOfSymbol(prop), selectedSymbol = prop;
5213
+ else
5214
+ return;
5215
+ }
5216
+ let propsType = resolvePropsFromComponentType(typescript, checker, componentType);
5217
+ if (!(!propsType || !selectedSymbol))
5218
+ return {
5219
+ componentRef,
5220
+ propsType,
5221
+ symbol: selectedSymbol
5222
+ };
5223
+ }
5224
+
4040
5225
  // src/componentManifest/componentMeta/ComponentMetaProject.ts
4041
5226
  var ComponentMetaProject = class extends ProgramBackedProject {
4042
5227
  constructor(typescript, commandLine, configFileName, fsFileSnapshots = /* @__PURE__ */ new Map(), getCommandLineFn, documentRegistry) {
@@ -4047,7 +5232,7 @@ var ComponentMetaProject = class extends ProgramBackedProject {
4047
5232
  this.documentRegistry = documentRegistry;
4048
5233
  /** Entries to extract - set by the generator, replayed during warmup for targeted type resolution. */
4049
5234
  this.entries = [];
4050
- this.files = new ProjectFileTracker(
5235
+ this.docgenTypeScript = createCompilerDocgenTypeScript(typescript), this.files = new ProjectFileTracker(
4051
5236
  typescript,
4052
5237
  commandLine,
4053
5238
  fsFileSnapshots,
@@ -4106,9 +5291,6 @@ var ComponentMetaProject = class extends ProgramBackedProject {
4106
5291
  }
4107
5292
  }, 100), this.warmupTimer?.unref?.());
4108
5293
  }
4109
- // ---------------------------------------------------------------------------
4110
- // Primary extraction method - probe-free
4111
- // ---------------------------------------------------------------------------
4112
5294
  extractPropsFromStories(entries) {
4113
5295
  this.entries = entries;
4114
5296
  let allFiles = entries.flatMap(
@@ -4116,104 +5298,61 @@ var ComponentMetaProject = class extends ProgramBackedProject {
4116
5298
  );
4117
5299
  this.files.ensureFiles(allFiles), this.files.ensureFresh(allFiles);
4118
5300
  let program = this.service.getProgram();
4119
- if (!program)
5301
+ program && extractEntries(
5302
+ {
5303
+ typescript: this.docgenTypeScript,
5304
+ checker: program.getTypeChecker(),
5305
+ program,
5306
+ resolveModule: (importId, fromFile) => this.typescript.resolveModuleName(
5307
+ importId,
5308
+ fromFile,
5309
+ this.commandLine.options,
5310
+ this.typescript.sys
5311
+ ).resolvedModule?.resolvedFileName
5312
+ },
5313
+ entries
5314
+ );
5315
+ }
5316
+ };
5317
+
5318
+ // src/componentManifest/componentMeta/native/native-component-meta-project.ts
5319
+ var WARMUP_DELAY_MS = 100, NativeComponentMetaProject = class extends NativeProject {
5320
+ constructor() {
5321
+ super(...arguments);
5322
+ this.entries = [];
5323
+ }
5324
+ extractPropsFromStories(entries) {
5325
+ if (this.disposed)
4120
5326
  return;
4121
- let checker = program.getTypeChecker(), serializationContextByComponentPath = /* @__PURE__ */ new Map();
4122
- for (let entry of entries)
5327
+ this.entries = entries;
5328
+ let allFiles = entries.flatMap(
5329
+ (entry) => entry.component?.path ? [entry.storyPath, entry.component.path] : [entry.storyPath]
5330
+ );
5331
+ this.ensureFiles(allFiles), this.ensureFresh(allFiles);
5332
+ try {
5333
+ extractEntries(
5334
+ {
5335
+ typescript: this.typescript,
5336
+ checker: this.getChecker(),
5337
+ program: { getSourceFile: (fileName) => this.getSourceFile(fileName) },
5338
+ resolveModule: (importId, fromFile) => this.resolveModule(importId, fromFile)
5339
+ },
5340
+ entries
5341
+ );
5342
+ } finally {
5343
+ this.typescript.releaseSourceFiles();
5344
+ }
5345
+ }
5346
+ afterFilesChanged() {
5347
+ this.entries.length !== 0 && (clearTimeout(this.warmupTimer), this.warmupTimer = setTimeout(() => {
4123
5348
  try {
4124
- let storySourceFile = program.getSourceFile(entry.storyPath), entryComponent = entry.component, componentPath = entryComponent?.path, exportName = entryComponent?.importName;
4125
- if (!storySourceFile || !componentPath || !exportName || !entryComponent)
4126
- continue;
4127
- let importId = entryComponent.importId, isPackageImport = importId && !importId.startsWith("."), componentSourceFile;
4128
- if (isPackageImport) {
4129
- let resolved = this.typescript.resolveModuleName(
4130
- importId,
4131
- entry.storyPath,
4132
- this.commandLine.options,
4133
- this.typescript.sys
4134
- );
4135
- componentSourceFile = resolved.resolvedModule ? program.getSourceFile(resolved.resolvedModule.resolvedFileName) : program.getSourceFile(componentPath);
4136
- } else
4137
- componentSourceFile = program.getSourceFile(componentPath);
4138
- if (!componentSourceFile)
4139
- continue;
4140
- let resolvedComponent;
4141
- if (importId && (resolvedComponent = resolvePropsFromStoryFile(
4142
- this.typescript,
4143
- checker,
4144
- storySourceFile,
4145
- entryComponent
4146
- )), resolvedComponent || (resolvedComponent = this.resolveFromMetaComponent(
4147
- checker,
4148
- storySourceFile,
4149
- entryComponent
4150
- )), resolvedComponent || (resolvedComponent = resolvePropsFromComponentExport(
4151
- this.typescript,
4152
- checker,
4153
- componentSourceFile,
4154
- entryComponent
4155
- )), !resolvedComponent)
4156
- continue;
4157
- let serializationContext = serializationContextByComponentPath.get(componentPath);
4158
- if (serializationContext === void 0) {
4159
- let resolvedFileName = componentSourceFile.fileName;
4160
- serializationContext = {
4161
- sourceFile: componentSourceFile,
4162
- defaultsSourcePath: resolvedFileName.endsWith(".d.ts") || resolvedFileName.endsWith(".d.mts") || resolvedFileName.endsWith(".d.cts") ? componentPath : void 0
4163
- }, serializationContextByComponentPath.set(componentPath, serializationContext);
4164
- }
4165
- let doc = serializeComponentDoc(this.typescript, checker, {
4166
- sourceFile: serializationContext.sourceFile,
4167
- resolvedComponent,
4168
- defaultsSourcePath: serializationContext.defaultsSourcePath
4169
- });
4170
- doc && (entryComponent.reactComponentMeta = doc, entryComponent.componentJsDocTags = doc.jsDocTags, entryComponent.importOverride = entryComponent.componentJsDocTags?.import?.[0]?.trim());
5349
+ this.extractPropsFromStories(this.entries);
4171
5350
  } catch {
4172
- continue;
4173
5351
  }
5352
+ }, WARMUP_DELAY_MS), this.warmupTimer?.unref?.());
4174
5353
  }
4175
- // ---------------------------------------------------------------------------
4176
- // Internal helpers
4177
- // ---------------------------------------------------------------------------
4178
- /**
4179
- * Path 2 fallback: resolve the component type from the story file's `meta.component` property.
4180
- * Only works when the user explicitly set `component:` in the meta - no node means no
4181
- * extraction.
4182
- */
4183
- resolveFromMetaComponent(checker, storySourceFile, componentRef) {
4184
- let { member: memberAccess } = componentRef, moduleSymbol = checker.getSymbolAtLocation(storySourceFile);
4185
- if (!moduleSymbol)
4186
- return;
4187
- let defaultExport = checker.getExportsOfModule(moduleSymbol).find((e) => e.getName() === "default");
4188
- if (!defaultExport)
4189
- return;
4190
- let componentProp = checker.getTypeOfSymbol(defaultExport).getProperty("component");
4191
- if (!componentProp?.valueDeclaration || !this.typescript.isPropertyAssignment(componentProp.valueDeclaration))
4192
- return;
4193
- let metaComponentInitializer = componentProp.valueDeclaration.initializer;
4194
- if (!metaComponentInitializer || !metaComponentMatchesRef(
4195
- this.typescript,
4196
- checker,
4197
- storySourceFile,
4198
- componentRef,
4199
- metaComponentInitializer
4200
- ))
4201
- return;
4202
- let componentType = checker.getTypeOfSymbol(componentProp), selectedSymbol = checker.getSymbolAtLocation(metaComponentInitializer);
4203
- if (memberAccess) {
4204
- let prop = componentType.getProperty(memberAccess);
4205
- if (prop)
4206
- componentType = checker.getTypeOfSymbol(prop), selectedSymbol = prop;
4207
- else
4208
- return;
4209
- }
4210
- let propsType = resolvePropsFromComponentType(this.typescript, checker, componentType);
4211
- if (!(!propsType || !selectedSymbol))
4212
- return {
4213
- componentRef,
4214
- propsType,
4215
- symbol: selectedSymbol
4216
- };
5354
+ dispose() {
5355
+ clearTimeout(this.warmupTimer), super.dispose();
4217
5356
  }
4218
5357
  };
4219
5358
 
@@ -4225,53 +5364,59 @@ var DEFAULT_INFERRED_OPTIONS = {
4225
5364
  allowJs: !0,
4226
5365
  skipLibCheck: !0
4227
5366
  };
4228
- function createReactProjectFactory(typescript) {
4229
- let fsFileSnapshots = /* @__PURE__ */ new Map(), documentRegistry = typescript.createDocumentRegistry(
5367
+ function createCompilerApiBackend(typescript, fsFileSnapshots) {
5368
+ let documentRegistry = typescript.createDocumentRegistry(
4230
5369
  typescript.sys.useCaseSensitiveFileNames
4231
5370
  );
4232
- return {
4233
- fsFileSnapshots,
4234
- factory: {
4235
- parseCommandLine: (tsconfig) => parseTsconfigCommandLine(typescript, tsconfig),
4236
- createConfiguredProject: (commandLine, tsconfig, getCommandLine) => new ComponentMetaProject(
4237
- typescript,
4238
- commandLine,
4239
- tsconfig,
4240
- fsFileSnapshots,
4241
- getCommandLine,
4242
- documentRegistry
4243
- ),
4244
- createInferredProject: () => new ComponentMetaProject(
4245
- typescript,
4246
- {
4247
- options: {
4248
- ...DEFAULT_INFERRED_OPTIONS,
4249
- target: typescript.ScriptTarget.Latest,
4250
- module: typescript.ModuleKind.ESNext,
4251
- moduleResolution: typescript.ModuleResolutionKind.Bundler,
4252
- jsx: typescript.JsxEmit.ReactJSX
4253
- },
4254
- fileNames: [],
4255
- errors: []
5371
+ return { fileSystem: typescript, factory: {
5372
+ parseCommandLine: (tsconfig) => parseTsconfigCommandLine(typescript, tsconfig),
5373
+ createConfiguredProject: (commandLine, tsconfig, getCommandLine) => new ComponentMetaProject(
5374
+ typescript,
5375
+ commandLine,
5376
+ tsconfig,
5377
+ fsFileSnapshots,
5378
+ getCommandLine,
5379
+ documentRegistry
5380
+ ),
5381
+ createInferredProject: () => new ComponentMetaProject(
5382
+ typescript,
5383
+ {
5384
+ options: {
5385
+ ...DEFAULT_INFERRED_OPTIONS,
5386
+ target: typescript.ScriptTarget.Latest,
5387
+ module: typescript.ModuleKind.ESNext,
5388
+ moduleResolution: typescript.ModuleResolutionKind.Bundler,
5389
+ jsx: typescript.JsxEmit.ReactJSX
4256
5390
  },
4257
- void 0,
4258
- fsFileSnapshots,
4259
- void 0,
4260
- documentRegistry
4261
- ),
4262
- dispose: () => fsFileSnapshots.clear()
4263
- }
4264
- };
5391
+ fileNames: [],
5392
+ errors: []
5393
+ },
5394
+ void 0,
5395
+ fsFileSnapshots,
5396
+ void 0,
5397
+ documentRegistry
5398
+ ),
5399
+ dispose: () => fsFileSnapshots.clear()
5400
+ } };
4265
5401
  }
4266
5402
  var ComponentMetaManager = class extends BaseComponentMetaManager {
4267
5403
  /**
4268
- * @param recycleHeapPressureRatio Fraction of the V8 heap limit at which the shared program(s)
4269
- * are recycled. Exposed for tuning and for the memory regression gate, which passes `Infinity`
4270
- * to disable recycling and assert the OOM still happens without the fix.
5404
+ * `recycleHeapPressureRatio` is the fraction of the V8 heap limit at which the shared program(s)
5405
+ * are recycled; the memory regression gate passes `Infinity` to disable recycling and assert the
5406
+ * OOM still happens without the fix.
4271
5407
  */
4272
5408
  constructor(typescript, recycleHeapPressureRatio) {
4273
- let { factory, fsFileSnapshots } = createReactProjectFactory(typescript);
4274
- super(typescript, factory, recycleHeapPressureRatio), this.fsFileSnapshots = fsFileSnapshots;
5409
+ let fsFileSnapshots = /* @__PURE__ */ new Map(), { fileSystem, factory } = createComponentMetaBackend(typescript, {
5410
+ compiler: (compilerApi) => createCompilerApiBackend(compilerApi, fsFileSnapshots),
5411
+ native: (modules) => createNativeBackend(modules, NativeComponentMetaProject, {
5412
+ ...DEFAULT_INFERRED_OPTIONS,
5413
+ target: modules.ast.ScriptTarget.Latest,
5414
+ module: modules.sync.ModuleKind.ESNext,
5415
+ moduleResolution: modules.sync.ModuleResolutionKind.Bundler,
5416
+ jsx: modules.sync.JsxEmit.ReactJSX
5417
+ })
5418
+ });
5419
+ super(fileSystem, factory, recycleHeapPressureRatio), this.fsFileSnapshots = fsFileSnapshots;
4275
5420
  }
4276
5421
  /**
4277
5422
  * Batch-extract component props across all entries, grouping by tsconfig project so each project
@@ -4288,14 +5433,14 @@ var ComponentMetaManager = class extends BaseComponentMetaManager {
4288
5433
  try {
4289
5434
  project.extractPropsFromStories(projectEntries);
4290
5435
  } catch (err) {
4291
- logger.debug(`[reactComponentMeta] Batch extraction failed: ${err}`);
5436
+ logger3.debug(`[reactComponentMeta] Batch extraction failed: ${err}`);
4292
5437
  }
4293
5438
  this.recycleProjectsIfHeapPressured();
4294
5439
  }
4295
5440
  };
4296
5441
 
4297
5442
  // ../../../node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
4298
- var _lazyMatch = () => {
5443
+ var _lazyMatch2 = () => {
4299
5444
  var __lib__ = (() => {
4300
5445
  var m = Object.defineProperty, V = Object.getOwnPropertyDescriptor, G = Object.getOwnPropertyNames, T = Object.prototype.hasOwnProperty, q = (r, e) => {
4301
5446
  for (var n in e) m(r, n, { get: e[n], enumerable: !0 });
@@ -4448,17 +5593,17 @@ var _lazyMatch = () => {
4448
5593
  return J(w);
4449
5594
  })();
4450
5595
  return __lib__.default || __lib__;
4451
- }, _match, zeptomatch = (path2, pattern) => (_match || (_match = _lazyMatch(), _lazyMatch = null), _match(path2, pattern)), _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
4452
- function normalizeWindowsPath(input = "") {
4453
- return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
5596
+ }, _match2, zeptomatch2 = (path2, pattern) => (_match2 || (_match2 = _lazyMatch2(), _lazyMatch2 = null), _match2(path2, pattern)), _DRIVE_LETTER_START_RE2 = /^[A-Za-z]:\//;
5597
+ function normalizeWindowsPath2(input = "") {
5598
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE2, (r) => r.toUpperCase());
4454
5599
  }
4455
- var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/, _EXTNAME_RE = /.(\.[^./]+|\.)$/, _PATH_ROOT_RE = /^[/\\]|^[a-zA-Z]:[/\\]/, sep = "/", normalize = function(path2) {
5600
+ var _UNC_REGEX2 = /^[/\\]{2}/, _IS_ABSOLUTE_RE2 = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE2 = /^[A-Za-z]:$/, _ROOT_FOLDER_RE2 = /^\/([A-Za-z]:)?$/, _EXTNAME_RE2 = /.(\.[^./]+|\.)$/, _PATH_ROOT_RE2 = /^[/\\]|^[a-zA-Z]:[/\\]/, sep2 = "/", normalize2 = function(path2) {
4456
5601
  if (path2.length === 0)
4457
5602
  return ".";
4458
- path2 = normalizeWindowsPath(path2);
4459
- let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
4460
- return path2 = normalizeString(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2);
4461
- }, join = function(...segments) {
5603
+ path2 = normalizeWindowsPath2(path2);
5604
+ let isUNCPath = path2.match(_UNC_REGEX2), isPathAbsolute = isAbsolute2(path2), trailingSeparator = path2[path2.length - 1] === "/";
5605
+ return path2 = normalizeString2(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE2.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute2(path2) ? `/${path2}` : path2);
5606
+ }, join2 = function(...segments) {
4462
5607
  let path2 = "";
4463
5608
  for (let seg of segments)
4464
5609
  if (seg)
@@ -4467,21 +5612,21 @@ var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)
4467
5612
  pathTrailing && segLeading ? path2 += seg.slice(1) : path2 += pathTrailing || segLeading ? seg : `/${seg}`;
4468
5613
  } else
4469
5614
  path2 += seg;
4470
- return normalize(path2);
5615
+ return normalize2(path2);
4471
5616
  };
4472
- function cwd() {
5617
+ function cwd2() {
4473
5618
  return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
4474
5619
  }
4475
- var resolve = function(...arguments_) {
4476
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
5620
+ var resolve2 = function(...arguments_) {
5621
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath2(argument));
4477
5622
  let resolvedPath = "", resolvedAbsolute = !1;
4478
5623
  for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
4479
- let path2 = index >= 0 ? arguments_[index] : cwd();
4480
- !path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path2));
5624
+ let path2 = index >= 0 ? arguments_[index] : cwd2();
5625
+ !path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute2(path2));
4481
5626
  }
4482
- return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
5627
+ return resolvedPath = normalizeString2(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute2(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
4483
5628
  };
4484
- function normalizeString(path2, allowAboveRoot) {
5629
+ function normalizeString2(path2, allowAboveRoot) {
4485
5630
  let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
4486
5631
  for (let index = 0; index <= path2.length; ++index) {
4487
5632
  if (index < path2.length)
@@ -4511,16 +5656,16 @@ function normalizeString(path2, allowAboveRoot) {
4511
5656
  }
4512
5657
  return res;
4513
5658
  }
4514
- var isAbsolute = function(p) {
4515
- return _IS_ABSOLUTE_RE.test(p);
4516
- }, toNamespacedPath = function(p) {
4517
- return normalizeWindowsPath(p);
4518
- }, extname = function(p) {
5659
+ var isAbsolute2 = function(p) {
5660
+ return _IS_ABSOLUTE_RE2.test(p);
5661
+ }, toNamespacedPath2 = function(p) {
5662
+ return normalizeWindowsPath2(p);
5663
+ }, extname2 = function(p) {
4519
5664
  if (p === "..") return "";
4520
- let match = _EXTNAME_RE.exec(normalizeWindowsPath(p));
5665
+ let match = _EXTNAME_RE2.exec(normalizeWindowsPath2(p));
4521
5666
  return match && match[1] || "";
4522
- }, relative = function(from, to) {
4523
- let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
5667
+ }, relative2 = function(from, to) {
5668
+ let _from = resolve2(from).replace(_ROOT_FOLDER_RE2, "$1").split("/"), _to = resolve2(to).replace(_ROOT_FOLDER_RE2, "$1").split("/");
4524
5669
  if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
4525
5670
  return _to.join("/");
4526
5671
  let _fromCopy = [..._from];
@@ -4530,18 +5675,18 @@ var isAbsolute = function(p) {
4530
5675
  _from.shift(), _to.shift();
4531
5676
  }
4532
5677
  return [..._from.map(() => ".."), ..._to].join("/");
4533
- }, dirname2 = function(p) {
4534
- let segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
4535
- return segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute(p) ? "/" : ".");
4536
- }, format = function(p) {
5678
+ }, dirname3 = function(p) {
5679
+ let segments = normalizeWindowsPath2(p).replace(/\/$/, "").split("/").slice(0, -1);
5680
+ return segments.length === 1 && _DRIVE_LETTER_RE2.test(segments[0]) && (segments[0] += "/"), segments.join("/") || (isAbsolute2(p) ? "/" : ".");
5681
+ }, format2 = function(p) {
4537
5682
  let ext = p.ext ? p.ext.startsWith(".") ? p.ext : `.${p.ext}` : "", segments = [p.root, p.dir, p.base ?? (p.name ?? "") + ext].filter(
4538
5683
  Boolean
4539
5684
  );
4540
- return normalizeWindowsPath(
4541
- p.root ? resolve(...segments) : segments.join("/")
5685
+ return normalizeWindowsPath2(
5686
+ p.root ? resolve2(...segments) : segments.join("/")
4542
5687
  );
4543
- }, basename = function(p, extension) {
4544
- let segments = normalizeWindowsPath(p).split("/"), lastSegment = "";
5688
+ }, basename2 = function(p, extension) {
5689
+ let segments = normalizeWindowsPath2(p).split("/"), lastSegment = "";
4545
5690
  for (let i = segments.length - 1; i >= 0; i--) {
4546
5691
  let val = segments[i];
4547
5692
  if (val) {
@@ -4550,39 +5695,39 @@ var isAbsolute = function(p) {
4550
5695
  }
4551
5696
  }
4552
5697
  return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment;
4553
- }, parse = function(p) {
4554
- let root = _PATH_ROOT_RE.exec(p)?.[0]?.replace(/\\/g, "/") || "", base = basename(p), extension = extname(base);
5698
+ }, parse2 = function(p) {
5699
+ let root = _PATH_ROOT_RE2.exec(p)?.[0]?.replace(/\\/g, "/") || "", base = basename2(p), extension = extname2(base);
4555
5700
  return {
4556
5701
  root,
4557
- dir: dirname2(p),
5702
+ dir: dirname3(p),
4558
5703
  base,
4559
5704
  ext: extension,
4560
5705
  name: base.slice(0, base.length - extension.length)
4561
5706
  };
4562
- }, matchesGlob = (path2, pattern) => zeptomatch(pattern, normalize(path2)), _path = {
5707
+ }, matchesGlob2 = (path2, pattern) => zeptomatch2(pattern, normalize2(path2)), _path2 = {
4563
5708
  __proto__: null,
4564
- basename,
4565
- dirname: dirname2,
4566
- extname,
4567
- format,
4568
- isAbsolute,
4569
- join,
4570
- matchesGlob,
4571
- normalize,
4572
- normalizeString,
4573
- parse,
4574
- relative,
4575
- resolve,
4576
- sep,
4577
- toNamespacedPath
5709
+ basename: basename2,
5710
+ dirname: dirname3,
5711
+ extname: extname2,
5712
+ format: format2,
5713
+ isAbsolute: isAbsolute2,
5714
+ join: join2,
5715
+ matchesGlob: matchesGlob2,
5716
+ normalize: normalize2,
5717
+ normalizeString: normalizeString2,
5718
+ parse: parse2,
5719
+ relative: relative2,
5720
+ resolve: resolve2,
5721
+ sep: sep2,
5722
+ toNamespacedPath: toNamespacedPath2
4578
5723
  };
4579
5724
 
4580
5725
  // ../../../node_modules/pathe/dist/index.mjs
4581
- var delimiter = globalThis.process?.platform === "win32" ? ";" : ":", _platforms = { posix: void 0, win32: void 0 }, mix = (del = delimiter) => new Proxy(_path, {
5726
+ var delimiter2 = globalThis.process?.platform === "win32" ? ";" : ":", _platforms2 = { posix: void 0, win32: void 0 }, mix2 = (del = delimiter2) => new Proxy(_path2, {
4582
5727
  get(_, prop) {
4583
- return prop === "delimiter" ? del : prop === "posix" ? posix : prop === "win32" ? win32 : _platforms[prop] || _path[prop];
5728
+ return prop === "delimiter" ? del : prop === "posix" ? posix2 : prop === "win32" ? win322 : _platforms2[prop] || _path2[prop];
4584
5729
  }
4585
- }), posix = mix(":"), win32 = mix(";");
5730
+ }), posix2 = mix2(":"), win322 = mix2(";");
4586
5731
 
4587
5732
  // src/componentManifest/generateCodeSnippet.ts
4588
5733
  import {
@@ -4601,21 +5746,47 @@ import {
4601
5746
  storyShapeError,
4602
5747
  walk
4603
5748
  } from "storybook/internal/csf-tools";
5749
+ import {
5750
+ createHoleMarks,
5751
+ stripHoles,
5752
+ withHoleSpace
5753
+ } from "storybook/internal/docs-tools";
5754
+
5755
+ // src/snippet-values.ts
5756
+ var unmarked = (_, text) => text, isAttributeName = (name) => /^[A-Za-z_][A-Za-z0-9_:-]*$/.test(name), isAttributeText = (text) => !/["&\r\n]/.test(text), isChildText = (text) => !/[{}<>&\r\n]/.test(text), valueCode = (value) => value.kind === "boolean" ? String(value.value) : value.code, printAttribute = (name, value) => value.kind === "boolean" ? value.value ? name : `${name}={false}` : value.kind === "string" && isAttributeText(value.value) ? `${name}="${value.value}"` : `${name}={${value.code}}`, printAttributes = (args, mark = unmarked) => {
5757
+ let unnamed = args.filter(([name]) => !isAttributeName(name)), attributes = args.filter(([name]) => isAttributeName(name)).map(([name, value]) => mark({ kind: "attr", arg: name }, printAttribute(name, value)));
5758
+ if (unnamed.length !== 0) {
5759
+ let members = unnamed.map(
5760
+ ([name, value]) => `${JSON.stringify(name)}: ${mark({ kind: "value", arg: name }, valueCode(value))}`
5761
+ );
5762
+ attributes.push(`{...{ ${members.join(", ")} }}`);
5763
+ }
5764
+ return attributes;
5765
+ }, printChildren = (value) => value.kind === "string" && isChildText(value.value) ? value.value : value.kind === "jsx" ? value.code : `{${valueCode(value)}}`;
5766
+
5767
+ // src/componentManifest/generateCodeSnippet.ts
4604
5768
  function renderFunctionOf(resolution) {
4605
5769
  return resolution.kind === "resolved" ? resolution.node : resolution.kind === "unresolved" ? resolution.shadowedRender : void 0;
4606
5770
  }
4607
5771
  function getCodeSnippet(csf, storyName, componentName, resolver = createStoryArgsResolver(csf)) {
4608
- let { args, imports, unresolved } = resolver.resolve(storyName), importedBind = importedBoundStory(csf, storyName, args);
4609
- return importedBind ? {
4610
- code: importedBind.code,
4611
- imports: [...imports, importedBind.importRef],
4612
- unresolved
4613
- } : {
4614
- code: buildSnippet(csf, storyName, componentName, args, resolver),
4615
- imports,
5772
+ let { args, imports, unresolved } = resolver.resolve(storyName), importedBind = importedBoundStory(csf, storyName, args), sources = [csf.editor.code, ...Object.values(args).map(detachedTextOf)], marks = createHoleMarks(sources, (mark) => `/*${mark}*/`), marked = importedBind ? importedBind.print(marks.mark) : buildSnippet(csf, storyName, componentName, args, resolver, marks.mark), holes = marks.toTemplate(marked);
5773
+ invariant(holes, "A place an arg prints was printed inside another.");
5774
+ let template = withHoleSpace(
5775
+ holes,
5776
+ // An attribute a control clears leaves no gap or empty line.
5777
+ (hole) => hole.kind === "attr"
5778
+ );
5779
+ return {
5780
+ snippet: stripHoles(template),
5781
+ template,
5782
+ imports: importedBind ? [...imports, importedBind.importRef] : imports,
4616
5783
  unresolved
4617
5784
  };
4618
5785
  }
5786
+ var printArgsObject = (args) => args.length === 0 ? "{}" : `{
5787
+ ${args.map(([name, code]) => ` ${JSON.stringify(name)}: ${code}`).join(`,
5788
+ `)}
5789
+ }`;
4619
5790
  function importedBoundStory(csf, storyName, args) {
4620
5791
  let declaration = csf._storyExports[storyName];
4621
5792
  if (declaration?.type !== "VariableDeclarator" || !isCanonicalCsf2BindCall(declaration.init))
@@ -4623,14 +5794,14 @@ function importedBoundStory(csf, storyName, args) {
4623
5794
  let local = declaration.init.callee.object.name, binding = collectImportBindings(csf.program).get(local);
4624
5795
  if (!binding)
4625
5796
  return;
4626
- let print = valuePrinter(" "), values = Object.entries(args).map(
4627
- ([key, value]) => ` ${JSON.stringify(key)}: ${print(value)}`
4628
- ), argsObject = values.length ? `{
4629
- ${values.join(`,
4630
- `)}
4631
- }` : "{}";
5797
+ let print = valuePrinter(" "), bound = textOf(declaration.init), argsObject = (mark) => printArgsObject(
5798
+ Object.entries(args).map(([key, value]) => [
5799
+ key,
5800
+ mark({ kind: "value", arg: key }, print(value))
5801
+ ])
5802
+ );
4632
5803
  return {
4633
- code: `const ${storyName} = () => ${textOf(declaration.init)}(${argsObject});`,
5804
+ print: (mark) => `const ${storyName} = () => ${bound}(${argsObject(mark)});`,
4634
5805
  importRef: {
4635
5806
  localImportName: local,
4636
5807
  importId: binding.importId,
@@ -4639,7 +5810,7 @@ ${values.join(`,
4639
5810
  }
4640
5811
  };
4641
5812
  }
4642
- function buildSnippet(csf, storyName, componentName, merged, resolver) {
5813
+ function buildSnippet(csf, storyName, componentName, merged, resolver, mark) {
4643
5814
  let editor = csf.editor, storyDeclaration = csf._storyExports[storyName];
4644
5815
  if (!storyDeclaration) {
4645
5816
  let message = "Expected story to be a function or variable declaration", statement = csf.program.body.find(
@@ -4656,30 +5827,31 @@ function buildSnippet(csf, storyName, componentName, merged, resolver) {
4656
5827
  storyName,
4657
5828
  storyFn,
4658
5829
  isMethod(editor.parentOf(storyFn)),
4659
- merged
5830
+ merged,
5831
+ mark
4660
5832
  );
4661
5833
  invariant(componentName, "Could not generate snippet without component name.");
4662
- let print = valuePrinter(""), attrs = injectedAttributes(merged, /* @__PURE__ */ new Set(), print), children = toJsxChildren(merged.children, print), opening = [componentName, ...attrs].join(" "), element = children ? `<${opening}>${children}</${componentName}>` : `<${opening} />`;
5834
+ let print = valuePrinter(""), attrs = injectedAttributes(merged, /* @__PURE__ */ new Set(), print, mark), added = addedAttributes(injectedNames(merged, /* @__PURE__ */ new Set()), !!merged.children, mark), opening = `<${[componentName, ...attrs].join(" ")}${added}`, element = merged.children ? `${opening}>${childrenHole(merged.children, print, mark)}</${componentName}>` : `${opening} />`;
4663
5835
  return `const ${storyName} = () => ${element};`;
4664
5836
  }
4665
5837
  var isMethod = (parent) => parent?.type === "Property" && (parent.method || parent.kind !== "init");
4666
- function functionSnippet(code, storyName, fn, method, merged) {
5838
+ function functionSnippet(code, storyName, fn, method, merged, mark) {
4667
5839
  let asyncPrefix = fn.async ? "async " : "", params = fn.params.length ? code.slice(fn.params[0].start, fn.params[fn.params.length - 1].end) : "", edits = [];
4668
5840
  if (fn.type === "ArrowFunctionExpression" && isJsx(fn.body)) {
4669
- if (rewriteJsx(code, fn.body, merged, edits)) {
5841
+ if (rewriteJsx(code, fn.body, merged, edits, mark)) {
4670
5842
  let body = printRange(code, fn.body, edits), kept = readsArgs(`${asyncPrefix}() => (${body});`) ? params : "";
4671
5843
  return `const ${storyName} = ${asyncPrefix}(${kept}) => ${body};`;
4672
5844
  }
4673
5845
  } else if (fn.body?.type === "BlockStatement") {
4674
5846
  let changed = !1;
4675
5847
  for (let statement of fn.body.body)
4676
- statement.type === "ReturnStatement" && isJsx(statement.argument) && (changed = rewriteJsx(code, statement.argument, merged, edits) || changed);
5848
+ statement.type === "ReturnStatement" && isJsx(statement.argument) && (changed = rewriteJsx(code, statement.argument, merged, edits, mark) || changed);
4677
5849
  if (changed) {
4678
5850
  let body = printRange(code, fn.body, edits), head = `${asyncPrefix}function${fn.generator ? "*" : ""}`, kept = readsArgs(`${head} f() ${body}`) ? params : "";
4679
5851
  return fn.type === "FunctionDeclaration" ? `${asyncPrefix}function${fn.generator ? "*" : ""} ${storyName}(${kept}) ${body}` : `const ${storyName} = ${asyncPrefix}(${kept}) => ${body};`;
4680
5852
  }
4681
5853
  }
4682
- return fn.type === "FunctionDeclaration" && fn.body ? `${asyncPrefix}function${fn.generator ? "*" : ""} ${storyName}(${params}) ${printRange(code, fn.body, [])}` : method && fn.body ? `const ${storyName} = ${asyncPrefix}(${params}) => ${printRange(code, fn.body, [])};` : `const ${storyName} = ${printRange(code, fn, [])};`;
5854
+ return fn.type === "FunctionDeclaration" && fn.body ? `${asyncPrefix}function${fn.generator ? "*" : ""} ${storyName}(${params}) ${printRange(code, fn.body, edits)}` : method && fn.body ? `const ${storyName} = ${asyncPrefix}(${params}) => ${printRange(code, fn.body, edits)};` : `const ${storyName} = ${printRange(code, fn, edits)};`;
4683
5855
  }
4684
5856
  var isJsx = (node) => node?.type === "JSXElement" || node?.type === "JSXFragment";
4685
5857
  function printRange(code, range, edits) {
@@ -4694,23 +5866,18 @@ function readsArgs(source) {
4694
5866
  current.type === "MemberExpression" && !current.computed && named.add(current.property), current.type === "Property" && !current.computed && !current.shorthand && named.add(current.key), current.type === "Identifier" && current.name === "args" && !named.has(current) && (reads = !0);
4695
5867
  }), reads;
4696
5868
  }
4697
- var valuePrinter = (indent) => (node) => reindent(detachedTextOf(node), "", indent), isValidJsxAttrName = (n) => /^[A-Za-z_][A-Za-z0-9_:-]*$/.test(n), toAttr = (key, value, print) => value.type === "Literal" && typeof value.value == "boolean" ? value.value ? key : `${key}={false}` : isStringLiteral(value) && !/["&\r\n]/.test(value.value) ? `${key}="${value.value}"` : `${key}={${print(value)}}`;
4698
- function injectedAttributes(merged, existing, print) {
4699
- let entries = Object.entries(merged).filter(
4700
- ([k, v]) => v != null && k !== "children" && !existing.has(k)
4701
- ), attrs = entries.filter(([k]) => isValidJsxAttrName(k)).map(([k, v]) => toAttr(k, v, print)), invalid = entries.filter(([k]) => !isValidJsxAttrName(k));
4702
- if (invalid.length > 0) {
4703
- let members = invalid.map(([k, v]) => `${JSON.stringify(k)}: ${print(v)}`);
4704
- attrs.push(`{...{ ${members.join(", ")} }}`);
4705
- }
4706
- return attrs;
4707
- }
4708
- var toJsxChildren = (node, print) => node ? isStringLiteral(node) && !/[{}<>&\r\n]/.test(node.value) ? node.value : isJsx(node) ? print(node) : `{${print(node)}}` : "";
5869
+ var valuePrinter = (indent) => (node) => reindent(detachedTextOf(node), "", indent), toJsxValue = (node, print) => node.type === "Literal" && typeof node.value == "boolean" ? { kind: "boolean", value: node.value } : isStringLiteral(node) ? { kind: "string", value: node.value, code: print(node) } : { kind: isJsx(node) ? "jsx" : "code", code: print(node) }, toAttr = (key, value, print) => printAttribute(key, toJsxValue(value, print)), injectedArgs = (merged, existing) => Object.entries(merged).filter(([k, v]) => v != null && k !== "children" && !existing.has(k)), injectedNames = (merged, existing) => injectedArgs(merged, existing).map(([k]) => k), injectedAttributes = (merged, existing, print, mark) => printAttributes(
5870
+ injectedArgs(merged, existing).map(([k, v]) => [k, toJsxValue(v, print)]),
5871
+ mark
5872
+ ), addedAttributes = (printed, hasContent, mark) => mark(
5873
+ { kind: "attrs", spread: !0, except: hasContent ? [...printed, "children"] : printed },
5874
+ ""
5875
+ ), childrenHole = (node, print, mark) => mark({ kind: "text", arg: "children" }, toJsxChildren(node, print)), toJsxChildren = (node, print) => node ? printChildren(toJsxValue(node, print)) : "";
4709
5876
  function getArgsMemberKey(expr) {
4710
5877
  let member = expr.type === "ChainExpression" ? expr.expression : expr;
4711
5878
  return member.type !== "MemberExpression" || member.object.type !== "Identifier" || member.object.name !== "args" ? null : member.property.type === "Identifier" && !member.computed ? member.property.name : isStringLiteral(member.property) && member.computed ? member.property.value : null;
4712
5879
  }
4713
- function rewriteJsx(code, node, merged, edits) {
5880
+ function rewriteJsx(code, node, merged, edits, mark) {
4714
5881
  let changed = !1, printAt = (offset) => valuePrinter(lineIndent(code, offset));
4715
5882
  if (node.type === "JSXElement") {
4716
5883
  let opening = node.openingElement, attrs = opening.attributes, isArgsSpread = (a) => a.type === "JSXSpreadAttribute" && a.argument.type === "Identifier" && a.argument.name === "args", firstSpread = attrs.findIndex(isArgsSpread), tagEnd = (opening.typeArguments ?? opening.name).end;
@@ -4720,45 +5887,67 @@ function rewriteJsx(code, node, merged, edits) {
4720
5887
  attrs.flatMap(
4721
5888
  (a) => a.type === "JSXAttribute" && a.name.type === "JSXIdentifier" ? [a.name.name] : []
4722
5889
  )
4723
- ), print = printAt(attrs[firstSpread].start), pieces = injectedAttributes(merged, existing, print).join(" ");
5890
+ ), print = printAt(attrs[firstSpread].start), injected = injectedNames(merged, existing), pieces = injectedAttributes(merged, existing, print, mark).join(" ") + addedAttributes(
5891
+ [...existing, ...injected],
5892
+ !!merged.children || node.children.length > 0,
5893
+ mark
5894
+ );
4724
5895
  if (attrs.forEach((a, index) => {
4725
- isArgsSpread(a) && (index === firstSpread && pieces ? edits.push({ start: a.start, end: a.end, text: pieces }) : edits.push({ start: index > 0 ? attrs[index - 1].end : tagEnd, end: a.end, text: "" }));
5896
+ if (isArgsSpread(a))
5897
+ if (index === firstSpread && injected.length > 0)
5898
+ edits.push({ start: a.start, end: a.end, text: pieces });
5899
+ else {
5900
+ let start = index > 0 ? attrs[index - 1].end : tagEnd;
5901
+ edits.push({ start, end: a.end, text: index === firstSpread ? pieces : "" });
5902
+ }
4726
5903
  }), node.children.length === 0 && merged.children) {
4727
- let children = toJsxChildren(merged.children, printAt(opening.start));
5904
+ let name = code.slice(opening.name.start, opening.name.end), children = childrenHole(merged.children, printAt(opening.start), mark);
4728
5905
  if (opening.selfClosing) {
4729
- let name = code.slice(opening.name.start, opening.name.end), lastEnd = attrs.length > 0 ? attrs[attrs.length - 1].end : tagEnd;
4730
- edits.push({ start: lastEnd, end: opening.end, text: `>${children}</${name}>` });
5906
+ let start = attrs.length > 0 ? attrs[attrs.length - 1].end : tagEnd;
5907
+ edits.push({ start, end: opening.end, text: `>${children}</${name}>` });
4731
5908
  } else
4732
5909
  edits.push({ start: opening.end, end: opening.end, text: children });
4733
5910
  }
4734
5911
  }
4735
- for (let a of attrs) {
4736
- if (a.type !== "JSXAttribute" || a.name.type !== "JSXIdentifier" || a.value?.type !== "JSXExpressionContainer")
4737
- continue;
4738
- let key = getArgsMemberKey(a.value.expression);
4739
- key !== null && Object.hasOwn(merged, key) && (edits.push({
5912
+ let lastSpread = attrs.findLastIndex(isArgsSpread);
5913
+ attrs.forEach((a, index) => {
5914
+ if (a.type !== "JSXAttribute" || a.name.type !== "JSXIdentifier")
5915
+ return;
5916
+ let name = a.name.name, key = a.value?.type === "JSXExpressionContainer" ? getArgsMemberKey(a.value.expression) : null, arg = index < lastSpread ? name : key;
5917
+ if (arg === null)
5918
+ return;
5919
+ let read = [arg, key].find((k) => k !== null && Object.hasOwn(merged, k)), set = read !== void 0, text = set ? toAttr(name, merged[read], printAt(a.start)) : code.slice(a.start, a.end);
5920
+ edits.push({
4740
5921
  start: a.start,
4741
5922
  end: a.end,
4742
- text: toAttr(a.name.name, merged[key], printAt(a.start))
4743
- }), changed = !0);
4744
- }
5923
+ text: mark({ kind: "attr", arg, ...arg !== name && { name } }, text)
5924
+ }), changed ||= set;
5925
+ });
4745
5926
  }
4746
5927
  for (let child of node.children)
4747
- isJsx(child) ? changed = rewriteJsx(code, child, merged, edits) || changed : child.type === "JSXExpressionContainer" && getArgsMemberKey(child.expression) === "children" && merged.children && (edits.push({
4748
- start: child.start,
4749
- end: child.end,
4750
- text: toJsxChildren(merged.children, printAt(child.start))
4751
- }), changed = !0);
5928
+ if (isJsx(child))
5929
+ changed = rewriteJsx(code, child, merged, edits, mark) || changed;
5930
+ else if (child.type === "JSXExpressionContainer") {
5931
+ let key = getArgsMemberKey(child.expression);
5932
+ if (key === null)
5933
+ continue;
5934
+ let set = Object.hasOwn(merged, key), text = set ? toJsxChildren(merged[key], printAt(child.start)) : code.slice(child.start, child.end);
5935
+ edits.push({
5936
+ start: child.start,
5937
+ end: child.end,
5938
+ text: mark({ kind: "text", arg: key }, text)
5939
+ }), changed ||= set;
5940
+ }
4752
5941
  return changed;
4753
5942
  }
4754
5943
 
4755
5944
  // src/componentManifest/reactDocgenTypescript.ts
4756
- import { dirname as dirname3, join as join2, resolve as resolve2 } from "node:path";
5945
+ import { dirname as dirname4, join as join3, resolve as resolve3 } from "node:path";
4757
5946
  import {
4758
5947
  extractComponentJsDocInfo as extractComponentJsDocInfo2,
4759
5948
  resolveExportedSymbol
4760
5949
  } from "storybook/internal/component-meta";
4761
- import { logger as logger2 } from "storybook/internal/node-logger";
5950
+ import { logger as logger4 } from "storybook/internal/node-logger";
4762
5951
  var typeScriptPromise, reactDocgenTypescriptPromise, loadTypeScript = () => typeScriptPromise ??= import("typescript").then((ts) => ts.default ?? ts), loadReactDocgenTypescript = () => reactDocgenTypescriptPromise ??= import("react-docgen-typescript"), LARGE_NON_USER_SOURCE_THRESHOLD = 30, getPropSource = (prop) => prop.parent?.fileName ?? prop.declarations?.[0]?.fileName, getLargeNonUserPropSources = (props) => {
4763
5952
  let countBySource = /* @__PURE__ */ new Map();
4764
5953
  for (let prop of Object.values(props)) {
@@ -4823,7 +6012,7 @@ async function getParser(filePath, userOptions) {
4823
6012
  let parsed = parseTsconfig(typescript, configPath);
4824
6013
  compilerOptions = { ...parsed.options, noErrorTruncation: !0 }, fileNames = parsed.fileNames;
4825
6014
  } else
4826
- logger2.warn(
6015
+ logger4.warn(
4827
6016
  "No tsconfig.json (or tsconfig.base.json / tsconfig.app.json) found. TypeScript component props will not be documented by react-docgen-typescript. Create a tsconfig.json in your project root to enable automatic controls."
4828
6017
  );
4829
6018
  let program = typescript.createProgram(
@@ -4905,15 +6094,15 @@ var parseWithReactDocgenTypescript = asyncCache(
4905
6094
  },
4906
6095
  { name: "parseWithReactDocgenTypescript" }
4907
6096
  ), findOwningTsconfigPath = cached(
4908
- (typescript, cwd2, filePath) => {
4909
- let configPath = findTsconfigPath(cwd2);
6097
+ (typescript, cwd3, filePath) => {
6098
+ let configPath = findTsconfigPath(cwd3);
4910
6099
  if (configPath)
4911
6100
  return findTsconfigPathIncludingFile(typescript, configPath, filePath, /* @__PURE__ */ new Set()) ?? configPath;
4912
6101
  },
4913
6102
  {
4914
- key: (typescript, cwd2, filePath) => `${normalizeFileName(typescript, resolve2(cwd2))}::${normalizeFileName(
6103
+ key: (typescript, cwd3, filePath) => `${normalizeFileName(typescript, resolve3(cwd3))}::${normalizeFileName(
4915
6104
  typescript,
4916
- resolve2(filePath)
6105
+ resolve3(filePath)
4917
6106
  )}`,
4918
6107
  name: "findOwningTsconfigPath"
4919
6108
  }
@@ -4938,8 +6127,8 @@ function findTsconfigPathIncludingFile(typescript, configPath, filePath, seenCon
4938
6127
  }
4939
6128
  }
4940
6129
  function getReferencedTsconfigPaths(typescript, configPath, config) {
4941
- return (Array.isArray(config?.references) ? config.references : []).map((reference) => reference.path).filter((referencePath) => typeof referencePath == "string").map((referencePath) => resolve2(dirname3(configPath), referencePath)).map(
4942
- (referencePath) => referencePath.endsWith(".json") ? referencePath : join2(referencePath, "tsconfig.json")
6130
+ return (Array.isArray(config?.references) ? config.references : []).map((reference) => reference.path).filter((referencePath) => typeof referencePath == "string").map((referencePath) => resolve3(dirname4(configPath), referencePath)).map(
6131
+ (referencePath) => referencePath.endsWith(".json") ? referencePath : join3(referencePath, "tsconfig.json")
4943
6132
  ).filter((referencePath) => typescript.sys.fileExists(referencePath));
4944
6133
  }
4945
6134
  function parseTsconfig(typescript, configPath) {
@@ -4951,7 +6140,7 @@ function readTsconfig(typescript, configPath) {
4951
6140
  return cachedTsconfig;
4952
6141
  let { config } = typescript.readConfigFile(configPath, typescript.sys.readFile), state = {
4953
6142
  config,
4954
- parsed: typescript.parseJsonConfigFileContent(config, typescript.sys, dirname3(configPath))
6143
+ parsed: typescript.parseJsonConfigFileContent(config, typescript.sys, dirname4(configPath))
4955
6144
  };
4956
6145
  return tsconfigCache.set(cacheKey, state), state;
4957
6146
  }
@@ -4959,7 +6148,7 @@ function isSameFileName(typescript, left, right) {
4959
6148
  return normalizeFileName(typescript, left) === normalizeFileName(typescript, right);
4960
6149
  }
4961
6150
  function normalizeFileName(typescript, fileName) {
4962
- let normalized = resolve2(fileName).replace(/\\/g, "/");
6151
+ let normalized = resolve3(fileName).replace(/\\/g, "/");
4963
6152
  return typescript.sys.useCaseSensitiveFileNames ? normalized : normalized.toLowerCase();
4964
6153
  }
4965
6154
 
@@ -4974,24 +6163,24 @@ import {
4974
6163
  } from "storybook/internal/csf-tools";
4975
6164
 
4976
6165
  // src/componentManifest/getComponentImports.ts
4977
- import { dirname as dirname4 } from "node:path";
6166
+ import { dirname as dirname5 } from "node:path";
4978
6167
  import {
4979
6168
  buildImportStatements,
4980
6169
  collectImportBindings as collectImportBindings2,
4981
6170
  resolveComponentImport,
4982
6171
  walk as walk2
4983
6172
  } from "storybook/internal/csf-tools";
4984
- import { isModuleNotFoundError as isModuleNotFoundError2 } from "storybook/internal/common";
4985
- import { logger as logger4 } from "storybook/internal/node-logger";
6173
+ import { isModuleNotFoundError as isModuleNotFoundError3 } from "storybook/internal/common";
6174
+ import { logger as logger6 } from "storybook/internal/node-logger";
4986
6175
 
4987
6176
  // src/componentManifest/loadReactDocgen.ts
4988
- import { getTypeScriptForDocgenError, isModuleNotFoundError } from "storybook/internal/common";
4989
- import { logger as logger3 } from "storybook/internal/node-logger";
6177
+ import { getTypeScriptForDocgenError, isModuleNotFoundError as isModuleNotFoundError2 } from "storybook/internal/common";
6178
+ import { logger as logger5 } from "storybook/internal/node-logger";
4990
6179
  var reactDocgenPromise;
4991
6180
  function loadReactDocgen() {
4992
- return reactDocgenPromise ??= import("./reactDocgen-6ZJPM2YE.js").catch((error) => {
4993
- if (isModuleNotFoundError(error)) {
4994
- logger3.debug(`Skipping react-docgen, which is not installed: ${error}`);
6181
+ return reactDocgenPromise ??= import("./reactDocgen-YAGNM6ZQ.js").catch((error) => {
6182
+ if (isModuleNotFoundError2(error)) {
6183
+ logger5.debug(`Skipping react-docgen, which is not installed: ${error}`);
4995
6184
  return;
4996
6185
  }
4997
6186
  throw error;
@@ -4999,7 +6188,10 @@ function loadReactDocgen() {
4999
6188
  }
5000
6189
  var getDocgenPackageMissingError = (packageName) => {
5001
6190
  let typescriptError = getTypeScriptForDocgenError(
5002
- (specifier) => import.meta.resolve(specifier)
6191
+ (specifier) => import.meta.resolve(specifier),
6192
+ {
6193
+ apis: packageName === "react-docgen-typescript" ? ["compiler"] : REACT_DOCGEN_TYPESCRIPT_APIS
6194
+ }
5003
6195
  );
5004
6196
  return typescriptError ? { name: typescriptError.name, message: typescriptError.message } : {
5005
6197
  name: `${packageName} is not installed`,
@@ -5055,14 +6247,14 @@ var isReactDocgenTypescriptResolvable = () => {
5055
6247
  jsxDepth: componentDepth.get(c)
5056
6248
  }, path2, isPackage = !1;
5057
6249
  try {
5058
- component.importId && storyFilePath && (path2 = cachedResolveImport(matchPath(component.importId, dirname4(storyFilePath)), {
5059
- basedir: dirname4(storyFilePath)
6250
+ component.importId && storyFilePath && (path2 = cachedResolveImport(matchPath(component.importId, dirname5(storyFilePath)), {
6251
+ basedir: dirname5(storyFilePath)
5060
6252
  }));
5061
6253
  } catch (e) {
5062
- logger4.debug(e);
6254
+ logger6.debug(e);
5063
6255
  }
5064
6256
  try {
5065
- component.importId && !component.importId.startsWith(".") && storyFilePath && (cachedResolveImport(component.importId, { basedir: dirname4(storyFilePath) }), isPackage = !0);
6257
+ component.importId && !component.importId.startsWith(".") && storyFilePath && (cachedResolveImport(component.importId, { basedir: dirname5(storyFilePath) }), isPackage = !0);
5066
6258
  } catch {
5067
6259
  }
5068
6260
  let componentWithPackage = { ...component, isPackage };
@@ -5074,7 +6266,7 @@ var isReactDocgenTypescriptResolvable = () => {
5074
6266
  reactDocgenTypescript = matchComponentDoc(docs, component), reactDocgenTypescript || (reactDocgenTypescriptError = getReactDocgenTypescriptError(path2, component, docs));
5075
6267
  } catch (e) {
5076
6268
  let message = e instanceof Error ? e.message : String(e);
5077
- logger4.debug(`react-docgen-typescript failed for ${path2}: ${message}`), reactDocgenTypescriptError = isModuleNotFoundError2(e) && !isReactDocgenTypescriptResolvable() ? getDocgenPackageMissingError("react-docgen-typescript") : {
6269
+ logger6.debug(`react-docgen-typescript failed for ${path2}: ${message}`), reactDocgenTypescriptError = isModuleNotFoundError3(e) && !isReactDocgenTypescriptResolvable() ? getDocgenPackageMissingError("react-docgen-typescript") : {
5078
6270
  name: "react-docgen-typescript parse error",
5079
6271
  message: `File: ${path2}
5080
6272
  ${message}`
@@ -5153,7 +6345,7 @@ async function resolveStoryFileComponents(options) {
5153
6345
  }));
5154
6346
  return { storyPath, storyFile, csf, componentName, allComponents, component, subcomponents };
5155
6347
  }
5156
- function extractStorySnippets(csf, componentName, filterStoryIds, references) {
6348
+ function extractStorySnippets(csf, componentName, filterStoryIds, references, withTemplate = !1) {
5157
6349
  let imports = [], resolver = createStoryArgsResolver2(csf, references);
5158
6350
  return { stories: Object.entries(csf._stories).filter(([, story]) => !filterStoryIds || filterStoryIds.has(story.id)).map(([storyExport, story]) => {
5159
6351
  let name = story.name ?? storyNameFromExport(storyExport);
@@ -5161,13 +6353,19 @@ function extractStorySnippets(csf, componentName, filterStoryIds, references) {
5161
6353
  let { description, summary } = extractStoryJSDocInfo(
5162
6354
  csf._storyStatements[storyExport],
5163
6355
  csf.editor
5164
- ), snippet = getCodeSnippet(csf, storyExport, componentName, resolver);
5165
- imports.push(...snippet.imports);
5166
- let warning = unresolvedWarning(snippet.unresolved);
6356
+ ), {
6357
+ snippet,
6358
+ template,
6359
+ imports: needs,
6360
+ unresolved
6361
+ } = getCodeSnippet(csf, storyExport, componentName, resolver);
6362
+ imports.push(...needs);
6363
+ let warning = unresolvedWarning(unresolved);
5167
6364
  return {
5168
6365
  id: story.id,
5169
6366
  name,
5170
- snippet: snippet.code,
6367
+ snippet,
6368
+ ...withTemplate && { template },
5171
6369
  description,
5172
6370
  summary,
5173
6371
  ...warning ? { warning } : {}
@@ -5202,7 +6400,7 @@ function hasRootEntry(pkg) {
5202
6400
  }
5203
6401
  function getImportablePackageName(componentPath, fallbackPath) {
5204
6402
  let nearestPkg = cachedFindUp("package.json", {
5205
- cwd: posix.dirname(componentPath ?? fallbackPath)
6403
+ cwd: posix2.dirname(componentPath ?? fallbackPath)
5206
6404
  });
5207
6405
  try {
5208
6406
  if (!nearestPkg)
@@ -5221,7 +6419,7 @@ function getFallbackImport(packageName, componentName) {
5221
6419
  `) : "";
5222
6420
  }
5223
6421
  function relativizeComponentMetaPaths(doc) {
5224
- let relativize = (fileName) => posix.relative(process.cwd(), fileName), relativizeProp = (prop) => ({
6422
+ let relativize = (fileName) => posix2.relative(process.cwd(), fileName), relativizeProp = (prop) => ({
5225
6423
  ...prop,
5226
6424
  parent: prop.parent ? { ...prop.parent, fileName: relativize(prop.parent.fileName) } : prop.parent,
5227
6425
  declarations: prop.declarations?.map((declaration) => ({
@@ -5295,7 +6493,8 @@ function buildStoryDocsFromResolved({
5295
6493
  componentName,
5296
6494
  component,
5297
6495
  allComponents,
5298
- filterStoryIds
6496
+ filterStoryIds,
6497
+ withTemplate
5299
6498
  }) {
5300
6499
  let id = getComponentIdFromEntry(entry), title = entry.title.split("/").at(-1).replace(/\s+/g, ""), packageName = getImportablePackageName(component?.path, storyPath), fallbackImport = getFallbackImport(packageName, componentName), storyEntries = extractStorySnippets(
5301
6500
  csf,
@@ -5304,7 +6503,8 @@ function buildStoryDocsFromResolved({
5304
6503
  {
5305
6504
  filePath: storyPath,
5306
6505
  ...openStoryReferences()
5307
- }
6506
+ },
6507
+ withTemplate
5308
6508
  ), argRefs = storyEntries.imports.map((ref) => ({ ...ref, isPackage: !0 })), imports = buildImportStatements2({ refs: [...allComponents, ...argRefs], packageName }).join(`
5309
6509
  `).trim() || fallbackImport;
5310
6510
  return {
@@ -5429,14 +6629,15 @@ function buildReactComponentDocgenFromResolved({
5429
6629
  }
5430
6630
 
5431
6631
  export {
5432
- join,
5433
- isAbsolute,
5434
- posix,
6632
+ join2 as join,
6633
+ isAbsolute2 as isAbsolute,
6634
+ posix2 as posix,
5435
6635
  getCodeSnippet,
5436
6636
  invalidateParser,
5437
6637
  resolveStoryFileComponents,
5438
6638
  buildStoryDocsFromResolved,
5439
6639
  buildComponentDocgenFromResolved,
5440
6640
  buildReactComponentDocgenFromResolved,
6641
+ loadDocgenTypeScript,
5441
6642
  ComponentMetaManager
5442
6643
  };