@storybook/react 10.1.0-alpha.3 → 10.1.0-alpha.5

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 (2) hide show
  1. package/dist/preset.js +710 -244
  2. package/package.json +4 -3
package/dist/preset.js CHANGED
@@ -1,10 +1,10 @@
1
- import CJS_COMPAT_NODE_URL_eqmqwiqjsm4 from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_eqmqwiqjsm4 from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_eqmqwiqjsm4 from "node:module";
1
+ import CJS_COMPAT_NODE_URL_31a066znggx from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_31a066znggx from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_31a066znggx from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_eqmqwiqjsm4.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_eqmqwiqjsm4.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_eqmqwiqjsm4.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_31a066znggx.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_31a066znggx.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_31a066znggx.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
@@ -1588,13 +1588,13 @@ var require_tsconfig_loader = __commonJS({
1588
1588
  "../../node_modules/tsconfig-paths/lib/tsconfig-loader.js"(exports) {
1589
1589
  "use strict";
1590
1590
  var __assign = exports && exports.__assign || function() {
1591
- __assign = Object.assign || function(t4) {
1591
+ __assign = Object.assign || function(t5) {
1592
1592
  for (var s, i = 1, n = arguments.length; i < n; i++) {
1593
1593
  s = arguments[i];
1594
1594
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1595
- t4[p] = s[p];
1595
+ t5[p] = s[p];
1596
1596
  }
1597
- return t4;
1597
+ return t5;
1598
1598
  };
1599
1599
  return __assign.apply(this, arguments);
1600
1600
  };
@@ -1662,19 +1662,19 @@ var require_tsconfig_loader = __commonJS({
1662
1662
  }
1663
1663
  __name(walkForTsConfig, "walkForTsConfig");
1664
1664
  exports.walkForTsConfig = walkForTsConfig;
1665
- function loadTsconfig(configFilePath, existsSync3, readFileSync) {
1665
+ function loadTsconfig(configFilePath, existsSync3, readFileSync2) {
1666
1666
  if (existsSync3 === void 0) {
1667
1667
  existsSync3 = fs.existsSync;
1668
1668
  }
1669
- if (readFileSync === void 0) {
1670
- readFileSync = /* @__PURE__ */ __name(function(filename) {
1669
+ if (readFileSync2 === void 0) {
1670
+ readFileSync2 = /* @__PURE__ */ __name(function(filename) {
1671
1671
  return fs.readFileSync(filename, "utf8");
1672
1672
  }, "readFileSync");
1673
1673
  }
1674
1674
  if (!existsSync3(configFilePath)) {
1675
1675
  return void 0;
1676
1676
  }
1677
- var configString = readFileSync(configFilePath);
1677
+ var configString = readFileSync2(configFilePath);
1678
1678
  var cleanedJson = StripBom(configString);
1679
1679
  var config;
1680
1680
  try {
@@ -1687,10 +1687,10 @@ var require_tsconfig_loader = __commonJS({
1687
1687
  var base = void 0;
1688
1688
  if (Array.isArray(extendedConfig)) {
1689
1689
  base = extendedConfig.reduce(function(currBase, extendedConfigElement) {
1690
- return mergeTsconfigs(currBase, loadTsconfigFromExtends(configFilePath, extendedConfigElement, existsSync3, readFileSync));
1690
+ return mergeTsconfigs(currBase, loadTsconfigFromExtends(configFilePath, extendedConfigElement, existsSync3, readFileSync2));
1691
1691
  }, {});
1692
1692
  } else {
1693
- base = loadTsconfigFromExtends(configFilePath, extendedConfig, existsSync3, readFileSync);
1693
+ base = loadTsconfigFromExtends(configFilePath, extendedConfig, existsSync3, readFileSync2);
1694
1694
  }
1695
1695
  return mergeTsconfigs(base, config);
1696
1696
  }
@@ -1698,7 +1698,7 @@ var require_tsconfig_loader = __commonJS({
1698
1698
  }
1699
1699
  __name(loadTsconfig, "loadTsconfig");
1700
1700
  exports.loadTsconfig = loadTsconfig;
1701
- function loadTsconfigFromExtends(configFilePath, extendedConfigValue, existsSync3, readFileSync) {
1701
+ function loadTsconfigFromExtends(configFilePath, extendedConfigValue, existsSync3, readFileSync2) {
1702
1702
  var _a;
1703
1703
  if (typeof extendedConfigValue === "string" && extendedConfigValue.indexOf(".json") === -1) {
1704
1704
  extendedConfigValue += ".json";
@@ -1708,7 +1708,7 @@ var require_tsconfig_loader = __commonJS({
1708
1708
  if (extendedConfigValue.indexOf("/") !== -1 && extendedConfigValue.indexOf(".") !== -1 && !existsSync3(extendedConfigPath)) {
1709
1709
  extendedConfigPath = path2.join(currentDir, "node_modules", extendedConfigValue);
1710
1710
  }
1711
- var config = loadTsconfig(extendedConfigPath, existsSync3, readFileSync) || {};
1711
+ var config = loadTsconfig(extendedConfigPath, existsSync3, readFileSync2) || {};
1712
1712
  if ((_a = config.compilerOptions) === null || _a === void 0 ? void 0 : _a.baseUrl) {
1713
1713
  var extendsDir = path2.dirname(extendedConfigValue);
1714
1714
  config.compilerOptions.baseUrl = path2.join(extendsDir, config.compilerOptions.baseUrl);
@@ -2095,14 +2095,14 @@ var require_register = __commonJS({
2095
2095
  console.warn("".concat(configLoaderResult.message, ". tsconfig-paths will be skipped"));
2096
2096
  return noOp;
2097
2097
  }
2098
- var matchPath = (0, match_path_sync_1.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
2098
+ var matchPath2 = (0, match_path_sync_1.createMatchPath)(configLoaderResult.absoluteBaseUrl, configLoaderResult.paths, configLoaderResult.mainFields, configLoaderResult.addMatchAll);
2099
2099
  var Module = __require("module");
2100
2100
  var originalResolveFilename = Module._resolveFilename;
2101
2101
  var coreModules = getCoreModules(Module.builtinModules);
2102
2102
  Module._resolveFilename = function(request, _parent) {
2103
2103
  var isCoreModule = coreModules.hasOwnProperty(request);
2104
2104
  if (!isCoreModule) {
2105
- var found = matchPath(request);
2105
+ var found = matchPath2(request);
2106
2106
  if (found) {
2107
2107
  var modifiedArguments = __spreadArray([found], [].slice.call(arguments, 1), true);
2108
2108
  return originalResolveFilename.apply(this, modifiedArguments);
@@ -2748,8 +2748,8 @@ var require_async = __commonJS({
2748
2748
  cb(null, x);
2749
2749
  }
2750
2750
  }, "maybeRealpath");
2751
- var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile2, pkgfile, cb) {
2752
- readFile2(pkgfile, function(readFileErr, body) {
2751
+ var defaultReadPackage = /* @__PURE__ */ __name(function defaultReadPackage2(readFile, pkgfile, cb) {
2752
+ readFile(pkgfile, function(readFileErr, body) {
2753
2753
  if (readFileErr) cb(readFileErr);
2754
2754
  else {
2755
2755
  try {
@@ -2784,7 +2784,7 @@ var require_async = __commonJS({
2784
2784
  opts = normalizeOptions(x, opts);
2785
2785
  var isFile = opts.isFile || defaultIsFile;
2786
2786
  var isDirectory = opts.isDirectory || defaultIsDir;
2787
- var readFile2 = opts.readFile || fs.readFile;
2787
+ var readFile = opts.readFile || fs.readFile;
2788
2788
  var realpath = opts.realpath || defaultRealpath;
2789
2789
  var readPackage = opts.readPackage || defaultReadPackage;
2790
2790
  if (opts.readFile && opts.readPackage) {
@@ -2910,7 +2910,7 @@ var require_async = __commonJS({
2910
2910
  var pkgfile = path2.join(pkgdir, "package.json");
2911
2911
  isFile(pkgfile, function(err2, ex) {
2912
2912
  if (!ex) return loadpkg(path2.dirname(dir), cb2);
2913
- readPackage(readFile2, pkgfile, function(err3, pkgParam) {
2913
+ readPackage(readFile, pkgfile, function(err3, pkgParam) {
2914
2914
  if (err3) cb2(err3);
2915
2915
  var pkg = pkgParam;
2916
2916
  if (pkg && opts.packageFilter) {
@@ -2935,7 +2935,7 @@ var require_async = __commonJS({
2935
2935
  isFile(pkgfile, function(err2, ex) {
2936
2936
  if (err2) return cb2(err2);
2937
2937
  if (!ex) return loadAsFile(path2.join(x2, "index"), fpkg, cb2);
2938
- readPackage(readFile2, pkgfile, function(err3, pkgParam) {
2938
+ readPackage(readFile, pkgfile, function(err3, pkgParam) {
2939
2939
  if (err3) return cb2(err3);
2940
2940
  var pkg = pkgParam;
2941
2941
  if (pkg && opts.packageFilter) {
@@ -3254,8 +3254,8 @@ var require_sync = __commonJS({
3254
3254
  }
3255
3255
  return x;
3256
3256
  }, "maybeRealpathSync");
3257
- var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync, pkgfile) {
3258
- var body = readFileSync(pkgfile);
3257
+ var defaultReadPackageSync = /* @__PURE__ */ __name(function defaultReadPackageSync2(readFileSync2, pkgfile) {
3258
+ var body = readFileSync2(pkgfile);
3259
3259
  try {
3260
3260
  var pkg = JSON.parse(body);
3261
3261
  return pkg;
@@ -3275,7 +3275,7 @@ var require_sync = __commonJS({
3275
3275
  }
3276
3276
  var opts = normalizeOptions(x, options);
3277
3277
  var isFile = opts.isFile || defaultIsFile;
3278
- var readFileSync = opts.readFileSync || fs.readFileSync;
3278
+ var readFileSync2 = opts.readFileSync || fs.readFileSync;
3279
3279
  var isDirectory = opts.isDirectory || defaultIsDir;
3280
3280
  var realpathSync = opts.realpathSync || defaultRealpathSync;
3281
3281
  var readPackageSync = opts.readPackageSync || defaultReadPackageSync;
@@ -3333,7 +3333,7 @@ var require_sync = __commonJS({
3333
3333
  if (!isFile(pkgfile)) {
3334
3334
  return loadpkg(path2.dirname(dir));
3335
3335
  }
3336
- var pkg = readPackageSync(readFileSync, pkgfile);
3336
+ var pkg = readPackageSync(readFileSync2, pkgfile);
3337
3337
  if (pkg && opts.packageFilter) {
3338
3338
  pkg = opts.packageFilter(
3339
3339
  pkg,
@@ -3348,7 +3348,7 @@ var require_sync = __commonJS({
3348
3348
  var pkgfile = path2.join(maybeRealpathSync(realpathSync, x2, opts), "/package.json");
3349
3349
  if (isFile(pkgfile)) {
3350
3350
  try {
3351
- var pkg = readPackageSync(readFileSync, pkgfile);
3351
+ var pkg = readPackageSync(readFileSync2, pkgfile);
3352
3352
  } catch (e) {
3353
3353
  }
3354
3354
  if (pkg && opts.packageFilter) {
@@ -3962,19 +3962,66 @@ var resolvePackageDir = /* @__PURE__ */ __name((pkg, parent) => {
3962
3962
  }, "resolvePackageDir");
3963
3963
 
3964
3964
  // src/componentManifest/generator.ts
3965
- import { readFile } from "node:fs/promises";
3966
- import { recast } from "storybook/internal/babel";
3967
- import { loadCsf } from "storybook/internal/csf-tools";
3968
- import { extractDescription } from "storybook/internal/csf-tools";
3965
+ import { recast as recast2 } from "storybook/internal/babel";
3966
+ import { combineTags } from "storybook/internal/csf";
3967
+ import { extractDescription, loadCsf } from "storybook/internal/csf-tools";
3968
+ import { logger as logger3 } from "storybook/internal/node-logger";
3969
3969
 
3970
3970
  // src/componentManifest/generateCodeSnippet.ts
3971
3971
  import { types as t } from "storybook/internal/babel";
3972
3972
 
3973
+ // src/componentManifest/utils.ts
3974
+ import { readFileSync } from "node:fs";
3975
+ import { resolveImport } from "storybook/internal/common";
3976
+ import { logger } from "storybook/internal/node-logger";
3977
+
3978
+ // ../../node_modules/empathic/find.mjs
3979
+ import { join as join3 } from "node:path";
3980
+ import { existsSync, statSync } from "node:fs";
3981
+
3982
+ // ../../node_modules/empathic/walk.mjs
3983
+ import { dirname as dirname2 } from "node:path";
3984
+
3985
+ // ../../node_modules/empathic/resolve.mjs
3986
+ import { isAbsolute as isAbsolute2, join as join2, resolve as resolve2 } from "node:path";
3987
+ function absolute(input, root) {
3988
+ return isAbsolute2(input) ? input : resolve2(root || ".", input);
3989
+ }
3990
+ __name(absolute, "absolute");
3991
+
3992
+ // ../../node_modules/empathic/walk.mjs
3993
+ function up(base, options) {
3994
+ let { last, cwd: cwd2 } = options || {};
3995
+ let tmp = absolute(base, cwd2);
3996
+ let root = absolute(last || "/", cwd2);
3997
+ let prev, arr = [];
3998
+ while (prev !== root) {
3999
+ arr.push(tmp);
4000
+ tmp = dirname2(prev = tmp);
4001
+ if (tmp === prev) break;
4002
+ }
4003
+ return arr;
4004
+ }
4005
+ __name(up, "up");
4006
+
4007
+ // ../../node_modules/empathic/find.mjs
4008
+ function up2(name, options) {
4009
+ let dir, tmp;
4010
+ let start = options && options.cwd || "";
4011
+ for (dir of up(start, options)) {
4012
+ tmp = join3(dir, name);
4013
+ if (existsSync(tmp)) return tmp;
4014
+ }
4015
+ }
4016
+ __name(up2, "up");
4017
+
3973
4018
  // src/componentManifest/utils.ts
3974
4019
  var groupBy = /* @__PURE__ */ __name((items, keySelector) => {
3975
4020
  return items.reduce((acc = {}, item, index) => {
3976
4021
  const key = keySelector(item, index);
3977
- acc[key] ??= [];
4022
+ if (!Array.isArray(acc[key])) {
4023
+ acc[key] = [];
4024
+ }
3978
4025
  acc[key].push(item);
3979
4026
  return acc;
3980
4027
  }, {});
@@ -3986,6 +4033,41 @@ function invariant(condition, message) {
3986
4033
  throw new Error((typeof message === "function" ? message() : message) ?? "Invariant failed");
3987
4034
  }
3988
4035
  __name(invariant, "invariant");
4036
+ var memoStore = /* @__PURE__ */ new WeakMap();
4037
+ var cached = /* @__PURE__ */ __name((fn, opts = {}) => {
4038
+ const keyOf2 = opts.key ?? ((...args) => {
4039
+ try {
4040
+ return JSON.stringify(args);
4041
+ } catch {
4042
+ return String(args[0]);
4043
+ }
4044
+ });
4045
+ return (...args) => {
4046
+ const k = keyOf2(...args);
4047
+ const name = fn.name || opts.name || "anonymous";
4048
+ let store = memoStore.get(fn);
4049
+ if (!store) {
4050
+ store = /* @__PURE__ */ new Map();
4051
+ memoStore.set(fn, store);
4052
+ }
4053
+ if (store.has(k)) {
4054
+ logger.verbose(`[cache] hit ${name} key=${k}`);
4055
+ return store.get(k);
4056
+ }
4057
+ const start = Date.now();
4058
+ const result = fn(...args);
4059
+ const duration = Date.now() - start;
4060
+ store.set(k, result);
4061
+ logger.verbose(`[cache] miss ${name} took ${duration}ms key=${k}`);
4062
+ return result;
4063
+ };
4064
+ }, "cached");
4065
+ var invalidateCache = /* @__PURE__ */ __name(() => {
4066
+ memoStore = /* @__PURE__ */ new WeakMap();
4067
+ }, "invalidateCache");
4068
+ var cachedReadFileSync = cached(readFileSync, { name: "cachedReadFile" });
4069
+ var cachedFindUp = cached(up2, { name: "findUp" });
4070
+ var cachedResolveImport = cached(resolveImport, { name: "resolveImport" });
3989
4071
 
3990
4072
  // src/componentManifest/generateCodeSnippet.ts
3991
4073
  function getCodeSnippet(csf, storyName, componentName) {
@@ -4376,6 +4458,24 @@ function pathForNode(program, target) {
4376
4458
  }
4377
4459
  __name(pathForNode, "pathForNode");
4378
4460
 
4461
+ // src/componentManifest/getComponentImports.ts
4462
+ import { dirname as dirname4 } from "node:path";
4463
+ import { babelParse as babelParse2, recast, types as t3 } from "storybook/internal/babel";
4464
+ import { logger as logger2 } from "storybook/internal/node-logger";
4465
+
4466
+ // src/componentManifest/reactDocgen.ts
4467
+ import { existsSync as existsSync2 } from "node:fs";
4468
+ import { dirname as dirname3, sep as sep2 } from "node:path";
4469
+ import { babelParse, types as t2 } from "storybook/internal/babel";
4470
+ import { getProjectRoot, supportedExtensions as supportedExtensions2 } from "storybook/internal/common";
4471
+ var TsconfigPaths = __toESM(require_lib2(), 1);
4472
+ import {
4473
+ builtinHandlers as docgenHandlers,
4474
+ builtinResolvers as docgenResolver,
4475
+ makeFsImporter,
4476
+ parse as parse3
4477
+ } from "react-docgen";
4478
+
4379
4479
  // ../../node_modules/comment-parser/es6/primitives.js
4380
4480
  var Markers;
4381
4481
  (function(Markers2) {
@@ -4574,9 +4674,9 @@ __name(typeTokenizer, "typeTokenizer");
4574
4674
  var trim = /* @__PURE__ */ __name((x) => x.trim(), "trim");
4575
4675
  function getJoiner(spacing) {
4576
4676
  if (spacing === "compact")
4577
- return (t4) => t4.map(trim).join("");
4677
+ return (t5) => t5.map(trim).join("");
4578
4678
  else if (spacing === "preserve")
4579
- return (t4) => t4.join("\n");
4679
+ return (t5) => t5.join("\n");
4580
4680
  else
4581
4681
  return spacing;
4582
4682
  }
@@ -4735,12 +4835,12 @@ function getParser4({ startLine = 0, fence = "```", spacing = "compact", markers
4735
4835
  __name(getParser4, "getParser");
4736
4836
 
4737
4837
  // ../../node_modules/comment-parser/es6/stringifier/index.js
4738
- function join2(tokens) {
4838
+ function join4(tokens) {
4739
4839
  return tokens.start + tokens.delimiter + tokens.postDelimiter + tokens.tag + tokens.postTag + tokens.type + tokens.postType + tokens.name + tokens.postName + tokens.description + tokens.end + tokens.lineEnd;
4740
4840
  }
4741
- __name(join2, "join");
4841
+ __name(join4, "join");
4742
4842
  function getStringifier() {
4743
- return (block) => block.source.map(({ tokens }) => join2(tokens)).join("\n");
4843
+ return (block) => block.source.map(({ tokens }) => join4(tokens)).join("\n");
4744
4844
  }
4745
4845
  __name(getStringifier, "getStringifier");
4746
4846
 
@@ -4786,64 +4886,6 @@ function extractJSDocInfo(jsdocComment) {
4786
4886
  }
4787
4887
  __name(extractJSDocInfo, "extractJSDocInfo");
4788
4888
 
4789
- // src/componentManifest/reactDocgen.ts
4790
- import { existsSync as existsSync2 } from "node:fs";
4791
- import { sep as sep2 } from "node:path";
4792
- import { types as t2 } from "storybook/internal/babel";
4793
- import { getProjectRoot } from "storybook/internal/common";
4794
- import { supportedExtensions as supportedExtensions2 } from "storybook/internal/common";
4795
- import { resolveImport } from "storybook/internal/common";
4796
-
4797
- // ../../node_modules/empathic/find.mjs
4798
- import { join as join4 } from "node:path";
4799
- import { existsSync, statSync } from "node:fs";
4800
-
4801
- // ../../node_modules/empathic/walk.mjs
4802
- import { dirname as dirname2 } from "node:path";
4803
-
4804
- // ../../node_modules/empathic/resolve.mjs
4805
- import { isAbsolute as isAbsolute2, join as join3, resolve as resolve2 } from "node:path";
4806
- function absolute(input, root) {
4807
- return isAbsolute2(input) ? input : resolve2(root || ".", input);
4808
- }
4809
- __name(absolute, "absolute");
4810
-
4811
- // ../../node_modules/empathic/walk.mjs
4812
- function up(base, options) {
4813
- let { last, cwd: cwd2 } = options || {};
4814
- let tmp = absolute(base, cwd2);
4815
- let root = absolute(last || "/", cwd2);
4816
- let prev, arr = [];
4817
- while (prev !== root) {
4818
- arr.push(tmp);
4819
- tmp = dirname2(prev = tmp);
4820
- if (tmp === prev) break;
4821
- }
4822
- return arr;
4823
- }
4824
- __name(up, "up");
4825
-
4826
- // ../../node_modules/empathic/find.mjs
4827
- function up2(name, options) {
4828
- let dir, tmp;
4829
- let start = options && options.cwd || "";
4830
- for (dir of up(start, options)) {
4831
- tmp = join4(dir, name);
4832
- if (existsSync(tmp)) return tmp;
4833
- }
4834
- }
4835
- __name(up2, "up");
4836
-
4837
- // src/componentManifest/reactDocgen.ts
4838
- var TsconfigPaths = __toESM(require_lib2(), 1);
4839
- import { ERROR_CODES } from "react-docgen";
4840
- import {
4841
- builtinHandlers as docgenHandlers,
4842
- builtinResolvers as docgenResolver,
4843
- makeFsImporter,
4844
- parse as parse3
4845
- } from "react-docgen";
4846
-
4847
4889
  // src/componentManifest/reactDocgen/actualNameHandler.ts
4848
4890
  import { utils } from "react-docgen";
4849
4891
  var { getNameOrValue, isReactForwardRefCall } = utils;
@@ -5018,65 +5060,154 @@ var exportNameHandler_default = exportNameHandler;
5018
5060
  var defaultHandlers = Object.values(docgenHandlers).map((handler) => handler);
5019
5061
  var defaultResolver = new docgenResolver.FindExportedDefinitionsResolver();
5020
5062
  var handlers = [...defaultHandlers, actualNameHandler_default, exportNameHandler_default];
5021
- function getMatchingDocgen(docgens, csf) {
5022
- const componentName = csf._meta?.component;
5063
+ function getMatchingDocgen(docgens, component) {
5023
5064
  if (docgens.length === 1) {
5024
5065
  return docgens[0];
5025
5066
  }
5026
- const importSpecifier = csf._componentImportSpecifier;
5027
- let importName;
5028
- if (t2.isImportSpecifier(importSpecifier)) {
5029
- const imported = importSpecifier.imported;
5030
- importName = t2.isIdentifier(imported) ? imported.name : imported.value;
5031
- } else if (t2.isImportDefaultSpecifier(importSpecifier)) {
5032
- importName = "default";
5033
- }
5034
- const docgen = docgens.find((docgen2) => docgen2.exportName === importName);
5035
- if (docgen || !componentName) {
5036
- return docgen;
5037
- }
5038
- return docgens.find(
5039
- (docgen2) => docgen2.displayName === componentName || docgen2.actualName === componentName
5067
+ const matchingDocgen = docgens.find(
5068
+ (docgen) => [component.importName, component.localImportName].includes(docgen.exportName)
5069
+ ) ?? docgens.find(
5070
+ (docgen) => [component.importName, component.localImportName, component.componentName].includes(
5071
+ docgen.displayName
5072
+ ) || [component.importName, component.localImportName, component.componentName].includes(
5073
+ docgen.actualName
5074
+ )
5040
5075
  );
5076
+ return matchingDocgen ?? docgens[0];
5041
5077
  }
5042
5078
  __name(getMatchingDocgen, "getMatchingDocgen");
5043
- async function parseWithReactDocgen({ code, filename }) {
5044
- const tsconfigPath = up2("tsconfig.json", { cwd: process.cwd(), last: getProjectRoot() });
5045
- const tsconfig = TsconfigPaths.loadConfig(tsconfigPath);
5046
- let matchPath;
5079
+ function matchPath(id, basedir) {
5080
+ basedir ??= process.cwd();
5081
+ const tsconfig = getTsConfig(basedir);
5047
5082
  if (tsconfig.resultType === "success") {
5048
- matchPath = TsconfigPaths.createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths, [
5083
+ const match = TsconfigPaths.createMatchPath(tsconfig.absoluteBaseUrl, tsconfig.paths, [
5049
5084
  "browser",
5050
5085
  "module",
5051
5086
  "main"
5052
5087
  ]);
5088
+ return match(id, void 0, void 0, supportedExtensions2) ?? id;
5053
5089
  }
5054
- try {
5090
+ return id;
5091
+ }
5092
+ __name(matchPath, "matchPath");
5093
+ var getTsConfig = cached(
5094
+ (cwd2) => {
5095
+ const tsconfigPath = up2("tsconfig.json", { cwd: cwd2, last: getProjectRoot() });
5096
+ return TsconfigPaths.loadConfig(tsconfigPath);
5097
+ },
5098
+ { name: "getTsConfig" }
5099
+ );
5100
+ var parseWithReactDocgen = cached(
5101
+ (code, path2) => {
5055
5102
  return parse3(code, {
5056
5103
  resolver: defaultResolver,
5057
5104
  handlers,
5058
- importer: getReactDocgenImporter(matchPath),
5059
- filename
5105
+ importer: getReactDocgenImporter(),
5106
+ filename: path2
5060
5107
  });
5061
- } catch (e) {
5062
- if (!(e instanceof Error && "code" in e && e.code === ERROR_CODES.MISSING_DEFINITION)) {
5063
- console.error(e);
5108
+ },
5109
+ { key: /* @__PURE__ */ __name((code, path2) => path2, "key"), name: "parseWithReactDocgen" }
5110
+ );
5111
+ var getExportPaths = cached(
5112
+ (code, filePath) => {
5113
+ const ast = (() => {
5114
+ try {
5115
+ return babelParse(code);
5116
+ } catch (_) {
5117
+ return void 0;
5118
+ }
5119
+ })();
5120
+ if (!ast) {
5121
+ return [];
5064
5122
  }
5065
- return [];
5066
- }
5067
- }
5068
- __name(parseWithReactDocgen, "parseWithReactDocgen");
5069
- function getReactDocgenImporter(matchPath) {
5123
+ const basedir = dirname3(filePath);
5124
+ const body = ast.program.body;
5125
+ return body.flatMap(
5126
+ (n) => t2.isExportAllDeclaration(n) ? [n.source.value] : t2.isExportNamedDeclaration(n) && !!n.source && !n.declaration ? [n.source.value] : []
5127
+ ).map((s) => matchPath(s, basedir)).map((s) => {
5128
+ try {
5129
+ return cachedResolveImport(s, { basedir });
5130
+ } catch {
5131
+ return void 0;
5132
+ }
5133
+ }).filter((p) => !!p && !p.includes("node_modules"));
5134
+ },
5135
+ { name: "getExportPaths" }
5136
+ );
5137
+ var gatherDocgensForPath = cached(
5138
+ (filePath, depth) => {
5139
+ if (depth > 5 || filePath.includes("node_modules")) {
5140
+ return { docgens: [], analyzed: [] };
5141
+ }
5142
+ let code;
5143
+ try {
5144
+ code = cachedReadFileSync(filePath, "utf-8");
5145
+ } catch {
5146
+ }
5147
+ if (!code) {
5148
+ return { docgens: [], analyzed: [{ path: filePath, code: "/* File not found */" }] };
5149
+ }
5150
+ const reexportResults = getExportPaths(code, filePath).map(
5151
+ (p) => gatherDocgensForPath(p, depth + 1)
5152
+ );
5153
+ const fromReexports = reexportResults.flatMap((r) => r.docgens);
5154
+ const analyzedChildren = reexportResults.flatMap((r) => r.analyzed);
5155
+ let locals;
5156
+ try {
5157
+ locals = parseWithReactDocgen(code, filePath);
5158
+ } catch {
5159
+ locals = [];
5160
+ }
5161
+ return {
5162
+ docgens: [...locals, ...fromReexports],
5163
+ analyzed: [{ path: filePath, code }, ...analyzedChildren]
5164
+ };
5165
+ },
5166
+ { name: "gatherDocgensWithTrace", key: /* @__PURE__ */ __name((filePath) => filePath, "key") }
5167
+ );
5168
+ var getReactDocgen = cached(
5169
+ (path2, component) => {
5170
+ if (path2.includes("node_modules")) {
5171
+ return {
5172
+ type: "error",
5173
+ error: {
5174
+ name: "Component file in node_modules",
5175
+ message: `Component files in node_modules are not supported. Please import your component file directly.`
5176
+ }
5177
+ };
5178
+ }
5179
+ const docgenWithInfo = gatherDocgensForPath(path2, 0);
5180
+ const docgens = docgenWithInfo.docgens;
5181
+ const noCompDefError = {
5182
+ type: "error",
5183
+ error: {
5184
+ name: "No component definition found",
5185
+ message: `Could not find a component definition.
5186
+ Prefer relative imports if possible.
5187
+ Avoid pointing to transpiled files.
5188
+ You can debug your component file in this playground: https://react-docgen.dev/playground
5189
+
5190
+ ` + docgenWithInfo.analyzed.map(({ path: path3, code }) => `File: ${path3}
5191
+ ${code}`).join("\n")
5192
+ }
5193
+ };
5194
+ if (!docgens || docgens.length === 0) {
5195
+ return noCompDefError;
5196
+ }
5197
+ const docgen = getMatchingDocgen(docgens, component);
5198
+ if (!docgen) {
5199
+ return noCompDefError;
5200
+ }
5201
+ return { type: "success", data: docgen };
5202
+ },
5203
+ { name: "getReactDocgen", key: /* @__PURE__ */ __name((path2, component) => path2 + JSON.stringify(component), "key") }
5204
+ );
5205
+ function getReactDocgenImporter() {
5070
5206
  return makeFsImporter((filename, basedir) => {
5071
5207
  const mappedFilenameByPaths = (() => {
5072
- if (matchPath) {
5073
- const match = matchPath(filename, void 0, void 0, supportedExtensions2);
5074
- return match || filename;
5075
- } else {
5076
- return filename;
5077
- }
5208
+ return matchPath(filename, basedir);
5078
5209
  })();
5079
- const result = resolveImport(mappedFilenameByPaths, { basedir });
5210
+ const result = cachedResolveImport(mappedFilenameByPaths, { basedir });
5080
5211
  if (result.includes(`${sep2}react-native${sep2}index.js`)) {
5081
5212
  const replaced = result.replace(
5082
5213
  `${sep2}react-native${sep2}index.js`,
@@ -5095,11 +5226,347 @@ function getReactDocgenImporter(matchPath) {
5095
5226
  });
5096
5227
  }
5097
5228
  __name(getReactDocgenImporter, "getReactDocgenImporter");
5229
+ function getImportTag(docgen) {
5230
+ const jsdocComment = docgen?.description;
5231
+ const tags = jsdocComment ? extractJSDocInfo(jsdocComment).tags : void 0;
5232
+ return tags?.import?.[0];
5233
+ }
5234
+ __name(getImportTag, "getImportTag");
5235
+
5236
+ // src/componentManifest/getComponentImports.ts
5237
+ var baseIdentifier = /* @__PURE__ */ __name((component) => component.split(".")[0] ?? component, "baseIdentifier");
5238
+ var isTypeSpecifier = /* @__PURE__ */ __name((s) => t3.isImportSpecifier(s) && s.importKind === "type", "isTypeSpecifier");
5239
+ var importedName = /* @__PURE__ */ __name((im) => t3.isIdentifier(im) ? im.name : im.value, "importedName");
5240
+ var addUniqueBy = /* @__PURE__ */ __name((arr, item, eq) => {
5241
+ if (!arr.find(eq)) {
5242
+ arr.push(item);
5243
+ }
5244
+ }, "addUniqueBy");
5245
+ var getComponents = /* @__PURE__ */ __name(({
5246
+ csf,
5247
+ storyFilePath
5248
+ }) => {
5249
+ const program = csf._file.path;
5250
+ const componentSet = /* @__PURE__ */ new Set();
5251
+ const localToImport = /* @__PURE__ */ new Map();
5252
+ program.traverse({
5253
+ JSXOpeningElement(p) {
5254
+ const n = p.node.name;
5255
+ if (t3.isJSXIdentifier(n)) {
5256
+ const name = n.name;
5257
+ if (name && /[A-Z]/.test(name.charAt(0))) {
5258
+ componentSet.add(name);
5259
+ }
5260
+ } else if (t3.isJSXMemberExpression(n)) {
5261
+ const jsxNameToString = /* @__PURE__ */ __name((name) => t3.isJSXIdentifier(name) ? name.name : `${jsxNameToString(name.object)}.${jsxNameToString(name.property)}`, "jsxNameToString");
5262
+ const full = jsxNameToString(n);
5263
+ componentSet.add(full);
5264
+ }
5265
+ }
5266
+ });
5267
+ const metaComp = csf._meta?.component;
5268
+ if (metaComp) {
5269
+ componentSet.add(metaComp);
5270
+ }
5271
+ const components = Array.from(componentSet).sort((a, b) => a.localeCompare(b));
5272
+ const body = program.get("body");
5273
+ for (const stmt of body) {
5274
+ if (!stmt.isImportDeclaration()) {
5275
+ continue;
5276
+ }
5277
+ const decl = stmt.node;
5278
+ if (decl.importKind === "type") {
5279
+ continue;
5280
+ }
5281
+ const specifiers = decl.specifiers ?? [];
5282
+ if (specifiers.length === 0) {
5283
+ continue;
5284
+ }
5285
+ for (const s of specifiers) {
5286
+ if (!("local" in s) || !s.local) {
5287
+ continue;
5288
+ }
5289
+ if (isTypeSpecifier(s)) {
5290
+ continue;
5291
+ }
5292
+ const importId = decl.source.value;
5293
+ if (t3.isImportDefaultSpecifier(s)) {
5294
+ localToImport.set(s.local.name, { importId, importName: "default" });
5295
+ } else if (t3.isImportNamespaceSpecifier(s)) {
5296
+ localToImport.set(s.local.name, { importId, importName: "*" });
5297
+ } else if (t3.isImportSpecifier(s)) {
5298
+ const imported = importedName(s.imported);
5299
+ localToImport.set(s.local.name, { importId, importName: imported });
5300
+ }
5301
+ }
5302
+ }
5303
+ const isLocallyDefinedWithoutImport = /* @__PURE__ */ __name((base) => {
5304
+ const binding = program.scope.getBinding(base);
5305
+ if (!binding) {
5306
+ return false;
5307
+ }
5308
+ const isImportBinding = Boolean(
5309
+ binding.path.isImportSpecifier?.() || binding.path.isImportDefaultSpecifier?.() || binding.path.isImportNamespaceSpecifier?.()
5310
+ );
5311
+ return !isImportBinding;
5312
+ }, "isLocallyDefinedWithoutImport");
5313
+ const filteredComponents = components.filter(
5314
+ (c) => !isLocallyDefinedWithoutImport(baseIdentifier(c))
5315
+ );
5316
+ const componentObjs = filteredComponents.map((c) => {
5317
+ const dot = c.indexOf(".");
5318
+ if (dot !== -1) {
5319
+ const ns = c.slice(0, dot);
5320
+ const member = c.slice(dot + 1);
5321
+ const direct2 = localToImport.get(ns);
5322
+ return !direct2 ? { componentName: c } : direct2.importName === "*" ? {
5323
+ componentName: c,
5324
+ localImportName: ns,
5325
+ importId: direct2.importId,
5326
+ importName: member,
5327
+ namespace: ns
5328
+ } : {
5329
+ componentName: c,
5330
+ localImportName: ns,
5331
+ importId: direct2.importId,
5332
+ importName: direct2.importName
5333
+ };
5334
+ }
5335
+ const direct = localToImport.get(c);
5336
+ return direct ? {
5337
+ componentName: c,
5338
+ localImportName: c,
5339
+ importId: direct.importId,
5340
+ importName: direct.importName
5341
+ } : { componentName: c };
5342
+ }).map((component) => {
5343
+ let path2;
5344
+ try {
5345
+ if (component.importId && storyFilePath) {
5346
+ path2 = cachedResolveImport(matchPath(component.importId, dirname4(storyFilePath)), {
5347
+ basedir: dirname4(storyFilePath)
5348
+ });
5349
+ }
5350
+ } catch (e) {
5351
+ logger2.error(e);
5352
+ }
5353
+ if (path2) {
5354
+ const reactDocgen = getReactDocgen(path2, component);
5355
+ return {
5356
+ ...component,
5357
+ path: path2,
5358
+ reactDocgen,
5359
+ importOverride: reactDocgen.type === "success" ? getImportTag(reactDocgen.data) : void 0
5360
+ };
5361
+ }
5362
+ return component;
5363
+ }).sort((a, b) => a.componentName.localeCompare(b.componentName));
5364
+ return componentObjs;
5365
+ }, "getComponents");
5366
+ var getImports = /* @__PURE__ */ __name(({
5367
+ components,
5368
+ packageName
5369
+ }) => {
5370
+ const isRelative = /* @__PURE__ */ __name((id) => id.startsWith(".") || id === ".", "isRelative");
5371
+ const withSource = components.filter((c) => Boolean(c.importId)).map((c, idx) => {
5372
+ const importId = c.importId;
5373
+ const overrideSource = (() => {
5374
+ if (!c.importOverride) {
5375
+ return void 0;
5376
+ }
5377
+ try {
5378
+ const parsed = babelParse2(c.importOverride);
5379
+ const decl = parsed.program.body.find((n) => t3.isImportDeclaration(n));
5380
+ const src = decl?.source?.value;
5381
+ return typeof src === "string" ? src : void 0;
5382
+ } catch {
5383
+ return void 0;
5384
+ }
5385
+ })();
5386
+ const rewritten = overrideSource !== void 0 ? overrideSource : packageName && isRelative(importId) ? packageName : importId;
5387
+ return { c, src: t3.stringLiteral(rewritten), key: rewritten, ord: idx };
5388
+ });
5389
+ const orderOfSource = {};
5390
+ for (const w of withSource) {
5391
+ if (orderOfSource[w.key] === void 0) {
5392
+ orderOfSource[w.key] = w.ord;
5393
+ }
5394
+ }
5395
+ const buckets = /* @__PURE__ */ new Map();
5396
+ const ensureBucket = /* @__PURE__ */ __name((key, src) => {
5397
+ const prev = buckets.get(key);
5398
+ if (prev) {
5399
+ return prev;
5400
+ }
5401
+ const b = {
5402
+ source: src,
5403
+ defaults: [],
5404
+ namespaces: [],
5405
+ named: [],
5406
+ order: orderOfSource[key] ?? 0
5407
+ };
5408
+ buckets.set(key, b);
5409
+ return b;
5410
+ }, "ensureBucket");
5411
+ for (const { c, src, key } of withSource) {
5412
+ const b = ensureBucket(key, src);
5413
+ const rewritten = src.value !== c.importId;
5414
+ const overrideSpec = (() => {
5415
+ if (!c.importOverride) {
5416
+ return void 0;
5417
+ }
5418
+ try {
5419
+ const parsed = babelParse2(c.importOverride);
5420
+ const decl = parsed.program.body.find((n) => t3.isImportDeclaration(n));
5421
+ if (!decl) {
5422
+ return void 0;
5423
+ }
5424
+ const spec = (decl.specifiers ?? []).find((s) => !isTypeSpecifier(s));
5425
+ if (!spec) {
5426
+ return void 0;
5427
+ }
5428
+ if (t3.isImportNamespaceSpecifier(spec)) {
5429
+ return { kind: "namespace", local: spec.local.name };
5430
+ }
5431
+ if (t3.isImportDefaultSpecifier(spec)) {
5432
+ return { kind: "default" };
5433
+ }
5434
+ if (t3.isImportSpecifier(spec)) {
5435
+ const imported = t3.isIdentifier(spec.imported) ? spec.imported.name : spec.imported.value;
5436
+ return { kind: "named", imported };
5437
+ }
5438
+ return void 0;
5439
+ } catch {
5440
+ return void 0;
5441
+ }
5442
+ })();
5443
+ if (overrideSpec) {
5444
+ if (overrideSpec.kind === "namespace") {
5445
+ const ns = t3.identifier(overrideSpec.local);
5446
+ addUniqueBy(b.namespaces, ns, (n) => n.name === ns.name);
5447
+ continue;
5448
+ }
5449
+ if (!c.localImportName) {
5450
+ continue;
5451
+ }
5452
+ if (overrideSpec.kind === "default") {
5453
+ const id = t3.identifier(c.localImportName);
5454
+ addUniqueBy(b.defaults, id, (d) => d.name === id.name);
5455
+ continue;
5456
+ }
5457
+ if (overrideSpec.kind === "named") {
5458
+ const local = t3.identifier(c.localImportName);
5459
+ const imported = t3.identifier(overrideSpec.imported);
5460
+ addUniqueBy(
5461
+ b.named,
5462
+ t3.importSpecifier(local, imported),
5463
+ (n) => n.local.name === local.name && importedName(n.imported) === imported.name
5464
+ );
5465
+ continue;
5466
+ }
5467
+ }
5468
+ if (c.namespace) {
5469
+ if (rewritten) {
5470
+ if (!c.importName) {
5471
+ continue;
5472
+ }
5473
+ const member = c.importName;
5474
+ const id = t3.identifier(member);
5475
+ addUniqueBy(
5476
+ b.named,
5477
+ t3.importSpecifier(id, id),
5478
+ (n) => n.local.name === member && importedName(n.imported) === member
5479
+ );
5480
+ } else {
5481
+ const ns = t3.identifier(c.namespace);
5482
+ addUniqueBy(b.namespaces, ns, (n) => n.name === ns.name);
5483
+ }
5484
+ continue;
5485
+ }
5486
+ if (c.importName === "default") {
5487
+ if (!c.localImportName) {
5488
+ continue;
5489
+ }
5490
+ if (rewritten) {
5491
+ const id = t3.identifier(c.localImportName);
5492
+ addUniqueBy(
5493
+ b.named,
5494
+ t3.importSpecifier(id, id),
5495
+ (n) => n.local.name === id.name && importedName(n.imported) === id.name
5496
+ );
5497
+ } else {
5498
+ const id = t3.identifier(c.localImportName);
5499
+ addUniqueBy(b.defaults, id, (d) => d.name === id.name);
5500
+ }
5501
+ continue;
5502
+ }
5503
+ if (c.importName) {
5504
+ if (!c.localImportName) {
5505
+ continue;
5506
+ }
5507
+ const local = t3.identifier(c.localImportName);
5508
+ const imported = t3.identifier(c.importName);
5509
+ addUniqueBy(
5510
+ b.named,
5511
+ t3.importSpecifier(local, imported),
5512
+ (n) => n.local.name === local.name && importedName(n.imported) === imported.name
5513
+ );
5514
+ continue;
5515
+ }
5516
+ }
5517
+ const merged = [];
5518
+ const printDecl = /* @__PURE__ */ __name((specs, src) => {
5519
+ const node = t3.importDeclaration(specs, src);
5520
+ const code = recast.print(node, {}).code;
5521
+ merged.push(code);
5522
+ }, "printDecl");
5523
+ const sortedBuckets = Array.from(buckets.values()).sort((a, b) => a.order - b.order);
5524
+ for (const bucket of sortedBuckets) {
5525
+ const { source, defaults, namespaces, named } = bucket;
5526
+ if (defaults.length === 0 && namespaces.length === 0 && named.length === 0) {
5527
+ continue;
5528
+ }
5529
+ if (namespaces.length > 0) {
5530
+ const firstSpecs = [];
5531
+ if (defaults[0]) {
5532
+ firstSpecs.push(t3.importDefaultSpecifier(defaults[0]));
5533
+ }
5534
+ firstSpecs.push(t3.importNamespaceSpecifier(namespaces[0]));
5535
+ printDecl(firstSpecs, source);
5536
+ if (named.length > 0) {
5537
+ printDecl(named, source);
5538
+ }
5539
+ for (const d of defaults.slice(1)) {
5540
+ printDecl([t3.importDefaultSpecifier(d)], source);
5541
+ }
5542
+ for (const ns of namespaces.slice(1)) {
5543
+ printDecl([t3.importNamespaceSpecifier(ns)], source);
5544
+ }
5545
+ } else {
5546
+ if (defaults.length > 0 || named.length > 0) {
5547
+ const specs = [];
5548
+ if (defaults[0]) {
5549
+ specs.push(t3.importDefaultSpecifier(defaults[0]));
5550
+ }
5551
+ specs.push(...named);
5552
+ printDecl(specs, source);
5553
+ }
5554
+ for (const d of defaults.slice(1)) {
5555
+ printDecl([t3.importDefaultSpecifier(d)], source);
5556
+ }
5557
+ }
5558
+ }
5559
+ return merged;
5560
+ }, "getImports");
5098
5561
 
5099
5562
  // src/componentManifest/generator.ts
5100
5563
  var componentManifestGenerator = /* @__PURE__ */ __name(async () => {
5101
5564
  return async (storyIndexGenerator) => {
5565
+ invalidateCache();
5566
+ const startIndex = performance.now();
5102
5567
  const index = await storyIndexGenerator.getIndex();
5568
+ logger3.verbose(`Story index generation took ${performance.now() - startIndex}ms`);
5569
+ const startPerformance = performance.now();
5103
5570
  const groupByComponentId = groupBy(
5104
5571
  Object.values(index.entries).filter((entry) => entry.type === "story").filter((entry) => entry.subtype === "story"),
5105
5572
  (it) => it.id.split("--")[0]
@@ -5107,102 +5574,101 @@ var componentManifestGenerator = /* @__PURE__ */ __name(async () => {
5107
5574
  const singleEntryPerComponent = Object.values(groupByComponentId).flatMap(
5108
5575
  (group) => group && group?.length > 0 ? [group[0]] : []
5109
5576
  );
5110
- const components = await Promise.all(
5111
- singleEntryPerComponent.flatMap(async (entry) => {
5112
- const storyFile = await readFile(path.join(process.cwd(), entry.importPath), "utf-8");
5113
- const csf = loadCsf(storyFile, { makeTitle: /* @__PURE__ */ __name((title) => title ?? "No title", "makeTitle") }).parse();
5114
- const name = csf._meta?.component ?? entry.title.split("/").at(-1);
5115
- const id = entry.id.split("--")[0];
5116
- const importPath = entry.importPath;
5117
- const examples = Object.keys(csf._stories).map((storyName) => {
5118
- try {
5119
- return {
5120
- name: storyName,
5121
- snippet: recast.print(getCodeSnippet(csf, storyName, name)).code
5122
- };
5123
- } catch (e) {
5124
- invariant(e instanceof Error);
5125
- return {
5126
- name: storyName,
5127
- error: {
5128
- name: e.name,
5129
- message: e.message
5130
- }
5131
- };
5132
- }
5133
- }).filter(Boolean);
5134
- const base = {
5135
- id,
5136
- name,
5137
- path: importPath,
5138
- examples,
5139
- jsDocTags: {}
5140
- };
5141
- if (!entry.componentPath) {
5142
- const componentName = csf._meta?.component;
5143
- const error2 = !componentName ? {
5144
- name: "No meta.component specified",
5145
- message: "Specify meta.component for the component to be included in the manifest."
5146
- } : {
5147
- name: "No component import found",
5148
- message: `No component file found for the "${componentName}" component.`
5149
- };
5150
- return {
5151
- ...base,
5152
- name,
5153
- examples,
5154
- error: {
5155
- name: error2.name,
5156
- message: csf._metaStatementPath?.buildCodeFrameError(error2.message).message ?? error2.message
5157
- }
5158
- };
5577
+ const components = singleEntryPerComponent.map((entry) => {
5578
+ const absoluteImportPath = path.join(process.cwd(), entry.importPath);
5579
+ const storyFile = cachedReadFileSync(absoluteImportPath, "utf-8");
5580
+ const csf = loadCsf(storyFile, { makeTitle: /* @__PURE__ */ __name((title2) => title2 ?? "No title", "makeTitle") }).parse();
5581
+ const manifestEnabled = csf.stories.map((it) => combineTags("manifest", ...csf.meta.tags ?? [], ...it.tags ?? [])).some((it) => it.includes("manifest"));
5582
+ if (!manifestEnabled) {
5583
+ return;
5584
+ }
5585
+ const componentName = csf._meta?.component;
5586
+ const id = entry.id.split("--")[0];
5587
+ const importPath = entry.importPath;
5588
+ const components2 = getComponents({ csf, storyFilePath: absoluteImportPath });
5589
+ const trimmedTitle = entry.title.replace(/\s+/g, "");
5590
+ const component = components2.find((it) => {
5591
+ return componentName ? [it.componentName, it.localImportName, it.importName].includes(componentName) : trimmedTitle.includes(it.componentName) || it.localImportName && trimmedTitle.includes(it.localImportName) || it.importName && trimmedTitle.includes(it.importName);
5592
+ });
5593
+ const stories = Object.keys(csf._stories).map((storyName) => {
5594
+ const story = csf._stories[storyName];
5595
+ const manifestEnabled2 = combineTags(
5596
+ "manifest",
5597
+ ...csf.meta.tags ?? [],
5598
+ ...story.tags ?? []
5599
+ ).includes("manifest");
5600
+ if (!manifestEnabled2) {
5601
+ return;
5159
5602
  }
5160
- let componentFile;
5161
5603
  try {
5162
- componentFile = await readFile(path.join(process.cwd(), entry.componentPath), "utf-8");
5604
+ const jsdocComment2 = extractDescription(csf._storyStatements[storyName]);
5605
+ const { tags: tags2 = {}, description: description2 } = jsdocComment2 ? extractJSDocInfo(jsdocComment2) : {};
5606
+ const finalDescription = (tags2?.describe?.[0] || tags2?.desc?.[0]) ?? description2;
5607
+ return {
5608
+ name: storyName,
5609
+ snippet: recast2.print(getCodeSnippet(csf, storyName, component?.componentName)).code,
5610
+ description: finalDescription?.trim(),
5611
+ summary: tags2.summary?.[0]
5612
+ };
5163
5613
  } catch (e) {
5164
5614
  invariant(e instanceof Error);
5165
5615
  return {
5166
- ...base,
5167
- name,
5168
- examples,
5169
- error: {
5170
- name: "Component file could not be read",
5171
- message: `Could not read the component file located at "${entry.componentPath}".
5172
- Prefer relative imports.`
5173
- }
5616
+ name: storyName,
5617
+ error: { name: e.name, message: e.message }
5174
5618
  };
5175
5619
  }
5176
- const docgens = await parseWithReactDocgen({
5177
- code: componentFile,
5178
- filename: path.join(process.cwd(), entry.componentPath)
5179
- });
5180
- const docgen = getMatchingDocgen(docgens, csf);
5181
- const error = !docgen ? {
5182
- name: "Docgen evaluation failed",
5183
- message: `Could not parse props information for the component file located at "${entry.componentPath}"
5184
- Avoid barrel files when importing your component file.
5185
- Prefer relative imports if possible.
5186
- Avoid pointing to transpiled files.
5187
- You can debug your component file in this playground: https://react-docgen.dev/playground`
5188
- } : void 0;
5189
- const metaDescription = extractDescription(csf._metaStatement);
5190
- const jsdocComment = metaDescription || docgen?.description;
5191
- const { tags = {}, description } = jsdocComment ? extractJSDocInfo(jsdocComment) : {};
5192
- const manifestDescription = (tags?.describe?.[0] || tags?.desc?.[0]) ?? description;
5620
+ }).filter((it) => it != null);
5621
+ const nearestPkg = cachedFindUp("package.json", {
5622
+ cwd: path.dirname(component?.path ?? absoluteImportPath)
5623
+ });
5624
+ let packageName;
5625
+ try {
5626
+ packageName = nearestPkg ? JSON.parse(cachedReadFileSync(nearestPkg, "utf-8")).name : void 0;
5627
+ } catch {
5628
+ }
5629
+ const fallbackImport = packageName && componentName ? `import { ${componentName} } from "${packageName}";` : "";
5630
+ const imports = getImports({ components: components2, packageName }).join("\n").trim() || fallbackImport;
5631
+ const title = entry.title.split("/").at(-1).replace(/\s+/g, "");
5632
+ const base = {
5633
+ id,
5634
+ name: componentName ?? title,
5635
+ path: importPath,
5636
+ stories,
5637
+ import: imports,
5638
+ jsDocTags: {}
5639
+ };
5640
+ if (!component?.reactDocgen) {
5641
+ const error2 = !component ? {
5642
+ name: "No meta.component specified",
5643
+ message: "Specify meta.component for the component to be included in the manifest."
5644
+ } : {
5645
+ name: "No component import found",
5646
+ message: `No component file found for the "${component.componentName}" component.`
5647
+ };
5193
5648
  return {
5194
5649
  ...base,
5195
- name,
5196
- description: manifestDescription?.trim(),
5197
- summary: tags.summary?.[0],
5198
- import: tags.import?.[0],
5199
- reactDocgen: docgen,
5200
- jsDocTags: tags,
5201
- examples,
5202
- error
5650
+ error: {
5651
+ name: error2.name,
5652
+ message: csf._metaStatementPath?.buildCodeFrameError(error2.message).message ?? error2.message
5653
+ }
5203
5654
  };
5204
- })
5205
- );
5655
+ }
5656
+ const docgenResult = component.reactDocgen;
5657
+ const docgen = docgenResult.type === "success" ? docgenResult.data : void 0;
5658
+ const error = docgenResult.type === "error" ? docgenResult.error : void 0;
5659
+ const jsdocComment = extractDescription(csf._metaStatement) || docgen?.description;
5660
+ const { tags = {}, description } = jsdocComment ? extractJSDocInfo(jsdocComment) : {};
5661
+ return {
5662
+ ...base,
5663
+ description: ((tags?.describe?.[0] || tags?.desc?.[0]) ?? description)?.trim(),
5664
+ summary: tags.summary?.[0],
5665
+ import: imports,
5666
+ reactDocgen: docgen,
5667
+ jsDocTags: tags,
5668
+ error
5669
+ };
5670
+ });
5671
+ logger3.verbose(`Component manifest generation took ${performance.now() - startPerformance}ms`);
5206
5672
  return {
5207
5673
  v: 0,
5208
5674
  components: Object.fromEntries(
@@ -5213,7 +5679,7 @@ You can debug your component file in this playground: https://react-docgen.dev/p
5213
5679
  }, "componentManifestGenerator");
5214
5680
 
5215
5681
  // src/enrichCsf.ts
5216
- import { recast as recast2, types as t3 } from "storybook/internal/babel";
5682
+ import { recast as recast3, types as t4 } from "storybook/internal/babel";
5217
5683
  import { getPrettier } from "storybook/internal/common";
5218
5684
  var enrichCsf = /* @__PURE__ */ __name(async (input, options) => {
5219
5685
  const features = await options.presets.apply("features");
@@ -5238,7 +5704,7 @@ var enrichCsf = /* @__PURE__ */ __name(async (input, options) => {
5238
5704
  }
5239
5705
  try {
5240
5706
  if (!snippet && node) {
5241
- snippet = await format3(recast2.print(node).code, {
5707
+ snippet = await format3(recast3.print(node).code, {
5242
5708
  filepath: join(process.cwd(), "component.tsx")
5243
5709
  });
5244
5710
  }
@@ -5251,35 +5717,35 @@ var enrichCsf = /* @__PURE__ */ __name(async (input, options) => {
5251
5717
  if (!snippet) {
5252
5718
  return;
5253
5719
  }
5254
- const originalParameters = t3.memberExpression(
5255
- csf._metaIsFactory ? t3.memberExpression(t3.identifier(key), t3.identifier("input")) : t3.identifier(key),
5256
- t3.identifier("parameters")
5720
+ const originalParameters = t4.memberExpression(
5721
+ csf._metaIsFactory ? t4.memberExpression(t4.identifier(key), t4.identifier("input")) : t4.identifier(key),
5722
+ t4.identifier("parameters")
5257
5723
  );
5258
- const docsParameter = t3.optionalMemberExpression(
5724
+ const docsParameter = t4.optionalMemberExpression(
5259
5725
  originalParameters,
5260
- t3.identifier("docs"),
5726
+ t4.identifier("docs"),
5261
5727
  false,
5262
5728
  true
5263
5729
  );
5264
5730
  csf._ast.program.body.push(
5265
- t3.expressionStatement(
5266
- t3.assignmentExpression(
5731
+ t4.expressionStatement(
5732
+ t4.assignmentExpression(
5267
5733
  "=",
5268
5734
  originalParameters,
5269
- t3.objectExpression([
5270
- t3.spreadElement(originalParameters),
5271
- t3.objectProperty(
5272
- t3.identifier("docs"),
5273
- t3.objectExpression([
5274
- t3.spreadElement(docsParameter),
5275
- t3.objectProperty(
5276
- t3.identifier("source"),
5277
- t3.objectExpression([
5278
- t3.objectProperty(t3.identifier("code"), t3.stringLiteral(snippet)),
5279
- t3.spreadElement(
5280
- t3.optionalMemberExpression(
5735
+ t4.objectExpression([
5736
+ t4.spreadElement(originalParameters),
5737
+ t4.objectProperty(
5738
+ t4.identifier("docs"),
5739
+ t4.objectExpression([
5740
+ t4.spreadElement(docsParameter),
5741
+ t4.objectProperty(
5742
+ t4.identifier("source"),
5743
+ t4.objectExpression([
5744
+ t4.objectProperty(t4.identifier("code"), t4.stringLiteral(snippet)),
5745
+ t4.spreadElement(
5746
+ t4.optionalMemberExpression(
5281
5747
  docsParameter,
5282
- t3.identifier("source"),
5748
+ t4.identifier("source"),
5283
5749
  false,
5284
5750
  true
5285
5751
  )
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/react",
3
- "version": "10.1.0-alpha.3",
3
+ "version": "10.1.0-alpha.5",
4
4
  "description": "Storybook React renderer",
5
5
  "keywords": [
6
6
  "storybook"
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@storybook/global": "^5.0.0",
57
- "@storybook/react-dom-shim": "10.1.0-alpha.3",
57
+ "@storybook/react-dom-shim": "10.1.0-alpha.5",
58
58
  "react-docgen": "^8.0.2"
59
59
  },
60
60
  "devDependencies": {
@@ -67,6 +67,7 @@
67
67
  "acorn-walk": "^7.2.0",
68
68
  "babel-plugin-react-docgen": "^4.2.1",
69
69
  "comment-parser": "^1.4.1",
70
+ "empathic": "^2.0.0",
70
71
  "es-toolkit": "^1.36.0",
71
72
  "escodegen": "^2.1.0",
72
73
  "expect-type": "^0.15.0",
@@ -80,7 +81,7 @@
80
81
  "peerDependencies": {
81
82
  "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
82
83
  "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
83
- "storybook": "^10.1.0-alpha.3",
84
+ "storybook": "^10.1.0-alpha.5",
84
85
  "typescript": ">= 4.9.x"
85
86
  },
86
87
  "peerDependenciesMeta": {