@storybook/builder-vite 10.3.0-alpha.0 → 10.3.0-alpha.10
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/_node-chunks/chunk-4UDKVYWO.js +651 -0
- package/dist/index.js +426 -788
- package/dist/preset.js +11 -220
- package/package.json +4 -4
- package/dist/_node-chunks/chunk-SWVYWF43.js +0 -121
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
import CJS_COMPAT_NODE_URL_undhjn4yhve from 'node:url';
|
|
2
|
+
import CJS_COMPAT_NODE_PATH_undhjn4yhve from 'node:path';
|
|
3
|
+
import CJS_COMPAT_NODE_MODULE_undhjn4yhve from "node:module";
|
|
4
|
+
|
|
5
|
+
var __filename = CJS_COMPAT_NODE_URL_undhjn4yhve.fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = CJS_COMPAT_NODE_PATH_undhjn4yhve.dirname(__filename);
|
|
7
|
+
var require = CJS_COMPAT_NODE_MODULE_undhjn4yhve.createRequire(import.meta.url);
|
|
8
|
+
|
|
9
|
+
// ------------------------------------------------------------
|
|
10
|
+
// end of CJS compatibility banner, injected by Storybook's esbuild configuration
|
|
11
|
+
// ------------------------------------------------------------
|
|
12
|
+
var __create = Object.create;
|
|
13
|
+
var __defProp = Object.defineProperty;
|
|
14
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
15
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
16
|
+
var __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
17
|
+
var __commonJS = (cb, mod) => function() {
|
|
18
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
19
|
+
};
|
|
20
|
+
var __copyProps = (to, from, except, desc) => {
|
|
21
|
+
if (from && typeof from == "object" || typeof from == "function")
|
|
22
|
+
for (let key of __getOwnPropNames(from))
|
|
23
|
+
!__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
24
|
+
return to;
|
|
25
|
+
};
|
|
26
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
27
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
28
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
29
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
30
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
31
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
|
|
32
|
+
mod
|
|
33
|
+
));
|
|
34
|
+
|
|
35
|
+
// src/preset.ts
|
|
36
|
+
import { findConfigFile } from "storybook/internal/common";
|
|
37
|
+
|
|
38
|
+
// src/plugins/storybook-config-plugin.ts
|
|
39
|
+
import { isPreservingSymlinks } from "storybook/internal/common";
|
|
40
|
+
function storybookConfigPlugin(options) {
|
|
41
|
+
return [
|
|
42
|
+
{
|
|
43
|
+
name: "storybook:config-plugin",
|
|
44
|
+
enforce: "pre",
|
|
45
|
+
async config(config) {
|
|
46
|
+
let { defaultClientConditions = [] } = await import("vite"), existingEnvPrefix = config.envPrefix, mergedEnvPrefix = existingEnvPrefix ? Array.from(
|
|
47
|
+
/* @__PURE__ */ new Set([
|
|
48
|
+
...Array.isArray(existingEnvPrefix) ? existingEnvPrefix : [existingEnvPrefix],
|
|
49
|
+
"STORYBOOK_"
|
|
50
|
+
])
|
|
51
|
+
) : ["VITE_", "STORYBOOK_"];
|
|
52
|
+
return {
|
|
53
|
+
resolve: {
|
|
54
|
+
conditions: ["storybook", "stories", "test", ...defaultClientConditions],
|
|
55
|
+
preserveSymlinks: isPreservingSymlinks()
|
|
56
|
+
},
|
|
57
|
+
envPrefix: mergedEnvPrefix
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: "storybook:allow-storybook-dir",
|
|
63
|
+
enforce: "post",
|
|
64
|
+
config(config) {
|
|
65
|
+
config?.server?.fs?.allow && config.server.fs.allow.push(options.configDir);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// src/plugins/storybook-optimize-deps-plugin.ts
|
|
72
|
+
import { loadPreviewOrConfigFile } from "storybook/internal/common";
|
|
73
|
+
|
|
74
|
+
// ../../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
|
|
75
|
+
var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
|
|
76
|
+
function normalizeWindowsPath(input = "") {
|
|
77
|
+
return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
|
|
78
|
+
}
|
|
79
|
+
var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
|
|
80
|
+
var normalize = function(path2) {
|
|
81
|
+
if (path2.length === 0)
|
|
82
|
+
return ".";
|
|
83
|
+
path2 = normalizeWindowsPath(path2);
|
|
84
|
+
let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
|
|
85
|
+
return path2 = normalizeString(path2, !isPathAbsolute), path2.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path2 += "/"), _DRIVE_LETTER_RE.test(path2) && (path2 += "/"), isUNCPath ? isPathAbsolute ? `//${path2}` : `//./${path2}` : isPathAbsolute && !isAbsolute(path2) ? `/${path2}` : path2);
|
|
86
|
+
}, join = function(...arguments_) {
|
|
87
|
+
if (arguments_.length === 0)
|
|
88
|
+
return ".";
|
|
89
|
+
let joined;
|
|
90
|
+
for (let argument of arguments_)
|
|
91
|
+
argument && argument.length > 0 && (joined === void 0 ? joined = argument : joined += `/${argument}`);
|
|
92
|
+
return joined === void 0 ? "." : normalize(joined.replace(/\/\/+/g, "/"));
|
|
93
|
+
};
|
|
94
|
+
function cwd() {
|
|
95
|
+
return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
|
|
96
|
+
}
|
|
97
|
+
var resolve = function(...arguments_) {
|
|
98
|
+
arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
|
|
99
|
+
let resolvedPath = "", resolvedAbsolute = !1;
|
|
100
|
+
for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
|
|
101
|
+
let path2 = index >= 0 ? arguments_[index] : cwd();
|
|
102
|
+
!path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path2));
|
|
103
|
+
}
|
|
104
|
+
return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
|
|
105
|
+
};
|
|
106
|
+
function normalizeString(path2, allowAboveRoot) {
|
|
107
|
+
let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
|
|
108
|
+
for (let index = 0; index <= path2.length; ++index) {
|
|
109
|
+
if (index < path2.length)
|
|
110
|
+
char = path2[index];
|
|
111
|
+
else {
|
|
112
|
+
if (char === "/")
|
|
113
|
+
break;
|
|
114
|
+
char = "/";
|
|
115
|
+
}
|
|
116
|
+
if (char === "/") {
|
|
117
|
+
if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
|
|
118
|
+
if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
|
|
119
|
+
if (res.length > 2) {
|
|
120
|
+
let lastSlashIndex = res.lastIndexOf("/");
|
|
121
|
+
lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
|
|
122
|
+
continue;
|
|
123
|
+
} else if (res.length > 0) {
|
|
124
|
+
res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
|
|
129
|
+
} else
|
|
130
|
+
res.length > 0 ? res += `/${path2.slice(lastSlash + 1, index)}` : res = path2.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
|
|
131
|
+
lastSlash = index, dots = 0;
|
|
132
|
+
} else char === "." && dots !== -1 ? ++dots : dots = -1;
|
|
133
|
+
}
|
|
134
|
+
return res;
|
|
135
|
+
}
|
|
136
|
+
var isAbsolute = function(p) {
|
|
137
|
+
return _IS_ABSOLUTE_RE.test(p);
|
|
138
|
+
};
|
|
139
|
+
var relative = function(from, to) {
|
|
140
|
+
let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
|
|
141
|
+
if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
|
|
142
|
+
return _to.join("/");
|
|
143
|
+
let _fromCopy = [..._from];
|
|
144
|
+
for (let segment of _fromCopy) {
|
|
145
|
+
if (_to[0] !== segment)
|
|
146
|
+
break;
|
|
147
|
+
_from.shift(), _to.shift();
|
|
148
|
+
}
|
|
149
|
+
return [..._from.map(() => ".."), ..._to].join("/");
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// src/utils/process-preview-annotation.ts
|
|
153
|
+
function processPreviewAnnotation(path2, projectRoot) {
|
|
154
|
+
return typeof path2 == "object" ? path2.bare != null && path2.absolute === "" ? path2.bare : normalize(path2.absolute) : isAbsolute(path2) ? normalize(path2) : normalize(resolve(projectRoot, path2));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/utils/unique-import-paths.ts
|
|
158
|
+
function getUniqueImportPaths(index) {
|
|
159
|
+
return [...new Set(Object.values(index.entries).map((entry) => entry.importPath))];
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/plugins/storybook-optimize-deps-plugin.ts
|
|
163
|
+
function storybookOptimizeDepsPlugin(options) {
|
|
164
|
+
return {
|
|
165
|
+
name: "storybook:optimize-deps-plugin",
|
|
166
|
+
async config(config, { command }) {
|
|
167
|
+
if (command !== "serve")
|
|
168
|
+
return;
|
|
169
|
+
let projectRoot = resolve(options.configDir, ".."), [extraOptimizeDeps, storyIndexGenerator, previewAnnotations] = await Promise.all([
|
|
170
|
+
options.presets.apply("optimizeViteDeps", []),
|
|
171
|
+
options.presets.apply("storyIndexGenerator"),
|
|
172
|
+
options.presets.apply("previewAnnotations", [], options)
|
|
173
|
+
]), index = await storyIndexGenerator.getIndex(), previewOrConfigFile = loadPreviewOrConfigFile({ configDir: options.configDir }), previewAnnotationEntries = [...previewAnnotations, previewOrConfigFile].filter((path2) => path2 !== void 0).map((path2) => processPreviewAnnotation(path2, projectRoot));
|
|
174
|
+
return {
|
|
175
|
+
optimizeDeps: {
|
|
176
|
+
// Story files + preview annotation files as entry points for the dep optimizer.
|
|
177
|
+
// Vite will crawl these to discover all transitive CJS dependencies that need
|
|
178
|
+
// pre-bundling, removing the need for a hard-coded include list.
|
|
179
|
+
entries: [
|
|
180
|
+
...typeof config.optimizeDeps?.entries == "string" ? [config.optimizeDeps.entries] : config.optimizeDeps?.entries ?? [],
|
|
181
|
+
...getUniqueImportPaths(index),
|
|
182
|
+
...previewAnnotationEntries
|
|
183
|
+
],
|
|
184
|
+
// Extra deps explicitly included by Storybook presets (e.g. framework-specific packages).
|
|
185
|
+
include: [...extraOptimizeDeps, ...config.optimizeDeps?.include ?? []]
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/codegen-project-annotations.ts
|
|
193
|
+
import { getFrameworkName, loadPreviewOrConfigFile as loadPreviewOrConfigFile2 } from "storybook/internal/common";
|
|
194
|
+
import { isCsfFactoryPreview, readConfig } from "storybook/internal/csf-tools";
|
|
195
|
+
|
|
196
|
+
// ../../../node_modules/knitwork/dist/index.mjs
|
|
197
|
+
function genString(input, options = {}) {
|
|
198
|
+
let str = JSON.stringify(input);
|
|
199
|
+
return options.singleQuotes ? `'${escapeString(str).slice(1, -1)}'` : str;
|
|
200
|
+
}
|
|
201
|
+
var NEEDS_ESCAPE_RE = /[\n\r'\\\u2028\u2029]/, QUOTE_NEWLINE_RE = /([\n\r'\u2028\u2029])/g, BACKSLASH_RE = /\\/g;
|
|
202
|
+
function escapeString(id) {
|
|
203
|
+
return NEEDS_ESCAPE_RE.test(id) ? id.replace(BACKSLASH_RE, "\\\\").replace(QUOTE_NEWLINE_RE, "\\$1") : id;
|
|
204
|
+
}
|
|
205
|
+
function genSafeVariableName(name) {
|
|
206
|
+
return reservedNames.has(name) ? `_${name}` : name.replace(/^\d/, (r) => `_${r}`).replace(/\W/g, (r) => "_" + r.charCodeAt(0));
|
|
207
|
+
}
|
|
208
|
+
var reservedNames = /* @__PURE__ */ new Set([
|
|
209
|
+
"Infinity",
|
|
210
|
+
"NaN",
|
|
211
|
+
"arguments",
|
|
212
|
+
"await",
|
|
213
|
+
"break",
|
|
214
|
+
"case",
|
|
215
|
+
"catch",
|
|
216
|
+
"class",
|
|
217
|
+
"const",
|
|
218
|
+
"continue",
|
|
219
|
+
"debugger",
|
|
220
|
+
"default",
|
|
221
|
+
"delete",
|
|
222
|
+
"do",
|
|
223
|
+
"else",
|
|
224
|
+
"enum",
|
|
225
|
+
"eval",
|
|
226
|
+
"export",
|
|
227
|
+
"extends",
|
|
228
|
+
"false",
|
|
229
|
+
"finally",
|
|
230
|
+
"for",
|
|
231
|
+
"function",
|
|
232
|
+
"if",
|
|
233
|
+
"implements",
|
|
234
|
+
"import",
|
|
235
|
+
"in",
|
|
236
|
+
"instanceof",
|
|
237
|
+
"interface",
|
|
238
|
+
"let",
|
|
239
|
+
"new",
|
|
240
|
+
"null",
|
|
241
|
+
"package",
|
|
242
|
+
"private",
|
|
243
|
+
"protected",
|
|
244
|
+
"public",
|
|
245
|
+
"return",
|
|
246
|
+
"static",
|
|
247
|
+
"super",
|
|
248
|
+
"switch",
|
|
249
|
+
"this",
|
|
250
|
+
"throw",
|
|
251
|
+
"true",
|
|
252
|
+
"try",
|
|
253
|
+
"typeof",
|
|
254
|
+
"undefined",
|
|
255
|
+
"var",
|
|
256
|
+
"void",
|
|
257
|
+
"while",
|
|
258
|
+
"with",
|
|
259
|
+
"yield"
|
|
260
|
+
]), VALID_IDENTIFIER_RE = /^[$_]?([A-Z_a-z]\w*|\d)$/;
|
|
261
|
+
function _genStatement(type, specifier, names, options = {}) {
|
|
262
|
+
let specifierString = genString(specifier, options);
|
|
263
|
+
if (!names)
|
|
264
|
+
return `${type} ${specifierString};`;
|
|
265
|
+
let nameArray = Array.isArray(names), namesString = (nameArray ? names : [names]).map((index) => typeof index == "string" ? { name: index } : (index.name === index.as && (index = { name: index.name }), index)).map((index) => index.as ? `${index.name} as ${index.as}` : index.name).join(", ");
|
|
266
|
+
return nameArray ? `${type} { ${namesString} } from ${genString(
|
|
267
|
+
specifier,
|
|
268
|
+
options
|
|
269
|
+
)}${_genImportAttributes(type, options)};` : `${type} ${namesString} from ${genString(
|
|
270
|
+
specifier,
|
|
271
|
+
options
|
|
272
|
+
)}${_genImportAttributes(type, options)};`;
|
|
273
|
+
}
|
|
274
|
+
function _genImportAttributes(type, options) {
|
|
275
|
+
return type === "import type" || type === "export type" ? "" : typeof options.attributes?.type == "string" ? ` with { type: ${genString(options.attributes.type)} }` : typeof options.assert?.type == "string" ? ` assert { type: ${genString(options.assert.type)} }` : "";
|
|
276
|
+
}
|
|
277
|
+
function genImport(specifier, imports, options = {}) {
|
|
278
|
+
return _genStatement("import", specifier, imports, options);
|
|
279
|
+
}
|
|
280
|
+
function genDynamicImport(specifier, options = {}) {
|
|
281
|
+
let commentString = options.comment ? ` /* ${options.comment} */` : "", wrapperString = options.wrapper === !1 ? "" : "() => ", interopString = options.interopDefault ? ".then(m => m.default || m)" : "", optionsString = _genDynamicImportAttributes(options);
|
|
282
|
+
return `${wrapperString}import(${genString(
|
|
283
|
+
specifier,
|
|
284
|
+
options
|
|
285
|
+
)}${commentString}${optionsString})${interopString}`;
|
|
286
|
+
}
|
|
287
|
+
function _genDynamicImportAttributes(options = {}) {
|
|
288
|
+
return typeof options.assert?.type == "string" ? `, { assert: { type: ${genString(options.assert.type)} } }` : typeof options.attributes?.type == "string" ? `, { with: { type: ${genString(options.attributes.type)} } }` : "";
|
|
289
|
+
}
|
|
290
|
+
function wrapInDelimiters(lines, indent = "", delimiters = "{}", withComma = !0) {
|
|
291
|
+
if (lines.length === 0)
|
|
292
|
+
return delimiters;
|
|
293
|
+
let [start, end] = delimiters;
|
|
294
|
+
return `${start}
|
|
295
|
+
` + lines.join(withComma ? `,
|
|
296
|
+
` : `
|
|
297
|
+
`) + `
|
|
298
|
+
${indent}${end}`;
|
|
299
|
+
}
|
|
300
|
+
function genObjectKey(key) {
|
|
301
|
+
return VALID_IDENTIFIER_RE.test(key) ? key : genString(key);
|
|
302
|
+
}
|
|
303
|
+
function genObjectFromRaw(object, indent = "", options = {}) {
|
|
304
|
+
return genObjectFromRawEntries(Object.entries(object), indent, options);
|
|
305
|
+
}
|
|
306
|
+
function genArrayFromRaw(array, indent = "", options = {}) {
|
|
307
|
+
let newIdent = indent + " ";
|
|
308
|
+
return wrapInDelimiters(
|
|
309
|
+
array.map((index) => `${newIdent}${genRawValue(index, newIdent, options)}`),
|
|
310
|
+
indent,
|
|
311
|
+
"[]"
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
function genObjectFromRawEntries(array, indent = "", options = {}) {
|
|
315
|
+
let newIdent = indent + " ";
|
|
316
|
+
return wrapInDelimiters(
|
|
317
|
+
array.map(
|
|
318
|
+
([key, value]) => `${newIdent}${genObjectKey(key)}: ${genRawValue(value, newIdent, options)}`
|
|
319
|
+
),
|
|
320
|
+
indent,
|
|
321
|
+
"{}"
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
function genRawValue(value, indent = "", options = {}) {
|
|
325
|
+
return value === void 0 ? "undefined" : value === null ? "null" : Array.isArray(value) ? genArrayFromRaw(value, indent, options) : value && typeof value == "object" ? genObjectFromRaw(value, indent, options) : options.preserveTypes && typeof value != "function" ? JSON.stringify(value) : value.toString();
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ../../../node_modules/pathe/dist/utils.mjs
|
|
329
|
+
var normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
|
|
330
|
+
var FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/;
|
|
331
|
+
function filename(path2) {
|
|
332
|
+
return path2.match(FILENAME_RE)?.[2];
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// src/codegen-project-annotations.ts
|
|
336
|
+
import { dedent } from "ts-dedent";
|
|
337
|
+
async function generateProjectAnnotationsCode(options, projectRoot) {
|
|
338
|
+
let { presets, configDir } = options, frameworkName = await getFrameworkName(options), previewOrConfigFile = loadPreviewOrConfigFile2({ configDir }), previewConfig = previewOrConfigFile ? await readConfig(previewOrConfigFile) : void 0, isCsf4 = previewConfig ? isCsfFactoryPreview(previewConfig) : !1, previewAnnotations = await presets.apply(
|
|
339
|
+
"previewAnnotations",
|
|
340
|
+
[],
|
|
341
|
+
options
|
|
342
|
+
);
|
|
343
|
+
return generateProjectAnnotationsCodeFromPreviews({
|
|
344
|
+
previewAnnotations: [...previewAnnotations, previewOrConfigFile],
|
|
345
|
+
projectRoot,
|
|
346
|
+
frameworkName,
|
|
347
|
+
isCsf4
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function generateProjectAnnotationsCodeFromPreviews(options) {
|
|
351
|
+
let { projectRoot } = options, previewAnnotationURLs = options.previewAnnotations.filter((path2) => path2 !== void 0).map((path2) => processPreviewAnnotation(path2, projectRoot)), variables = [], imports = [];
|
|
352
|
+
for (let previewAnnotation of previewAnnotationURLs) {
|
|
353
|
+
let variable = genSafeVariableName(filename(previewAnnotation)).replace(/_(45|46|47)/g, "_") + "_" + hash(previewAnnotation);
|
|
354
|
+
variables.push(variable), imports.push(genImport(previewAnnotation, { name: "*", as: variable }));
|
|
355
|
+
}
|
|
356
|
+
let previewFileURL = previewAnnotationURLs[previewAnnotationURLs.length - 1], previewFileVariable = variables[variables.length - 1], previewFileImport = imports[imports.length - 1];
|
|
357
|
+
return options.isCsf4 ? dedent`
|
|
358
|
+
${previewFileImport}
|
|
359
|
+
|
|
360
|
+
export function getProjectAnnotations(hmrPreviewAnnotationModules = []) {
|
|
361
|
+
const preview = hmrPreviewAnnotationModules[0] ?? ${previewFileVariable};
|
|
362
|
+
return preview.default.composed;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
if (import.meta.hot) {
|
|
366
|
+
import.meta.hot.accept([${JSON.stringify(previewFileURL)}], (previewAnnotationModules) => {
|
|
367
|
+
// getProjectAnnotations has changed so we need to patch the new one in
|
|
368
|
+
window?.__STORYBOOK_PREVIEW__?.onGetProjectAnnotationsChanged({
|
|
369
|
+
getProjectAnnotations: () => getProjectAnnotations(previewAnnotationModules),
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
`.trim() : dedent`
|
|
374
|
+
import { composeConfigs } from 'storybook/preview-api';
|
|
375
|
+
|
|
376
|
+
${imports.join(`
|
|
377
|
+
`)}
|
|
378
|
+
|
|
379
|
+
export function getProjectAnnotations(hmrPreviewAnnotationModules = []) {
|
|
380
|
+
const configs = ${genArrayFromRaw(
|
|
381
|
+
variables.map(
|
|
382
|
+
(previewAnnotation, index) => (
|
|
383
|
+
// Prefer the updated module from an HMR update, otherwise the original module
|
|
384
|
+
`hmrPreviewAnnotationModules[${index}] ?? ${previewAnnotation}`
|
|
385
|
+
)
|
|
386
|
+
),
|
|
387
|
+
" "
|
|
388
|
+
)};
|
|
389
|
+
return composeConfigs(configs);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
if (import.meta.hot) {
|
|
393
|
+
import.meta.hot.accept(${JSON.stringify(previewAnnotationURLs)}, (previewAnnotationModules) => {
|
|
394
|
+
// getProjectAnnotations has changed so we need to patch the new one in
|
|
395
|
+
window?.__STORYBOOK_PREVIEW__?.onGetProjectAnnotationsChanged({
|
|
396
|
+
getProjectAnnotations: () => getProjectAnnotations(previewAnnotationModules),
|
|
397
|
+
});
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
`.trim();
|
|
401
|
+
}
|
|
402
|
+
function hash(value) {
|
|
403
|
+
return value.split("").reduce((acc, char) => acc + char.charCodeAt(0), 0);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// src/virtual-file-names.ts
|
|
407
|
+
var SB_VIRTUAL_FILES = {
|
|
408
|
+
VIRTUAL_APP_FILE: "virtual:/@storybook/builder-vite/vite-app.js",
|
|
409
|
+
VIRTUAL_STORIES_FILE: "virtual:/@storybook/builder-vite/storybook-stories.js",
|
|
410
|
+
VIRTUAL_ADDON_SETUP_FILE: "virtual:/@storybook/builder-vite/setup-addons.js"
|
|
411
|
+
}, SB_VIRTUAL_FILE_IDS = Object.values(SB_VIRTUAL_FILES);
|
|
412
|
+
function getResolvedVirtualModuleId(virtualModuleId) {
|
|
413
|
+
return `\0${virtualModuleId}`;
|
|
414
|
+
}
|
|
415
|
+
function getOriginalVirtualModuleId(resolvedVirtualModuleId) {
|
|
416
|
+
return resolvedVirtualModuleId.slice(1);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// src/plugins/storybook-project-annotations-plugin.ts
|
|
420
|
+
var VIRTUAL_ID = "virtual:/@storybook/builder-vite/project-annotations.js", RESOLVED_VIRTUAL_ID = getResolvedVirtualModuleId(VIRTUAL_ID);
|
|
421
|
+
function storybookProjectAnnotationsPlugin(options) {
|
|
422
|
+
let projectRoot;
|
|
423
|
+
return {
|
|
424
|
+
name: "storybook:project-annotations-plugin",
|
|
425
|
+
enforce: "pre",
|
|
426
|
+
configResolved(config) {
|
|
427
|
+
projectRoot = config.root;
|
|
428
|
+
},
|
|
429
|
+
resolveId(source) {
|
|
430
|
+
if (source === VIRTUAL_ID)
|
|
431
|
+
return RESOLVED_VIRTUAL_ID;
|
|
432
|
+
},
|
|
433
|
+
async load(id) {
|
|
434
|
+
if (id === RESOLVED_VIRTUAL_ID)
|
|
435
|
+
return generateProjectAnnotationsCode(options, projectRoot);
|
|
436
|
+
}
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// src/envs.ts
|
|
441
|
+
import { stringifyEnvs } from "storybook/internal/common";
|
|
442
|
+
var allowedEnvVariables = [
|
|
443
|
+
"STORYBOOK",
|
|
444
|
+
// Vite `import.meta.env` default variables
|
|
445
|
+
// @see https://github.com/vitejs/vite/blob/6b8d94dca2a1a8b4952e3e3fcd0aed1aedb94215/packages/vite/types/importMeta.d.ts#L68-L75
|
|
446
|
+
"BASE_URL",
|
|
447
|
+
"MODE",
|
|
448
|
+
"DEV",
|
|
449
|
+
"PROD",
|
|
450
|
+
"SSR"
|
|
451
|
+
];
|
|
452
|
+
function stringifyProcessEnvs(raw, envPrefix) {
|
|
453
|
+
let updatedRaw = {}, envs = Object.entries(raw).reduce((acc, [key, value]) => ((allowedEnvVariables.includes(key) || Array.isArray(envPrefix) && envPrefix.find((prefix) => key.startsWith(prefix)) || typeof envPrefix == "string" && key.startsWith(envPrefix)) && (acc[`import.meta.env.${key}`] = JSON.stringify(value), updatedRaw[key] = value), acc), {});
|
|
454
|
+
return envs["import.meta.env"] = JSON.stringify(stringifyEnvs(updatedRaw)), envs;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
// src/plugins/storybook-runtime-plugin.ts
|
|
458
|
+
async function storybookSanitizeEnvs(options) {
|
|
459
|
+
let plugins = [], envs = await options.presets.apply("env");
|
|
460
|
+
return envs && Object.keys(envs).length > 0 && plugins.push({
|
|
461
|
+
name: "storybook:env-plugin",
|
|
462
|
+
config(config) {
|
|
463
|
+
return {
|
|
464
|
+
define: stringifyProcessEnvs(envs, config.envPrefix)
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
}), plugins;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// src/plugins/vite-inject-mocker/plugin.ts
|
|
471
|
+
import { fileURLToPath } from "node:url";
|
|
472
|
+
var ENTRY_PATH = "/vite-inject-mocker-entry.js", viteInjectMockerRuntime = (options) => {
|
|
473
|
+
let mockerRuntimePath = fileURLToPath(
|
|
474
|
+
import.meta.resolve("storybook/internal/mocking-utils/mocker-runtime")
|
|
475
|
+
), viteConfig;
|
|
476
|
+
return {
|
|
477
|
+
name: "vite:storybook-inject-mocker-runtime",
|
|
478
|
+
enforce: "pre",
|
|
479
|
+
buildStart() {
|
|
480
|
+
viteConfig.command === "build" && this.emitFile({
|
|
481
|
+
type: "chunk",
|
|
482
|
+
id: mockerRuntimePath,
|
|
483
|
+
fileName: ENTRY_PATH.slice(1)
|
|
484
|
+
});
|
|
485
|
+
},
|
|
486
|
+
configResolved(config) {
|
|
487
|
+
viteConfig = config;
|
|
488
|
+
},
|
|
489
|
+
configureServer(server) {
|
|
490
|
+
options.previewConfigPath && server.watcher.on("change", (file) => {
|
|
491
|
+
file === options.previewConfigPath && server.ws.send({
|
|
492
|
+
type: "custom",
|
|
493
|
+
event: "invalidate-mocker"
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
},
|
|
497
|
+
resolveId(source) {
|
|
498
|
+
if (source === ENTRY_PATH)
|
|
499
|
+
return mockerRuntimePath;
|
|
500
|
+
},
|
|
501
|
+
transformIndexHtml(html) {
|
|
502
|
+
let headTag = html.match(/<head[^>]*>/);
|
|
503
|
+
if (headTag) {
|
|
504
|
+
let entryCode = `<script type="module" src="${viteConfig.command === "build" ? `.${ENTRY_PATH}` : ENTRY_PATH}"></script>`, headTagIndex = html.indexOf(headTag[0]);
|
|
505
|
+
return html.slice(0, headTagIndex + headTag[0].length) + entryCode + html.slice(headTagIndex + headTag[0].length);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
};
|
|
510
|
+
|
|
511
|
+
// src/plugins/vite-mock/plugin.ts
|
|
512
|
+
import { readFileSync } from "node:fs";
|
|
513
|
+
import {
|
|
514
|
+
babelParser,
|
|
515
|
+
extractMockCalls,
|
|
516
|
+
findMockRedirect,
|
|
517
|
+
getAutomockCode,
|
|
518
|
+
getRealPath,
|
|
519
|
+
rewriteSbMockImportCalls
|
|
520
|
+
} from "storybook/internal/mocking-utils";
|
|
521
|
+
import { logger } from "storybook/internal/node-logger";
|
|
522
|
+
|
|
523
|
+
// src/plugins/vite-mock/utils.ts
|
|
524
|
+
function getCleanId(id) {
|
|
525
|
+
return id.replace(/^.*\/deps\//, "").replace(/\.js.*$/, "").replace(/_/g, "/");
|
|
526
|
+
}
|
|
527
|
+
function invalidateAllRelatedModules(server, absPath, pkgName) {
|
|
528
|
+
for (let mod of server.moduleGraph.idToModuleMap.values())
|
|
529
|
+
(mod.id === absPath || mod.id && getCleanId(mod.id) === pkgName) && server.moduleGraph.invalidateModule(mod);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// src/plugins/vite-mock/plugin.ts
|
|
533
|
+
function viteMockPlugin(options) {
|
|
534
|
+
let viteConfig, mockCalls = [], normalizedPreviewConfigPath = normalize(options.previewConfigPath);
|
|
535
|
+
return [
|
|
536
|
+
{
|
|
537
|
+
name: "storybook:mock-loader",
|
|
538
|
+
configResolved(config) {
|
|
539
|
+
viteConfig = config;
|
|
540
|
+
},
|
|
541
|
+
buildStart() {
|
|
542
|
+
mockCalls = extractMockCalls(options, babelParser, viteConfig.root, findMockRedirect);
|
|
543
|
+
},
|
|
544
|
+
configureServer(server) {
|
|
545
|
+
async function invalidateAffectedFiles(file) {
|
|
546
|
+
if (file === options.previewConfigPath || file.includes("__mocks__")) {
|
|
547
|
+
let oldMockCalls = mockCalls;
|
|
548
|
+
mockCalls = extractMockCalls(options, babelParser, viteConfig.root, findMockRedirect);
|
|
549
|
+
let previewMod = server.moduleGraph.getModuleById(options.previewConfigPath);
|
|
550
|
+
previewMod && server.moduleGraph.invalidateModule(previewMod);
|
|
551
|
+
for (let call of mockCalls)
|
|
552
|
+
invalidateAllRelatedModules(server, call.absolutePath, call.path);
|
|
553
|
+
let newAbsPaths = new Set(mockCalls.map((c) => c.absolutePath));
|
|
554
|
+
for (let oldCall of oldMockCalls)
|
|
555
|
+
newAbsPaths.has(oldCall.absolutePath) || invalidateAllRelatedModules(server, oldCall.absolutePath, oldCall.path);
|
|
556
|
+
return server.ws.send({ type: "full-reload" }), [];
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
server.watcher.on("change", invalidateAffectedFiles), server.watcher.on("add", invalidateAffectedFiles), server.watcher.on("unlink", invalidateAffectedFiles);
|
|
560
|
+
},
|
|
561
|
+
load: {
|
|
562
|
+
order: "pre",
|
|
563
|
+
handler(id) {
|
|
564
|
+
let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), cleanId = getCleanId(idNorm);
|
|
565
|
+
for (let call of mockCalls)
|
|
566
|
+
if (!(getRealPath(call.absolutePath, preserveSymlinks) !== idNorm && call.path !== cleanId) && call.redirectPath)
|
|
567
|
+
return this.addWatchFile(call.redirectPath), readFileSync(call.redirectPath, "utf-8");
|
|
568
|
+
return null;
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
transform: {
|
|
572
|
+
order: "pre",
|
|
573
|
+
handler(code, id) {
|
|
574
|
+
for (let call of mockCalls) {
|
|
575
|
+
let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), callNorm = getRealPath(call.absolutePath, preserveSymlinks);
|
|
576
|
+
if (viteConfig.command !== "serve") {
|
|
577
|
+
if (callNorm !== idNorm)
|
|
578
|
+
continue;
|
|
579
|
+
} else {
|
|
580
|
+
let cleanId = getCleanId(idNorm);
|
|
581
|
+
if (call.path !== cleanId && callNorm !== idNorm)
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
if (!call.redirectPath) {
|
|
586
|
+
let automockedCode = getAutomockCode(code, call.spy, babelParser);
|
|
587
|
+
return {
|
|
588
|
+
code: automockedCode.toString(),
|
|
589
|
+
map: automockedCode.generateMap()
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
} catch (e) {
|
|
593
|
+
return logger.error(`Error automocking ${id}: ${e}`), null;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return null;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
},
|
|
600
|
+
{
|
|
601
|
+
name: "storybook:mock-loader-preview",
|
|
602
|
+
transform(code, id) {
|
|
603
|
+
if (id === normalizedPreviewConfigPath)
|
|
604
|
+
try {
|
|
605
|
+
return rewriteSbMockImportCalls(code);
|
|
606
|
+
} catch (e) {
|
|
607
|
+
return logger.debug(`Could not transform sb.mock(import(...)) calls in ${id}: ${e}`), null;
|
|
608
|
+
}
|
|
609
|
+
return null;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
];
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/preset.ts
|
|
616
|
+
var optimizeViteDeps = ["storybook/internal/preview/runtime"];
|
|
617
|
+
async function viteCorePlugins(_, options) {
|
|
618
|
+
let previewConfigPath = findConfigFile("preview", options.configDir);
|
|
619
|
+
return [
|
|
620
|
+
storybookProjectAnnotationsPlugin(options),
|
|
621
|
+
...storybookConfigPlugin({ configDir: options.configDir }),
|
|
622
|
+
storybookOptimizeDepsPlugin(options),
|
|
623
|
+
...await storybookSanitizeEnvs(options),
|
|
624
|
+
...previewConfigPath ? [
|
|
625
|
+
viteInjectMockerRuntime({ previewConfigPath }),
|
|
626
|
+
viteMockPlugin({
|
|
627
|
+
previewConfigPath,
|
|
628
|
+
coreOptions: await options.presets.apply("core"),
|
|
629
|
+
configDir: options.configDir
|
|
630
|
+
})
|
|
631
|
+
] : []
|
|
632
|
+
];
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
export {
|
|
636
|
+
__commonJS,
|
|
637
|
+
__toESM,
|
|
638
|
+
normalize,
|
|
639
|
+
join,
|
|
640
|
+
relative,
|
|
641
|
+
getUniqueImportPaths,
|
|
642
|
+
genDynamicImport,
|
|
643
|
+
genObjectFromRawEntries,
|
|
644
|
+
SB_VIRTUAL_FILES,
|
|
645
|
+
SB_VIRTUAL_FILE_IDS,
|
|
646
|
+
getResolvedVirtualModuleId,
|
|
647
|
+
getOriginalVirtualModuleId,
|
|
648
|
+
VIRTUAL_ID,
|
|
649
|
+
optimizeViteDeps,
|
|
650
|
+
viteCorePlugins
|
|
651
|
+
};
|