@storybook/addon-docs
Version:
Storybook Docs: Document UI components automatically with stories and MDX
629 lines (620 loc) • 20.8 kB
JavaScript
import CJS_COMPAT_NODE_URL_o8fb71raa5h from 'node:url';
import CJS_COMPAT_NODE_PATH_o8fb71raa5h from 'node:path';
import CJS_COMPAT_NODE_MODULE_o8fb71raa5h from "node:module";
var __filename = CJS_COMPAT_NODE_URL_o8fb71raa5h.fileURLToPath(import.meta.url);
var __dirname = CJS_COMPAT_NODE_PATH_o8fb71raa5h.dirname(__filename);
var require = CJS_COMPAT_NODE_MODULE_o8fb71raa5h.createRequire(import.meta.url);
// ------------------------------------------------------------
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
// ------------------------------------------------------------
import {
__name
} from "./_node-chunks/chunk-O6ZJH52M.js";
// src/preset.ts
import { isAbsolute as isAbsolute2 } from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
import { logger } from "storybook/internal/node-logger";
// ../../core/src/shared/utils/module.ts
import { fileURLToPath, pathToFileURL } from "node:url";
// ../../node_modules/exsolve/dist/index.mjs
import assert from "node:assert";
import v8 from "node:v8";
import { format, inspect } from "node:util";
var own$1 = {}.hasOwnProperty;
var classRegExp = /^([A-Z][a-z\d]*)+$/;
var kTypes = /* @__PURE__ */ new Set([
"string",
"function",
"number",
"object",
// Accept 'Function' and 'Object' as alternative to the lower cased version.
"Function",
"Object",
"boolean",
"bigint",
"symbol"
]);
var messages = /* @__PURE__ */ new Map();
var nodeInternalPrefix = "__node_internal_";
var userStackTraceLimit;
function formatList(array, type = "and") {
return array.length < 3 ? array.join(` ${type} `) : `${array.slice(0, -1).join(", ")}, ${type} ${array.at(-1)}`;
}
__name(formatList, "formatList");
function createError(sym, value, constructor) {
messages.set(sym, value);
return makeNodeErrorWithCode(constructor, sym);
}
__name(createError, "createError");
function makeNodeErrorWithCode(Base, key) {
return /* @__PURE__ */ __name(function NodeError(...parameters) {
const limit = Error.stackTraceLimit;
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
const error = new Base();
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
const message = getMessage(key, parameters, error);
Object.defineProperties(error, {
// Note: no need to implement `kIsNodeError` symbol, would be hard,
// probably.
message: {
value: message,
enumerable: false,
writable: true,
configurable: true
},
toString: {
/** @this {Error} */
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
}
});
captureLargerStackTrace(error);
error.code = key;
return error;
}, "NodeError");
}
__name(makeNodeErrorWithCode, "makeNodeErrorWithCode");
function isErrorStackTraceLimitWritable() {
try {
if (v8.startupSnapshot.isBuildingSnapshot()) {
return false;
}
} catch {
}
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
if (desc === void 0) {
return Object.isExtensible(Error);
}
return own$1.call(desc, "writable") && desc.writable !== void 0 ? desc.writable : desc.set !== void 0;
}
__name(isErrorStackTraceLimitWritable, "isErrorStackTraceLimitWritable");
function hideStackFrames(wrappedFunction) {
const hidden = nodeInternalPrefix + wrappedFunction.name;
Object.defineProperty(wrappedFunction, "name", { value: hidden });
return wrappedFunction;
}
__name(hideStackFrames, "hideStackFrames");
var captureLargerStackTrace = hideStackFrames(function(error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
return error;
});
function getMessage(key, parameters, self) {
const message = messages.get(key);
assert(message !== void 0, "expected `message` to be found");
if (typeof message === "function") {
assert(
message.length <= parameters.length,
// Default options do not count.
`Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${message.length}).`
);
return Reflect.apply(message, self, parameters);
}
const regex = /%[dfijoOs]/g;
let expectedLength = 0;
while (regex.exec(message) !== null) expectedLength++;
assert(
expectedLength === parameters.length,
`Code: ${key}; The provided arguments length (${parameters.length}) does not match the required ones (${expectedLength}).`
);
if (parameters.length === 0) return message;
parameters.unshift(message);
return Reflect.apply(format, null, parameters);
}
__name(getMessage, "getMessage");
function determineSpecificType(value) {
if (value === null || value === void 0) {
return String(value);
}
if (typeof value === "function" && value.name) {
return `function ${value.name}`;
}
if (typeof value === "object") {
if (value.constructor && value.constructor.name) {
return `an instance of ${value.constructor.name}`;
}
return `${inspect(value, { depth: -1 })}`;
}
let inspected = inspect(value, { colors: false });
if (inspected.length > 28) {
inspected = `${inspected.slice(0, 25)}...`;
}
return `type ${typeof value} (${inspected})`;
}
__name(determineSpecificType, "determineSpecificType");
createError(
"ERR_INVALID_ARG_TYPE",
(name, expected, actual) => {
assert(typeof name === "string", "'name' must be a string");
if (!Array.isArray(expected)) {
expected = [expected];
}
let message = "The ";
if (name.endsWith(" argument")) {
message += `${name} `;
} else {
const type = name.includes(".") ? "property" : "argument";
message += `"${name}" ${type} `;
}
message += "must be ";
const types = [];
const instances = [];
const other = [];
for (const value of expected) {
assert(
typeof value === "string",
"All expected entries have to be of type string"
);
if (kTypes.has(value)) {
types.push(value.toLowerCase());
} else if (classRegExp.exec(value) === null) {
assert(
value !== "object",
'The value "object" should be written as "Object"'
);
other.push(value);
} else {
instances.push(value);
}
}
if (instances.length > 0) {
const pos = types.indexOf("object");
if (pos !== -1) {
types.slice(pos, 1);
instances.push("Object");
}
}
if (types.length > 0) {
message += `${types.length > 1 ? "one of type" : "of type"} ${formatList(
types,
"or"
)}`;
if (instances.length > 0 || other.length > 0) message += " or ";
}
if (instances.length > 0) {
message += `an instance of ${formatList(instances, "or")}`;
if (other.length > 0) message += " or ";
}
if (other.length > 0) {
if (other.length > 1) {
message += `one of ${formatList(other, "or")}`;
} else {
if (other[0]?.toLowerCase() !== other[0]) message += "an ";
message += `${other[0]}`;
}
}
message += `. Received ${determineSpecificType(actual)}`;
return message;
},
TypeError
);
var ERR_INVALID_MODULE_SPECIFIER = createError(
"ERR_INVALID_MODULE_SPECIFIER",
/**
* @param {string} request
* @param {string} reason
* @param {string} [base]
*/
(request, reason, base) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ""}`;
},
TypeError
);
var ERR_INVALID_PACKAGE_CONFIG = createError(
"ERR_INVALID_PACKAGE_CONFIG",
(path2, base, message) => {
return `Invalid package config ${path2}${base ? ` while importing ${base}` : ""}${message ? `. ${message}` : ""}`;
},
Error
);
var ERR_INVALID_PACKAGE_TARGET = createError(
"ERR_INVALID_PACKAGE_TARGET",
(packagePath, key, target, isImport = false, base) => {
const relatedError = typeof target === "string" && !isImport && target.length > 0 && !target.startsWith("./");
if (key === ".") {
assert(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} defined in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
}
return `Invalid "${isImport ? "imports" : "exports"}" target ${JSON.stringify(
target
)} defined for '${key}' in the package config ${packagePath}package.json${base ? ` imported from ${base}` : ""}${relatedError ? '; targets must start with "./"' : ""}`;
},
Error
);
var ERR_MODULE_NOT_FOUND = createError(
"ERR_MODULE_NOT_FOUND",
(path2, base, exactUrl = false) => {
return `Cannot find ${exactUrl ? "module" : "package"} '${path2}' imported from ${base}`;
},
Error
);
createError(
"ERR_NETWORK_IMPORT_DISALLOWED",
"import of '%s' by %s is not supported: %s",
Error
);
var ERR_PACKAGE_IMPORT_NOT_DEFINED = createError(
"ERR_PACKAGE_IMPORT_NOT_DEFINED",
(specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath || ""}package.json` : ""} imported from ${base}`;
},
TypeError
);
var ERR_PACKAGE_PATH_NOT_EXPORTED = createError(
"ERR_PACKAGE_PATH_NOT_EXPORTED",
/**
* @param {string} packagePath
* @param {string} subpath
* @param {string} [base]
*/
(packagePath, subpath, base) => {
if (subpath === ".")
return `No "exports" main defined in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${packagePath}package.json${base ? ` imported from ${base}` : ""}`;
},
Error
);
var ERR_UNSUPPORTED_DIR_IMPORT = createError(
"ERR_UNSUPPORTED_DIR_IMPORT",
"Directory import '%s' is not supported resolving ES modules imported from %s",
Error
);
var ERR_UNSUPPORTED_RESOLVE_REQUEST = createError(
"ERR_UNSUPPORTED_RESOLVE_REQUEST",
'Failed to resolve module specifier "%s" from "%s": Invalid relative URL or base scheme is not hierarchical.',
TypeError
);
var ERR_UNKNOWN_FILE_EXTENSION = createError(
"ERR_UNKNOWN_FILE_EXTENSION",
(extension, path2) => {
return `Unknown file extension "${extension}" for ${path2}`;
},
TypeError
);
createError(
"ERR_INVALID_ARG_VALUE",
(name, value, reason = "is invalid") => {
let inspected = inspect(value);
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`;
}
const type = name.includes(".") ? "property" : "argument";
return `The ${type} '${name}' ${reason}. Received ${inspected}`;
},
TypeError
// Note: extra classes have been shaken out.
// , RangeError
);
var hasOwnProperty$1 = {}.hasOwnProperty;
var hasOwnProperty = {}.hasOwnProperty;
var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace];
var own = {}.hasOwnProperty;
var isWindows = (() => process.platform === "win32")();
var globalCache = (() => (
// eslint-disable-next-line unicorn/no-unreadable-iife
globalThis["__EXSOLVE_CACHE__"] ||= /* @__PURE__ */ new Map()
))();
// ../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(input = "") {
if (!input) {
return input;
}
return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
}
__name(normalizeWindowsPath, "normalizeWindowsPath");
var _UNC_REGEX = /^[/\\]{2}/;
var _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/;
var _DRIVE_LETTER_RE = /^[A-Za-z]:$/;
var normalize = /* @__PURE__ */ __name(function(path2) {
if (path2.length === 0) {
return ".";
}
path2 = normalizeWindowsPath(path2);
const isUNCPath = path2.match(_UNC_REGEX);
const isPathAbsolute = isAbsolute(path2);
const trailingSeparator = path2[path2.length - 1] === "/";
path2 = normalizeString(path2, !isPathAbsolute);
if (path2.length === 0) {
if (isPathAbsolute) {
return "/";
}
return trailingSeparator ? "./" : ".";
}
if (trailingSeparator) {
path2 += "/";
}
if (_DRIVE_LETTER_RE.test(path2)) {
path2 += "/";
}
if (isUNCPath) {
if (!isPathAbsolute) {
return `//./${path2}`;
}
return `//${path2}`;
}
return isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2;
}, "normalize");
var join = /* @__PURE__ */ __name(function(...arguments_) {
if (arguments_.length === 0) {
return ".";
}
let joined;
for (const argument of arguments_) {
if (argument && argument.length > 0) {
if (joined === void 0) {
joined = argument;
} else {
joined += `/${argument}`;
}
}
}
if (joined === void 0) {
return ".";
}
return normalize(joined.replace(/\/\/+/g, "/"));
}, "join");
function normalizeString(path2, allowAboveRoot) {
let res = "";
let lastSegmentLength = 0;
let lastSlash = -1;
let dots = 0;
let char = null;
for (let index = 0; index <= path2.length; ++index) {
if (index < path2.length) {
char = path2[index];
} else if (char === "/") {
break;
} else {
char = "/";
}
if (char === "/") {
if (lastSlash === index - 1 || dots === 1) ;
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf("/");
if (lastSlashIndex === -1) {
res = "";
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf("/");
}
lastSlash = index;
dots = 0;
continue;
} else if (res.length > 0) {
res = "";
lastSegmentLength = 0;
lastSlash = index;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
res += res.length > 0 ? "/.." : "..";
lastSegmentLength = 2;
}
} else {
if (res.length > 0) {
res += `/${path2.slice(lastSlash + 1, index)}`;
} else {
res = path2.slice(lastSlash + 1, index);
}
lastSegmentLength = index - lastSlash - 1;
}
lastSlash = index;
dots = 0;
} else if (char === "." && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
__name(normalizeString, "normalizeString");
var isAbsolute = /* @__PURE__ */ __name(function(p) {
return _IS_ABSOLUTE_RE.test(p);
}, "isAbsolute");
var dirname = /* @__PURE__ */ __name(function(p) {
const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1);
if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) {
segments[0] += "/";
}
return segments.join("/") || (isAbsolute(p) ? "/" : ".");
}, "dirname");
// ../../core/src/shared/utils/module.ts
var importMetaResolve = /* @__PURE__ */ __name((...args) => {
if (typeof import.meta.resolve !== "function" && process.env.VITEST === "true") {
console.warn(
"importMetaResolve from within Storybook is being used in a Vitest test, but it shouldn't be. Please report this at https://github.com/storybookjs/storybook/issues/new?template=bug_report.yml"
);
return pathToFileURL(args[0]).href;
}
return import.meta.resolve(...args);
}, "importMetaResolve");
var resolvePackageDir = /* @__PURE__ */ __name((pkg, parent) => {
return dirname(fileURLToPath(importMetaResolve(join(pkg, "package.json"), parent)));
}, "resolvePackageDir");
// src/preset.ts
var getResolvedReact = /* @__PURE__ */ __name(async (options) => {
const resolvedReact2 = await options.presets.apply("resolvedReact", {});
return {
react: resolvedReact2.react ?? resolvePackageDir("react"),
reactDom: resolvedReact2.reactDom ?? resolvePackageDir("react-dom"),
// In Webpack, symlinked MDX files will cause @mdx-js/react to not be resolvable if it is not hoisted
// This happens for the SB monorepo's template stories when a sandbox has a different react version than
// addon-docs, causing addon-docs's dependencies not to be hoisted.
// This might also affect regular users who have a similar setup.
// Explicitly alias @mdx-js/react to avoid this issue.
mdx: resolvedReact2.mdx ?? fileURLToPath2(import.meta.resolve("@mdx-js/react"))
};
}, "getResolvedReact");
async function webpack(webpackConfig = {}, options) {
const { module = {} } = webpackConfig;
const { csfPluginOptions = {}, mdxPluginOptions = {} } = options;
const rehypeSlug = (await import("./_node-chunks/rehype-slug-QDFXIH3R.js")).default;
const rehypeExternalLinks = (await import("./_node-chunks/rehype-external-links-DE7ZVD6K.js")).default;
const mdxLoaderOptions = await options.presets.apply("mdxLoaderOptions", {
...mdxPluginOptions,
mdxCompileOptions: {
providerImportSource: import.meta.resolve("@storybook/addon-docs/mdx-react-shim"),
...mdxPluginOptions.mdxCompileOptions,
rehypePlugins: [
...mdxPluginOptions?.mdxCompileOptions?.rehypePlugins ?? [],
rehypeSlug,
rehypeExternalLinks
]
}
});
logger.info(`Addon-docs: using MDX3`);
const { react, reactDom, mdx } = await getResolvedReact(options);
let alias;
if (Array.isArray(webpackConfig.resolve?.alias)) {
alias = [...webpackConfig.resolve?.alias];
alias.push(
{
name: "react",
alias: react
},
{
name: "react-dom",
alias: reactDom
},
{
name: "@mdx-js/react",
alias: mdx
}
);
} else {
alias = {
...webpackConfig.resolve?.alias,
react,
"react-dom": reactDom,
"@mdx-js/react": mdx
};
}
const result = {
...webpackConfig,
plugins: [
...webpackConfig.plugins || [],
...csfPluginOptions ? [(await import("@storybook/csf-plugin")).webpack(csfPluginOptions)] : []
],
resolve: {
...webpackConfig.resolve,
alias
},
module: {
...module,
rules: [
...module.rules || [],
{
test: /\.mdx$/,
exclude: /(stories|story)\.mdx$/,
use: [
{
loader: fileURLToPath2(import.meta.resolve("@storybook/addon-docs/mdx-loader")),
options: mdxLoaderOptions
}
]
}
]
}
};
return result;
}
__name(webpack, "webpack");
var docs = /* @__PURE__ */ __name((input = {}, options) => {
if (options?.build?.test?.disableAutoDocs) {
return void 0;
}
const result = {
...input,
defaultName: "Docs"
};
const docsMode = options.docs;
if (docsMode) {
result.docsMode = docsMode;
}
return result;
}, "docs");
var addons = [
import.meta.resolve("@storybook/react-dom-shim/preset")
];
var viteFinal = /* @__PURE__ */ __name(async (config, options) => {
const { plugins = [] } = config;
const { mdxPlugin } = await import("./_node-chunks/mdx-plugin-F4UPHDSI.js");
const { react, reactDom, mdx } = await getResolvedReact(options);
const packageDeduplicationPlugin = {
name: "storybook:package-deduplication",
enforce: "pre",
config: /* @__PURE__ */ __name(() => ({
resolve: {
alias: {
react,
// Vite doesn't respect export maps when resolving an absolute path, so we need to do that manually here
...isAbsolute2(reactDom) && { "react-dom/server": `${reactDom}/server.browser.js` },
"react-dom": reactDom,
"@mdx-js/react": mdx
}
}
}), "config")
};
plugins.unshift(packageDeduplicationPlugin);
plugins.unshift(mdxPlugin(options));
return {
...config,
plugins
};
}, "viteFinal");
var webpackX = webpack;
var docsX = docs;
var resolvedReact = /* @__PURE__ */ __name(async (existing) => ({
react: existing?.react ?? resolvePackageDir("react"),
reactDom: existing?.reactDom ?? resolvePackageDir("react-dom"),
mdx: existing?.mdx ?? fileURLToPath2(import.meta.resolve("@mdx-js/react"))
}), "resolvedReact");
var optimizeViteDeps = [
"@storybook/addon-docs",
"@storybook/addon-docs/blocks",
"@storybook/addon-docs > @mdx-js/react"
];
export {
addons,
docsX as docs,
optimizeViteDeps,
resolvedReact,
viteFinal,
webpackX as webpack
};