storybook-builder-rsbuild 2.1.6 → 3.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.
package/dist/index.mjs DELETED
@@ -1,947 +0,0 @@
1
- import { __commonJS, __toESM, __require } from './chunk-TTFRSOOU.mjs';
2
- import { createServer } from 'net';
3
- import { dirname, join, resolve, parse, isAbsolute } from 'path';
4
- import * as rsbuildReal from '@rsbuild/core';
5
- import { loadConfig, mergeRsbuildConfig } from '@rsbuild/core';
6
- import fs from 'fs-extra';
7
- import sirv from 'sirv';
8
- import { getBuilderOptions, normalizeStories, loadPreviewOrConfigFile, readTemplate, resolveAddonName, getPresets, stringifyProcessEnvs, isPreservingSymlinks } from 'storybook/internal/common';
9
- import { WebpackInvocationError } from 'storybook/internal/server-errors';
10
- import { pluginTypeCheck } from '@rsbuild/plugin-type-check';
11
- import CaseSensitivePathsPlugin from 'case-sensitive-paths-webpack-plugin';
12
- import { pluginHtmlMinifierTerser } from 'rsbuild-plugin-html-minifier-terser';
13
- import { globalsNameReferenceMap } from 'storybook/internal/preview/globals';
14
- import { dedent } from 'ts-dedent';
15
- import { readFile } from 'fs/promises';
16
-
17
- // ../../node_modules/.pnpm/pretty-hrtime@1.0.3/node_modules/pretty-hrtime/index.js
18
- var require_pretty_hrtime = __commonJS({
19
- "../../node_modules/.pnpm/pretty-hrtime@1.0.3/node_modules/pretty-hrtime/index.js"(exports, module) {
20
- var minimalDesc = ["h", "min", "s", "ms", "\u03BCs", "ns"];
21
- var verboseDesc = ["hour", "minute", "second", "millisecond", "microsecond", "nanosecond"];
22
- var convert = [60 * 60, 60, 1, 1e6, 1e3, 1];
23
- module.exports = function(source, opts) {
24
- var verbose, precise, i, spot, sourceAtStep, valAtStep, decimals, strAtStep, results, totalSeconds;
25
- verbose = false;
26
- precise = false;
27
- if (opts) {
28
- verbose = opts.verbose || false;
29
- precise = opts.precise || false;
30
- }
31
- if (!Array.isArray(source) || source.length !== 2) {
32
- return "";
33
- }
34
- if (typeof source[0] !== "number" || typeof source[1] !== "number") {
35
- return "";
36
- }
37
- if (source[1] < 0) {
38
- totalSeconds = source[0] + source[1] / 1e9;
39
- source[0] = parseInt(totalSeconds);
40
- source[1] = parseFloat((totalSeconds % 1).toPrecision(9)) * 1e9;
41
- }
42
- results = "";
43
- for (i = 0; i < 6; i++) {
44
- spot = i < 3 ? 0 : 1;
45
- sourceAtStep = source[spot];
46
- if (i !== 3 && i !== 0) {
47
- sourceAtStep = sourceAtStep % convert[i - 1];
48
- }
49
- if (i === 2) {
50
- sourceAtStep += source[1] / 1e9;
51
- }
52
- valAtStep = sourceAtStep / convert[i];
53
- if (valAtStep >= 1) {
54
- if (verbose) {
55
- valAtStep = Math.floor(valAtStep);
56
- }
57
- if (!precise) {
58
- decimals = valAtStep >= 10 ? 0 : 2;
59
- strAtStep = valAtStep.toFixed(decimals);
60
- } else {
61
- strAtStep = valAtStep.toString();
62
- }
63
- if (strAtStep.indexOf(".") > -1 && strAtStep[strAtStep.length - 1] === "0") {
64
- strAtStep = strAtStep.replace(/\.?0+$/, "");
65
- }
66
- if (results) {
67
- results += " ";
68
- }
69
- results += strAtStep;
70
- if (verbose) {
71
- results += " " + verboseDesc[i];
72
- if (strAtStep !== "1") {
73
- results += "s";
74
- }
75
- } else {
76
- results += " " + minimalDesc[i];
77
- }
78
- if (!verbose) {
79
- break;
80
- }
81
- }
82
- }
83
- return results;
84
- };
85
- }
86
- });
87
-
88
- // compiled/@storybook/core-webpack/index.js
89
- var require_core_webpack = __commonJS({
90
- "compiled/@storybook/core-webpack/index.js"(exports, module) {
91
- (() => {
92
- var __webpack_modules__ = {
93
- 830: (module2, __unused_webpack_exports, __nccwpck_require__2) => {
94
- var __defProp = Object.defineProperty;
95
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
96
- var __getOwnPropNames = Object.getOwnPropertyNames;
97
- var __hasOwnProp = Object.prototype.hasOwnProperty;
98
- var __export = (target, all) => {
99
- for (var name in all)
100
- __defProp(target, name, { get: all[name], enumerable: true });
101
- }, __copyProps = (to, from, except, desc) => {
102
- if (from && typeof from == "object" || typeof from == "function")
103
- for (let key of __getOwnPropNames(from))
104
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, {
105
- get: () => from[key],
106
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
107
- });
108
- return to;
109
- };
110
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
111
- var index_exports = {};
112
- __export(index_exports, {
113
- checkWebpackVersion: () => checkWebpackVersion,
114
- loadCustomWebpackConfig: () => loadCustomWebpackConfig,
115
- mergeConfigs: () => mergeConfigs,
116
- toImportFn: () => toImportFn2,
117
- toImportFnPart: () => toImportFnPart,
118
- toRequireContext: () => toRequireContext,
119
- toRequireContextString: () => toRequireContextString,
120
- webpackIncludeRegexp: () => webpackIncludeRegexp
121
- });
122
- module2.exports = __toCommonJS(index_exports);
123
- var import_node_path5 = __nccwpck_require__2(928), import_common4 = __nccwpck_require__2(253), webpackConfigs = ["webpack.config", "webpackfile"], loadCustomWebpackConfig = (configDir) => (0, import_common4.serverRequire)(
124
- webpackConfigs.map(
125
- (configName) => (0, import_node_path5.resolve)(configDir, configName)
126
- )
127
- );
128
- var import_node_logger = __nccwpck_require__2(519), import_ts_dedent2 = __nccwpck_require__2(980), checkWebpackVersion = (webpack, specifier, caption) => {
129
- if (!webpack.version) {
130
- import_node_logger.logger.info(
131
- "Skipping webpack version check, no version available"
132
- );
133
- return;
134
- }
135
- webpack.version !== specifier && import_node_logger.logger.warn(import_ts_dedent2.dedent`
136
- Unexpected webpack version in ${caption}:
137
- - Received '${webpack.version}'
138
- - Expected '${specifier}'
139
-
140
- If you're using Webpack 5 in SB6.2 and upgrading, consider: https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#webpack-5-manager-build
141
-
142
- For more info about Webpack 5 support: https://gist.github.com/shilman/8856ea1786dcd247139b47b270912324#troubleshooting
143
- `);
144
- };
145
- function mergePluginsField(defaultPlugins = [], customPlugins = []) {
146
- return [...defaultPlugins, ...customPlugins];
147
- }
148
- function mergeRulesField(defaultRules = [], customRules = []) {
149
- return [...defaultRules, ...customRules];
150
- }
151
- function mergeExtensionsField({ extensions: defaultExtensions = [] }, { extensions: customExtensions = [] }) {
152
- return [...defaultExtensions, ...customExtensions];
153
- }
154
- function mergeAliasField({ alias: defaultAlias = {} }, { alias: customAlias = {} }) {
155
- return { ...defaultAlias, ...customAlias };
156
- }
157
- function mergeModuleField(a, b) {
158
- return {
159
- ...a,
160
- ...b,
161
- rules: mergeRulesField(a.rules || [], b.rules || [])
162
- };
163
- }
164
- function mergeResolveField({ resolve: defaultResolve = {} }, { resolve: customResolve = {} }) {
165
- return {
166
- ...defaultResolve,
167
- ...customResolve,
168
- alias: mergeAliasField(defaultResolve, customResolve),
169
- extensions: mergeExtensionsField(defaultResolve, customResolve)
170
- };
171
- }
172
- function mergeOptimizationField({ optimization: defaultOptimization = {} }, { optimization: customOptimization = {} }) {
173
- return { ...defaultOptimization, ...customOptimization };
174
- }
175
- function mergeConfigs(config, customConfig) {
176
- return {
177
- ...customConfig,
178
- ...config,
179
- devtool: customConfig.devtool || config.devtool,
180
- plugins: mergePluginsField(config.plugins, customConfig.plugins),
181
- module: mergeModuleField(
182
- config.module || {},
183
- customConfig.module || {}
184
- ),
185
- resolve: mergeResolveField(config, customConfig),
186
- optimization: mergeOptimizationField(config, customConfig)
187
- };
188
- }
189
- var import_common22 = __nccwpck_require__2(253), import_ts_dedent22 = __nccwpck_require__2(980);
190
- function importPipeline() {
191
- let importGate = Promise.resolve();
192
- return async (importFn) => {
193
- await importGate;
194
- let moduleExportsPromise = importFn();
195
- return importGate = importGate.then(async () => {
196
- await moduleExportsPromise;
197
- }), moduleExportsPromise;
198
- };
199
- }
200
- function adjustRegexToExcludeNodeModules(originalRegex) {
201
- let originalRegexString = originalRegex.source, startsWithCaret = originalRegexString.startsWith("^"), excludeNodeModulesPattern = startsWithCaret ? "(?!.*node_modules)" : "^(?!.*node_modules)", adjustedRegexString = startsWithCaret ? `^${excludeNodeModulesPattern}${originalRegexString.substring(1)}` : excludeNodeModulesPattern + originalRegexString;
202
- return new RegExp(adjustedRegexString);
203
- }
204
- function webpackIncludeRegexp(specifier) {
205
- let { directory, files } = specifier, directoryWithoutLeadingDots = directory.replace(/^(\.+\/)+/, "/"), webpackIncludeGlob = [".", ".."].includes(directory) ? files : `${directoryWithoutLeadingDots}/${files}`, webpackIncludeRegexpWithCaret = webpackIncludeGlob.includes(
206
- "node_modules"
207
- ) ? (0, import_common22.globToRegexp)(webpackIncludeGlob) : adjustRegexToExcludeNodeModules(
208
- (0, import_common22.globToRegexp)(webpackIncludeGlob)
209
- );
210
- return new RegExp(
211
- webpackIncludeRegexpWithCaret.source.replace(/^\^/, "")
212
- );
213
- }
214
- function toImportFnPart(specifier) {
215
- let { directory, importPathMatcher } = specifier;
216
- return import_ts_dedent22.dedent`
217
- async (path) => {
218
- if (!${importPathMatcher}.exec(path)) {
219
- return;
220
- }
221
-
222
- const pathRemainder = path.substring(${directory.length + 1});
223
- return import(
224
- /* webpackChunkName: "[request]" */
225
- /* webpackInclude: ${webpackIncludeRegexp(specifier)} */
226
- '${directory}/' + pathRemainder
227
- );
228
- }
229
-
230
- `;
231
- }
232
- function toImportFn2(stories, { needPipelinedImport } = {}) {
233
- let pipelinedImport = "const pipeline = (x) => x();";
234
- return needPipelinedImport && (pipelinedImport = `
235
- const importPipeline = ${importPipeline};
236
- const pipeline = importPipeline();
237
- `), import_ts_dedent22.dedent`
238
- ${pipelinedImport}
239
-
240
- const importers = [
241
- ${stories.map(toImportFnPart).join(`,
242
- `)}
243
- ];
244
-
245
- export async function importFn(path) {
246
- for (let i = 0; i < importers.length; i++) {
247
- const moduleExports = await pipeline(() => importers[i](path));
248
- if (moduleExports) {
249
- return moduleExports;
250
- }
251
- }
252
- }
253
- `;
254
- }
255
- var import_common32 = __nccwpck_require__2(253), toRequireContext = (specifier) => {
256
- let { directory, files } = specifier, match = (0, import_common32.globToRegexp)(`./${files}`);
257
- return {
258
- path: directory,
259
- recursive: files.includes("**") || files.split("/").length > 1,
260
- match
261
- };
262
- }, toRequireContextString = (specifier) => {
263
- let { path: p, recursive: r, match: m } = toRequireContext(specifier);
264
- return `require.context('${p}', ${r}, ${m})`;
265
- };
266
- },
267
- 980: (__unused_webpack_module, exports2) => {
268
- Object.defineProperty(exports2, "__esModule", { value: true });
269
- exports2.dedent = void 0;
270
- function dedent2(templ) {
271
- var values = [];
272
- for (var _i = 1; _i < arguments.length; _i++) {
273
- values[_i - 1] = arguments[_i];
274
- }
275
- var strings = Array.from(typeof templ === "string" ? [templ] : templ);
276
- strings[strings.length - 1] = strings[strings.length - 1].replace(
277
- /\r?\n([\t ]*)$/,
278
- ""
279
- );
280
- var indentLengths = strings.reduce(function(arr, str) {
281
- var matches = str.match(/\n([\t ]+|(?!\s).)/g);
282
- if (matches) {
283
- return arr.concat(
284
- matches.map(function(match) {
285
- var _a, _b;
286
- return (_b = (_a = match.match(/[\t ]/g)) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
287
- })
288
- );
289
- }
290
- return arr;
291
- }, []);
292
- if (indentLengths.length) {
293
- var pattern_1 = new RegExp(
294
- "\n[ ]{" + Math.min.apply(Math, indentLengths) + "}",
295
- "g"
296
- );
297
- strings = strings.map(function(str) {
298
- return str.replace(pattern_1, "\n");
299
- });
300
- }
301
- strings[0] = strings[0].replace(/^\r?\n/, "");
302
- var string = strings[0];
303
- values.forEach(function(value, i) {
304
- var endentations = string.match(/(?:^|\n)( *)$/);
305
- var endentation = endentations ? endentations[1] : "";
306
- var indentedValue = value;
307
- if (typeof value === "string" && value.includes("\n")) {
308
- indentedValue = String(value).split("\n").map(function(str, i2) {
309
- return i2 === 0 ? str : "" + endentation + str;
310
- }).join("\n");
311
- }
312
- string += indentedValue + strings[i + 1];
313
- });
314
- return string;
315
- }
316
- exports2.dedent = dedent2;
317
- exports2["default"] = dedent2;
318
- },
319
- 928: (module2) => {
320
- module2.exports = __require("path");
321
- },
322
- 253: (module2) => {
323
- module2.exports = __require("storybook/internal/common");
324
- },
325
- 519: (module2) => {
326
- module2.exports = __require("storybook/internal/node-logger");
327
- }
328
- };
329
- var __webpack_module_cache__ = {};
330
- function __nccwpck_require__(moduleId) {
331
- var cachedModule = __webpack_module_cache__[moduleId];
332
- if (cachedModule !== void 0) {
333
- return cachedModule.exports;
334
- }
335
- var module2 = __webpack_module_cache__[moduleId] = { exports: {} };
336
- var threw = true;
337
- try {
338
- __webpack_modules__[moduleId](
339
- module2,
340
- module2.exports,
341
- __nccwpck_require__
342
- );
343
- threw = false;
344
- } finally {
345
- if (threw)
346
- delete __webpack_module_cache__[moduleId];
347
- }
348
- return module2.exports;
349
- }
350
- if (typeof __nccwpck_require__ !== "undefined")
351
- __nccwpck_require__.ab = __dirname + "/";
352
- var __webpack_exports__ = __nccwpck_require__(830);
353
- module.exports = __webpack_exports__;
354
- })();
355
- }
356
- });
357
-
358
- // src/index.ts
359
- var import_pretty_hrtime = __toESM(require_pretty_hrtime());
360
-
361
- // ../../node_modules/.pnpm/slash@5.1.0/node_modules/slash/index.js
362
- function slash(path) {
363
- const isExtendedLengthPath = path.startsWith("\\\\?\\");
364
- if (isExtendedLengthPath) {
365
- return path;
366
- }
367
- return path.replace(/\\/g, "/");
368
- }
369
-
370
- // src/preview/virtual-module-mapping.ts
371
- var import_core_webpack = __toESM(require_core_webpack());
372
- var getVirtualModules = async (options) => {
373
- const virtualModules = {};
374
- const builderOptions = await getBuilderOptions(options);
375
- const workingDir = process.cwd();
376
- const isProd = options.configType === "PRODUCTION";
377
- const nonNormalizedStories = await options.presets.apply("stories", []);
378
- const entries = [];
379
- const stories = normalizeStories(nonNormalizedStories, {
380
- configDir: options.configDir,
381
- workingDir
382
- });
383
- const previewAnnotations = [
384
- ...(await options.presets.apply(
385
- "previewAnnotations",
386
- [],
387
- options
388
- )).map((entry) => {
389
- if (typeof entry === "object") {
390
- return entry.absolute;
391
- }
392
- return slash(entry);
393
- }),
394
- loadPreviewOrConfigFile(options)
395
- ].filter(Boolean);
396
- const storiesFilename = "storybook-stories.js";
397
- const storiesPath = resolve(join(workingDir, storiesFilename));
398
- const needPipelinedImport = !!builderOptions.lazyCompilation && !isProd;
399
- virtualModules[storiesPath] = (0, import_core_webpack.toImportFn)(stories, {
400
- needPipelinedImport
401
- });
402
- const configEntryPath = resolve(join(workingDir, "storybook-config-entry.js"));
403
- virtualModules[configEntryPath] = (await readTemplate(
404
- __require.resolve(
405
- "storybook-builder-rsbuild/templates/virtualModuleModernEntry.js"
406
- )
407
- )).replaceAll(`'{{storiesFilename}}'`, `'./${storiesFilename}'`).replaceAll(
408
- `'{{previewAnnotations}}'`,
409
- previewAnnotations.filter(Boolean).map((entry) => `'${entry}'`).join(",")
410
- ).replaceAll(
411
- `'{{previewAnnotations_requires}}'`,
412
- previewAnnotations.filter(Boolean).map((entry) => `require('${entry}')`).join(",")
413
- ).replace(/\\/g, "\\\\");
414
- entries.push(configEntryPath);
415
- return {
416
- virtualModules,
417
- entries
418
- };
419
- };
420
-
421
- // src/preview/iframe-rsbuild.config.ts
422
- var getAbsolutePath = (input) => dirname(__require.resolve(join(input, "package.json")));
423
- var maybeGetAbsolutePath = (input) => {
424
- try {
425
- return getAbsolutePath(input);
426
- } catch (e) {
427
- return false;
428
- }
429
- };
430
- var builtInResolveExtensions = [
431
- ".mjs",
432
- ".js",
433
- ".jsx",
434
- ".ts",
435
- ".tsx",
436
- ".json",
437
- ".cjs"
438
- ];
439
- var globalPath = maybeGetAbsolutePath("@storybook/global");
440
- var storybookPaths = {
441
- // biome-ignore lint/complexity/useLiteralKeys: <explanation>
442
- ...globalPath ? { ["@storybook/global"]: globalPath } : {}
443
- };
444
- var iframe_rsbuild_config_default = async (options, extraWebpackConfig) => {
445
- const { rsbuildConfigPath, addonDocs } = await getBuilderOptions(options);
446
- const webpackConfigFromPresets = await options.presets.apply("webpack", {}, options);
447
- if (addonDocs) {
448
- console.warn(
449
- "`addonDocs` option is deprecated and will be removed in future versions. Please use `@storybook/addon-docs` option instead."
450
- );
451
- }
452
- const {
453
- outputDir = join(".", "public"),
454
- quiet,
455
- packageJson,
456
- configType,
457
- presets,
458
- previewUrl,
459
- typescriptOptions,
460
- features
461
- } = options;
462
- const isProd = configType === "PRODUCTION";
463
- const workingDir = process.cwd();
464
- const [
465
- coreOptions,
466
- frameworkOptions,
467
- envs,
468
- logLevel,
469
- headHtmlSnippet,
470
- bodyHtmlSnippet,
471
- template,
472
- docsOptions,
473
- entries,
474
- nonNormalizedStories,
475
- _modulesCount,
476
- build2,
477
- tagsOptions
478
- ] = await Promise.all([
479
- presets.apply("core"),
480
- presets.apply("frameworkOptions"),
481
- presets.apply("env"),
482
- presets.apply("logLevel", void 0),
483
- presets.apply("previewHead"),
484
- presets.apply("previewBody"),
485
- presets.apply("previewMainTemplate"),
486
- presets.apply("docs"),
487
- presets.apply("entries", []),
488
- presets.apply("stories", []),
489
- options.cache?.get("modulesCount", 1e3),
490
- options.presets.apply("build"),
491
- presets.apply("tags", {})
492
- ]);
493
- const stories = normalizeStories(nonNormalizedStories, {
494
- configDir: options.configDir,
495
- workingDir
496
- });
497
- const shouldCheckTs = typescriptOptions.check && !typescriptOptions.skipCompiler;
498
- const tsCheckOptions = typescriptOptions.checkOptions || {};
499
- const builderOptions = await getBuilderOptions(options);
500
- const cacheConfig = builderOptions.fsCache ? true : void 0;
501
- const lazyCompilationConfig = builderOptions.lazyCompilation && !isProd ? {
502
- lazyCompilation: { entries: false }
503
- } : {};
504
- if (!template) {
505
- throw new Error(dedent`
506
- Storybook's Webpack5 builder requires a template to be specified.
507
- Somehow you've ended up with a falsy value for the template option.
508
-
509
- Please file an issue at https://github.com/storybookjs/storybook with a reproduction.
510
- `);
511
- }
512
- const externals = globalsNameReferenceMap;
513
- if (build2?.test?.disableBlocks) {
514
- externals["@storybook/blocks"] = "__STORYBOOK_BLOCKS_EMPTY_MODULE__";
515
- }
516
- const { virtualModules: virtualModuleMapping, entries: dynamicEntries } = await getVirtualModules(options);
517
- if (!options.cache) {
518
- throw new Error("Cache is required");
519
- }
520
- let contentFromConfig = {};
521
- const { content } = await loadConfig({
522
- cwd: workingDir,
523
- path: rsbuildConfigPath
524
- });
525
- const { environments, ...withoutEnv } = content;
526
- if (content.environments) {
527
- const envCount = Object.keys(content.environments).length;
528
- if (envCount === 0) {
529
- contentFromConfig = withoutEnv;
530
- } else if (envCount === 1) {
531
- contentFromConfig = mergeRsbuildConfig(
532
- withoutEnv,
533
- content.environments[0]
534
- );
535
- } else {
536
- const userEnv = builderOptions.environment;
537
- if (typeof userEnv !== "string") {
538
- throw new Error(
539
- "You must specify an environment when there are multiple environments in the Rsbuild config."
540
- );
541
- }
542
- if (Object.keys(content.environments).includes(userEnv)) {
543
- contentFromConfig = mergeRsbuildConfig(
544
- withoutEnv,
545
- content.environments[userEnv]
546
- );
547
- } else {
548
- throw new Error(
549
- `The specified environment "${userEnv}" is not found in the Rsbuild config.`
550
- );
551
- }
552
- }
553
- } else {
554
- contentFromConfig = content;
555
- }
556
- const resourceFilename = isProd ? "static/media/[name].[contenthash:8][ext]" : "static/media/[path][name][ext]";
557
- const rsbuildConfig = mergeRsbuildConfig(contentFromConfig, {
558
- output: {
559
- cleanDistPath: false,
560
- assetPrefix: "/",
561
- dataUriLimit: {
562
- media: 1e4
563
- },
564
- sourceMap: {
565
- js: options.build?.test?.disableSourcemaps ? false : "cheap-module-source-map",
566
- css: !options.build?.test?.disableSourcemaps
567
- },
568
- distPath: {
569
- root: resolve(process.cwd(), outputDir)
570
- },
571
- filename: {
572
- js: isProd ? "[name].[contenthash:8].iframe.bundle.js" : "[name].iframe.bundle.js",
573
- image: resourceFilename,
574
- font: resourceFilename,
575
- media: resourceFilename
576
- },
577
- externals
578
- },
579
- server: {
580
- // Storybook will handle public directory itself, disable Rsbuild's public dir
581
- // feature to prevent overwriting Storybook's public directory.
582
- publicDir: false
583
- },
584
- dev: {
585
- assetPrefix: "/",
586
- progressBar: !quiet
587
- },
588
- resolve: {
589
- alias: {
590
- ...storybookPaths
591
- }
592
- },
593
- source: {
594
- define: {
595
- ...stringifyProcessEnvs(envs),
596
- NODE_ENV: JSON.stringify(process.env.NODE_ENV)
597
- }
598
- },
599
- performance: {
600
- chunkSplit: {
601
- strategy: "custom",
602
- splitChunks: {
603
- chunks: "all"
604
- }
605
- },
606
- buildCache: cacheConfig
607
- },
608
- plugins: [
609
- shouldCheckTs ? pluginTypeCheck(tsCheckOptions) : null,
610
- pluginHtmlMinifierTerser(() => ({
611
- collapseWhitespace: true,
612
- removeComments: true,
613
- removeRedundantAttributes: true,
614
- removeScriptTypeAttributes: false,
615
- removeStyleLinkTypeAttributes: true,
616
- useShortDoctype: true
617
- }))
618
- ].filter(Boolean),
619
- tools: {
620
- rspack: (config, { addRules, rspack: rspack2, mergeConfig }) => {
621
- addRules({
622
- test: /\.stories\.([tj])sx?$|(stories|story)\.mdx$/,
623
- exclude: /node_modules/,
624
- enforce: "post",
625
- use: [
626
- {
627
- loader: __require.resolve(
628
- "storybook-builder-rsbuild/loaders/export-order-loader"
629
- )
630
- }
631
- ]
632
- });
633
- config.module ??= {};
634
- config.module.parser ??= {};
635
- config.module.parser.javascript ??= {};
636
- config.module.parser.javascript.unknownContextCritical = false;
637
- config.resolve ??= {};
638
- config.resolve.symlinks = !isPreservingSymlinks();
639
- config.resolve.extensions = Array.from(
640
- /* @__PURE__ */ new Set([
641
- ...config.resolve.extensions ?? [],
642
- ...builtInResolveExtensions
643
- ])
644
- );
645
- config.watchOptions = {
646
- ignored: /node_modules/
647
- };
648
- config.ignoreWarnings = [
649
- ...config.ignoreWarnings || [],
650
- /export '\S+' was not found in 'global'/,
651
- /export '\S+' was not found in '@storybook\/global'/
652
- ];
653
- config.resolve ??= {};
654
- config.resolve.fallback ??= {
655
- stream: false,
656
- path: __require.resolve("path-browserify"),
657
- assert: __require.resolve("browser-assert"),
658
- util: __require.resolve("util"),
659
- url: __require.resolve("url"),
660
- fs: false,
661
- constants: __require.resolve("constants-browserify")
662
- };
663
- config.optimization ??= {};
664
- config.optimization.runtimeChunk = true;
665
- config.optimization.usedExports = options.build?.test?.disableTreeShaking ? false : isProd;
666
- config.optimization.moduleIds = "named";
667
- config.module ??= {};
668
- config.module.parser ??= {};
669
- config.module.parser.javascript ??= {};
670
- config.module.parser.javascript.exportsPresence = false;
671
- if (!rspack2.experiments?.VirtualModulesPlugin) {
672
- throw new Error(
673
- "rspack.experiments.VirtualModulesPlugin requires at least 1.5.0 version of @rsbuild/core, please upgrade or downgrade storybook-rsbuild-builder to lower version."
674
- );
675
- }
676
- config.plugins ??= [];
677
- config.plugins.push(
678
- ...[
679
- Object.keys(virtualModuleMapping).length > 0 ? new rspack2.experiments.VirtualModulesPlugin(
680
- virtualModuleMapping
681
- ) : null,
682
- new rspack2.ProvidePlugin({
683
- process: __require.resolve("process/browser.js")
684
- }),
685
- new CaseSensitivePathsPlugin()
686
- ].filter(Boolean)
687
- );
688
- config.experiments ??= {};
689
- config.experiments.outputModule = false;
690
- config.externalsType = "var";
691
- config.output ??= {};
692
- config.output.module = false;
693
- config.output.chunkFormat = "array-push";
694
- config.output.chunkLoading = "jsonp";
695
- config.experiments = {
696
- ...config.experiments,
697
- ...lazyCompilationConfig
698
- };
699
- return mergeConfig(
700
- config,
701
- extraWebpackConfig || {},
702
- webpackConfigFromPresets
703
- );
704
- },
705
- htmlPlugin: {
706
- filename: "iframe.html",
707
- // FIXME: `none` isn't a known option
708
- chunksSortMode: "none",
709
- alwaysWriteToDisk: true,
710
- inject: false,
711
- template,
712
- templateParameters: {
713
- version: packageJson?.version ?? "0.0.0-storybook-rsbuild-unknown-version",
714
- globals: {
715
- CONFIG_TYPE: configType,
716
- LOGLEVEL: logLevel,
717
- FRAMEWORK_OPTIONS: frameworkOptions,
718
- CHANNEL_OPTIONS: coreOptions.channelOptions,
719
- FEATURES: features,
720
- PREVIEW_URL: previewUrl,
721
- STORIES: stories.map((specifier) => ({
722
- ...specifier,
723
- importPathMatcher: specifier.importPathMatcher.source
724
- })),
725
- DOCS_OPTIONS: docsOptions,
726
- TAGS_OPTIONS: tagsOptions,
727
- ...build2?.test?.disableBlocks ? { __STORYBOOK_BLOCKS_EMPTY_MODULE__: {} } : {}
728
- },
729
- headHtmlSnippet,
730
- bodyHtmlSnippet
731
- }
732
- }
733
- }
734
- });
735
- rsbuildConfig.source ??= {};
736
- rsbuildConfig.source.entry = {
737
- main: [...entries ?? [], ...dynamicEntries]
738
- };
739
- return rsbuildConfig;
740
- };
741
- var getIsReactVersion18or19 = async (options) => {
742
- const { legacyRootApi } = await options.presets.apply(
743
- "frameworkOptions"
744
- ) || {};
745
- if (legacyRootApi) {
746
- return false;
747
- }
748
- const resolvedReact = await options.presets.apply(
749
- "resolvedReact",
750
- {}
751
- );
752
- let reactDom = "";
753
- reactDom = resolvedReact.reactDom || dirname(__require.resolve("react-dom/package.json"));
754
- if (!isAbsolute(reactDom)) {
755
- return false;
756
- }
757
- const { version } = JSON.parse(
758
- await readFile(join(reactDom, "package.json"), "utf-8")
759
- );
760
- return version.startsWith("18") || version.startsWith("19") || version.startsWith("0.0.0");
761
- };
762
- var applyReactShims = async (config, options) => {
763
- const isReactVersion18 = await getIsReactVersion18or19(options);
764
- if (isReactVersion18) {
765
- return {};
766
- }
767
- return {
768
- resolve: {
769
- alias: {
770
- "@storybook/react-dom-shim": "@storybook/react-dom-shim/dist/react-16"
771
- }
772
- }
773
- };
774
- };
775
-
776
- // src/index.ts
777
- var corePath = dirname(__require.resolve("storybook/package.json"));
778
- var printDuration = (startTime) => (0, import_pretty_hrtime.default)(process.hrtime(startTime)).replace(" ms", " milliseconds").replace(" s", " seconds").replace(" m", " minutes");
779
- var executor = {
780
- get: async (options) => {
781
- const rsbuildInstance = await options.presets.apply("rsbuildInstance") || rsbuildReal;
782
- return rsbuildInstance;
783
- }
784
- };
785
- var isObject = (val) => val != null && typeof val === "object" && Array.isArray(val) === false;
786
- function nonNullables(value) {
787
- return value !== void 0;
788
- }
789
- var rsbuild = async (_, options) => {
790
- const { presets } = options;
791
- const webpackAddons = await presets.apply("webpackAddons");
792
- const resolvedWebpackAddons = (webpackAddons ?? []).map((preset) => {
793
- const addonOptions = isObject(preset) ? preset.options || void 0 : void 0;
794
- const name = isObject(preset) ? preset.name : preset;
795
- return resolveAddonName(options.configDir, name, addonOptions);
796
- }).filter(nonNullables);
797
- const { apply } = await getPresets(resolvedWebpackAddons, options);
798
- const webpackAddonsConfig = await apply(
799
- "webpackFinal",
800
- // TODO: using empty webpack config as base for now. It's better to using the composed rspack
801
- // config in `iframe-rsbuild.config.ts` as base config. But when `tools.rspack` is an async function,
802
- // the following `tools.rspack` raise an `Promises are not supported` error.
803
- {
804
- output: {},
805
- module: {},
806
- plugins: [],
807
- resolve: {},
808
- // https://github.com/web-infra-dev/rsbuild/blob/8dc35dc1d1500d2f119875d46b6a07e27986d532/packages/core/src/provider/rspackConfig.ts#L167
809
- devServer: void 0,
810
- optimization: {},
811
- performance: {},
812
- externals: {},
813
- experiments: {},
814
- node: {},
815
- stats: {},
816
- entry: {}
817
- },
818
- options
819
- );
820
- let intrinsicRsbuildConfig = await iframe_rsbuild_config_default(options, webpackAddonsConfig);
821
- const shimsConfig = await applyReactShims(intrinsicRsbuildConfig, options);
822
- intrinsicRsbuildConfig = rsbuildReal.mergeRsbuildConfig(
823
- intrinsicRsbuildConfig,
824
- shimsConfig
825
- );
826
- const finalConfig = await presets.apply(
827
- "rsbuildFinal",
828
- intrinsicRsbuildConfig,
829
- options
830
- );
831
- return finalConfig;
832
- };
833
- var getConfig = async (options) => {
834
- const { presets } = options;
835
- const typescriptOptions = await presets.apply("typescript", {}, options);
836
- const frameworkOptions = await presets.apply("frameworkOptions");
837
- return rsbuild({}, {
838
- ...options,
839
- typescriptOptions,
840
- frameworkOptions
841
- });
842
- };
843
- var server;
844
- async function bail() {
845
- return server?.close();
846
- }
847
- var start = async ({
848
- startTime,
849
- options,
850
- router,
851
- server: storybookServer,
852
- channel
853
- }) => {
854
- const { createRsbuild } = await executor.get(options);
855
- const config = await getConfig(options);
856
- const rsbuildBuild = await createRsbuild({
857
- cwd: process.cwd(),
858
- rsbuildConfig: {
859
- ...config,
860
- server: {
861
- ...config.server,
862
- port: await getRandomPort(options.host),
863
- host: options.host,
864
- htmlFallback: false,
865
- printUrls: false
866
- }
867
- }
868
- });
869
- const rsbuildServer = await rsbuildBuild.createDevServer();
870
- const waitFirstCompileDone = new Promise((resolve3) => {
871
- rsbuildBuild.onDevCompileDone(({ stats: stats2, isFirstCompile }) => {
872
- if (!isFirstCompile) {
873
- return;
874
- }
875
- resolve3(stats2);
876
- });
877
- });
878
- server = rsbuildServer;
879
- if (!rsbuildBuild) {
880
- throw new WebpackInvocationError({
881
- // eslint-disable-next-line local-rules/no-uncategorized-errors
882
- error: new Error("Missing Rsbuild build instance at runtime!")
883
- });
884
- }
885
- const previewResolvedDir = join(corePath, "dist/preview");
886
- const previewDirOrigin = previewResolvedDir;
887
- router.use(
888
- "/sb-preview",
889
- sirv(previewDirOrigin, { maxAge: 3e5, dev: true, immutable: true })
890
- );
891
- router.use(rsbuildServer.middlewares);
892
- rsbuildServer.connectWebSocket({ server: storybookServer });
893
- const stats = await waitFirstCompileDone;
894
- await server.afterListen();
895
- return {
896
- bail,
897
- stats,
898
- totalTime: process.hrtime(startTime)
899
- };
900
- };
901
- var build = async ({ options }) => {
902
- const { createRsbuild } = await executor.get(options);
903
- const config = await getConfig(options);
904
- const rsbuildBuild = await createRsbuild({
905
- cwd: process.cwd(),
906
- rsbuildConfig: config
907
- });
908
- const previewResolvedDir = join(corePath, "dist/preview");
909
- const previewDirOrigin = previewResolvedDir;
910
- const previewDirTarget = join(options.outputDir || "", "sb-preview");
911
- let stats;
912
- rsbuildBuild.onAfterBuild((params) => {
913
- stats = params.stats;
914
- });
915
- const previewFiles = fs.copy(previewDirOrigin, previewDirTarget, {
916
- filter: (src) => {
917
- const { ext } = parse(src);
918
- if (ext) {
919
- return ext === ".js";
920
- }
921
- return true;
922
- }
923
- });
924
- rsbuildBuild.onAfterBuild((params) => {
925
- stats = params.stats;
926
- });
927
- const [{ close }] = await Promise.all([rsbuildBuild.build(), previewFiles]);
928
- await close();
929
- return stats;
930
- };
931
- var corePresets = [join(__dirname, "./preview-preset.js")];
932
- var previewMainTemplate = () => __require.resolve("storybook-builder-rsbuild/templates/preview.ejs");
933
- function getRandomPort(host) {
934
- return new Promise((resolve3, reject) => {
935
- const server2 = createServer();
936
- server2.unref();
937
- server2.on("error", reject);
938
- server2.listen({ port: 0, host }, () => {
939
- const { port } = server2.address();
940
- server2.close(() => {
941
- resolve3(port);
942
- });
943
- });
944
- });
945
- }
946
-
947
- export { bail, build, corePresets, executor, getConfig, getVirtualModules, previewMainTemplate, printDuration, start };