storybook-react-rsbuild
Version:
Storybook for React and Rsbuild: Develop React components in isolation with Hot Reloading.
234 lines (230 loc) • 8.69 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/loaders/react-docgen-loader.ts
var react_docgen_loader_exports = {};
__export(react_docgen_loader_exports, {
default: () => reactDocgenLoader,
getReactDocgenImporter: () => getReactDocgenImporter
});
module.exports = __toCommonJS(react_docgen_loader_exports);
var import_find_up = __toESM(require("find-up"));
var import_magic_string = __toESM(require("magic-string"));
var import_react_docgen = require("react-docgen");
var import_node_logger = require("storybook/internal/node-logger");
var TsconfigPaths = __toESM(require("tsconfig-paths"));
// src/loaders/docgen-resolver.ts
var import_node_path = require("path");
var import_resolve = __toESM(require("resolve"));
var ReactDocgenResolveError = class extends Error {
constructor(filename) {
super(`'${filename}' was ignored by react-docgen.`);
// the magic string that react-docgen uses to check if a module is ignored
this.code = "MODULE_NOT_FOUND";
}
};
var RESOLVE_EXTENSIONS = [
".js",
".cts",
// These were originally not in the code, I added them
".mts",
// These were originally not in the code, I added them
".ctsx",
// These were originally not in the code, I added them
".mtsx",
// These were originally not in the code, I added them
".ts",
".tsx",
".mjs",
".cjs",
".mts",
".cts",
".jsx"
];
function defaultLookupModule(filename, basedir) {
const resolveOptions = {
basedir,
extensions: RESOLVE_EXTENSIONS,
// we do not need to check core modules as we cannot import them anyway
includeCoreModules: false
};
try {
return import_resolve.default.sync(filename, resolveOptions);
} catch (error) {
const ext = (0, import_node_path.extname)(filename);
let newFilename;
switch (ext) {
case ".js":
case ".mjs":
case ".cjs":
newFilename = `${filename.slice(0, -2)}ts`;
break;
case ".jsx":
newFilename = `${filename.slice(0, -3)}tsx`;
break;
default:
throw error;
}
return import_resolve.default.sync(newFilename, {
...resolveOptions,
// we already know that there is an extension at this point, so no need to check other extensions
extensions: []
});
}
}
// src/loaders/react-docgen-loader.ts
var { getNameOrValue, isReactForwardRefCall } = import_react_docgen.utils;
var actualNameHandler = function actualNameHandler2(documentation, componentDefinition) {
documentation.set("definedInFile", componentDefinition.hub.file.opts.filename);
if ((componentDefinition.isClassDeclaration() || componentDefinition.isFunctionDeclaration()) && componentDefinition.has("id")) {
documentation.set(
"actualName",
getNameOrValue(componentDefinition.get("id"))
);
} else if (componentDefinition.isArrowFunctionExpression() || componentDefinition.isFunctionExpression() || isReactForwardRefCall(componentDefinition)) {
let currentPath = componentDefinition;
while (currentPath.parentPath) {
if (currentPath.parentPath.isVariableDeclarator()) {
documentation.set(
"actualName",
getNameOrValue(currentPath.parentPath.get("id"))
);
return;
}
if (currentPath.parentPath.isAssignmentExpression()) {
const leftPath = currentPath.parentPath.get("left");
if (leftPath.isIdentifier() || leftPath.isLiteral()) {
documentation.set("actualName", getNameOrValue(leftPath));
return;
}
}
currentPath = currentPath.parentPath;
}
documentation.set("actualName", "");
}
};
var defaultHandlers = Object.values(import_react_docgen.builtinHandlers).map((handler) => handler);
var defaultResolver = new import_react_docgen.builtinResolvers.FindExportedDefinitionsResolver();
var handlers = [...defaultHandlers, actualNameHandler];
var tsconfigPathsInitializeStatus = "uninitialized";
var resolveTsconfigPathsInitialingPromise;
var tsconfigPathsInitialingPromise = new Promise((resolve2) => {
resolveTsconfigPathsInitialingPromise = resolve2;
});
var finishInitialization = () => {
resolveTsconfigPathsInitialingPromise();
tsconfigPathsInitializeStatus = "initialized";
};
var matchPath;
async function reactDocgenLoader(source, map) {
const callback = this.async();
const options = this.getOptions() || {};
const { debug = false } = options;
if (tsconfigPathsInitializeStatus === "uninitialized") {
tsconfigPathsInitializeStatus = "initializing";
const tsconfigPath = await (0, import_find_up.default)("tsconfig.json", { cwd: process.cwd() });
const tsconfig = TsconfigPaths.loadConfig(tsconfigPath);
if (tsconfig.resultType === "success") {
import_node_logger.logger.info("Using tsconfig paths for react-docgen");
matchPath = TsconfigPaths.createMatchPath(
tsconfig.absoluteBaseUrl,
tsconfig.paths,
["browser", "module", "main"]
);
}
finishInitialization();
}
if (tsconfigPathsInitializeStatus === "initializing") {
await tsconfigPathsInitialingPromise;
}
try {
const docgenResults = (0, import_react_docgen.parse)(source, {
filename: this.resourcePath,
resolver: defaultResolver,
handlers,
importer: getReactDocgenImporter(matchPath),
babelOptions: {
babelrc: false,
configFile: false
}
});
const magicString = new import_magic_string.default(source);
for (const info of docgenResults) {
const { actualName, definedInFile, ...docgenInfo } = info;
if (actualName && definedInFile === this.resourcePath) {
const docNode = JSON.stringify(docgenInfo);
magicString.append(`;${actualName}.__docgenInfo=${docNode}`);
}
}
callback(
null,
magicString.toString(),
map ?? magicString.generateMap({
hires: true,
source: this.resourcePath,
includeContent: true
})
);
} catch (error) {
if (error.code === import_react_docgen.ERROR_CODES.MISSING_DEFINITION) {
callback(null, source);
} else {
if (!debug) {
import_node_logger.logger.warn(
`Failed to parse ${this.resourcePath} with react-docgen. Rerun Storybook with --loglevel=debug to get more info.`
);
} else {
import_node_logger.logger.warn(
`Failed to parse ${this.resourcePath} with react-docgen. Please use the below error message and the content of the file which causes the error to report the issue to the maintainers of react-docgen. https://github.com/reactjs/react-docgen`
);
import_node_logger.logger.error(error);
}
callback(null, source);
}
}
}
function getReactDocgenImporter(matchingPath) {
return (0, import_react_docgen.makeFsImporter)((filename, basedir) => {
const mappedFilenameByPaths = (() => {
if (matchingPath) {
const match = matchingPath(filename);
return match || filename;
}
return filename;
})();
const result = defaultLookupModule(mappedFilenameByPaths, basedir);
if (RESOLVE_EXTENSIONS.find((ext) => result.endsWith(ext))) {
return result;
}
throw new ReactDocgenResolveError(filename);
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getReactDocgenImporter
});
;