@storybook/builder-vite 10.1.0-alpha.12 → 10.1.0-alpha.14

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.
@@ -0,0 +1,113 @@
1
+ import CJS_COMPAT_NODE_URL_6a22v2i9lmi from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_6a22v2i9lmi from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_6a22v2i9lmi from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_6a22v2i9lmi.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_6a22v2i9lmi.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_6a22v2i9lmi.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
+ // ../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
36
+ var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
37
+ function normalizeWindowsPath(input = "") {
38
+ return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
39
+ }
40
+ var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
41
+ var normalize = function(path2) {
42
+ if (path2.length === 0)
43
+ return ".";
44
+ path2 = normalizeWindowsPath(path2);
45
+ let isUNCPath = path2.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path2), trailingSeparator = path2[path2.length - 1] === "/";
46
+ 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);
47
+ };
48
+ function cwd() {
49
+ return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
50
+ }
51
+ var resolve = function(...arguments_) {
52
+ arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
53
+ let resolvedPath = "", resolvedAbsolute = !1;
54
+ for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
55
+ let path2 = index >= 0 ? arguments_[index] : cwd();
56
+ !path2 || path2.length === 0 || (resolvedPath = `${path2}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path2));
57
+ }
58
+ return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
59
+ };
60
+ function normalizeString(path2, allowAboveRoot) {
61
+ let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
62
+ for (let index = 0; index <= path2.length; ++index) {
63
+ if (index < path2.length)
64
+ char = path2[index];
65
+ else {
66
+ if (char === "/")
67
+ break;
68
+ char = "/";
69
+ }
70
+ if (char === "/") {
71
+ if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
72
+ if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
73
+ if (res.length > 2) {
74
+ let lastSlashIndex = res.lastIndexOf("/");
75
+ lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
76
+ continue;
77
+ } else if (res.length > 0) {
78
+ res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
79
+ continue;
80
+ }
81
+ }
82
+ allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
83
+ } else
84
+ res.length > 0 ? res += `/${path2.slice(lastSlash + 1, index)}` : res = path2.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
85
+ lastSlash = index, dots = 0;
86
+ } else char === "." && dots !== -1 ? ++dots : dots = -1;
87
+ }
88
+ return res;
89
+ }
90
+ var isAbsolute = function(p) {
91
+ return _IS_ABSOLUTE_RE.test(p);
92
+ };
93
+ var relative = function(from, to) {
94
+ let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
95
+ if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
96
+ return _to.join("/");
97
+ let _fromCopy = [..._from];
98
+ for (let segment of _fromCopy) {
99
+ if (_to[0] !== segment)
100
+ break;
101
+ _from.shift(), _to.shift();
102
+ }
103
+ return [..._from.map(() => ".."), ..._to].join("/");
104
+ };
105
+
106
+ export {
107
+ __commonJS,
108
+ __toESM,
109
+ normalize,
110
+ resolve,
111
+ isAbsolute,
112
+ relative
113
+ };
package/dist/index.d.ts CHANGED
@@ -26,5 +26,6 @@ declare function hasVitePlugins(plugins: PluginOption[], names: string[]): Promi
26
26
  declare function bail(): Promise<void>;
27
27
  declare const start: ViteBuilder['start'];
28
28
  declare const build: ViteBuilder['build'];
29
+ declare const corePresets: string[];
29
30
 
30
- export { type BuilderOptions, type StorybookConfigVite, type ViteBuilder, type ViteFinal, bail, build, hasVitePlugins, start, withoutVitePlugins };
31
+ export { type BuilderOptions, type StorybookConfigVite, type ViteBuilder, type ViteFinal, bail, build, corePresets, hasVitePlugins, start, withoutVitePlugins };
package/dist/index.js CHANGED
@@ -1,36 +1,86 @@
1
- import CJS_COMPAT_NODE_URL_kokwc782jf9 from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_kokwc782jf9 from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_kokwc782jf9 from "node:module";
1
+ import CJS_COMPAT_NODE_URL_6a22v2i9lmi from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_6a22v2i9lmi from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_6a22v2i9lmi from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_kokwc782jf9.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_kokwc782jf9.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_kokwc782jf9.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_6a22v2i9lmi.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_6a22v2i9lmi.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_6a22v2i9lmi.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
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
- ));
12
+ import {
13
+ __commonJS,
14
+ __toESM,
15
+ isAbsolute,
16
+ normalize,
17
+ relative,
18
+ resolve
19
+ } from "./_node-chunks/chunk-PP77TN5J.js";
20
+
21
+ // ../../node_modules/picocolors/picocolors.js
22
+ var require_picocolors = __commonJS({
23
+ "../../node_modules/picocolors/picocolors.js"(exports, module) {
24
+ var p = process || {}, argv = p.argv || [], env2 = p.env || {}, isColorSupported = !(env2.NO_COLOR || argv.includes("--no-color")) && (!!env2.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env2.TERM !== "dumb" || !!env2.CI), formatter = (open, close, replace = open) => (input) => {
25
+ let string = "" + input, index = string.indexOf(close, open.length);
26
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
27
+ }, replaceClose = (string, close, replace, index) => {
28
+ let result = "", cursor = 0;
29
+ do
30
+ result += string.substring(cursor, index) + replace, cursor = index + close.length, index = string.indexOf(close, cursor);
31
+ while (~index);
32
+ return result + string.substring(cursor);
33
+ }, createColors = (enabled = isColorSupported) => {
34
+ let f = enabled ? formatter : () => String;
35
+ return {
36
+ isColorSupported: enabled,
37
+ reset: f("\x1B[0m", "\x1B[0m"),
38
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
39
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
40
+ italic: f("\x1B[3m", "\x1B[23m"),
41
+ underline: f("\x1B[4m", "\x1B[24m"),
42
+ inverse: f("\x1B[7m", "\x1B[27m"),
43
+ hidden: f("\x1B[8m", "\x1B[28m"),
44
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
45
+ black: f("\x1B[30m", "\x1B[39m"),
46
+ red: f("\x1B[31m", "\x1B[39m"),
47
+ green: f("\x1B[32m", "\x1B[39m"),
48
+ yellow: f("\x1B[33m", "\x1B[39m"),
49
+ blue: f("\x1B[34m", "\x1B[39m"),
50
+ magenta: f("\x1B[35m", "\x1B[39m"),
51
+ cyan: f("\x1B[36m", "\x1B[39m"),
52
+ white: f("\x1B[37m", "\x1B[39m"),
53
+ gray: f("\x1B[90m", "\x1B[39m"),
54
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
55
+ bgRed: f("\x1B[41m", "\x1B[49m"),
56
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
57
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
58
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
59
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
60
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
61
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
62
+ blackBright: f("\x1B[90m", "\x1B[39m"),
63
+ redBright: f("\x1B[91m", "\x1B[39m"),
64
+ greenBright: f("\x1B[92m", "\x1B[39m"),
65
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
66
+ blueBright: f("\x1B[94m", "\x1B[39m"),
67
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
68
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
69
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
70
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
71
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
72
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
73
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
74
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
75
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
76
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
77
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
78
+ };
79
+ };
80
+ module.exports = createColors();
81
+ module.exports.createColors = createColors;
82
+ }
83
+ });
34
84
 
35
85
  // ../../node_modules/balanced-match/index.js
36
86
  var require_balanced_match = __commonJS({
@@ -169,7 +219,7 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
169
219
  import { NoStatsForViteDevError } from "storybook/internal/server-errors";
170
220
 
171
221
  // src/build.ts
172
- import { logger } from "storybook/internal/node-logger";
222
+ import { logger as logger2 } from "storybook/internal/node-logger";
173
223
  import { dedent as dedent3 } from "ts-dedent";
174
224
 
175
225
  // src/envs.ts
@@ -203,6 +253,17 @@ async function sanitizeEnvVars(options, config) {
203
253
  };
204
254
  }
205
255
 
256
+ // src/logger.ts
257
+ var import_picocolors = __toESM(require_picocolors(), 1);
258
+ import { logger } from "storybook/internal/node-logger";
259
+ var seenWarnings = /* @__PURE__ */ new Set();
260
+ async function createViteLogger() {
261
+ let { createLogger } = await import("vite"), customViteLogger = createLogger(), logWithPrefix = (fn) => (msg) => fn(`${import_picocolors.default.bgYellow("Vite")} ${msg}`);
262
+ return customViteLogger.error = logWithPrefix(logger.error), customViteLogger.warn = logWithPrefix(logger.warn), customViteLogger.warnOnce = (msg) => {
263
+ seenWarnings.has(msg) || (seenWarnings.add(msg), logWithPrefix(logger.warn)(msg));
264
+ }, customViteLogger.info = logWithPrefix((msg) => logger.log(msg, { spacing: 0 })), customViteLogger;
265
+ }
266
+
206
267
  // src/utils/has-vite-plugins.ts
207
268
  function checkName(plugin, names) {
208
269
  return plugin !== null && typeof plugin == "object" && "name" in plugin && names.includes(plugin.name);
@@ -1103,77 +1164,6 @@ var hasOwnProperty = {}.hasOwnProperty;
1103
1164
  var RegExpPrototypeSymbolReplace = RegExp.prototype[Symbol.replace], own = {}.hasOwnProperty;
1104
1165
  var isWindows = process.platform === "win32", globalCache = globalThis.__EXSOLVE_CACHE__ ||= /* @__PURE__ */ new Map();
1105
1166
 
1106
- // ../../node_modules/pathe/dist/shared/pathe.ff20891b.mjs
1107
- var _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
1108
- function normalizeWindowsPath(input = "") {
1109
- return input && input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase());
1110
- }
1111
- var _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/;
1112
- var normalize = function(path3) {
1113
- if (path3.length === 0)
1114
- return ".";
1115
- path3 = normalizeWindowsPath(path3);
1116
- let isUNCPath = path3.match(_UNC_REGEX), isPathAbsolute = isAbsolute(path3), trailingSeparator = path3[path3.length - 1] === "/";
1117
- return path3 = normalizeString(path3, !isPathAbsolute), path3.length === 0 ? isPathAbsolute ? "/" : trailingSeparator ? "./" : "." : (trailingSeparator && (path3 += "/"), _DRIVE_LETTER_RE.test(path3) && (path3 += "/"), isUNCPath ? isPathAbsolute ? `//${path3}` : `//./${path3}` : isPathAbsolute && !isAbsolute(path3) ? `/${path3}` : path3);
1118
- };
1119
- function cwd() {
1120
- return typeof process < "u" && typeof process.cwd == "function" ? process.cwd().replace(/\\/g, "/") : "/";
1121
- }
1122
- var resolve = function(...arguments_) {
1123
- arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument));
1124
- let resolvedPath = "", resolvedAbsolute = !1;
1125
- for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) {
1126
- let path3 = index >= 0 ? arguments_[index] : cwd();
1127
- !path3 || path3.length === 0 || (resolvedPath = `${path3}/${resolvedPath}`, resolvedAbsolute = isAbsolute(path3));
1128
- }
1129
- return resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute), resolvedAbsolute && !isAbsolute(resolvedPath) ? `/${resolvedPath}` : resolvedPath.length > 0 ? resolvedPath : ".";
1130
- };
1131
- function normalizeString(path3, allowAboveRoot) {
1132
- let res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, char = null;
1133
- for (let index = 0; index <= path3.length; ++index) {
1134
- if (index < path3.length)
1135
- char = path3[index];
1136
- else {
1137
- if (char === "/")
1138
- break;
1139
- char = "/";
1140
- }
1141
- if (char === "/") {
1142
- if (!(lastSlash === index - 1 || dots === 1)) if (dots === 2) {
1143
- if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") {
1144
- if (res.length > 2) {
1145
- let lastSlashIndex = res.lastIndexOf("/");
1146
- lastSlashIndex === -1 ? (res = "", lastSegmentLength = 0) : (res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/")), lastSlash = index, dots = 0;
1147
- continue;
1148
- } else if (res.length > 0) {
1149
- res = "", lastSegmentLength = 0, lastSlash = index, dots = 0;
1150
- continue;
1151
- }
1152
- }
1153
- allowAboveRoot && (res += res.length > 0 ? "/.." : "..", lastSegmentLength = 2);
1154
- } else
1155
- res.length > 0 ? res += `/${path3.slice(lastSlash + 1, index)}` : res = path3.slice(lastSlash + 1, index), lastSegmentLength = index - lastSlash - 1;
1156
- lastSlash = index, dots = 0;
1157
- } else char === "." && dots !== -1 ? ++dots : dots = -1;
1158
- }
1159
- return res;
1160
- }
1161
- var isAbsolute = function(p) {
1162
- return _IS_ABSOLUTE_RE.test(p);
1163
- };
1164
- var relative = function(from, to) {
1165
- let _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"), _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/");
1166
- if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0])
1167
- return _to.join("/");
1168
- let _fromCopy = [..._from];
1169
- for (let segment of _fromCopy) {
1170
- if (_to[0] !== segment)
1171
- break;
1172
- _from.shift(), _to.shift();
1173
- }
1174
- return [..._from.map(() => ".."), ..._to].join("/");
1175
- };
1176
-
1177
1167
  // ../../core/src/shared/utils/module.ts
1178
1168
  var importMetaResolve = (...args) => typeof import.meta.resolve != "function" && process.env.VITEST === "true" ? (console.warn(
1179
1169
  "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"
@@ -1760,11 +1750,11 @@ var minimatch = (p, pattern, options = {}) => (assertValidPattern(pattern), !opt
1760
1750
  }, qmarksTestNoExtDot = ([$0]) => {
1761
1751
  let len = $0.length;
1762
1752
  return (f) => f.length === len && f !== "." && f !== "..";
1763
- }, defaultPlatform = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", path2 = {
1753
+ }, defaultPlatform = typeof process == "object" && process ? typeof process.env == "object" && process.env && process.env.__MINIMATCH_TESTING_PLATFORM__ || process.platform : "posix", path = {
1764
1754
  win32: { sep: "\\" },
1765
1755
  posix: { sep: "/" }
1766
- }, sep2 = defaultPlatform === "win32" ? path2.win32.sep : path2.posix.sep;
1767
- minimatch.sep = sep2;
1756
+ }, sep = defaultPlatform === "win32" ? path.win32.sep : path.posix.sep;
1757
+ minimatch.sep = sep;
1768
1758
  var GLOBSTAR = Symbol("globstar **");
1769
1759
  minimatch.GLOBSTAR = GLOBSTAR;
1770
1760
  var qmark2 = "[^/]", star2 = qmark2 + "*?", twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?", twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?", filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
@@ -3844,10 +3834,10 @@ var realpathSync = rps.native, defaultFS = {
3844
3834
  /**
3845
3835
  * Get the Path object referenced by the string path, resolved from this Path
3846
3836
  */
3847
- resolve(path3) {
3848
- if (!path3)
3837
+ resolve(path2) {
3838
+ if (!path2)
3849
3839
  return this;
3850
- let rootPath = this.getRootString(path3), dirParts = path3.substring(rootPath.length).split(this.splitSep);
3840
+ let rootPath = this.getRootString(path2), dirParts = path2.substring(rootPath.length).split(this.splitSep);
3851
3841
  return rootPath ? this.getRoot(rootPath).#resolveParts(dirParts) : this.#resolveParts(dirParts);
3852
3842
  }
3853
3843
  #resolveParts(dirParts) {
@@ -4438,8 +4428,8 @@ var realpathSync = rps.native, defaultFS = {
4438
4428
  /**
4439
4429
  * @internal
4440
4430
  */
4441
- getRootString(path3) {
4442
- return win32.parse(path3).root;
4431
+ getRootString(path2) {
4432
+ return win32.parse(path2).root;
4443
4433
  }
4444
4434
  /**
4445
4435
  * @internal
@@ -4479,8 +4469,8 @@ var realpathSync = rps.native, defaultFS = {
4479
4469
  /**
4480
4470
  * @internal
4481
4471
  */
4482
- getRootString(path3) {
4483
- return path3.startsWith("/") ? "/" : "";
4472
+ getRootString(path2) {
4473
+ return path2.startsWith("/") ? "/" : "";
4484
4474
  }
4485
4475
  /**
4486
4476
  * @internal
@@ -4528,11 +4518,11 @@ var realpathSync = rps.native, defaultFS = {
4528
4518
  *
4529
4519
  * @internal
4530
4520
  */
4531
- constructor(cwd2 = process.cwd(), pathImpl, sep3, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS } = {}) {
4532
- this.#fs = fsFromOption(fs), (cwd2 instanceof URL || cwd2.startsWith("file://")) && (cwd2 = fileURLToPath2(cwd2));
4533
- let cwdPath = pathImpl.resolve(cwd2);
4521
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs = defaultFS } = {}) {
4522
+ this.#fs = fsFromOption(fs), (cwd instanceof URL || cwd.startsWith("file://")) && (cwd = fileURLToPath2(cwd));
4523
+ let cwdPath = pathImpl.resolve(cwd);
4534
4524
  this.roots = /* @__PURE__ */ Object.create(null), this.rootPath = this.parseRootPath(cwdPath), this.#resolveCache = new ResolveCache(), this.#resolvePosixCache = new ResolveCache(), this.#children = new ChildrenCache(childrenCacheSize);
4535
- let split = cwdPath.substring(this.rootPath.length).split(sep3);
4525
+ let split = cwdPath.substring(this.rootPath.length).split(sep2);
4536
4526
  if (split.length === 1 && !split[0] && split.pop(), nocase === void 0)
4537
4527
  throw new TypeError("must provide nocase setting to PathScurryBase ctor");
4538
4528
  this.nocase = nocase, this.root = this.newRoot(this.#fs), this.roots[this.rootPath] = this.root;
@@ -4550,8 +4540,8 @@ var realpathSync = rps.native, defaultFS = {
4550
4540
  /**
4551
4541
  * Get the depth of a provided path, string, or the cwd
4552
4542
  */
4553
- depth(path3 = this.cwd) {
4554
- return typeof path3 == "string" && (path3 = this.cwd.resolve(path3)), path3.depth();
4543
+ depth(path2 = this.cwd) {
4544
+ return typeof path2 == "string" && (path2 = this.cwd.resolve(path2)), path2.depth();
4555
4545
  }
4556
4546
  /**
4557
4547
  * Return the cache of child entries. Exposed so subclasses can create
@@ -4861,18 +4851,18 @@ var realpathSync = rps.native, defaultFS = {
4861
4851
  };
4862
4852
  return process2(), results;
4863
4853
  }
4864
- chdir(path3 = this.cwd) {
4854
+ chdir(path2 = this.cwd) {
4865
4855
  let oldCwd = this.cwd;
4866
- this.cwd = typeof path3 == "string" ? this.cwd.resolve(path3) : path3, this.cwd[setAsCwd](oldCwd);
4856
+ this.cwd = typeof path2 == "string" ? this.cwd.resolve(path2) : path2, this.cwd[setAsCwd](oldCwd);
4867
4857
  }
4868
4858
  }, PathScurryWin32 = class extends PathScurryBase {
4869
4859
  /**
4870
4860
  * separator for generating path strings
4871
4861
  */
4872
4862
  sep = "\\";
4873
- constructor(cwd2 = process.cwd(), opts = {}) {
4863
+ constructor(cwd = process.cwd(), opts = {}) {
4874
4864
  let { nocase = !0 } = opts;
4875
- super(cwd2, win32, "\\", { ...opts, nocase }), this.nocase = nocase;
4865
+ super(cwd, win32, "\\", { ...opts, nocase }), this.nocase = nocase;
4876
4866
  for (let p = this.cwd; p; p = p.parent)
4877
4867
  p.nocase = this.nocase;
4878
4868
  }
@@ -4899,9 +4889,9 @@ var realpathSync = rps.native, defaultFS = {
4899
4889
  * separator for generating path strings
4900
4890
  */
4901
4891
  sep = "/";
4902
- constructor(cwd2 = process.cwd(), opts = {}) {
4892
+ constructor(cwd = process.cwd(), opts = {}) {
4903
4893
  let { nocase = !1 } = opts;
4904
- super(cwd2, posix, "/", { ...opts, nocase }), this.nocase = nocase;
4894
+ super(cwd, posix, "/", { ...opts, nocase }), this.nocase = nocase;
4905
4895
  }
4906
4896
  /**
4907
4897
  * @internal
@@ -4922,9 +4912,9 @@ var realpathSync = rps.native, defaultFS = {
4922
4912
  return p.startsWith("/");
4923
4913
  }
4924
4914
  }, PathScurryDarwin = class extends PathScurryPosix {
4925
- constructor(cwd2 = process.cwd(), opts = {}) {
4915
+ constructor(cwd = process.cwd(), opts = {}) {
4926
4916
  let { nocase = !0 } = opts;
4927
- super(cwd2, { ...opts, nocase });
4917
+ super(cwd, { ...opts, nocase });
4928
4918
  }
4929
4919
  }, Path = process.platform === "win32" ? PathWin32 : PathPosix, PathScurry = process.platform === "win32" ? PathScurryWin32 : process.platform === "darwin" ? PathScurryDarwin : PathScurryPosix;
4930
4920
 
@@ -5138,8 +5128,8 @@ var HasWalkedCache = class _HasWalkedCache {
5138
5128
  }
5139
5129
  // match, absolute, ifdir
5140
5130
  entries() {
5141
- return [...this.store.entries()].map(([path3, n2]) => [
5142
- path3,
5131
+ return [...this.store.entries()].map(([path2, n2]) => [
5132
+ path2,
5143
5133
  !!(n2 & 2),
5144
5134
  !!(n2 & 1)
5145
5135
  ]);
@@ -5271,8 +5261,8 @@ var makeIgnore = (ignore, opts) => typeof ignore == "string" ? new Ignore([ignor
5271
5261
  signal;
5272
5262
  maxDepth;
5273
5263
  includeChildMatches;
5274
- constructor(patterns, path3, opts) {
5275
- if (this.patterns = patterns, this.path = path3, this.opts = opts, this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/", this.includeChildMatches = opts.includeChildMatches !== !1, (opts.ignore || !this.includeChildMatches) && (this.#ignore = makeIgnore(opts.ignore ?? [], opts), !this.includeChildMatches && typeof this.#ignore.add != "function")) {
5264
+ constructor(patterns, path2, opts) {
5265
+ if (this.patterns = patterns, this.path = path2, this.opts = opts, this.#sep = !opts.posix && opts.platform === "win32" ? "\\" : "/", this.includeChildMatches = opts.includeChildMatches !== !1, (opts.ignore || !this.includeChildMatches) && (this.#ignore = makeIgnore(opts.ignore ?? [], opts), !this.includeChildMatches && typeof this.#ignore.add != "function")) {
5276
5266
  let m = "cannot ignore child matches, ignore lacks add() method.";
5277
5267
  throw new Error(m);
5278
5268
  }
@@ -5280,11 +5270,11 @@ var makeIgnore = (ignore, opts) => typeof ignore == "string" ? new Ignore([ignor
5280
5270
  this.#onResume.length = 0;
5281
5271
  }));
5282
5272
  }
5283
- #ignored(path3) {
5284
- return this.seen.has(path3) || !!this.#ignore?.ignored?.(path3);
5273
+ #ignored(path2) {
5274
+ return this.seen.has(path2) || !!this.#ignore?.ignored?.(path2);
5285
5275
  }
5286
- #childrenIgnored(path3) {
5287
- return !!this.#ignore?.childrenIgnored?.(path3);
5276
+ #childrenIgnored(path2) {
5277
+ return !!this.#ignore?.childrenIgnored?.(path2);
5288
5278
  }
5289
5279
  // backpressure mechanism
5290
5280
  pause() {
@@ -5440,8 +5430,8 @@ var makeIgnore = (ignore, opts) => typeof ignore == "string" ? new Ignore([ignor
5440
5430
  }
5441
5431
  }, GlobWalker = class extends GlobUtil {
5442
5432
  matches = /* @__PURE__ */ new Set();
5443
- constructor(patterns, path3, opts) {
5444
- super(patterns, path3, opts);
5433
+ constructor(patterns, path2, opts) {
5434
+ super(patterns, path2, opts);
5445
5435
  }
5446
5436
  matchEmit(e) {
5447
5437
  this.matches.add(e);
@@ -5465,8 +5455,8 @@ var makeIgnore = (ignore, opts) => typeof ignore == "string" ? new Ignore([ignor
5465
5455
  }
5466
5456
  }, GlobStream = class extends GlobUtil {
5467
5457
  results;
5468
- constructor(patterns, path3, opts) {
5469
- super(patterns, path3, opts), this.results = new Minipass({
5458
+ constructor(patterns, path2, opts) {
5459
+ super(patterns, path2, opts), this.results = new Minipass({
5470
5460
  signal: this.signal,
5471
5461
  objectMode: !0
5472
5462
  }), this.results.on("drain", () => this.resume()), this.results.on("resume", () => this.resume());
@@ -5691,8 +5681,8 @@ var streamSync = globStreamSync, stream = Object.assign(globStream, { sync: glob
5691
5681
  glob.glob = glob;
5692
5682
 
5693
5683
  // ../../node_modules/slash/index.js
5694
- function slash(path3) {
5695
- return path3.startsWith("\\\\?\\") ? path3 : path3.replace(/\\/g, "/");
5684
+ function slash(path2) {
5685
+ return path2.startsWith("\\\\?\\") ? path2 : path2.replace(/\\/g, "/");
5696
5686
  }
5697
5687
 
5698
5688
  // src/list-stories.ts
@@ -5742,16 +5732,16 @@ import { isCsfFactoryPreview, readConfig } from "storybook/internal/csf-tools";
5742
5732
  // ../../node_modules/pathe/dist/utils.mjs
5743
5733
  var normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
5744
5734
  var FILENAME_RE = /(^|[/\\])([^/\\]+?)(?=(\.[^.]+)?$)/;
5745
- function filename(path3) {
5746
- return path3.match(FILENAME_RE)?.[2];
5735
+ function filename(path2) {
5736
+ return path2.match(FILENAME_RE)?.[2];
5747
5737
  }
5748
5738
 
5749
5739
  // src/codegen-modern-iframe-script.ts
5750
5740
  import { dedent as dedent2 } from "ts-dedent";
5751
5741
 
5752
5742
  // src/utils/process-preview-annotation.ts
5753
- function processPreviewAnnotation(path3, projectRoot) {
5754
- return typeof path3 == "object" ? path3.bare != null && path3.absolute === "" ? path3.bare : normalize(path3.absolute) : isAbsolute(path3) ? normalize(path3) : normalize(resolve(projectRoot, path3));
5743
+ function processPreviewAnnotation(path2, projectRoot) {
5744
+ return typeof path2 == "object" ? path2.bare != null && path2.absolute === "" ? path2.bare : normalize(path2.absolute) : isAbsolute(path2) ? normalize(path2) : normalize(resolve(projectRoot, path2));
5755
5745
  }
5756
5746
 
5757
5747
  // src/virtual-file-names.ts
@@ -5783,7 +5773,7 @@ async function generateModernIframeScriptCode(options, projectRoot) {
5783
5773
  });
5784
5774
  }
5785
5775
  async function generateModernIframeScriptCodeFromPreviews(options) {
5786
- let { projectRoot, frameworkName } = options, previewAnnotationURLs = options.previewAnnotations.filter((path3) => path3 !== void 0).map((path3) => processPreviewAnnotation(path3, projectRoot)), variables = [], imports = [];
5776
+ let { projectRoot, frameworkName } = options, previewAnnotationURLs = options.previewAnnotations.filter((path2) => path2 !== void 0).map((path2) => processPreviewAnnotation(path2, projectRoot)), variables = [], imports = [];
5787
5777
  for (let previewAnnotation of previewAnnotationURLs) {
5788
5778
  let variable = genSafeVariableName(filename(previewAnnotation)).replace(/_(45|46|47)/g, "_") + "_" + hash(previewAnnotation);
5789
5779
  variables.push(variable), imports.push(genImport(previewAnnotation, { name: "*", as: variable }));
@@ -5906,8 +5896,8 @@ function codeGeneratorPlugin(options) {
5906
5896
  getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE)
5907
5897
  );
5908
5898
  storiesModule && server2.moduleGraph.invalidateModule(storiesModule);
5909
- }), server2.watcher.on("add", (path3) => {
5910
- (/\.stories\.([tj])sx?$/.test(path3) || /\.mdx$/.test(path3)) && server2.watcher.emit(
5899
+ }), server2.watcher.on("add", (path2) => {
5900
+ (/\.stories\.([tj])sx?$/.test(path2) || /\.mdx$/.test(path2)) && server2.watcher.emit(
5911
5901
  "change",
5912
5902
  getResolvedVirtualModuleId(SB_VIRTUAL_FILES.VIRTUAL_STORIES_FILE)
5913
5903
  );
@@ -5979,15 +5969,15 @@ import { existsSync as existsSync2, mkdirSync } from "node:fs";
5979
5969
 
5980
5970
  // ../../node_modules/empathic/access.mjs
5981
5971
  import { accessSync, constants } from "node:fs";
5982
- function ok(path3, mode) {
5972
+ function ok(path2, mode) {
5983
5973
  try {
5984
- return accessSync(path3, mode), !0;
5974
+ return accessSync(path2, mode), !0;
5985
5975
  } catch {
5986
5976
  return !1;
5987
5977
  }
5988
5978
  }
5989
- function writable(path3) {
5990
- return ok(path3, constants.W_OK);
5979
+ function writable(path2) {
5980
+ return ok(path2, constants.W_OK);
5991
5981
  }
5992
5982
 
5993
5983
  // ../../node_modules/empathic/find.mjs
@@ -6005,7 +5995,7 @@ function absolute(input, root) {
6005
5995
 
6006
5996
  // ../../node_modules/empathic/walk.mjs
6007
5997
  function up(base, options) {
6008
- let { last, cwd: cwd2 } = options || {}, tmp = absolute(base, cwd2), root = absolute(last || "/", cwd2), prev, arr = [];
5998
+ let { last, cwd } = options || {}, tmp = absolute(base, cwd), root = absolute(last || "/", cwd), prev, arr = [];
6009
5999
  for (; prev !== root && (arr.push(tmp), tmp = dirname2(prev = tmp), tmp !== prev); )
6010
6000
  ;
6011
6001
  return arr;
@@ -6078,8 +6068,8 @@ async function externalGlobalsPlugin(externals) {
6078
6068
  if (globalsList.every((glob2) => !code.includes(glob2)))
6079
6069
  return;
6080
6070
  let [imports] = parse(code), src = new MagicString(code);
6081
- return imports.forEach(({ n: path3, ss: startPosition, se: endPosition }) => {
6082
- let packageName = path3;
6071
+ return imports.forEach(({ n: path2, ss: startPosition, se: endPosition }) => {
6072
+ let packageName = path2;
6083
6073
  if (packageName && globalsList.includes(packageName)) {
6084
6074
  let importStatement = src.slice(startPosition, endPosition), transformedImport = rewriteImport(importStatement, externals, packageName);
6085
6075
  src.update(startPosition, endPosition, transformedImport);
@@ -6242,17 +6232,17 @@ async function build(options) {
6242
6232
  })
6243
6233
  });
6244
6234
  let turbosnapPluginName = "rollup-plugin-turbosnap";
6245
- return finalConfig.plugins && await hasVitePlugins(finalConfig.plugins, [turbosnapPluginName]) && (logger.warn(dedent3`Found '${turbosnapPluginName}' which is now included by default in Storybook 8.
6235
+ return finalConfig.plugins && await hasVitePlugins(finalConfig.plugins, [turbosnapPluginName]) && (logger2.warn(dedent3`Found '${turbosnapPluginName}' which is now included by default in Storybook 8.
6246
6236
  Removing from your plugins list. Ensure you pass \`--stats-json\` to generate stats.
6247
6237
 
6248
- For more information, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#turbosnap-vite-plugin-is-no-longer-needed`), finalConfig.plugins = await withoutVitePlugins(finalConfig.plugins, [turbosnapPluginName])), await viteBuild(await sanitizeEnvVars(options, finalConfig)), findPlugin(
6238
+ For more information, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#turbosnap-vite-plugin-is-no-longer-needed`), finalConfig.plugins = await withoutVitePlugins(finalConfig.plugins, [turbosnapPluginName])), finalConfig.customLogger ??= await createViteLogger(), await viteBuild(await sanitizeEnvVars(options, finalConfig)), findPlugin(
6249
6239
  finalConfig,
6250
6240
  "storybook:rollup-plugin-webpack-stats"
6251
6241
  )?.storybookGetStats();
6252
6242
  }
6253
6243
 
6254
6244
  // src/vite-server.ts
6255
- import { logger as logger2 } from "storybook/internal/node-logger";
6245
+ import { logger as logger3 } from "storybook/internal/node-logger";
6256
6246
  import { dedent as dedent4 } from "ts-dedent";
6257
6247
 
6258
6248
  // src/optimizeDeps.ts
@@ -6409,7 +6399,7 @@ async function createViteServer(options, devServer) {
6409
6399
  appType: "custom",
6410
6400
  optimizeDeps: await getOptimizeDeps(commonCfg, options)
6411
6401
  };
6412
- options.host === "0.0.0.0" && !config.server.allowedHosts && (config.server.allowedHosts = !0, logger2.warn(dedent4`'host' is set to '0.0.0.0' but 'allowedHosts' is not defined.
6402
+ options.host === "0.0.0.0" && !config.server.allowedHosts && (config.server.allowedHosts = !0, logger3.warn(dedent4`'host' is set to '0.0.0.0' but 'allowedHosts' is not defined.
6413
6403
  Defaulting 'allowedHosts' to true, which permits all hostnames.
6414
6404
  To restrict allowed hostnames, add the following to your 'viteFinal' config:
6415
6405
  Example: { server: { allowedHosts: ['mydomain.com'] } }
@@ -6418,7 +6408,7 @@ async function createViteServer(options, devServer) {
6418
6408
  - https://storybook.js.org/docs/api/main-config/main-config-vite-final
6419
6409
  `));
6420
6410
  let finalConfig = await presets.apply("viteFinal", config, options), { createServer } = await import("vite");
6421
- return createServer(await sanitizeEnvVars(options, finalConfig));
6411
+ return finalConfig.customLogger ??= await createViteLogger(), createServer(await sanitizeEnvVars(options, finalConfig));
6422
6412
  }
6423
6413
 
6424
6414
  // src/index.ts
@@ -6450,10 +6440,11 @@ var start = async ({
6450
6440
  }
6451
6441
  },
6452
6442
  totalTime: process.hrtime(startTime)
6453
- }), build2 = async ({ options }) => build(options);
6443
+ }), build2 = async ({ options }) => build(options), corePresets = [import.meta.resolve("./preset.js")];
6454
6444
  export {
6455
6445
  bail,
6456
6446
  build2 as build,
6447
+ corePresets,
6457
6448
  hasVitePlugins,
6458
6449
  start,
6459
6450
  withoutVitePlugins
package/dist/preset.js ADDED
@@ -0,0 +1,228 @@
1
+ import CJS_COMPAT_NODE_URL_6a22v2i9lmi from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_6a22v2i9lmi from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_6a22v2i9lmi from "node:module";
4
+
5
+ var __filename = CJS_COMPAT_NODE_URL_6a22v2i9lmi.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_6a22v2i9lmi.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_6a22v2i9lmi.createRequire(import.meta.url);
8
+
9
+ // ------------------------------------------------------------
10
+ // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
+ // ------------------------------------------------------------
12
+ import {
13
+ normalize
14
+ } from "./_node-chunks/chunk-PP77TN5J.js";
15
+
16
+ // src/preset.ts
17
+ import { findConfigFile } from "storybook/internal/common";
18
+
19
+ // src/plugins/vite-inject-mocker/plugin.ts
20
+ import { readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+ import { resolvePackageDir } from "storybook/internal/common";
24
+
25
+ // ../../node_modules/@rolldown/pluginutils/dist/index.js
26
+ function exactRegex(str, flags) {
27
+ return new RegExp(`^${escapeRegex(str)}$`, flags);
28
+ }
29
+ var escapeRegexRE = /[-/\\^$*+?.()|[\]{}]/g;
30
+ function escapeRegex(str) {
31
+ return str.replace(escapeRegexRE, "\\$&");
32
+ }
33
+
34
+ // src/plugins/vite-inject-mocker/plugin.ts
35
+ import { dedent } from "ts-dedent";
36
+ var entryPath = "/vite-inject-mocker-entry.js", entryCode = dedent`
37
+ <script type="module" src=".${entryPath}"></script>
38
+ `, server, viteInjectMockerRuntime = (options) => {
39
+ let viteConfig;
40
+ return {
41
+ name: "vite:storybook-inject-mocker-runtime",
42
+ buildStart() {
43
+ viteConfig.command === "build" && this.emitFile({
44
+ type: "chunk",
45
+ id: join(
46
+ resolvePackageDir("storybook"),
47
+ "assets",
48
+ "server",
49
+ "mocker-runtime.template.js"
50
+ ),
51
+ fileName: entryPath.slice(1)
52
+ });
53
+ },
54
+ config() {
55
+ return {
56
+ optimizeDeps: {
57
+ include: ["@vitest/mocker", "@vitest/mocker/browser"]
58
+ },
59
+ resolve: {
60
+ // Aliasing necessary for package managers like pnpm, since resolving modules from a virtual module
61
+ // leads to errors, if the imported module is not a dependency of the project.
62
+ // By resolving the module to the real path, we can avoid this issue.
63
+ alias: {
64
+ "@vitest/mocker/browser": fileURLToPath(import.meta.resolve("@vitest/mocker/browser")),
65
+ "@vitest/mocker": fileURLToPath(import.meta.resolve("@vitest/mocker"))
66
+ }
67
+ }
68
+ };
69
+ },
70
+ configResolved(config) {
71
+ viteConfig = config;
72
+ },
73
+ configureServer(server_) {
74
+ server = server_, options.previewConfigPath && server.watcher.on("change", (file) => {
75
+ file === options.previewConfigPath && server.ws.send({
76
+ type: "custom",
77
+ event: "invalidate-mocker"
78
+ });
79
+ });
80
+ },
81
+ resolveId: {
82
+ filter: {
83
+ id: [exactRegex(entryPath)]
84
+ },
85
+ handler(id) {
86
+ return exactRegex(id).test(entryPath) ? id : null;
87
+ }
88
+ },
89
+ async load(id) {
90
+ return exactRegex(id).test(entryPath) ? readFileSync(
91
+ join(resolvePackageDir("storybook"), "assets", "server", "mocker-runtime.template.js"),
92
+ "utf-8"
93
+ ) : null;
94
+ },
95
+ transformIndexHtml(html) {
96
+ let headTag = html.match(/<head[^>]*>/);
97
+ if (headTag) {
98
+ let headTagIndex = html.indexOf(headTag[0]);
99
+ return html.slice(0, headTagIndex + headTag[0].length) + entryCode + html.slice(headTagIndex + headTag[0].length);
100
+ }
101
+ }
102
+ };
103
+ };
104
+
105
+ // src/plugins/vite-mock/plugin.ts
106
+ import { readFileSync as readFileSync2 } from "node:fs";
107
+ import {
108
+ babelParser,
109
+ extractMockCalls,
110
+ getAutomockCode,
111
+ getRealPath,
112
+ rewriteSbMockImportCalls
113
+ } from "storybook/internal/mocking-utils";
114
+ import { logger } from "storybook/internal/node-logger";
115
+ import { findMockRedirect } from "@vitest/mocker/redirect";
116
+
117
+ // src/plugins/vite-mock/utils.ts
118
+ function getCleanId(id) {
119
+ return id.replace(/^.*\/deps\//, "").replace(/\.js.*$/, "").replace(/_/g, "/");
120
+ }
121
+ function invalidateAllRelatedModules(server2, absPath, pkgName) {
122
+ for (let mod of server2.moduleGraph.idToModuleMap.values())
123
+ (mod.id === absPath || mod.id && getCleanId(mod.id) === pkgName) && server2.moduleGraph.invalidateModule(mod);
124
+ }
125
+
126
+ // src/plugins/vite-mock/plugin.ts
127
+ function viteMockPlugin(options) {
128
+ let viteConfig, mockCalls = [], normalizedPreviewConfigPath = normalize(options.previewConfigPath);
129
+ return [
130
+ {
131
+ name: "storybook:mock-loader",
132
+ configResolved(config) {
133
+ viteConfig = config;
134
+ },
135
+ buildStart() {
136
+ mockCalls = extractMockCalls(options, babelParser, viteConfig.root, findMockRedirect);
137
+ },
138
+ configureServer(server2) {
139
+ async function invalidateAffectedFiles(file) {
140
+ if (file === options.previewConfigPath || file.includes("__mocks__")) {
141
+ let oldMockCalls = mockCalls;
142
+ mockCalls = extractMockCalls(options, babelParser, viteConfig.root, findMockRedirect);
143
+ let previewMod = server2.moduleGraph.getModuleById(options.previewConfigPath);
144
+ previewMod && server2.moduleGraph.invalidateModule(previewMod);
145
+ for (let call of mockCalls)
146
+ invalidateAllRelatedModules(server2, call.absolutePath, call.path);
147
+ let newAbsPaths = new Set(mockCalls.map((c) => c.absolutePath));
148
+ for (let oldCall of oldMockCalls)
149
+ newAbsPaths.has(oldCall.absolutePath) || invalidateAllRelatedModules(server2, oldCall.absolutePath, oldCall.path);
150
+ return server2.ws.send({ type: "full-reload" }), [];
151
+ }
152
+ }
153
+ server2.watcher.on("change", invalidateAffectedFiles), server2.watcher.on("add", invalidateAffectedFiles), server2.watcher.on("unlink", invalidateAffectedFiles);
154
+ },
155
+ load: {
156
+ order: "pre",
157
+ handler(id) {
158
+ let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), cleanId = getCleanId(idNorm);
159
+ for (let call of mockCalls)
160
+ if (!(getRealPath(call.absolutePath, preserveSymlinks) !== idNorm && call.path !== cleanId) && call.redirectPath)
161
+ return this.addWatchFile(call.redirectPath), readFileSync2(call.redirectPath, "utf-8");
162
+ return null;
163
+ }
164
+ },
165
+ transform: {
166
+ order: "pre",
167
+ handler(code, id) {
168
+ for (let call of mockCalls) {
169
+ let preserveSymlinks = viteConfig.resolve.preserveSymlinks, idNorm = getRealPath(id, preserveSymlinks), callNorm = getRealPath(call.absolutePath, preserveSymlinks);
170
+ if (viteConfig.command !== "serve") {
171
+ if (callNorm !== idNorm)
172
+ continue;
173
+ } else {
174
+ let cleanId = getCleanId(idNorm);
175
+ if (call.path !== cleanId && callNorm !== idNorm)
176
+ continue;
177
+ }
178
+ try {
179
+ if (!call.redirectPath) {
180
+ let automockedCode = getAutomockCode(code, call.spy, babelParser);
181
+ return {
182
+ code: automockedCode.toString(),
183
+ map: automockedCode.generateMap()
184
+ };
185
+ }
186
+ } catch (e) {
187
+ return logger.error(`Error automocking ${id}: ${e}`), null;
188
+ }
189
+ }
190
+ return null;
191
+ }
192
+ }
193
+ },
194
+ {
195
+ name: "storybook:mock-loader-preview",
196
+ transform(code, id) {
197
+ if (id === normalizedPreviewConfigPath)
198
+ try {
199
+ return rewriteSbMockImportCalls(code);
200
+ } catch (e) {
201
+ return logger.debug(`Could not transform sb.mock(import(...)) calls in ${id}: ${e}`), null;
202
+ }
203
+ return null;
204
+ }
205
+ }
206
+ ];
207
+ }
208
+
209
+ // src/preset.ts
210
+ async function viteFinal(existing, options) {
211
+ let previewConfigPath = findConfigFile("preview", options.configDir);
212
+ if (!previewConfigPath)
213
+ return existing;
214
+ let coreOptions = await options.presets.apply("core");
215
+ return {
216
+ ...existing,
217
+ plugins: [
218
+ ...existing.plugins ?? [],
219
+ ...previewConfigPath ? [
220
+ viteInjectMockerRuntime({ previewConfigPath }),
221
+ viteMockPlugin({ previewConfigPath, coreOptions, configDir: options.configDir })
222
+ ] : []
223
+ ]
224
+ };
225
+ }
226
+ export {
227
+ viteFinal
228
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@storybook/builder-vite",
3
- "version": "10.1.0-alpha.12",
3
+ "version": "10.1.0-alpha.14",
4
4
  "description": "A Storybook builder to dev and build with Vite",
5
5
  "keywords": [
6
6
  "storybook",
@@ -33,7 +33,8 @@
33
33
  "default": "./dist/index.js"
34
34
  },
35
35
  "./input/iframe.html": "./input/iframe.html",
36
- "./package.json": "./package.json"
36
+ "./package.json": "./package.json",
37
+ "./preset": "./dist/preset.js"
37
38
  },
38
39
  "files": [
39
40
  "dist/**/*",
@@ -41,6 +42,7 @@
41
42
  "README.md",
42
43
  "*.js",
43
44
  "*.d.ts",
45
+ "preset.js",
44
46
  "!src/**/*"
45
47
  ],
46
48
  "scripts": {
@@ -48,7 +50,8 @@
48
50
  "prep": "jiti ../../../scripts/build/build-package.ts"
49
51
  },
50
52
  "dependencies": {
51
- "@storybook/csf-plugin": "10.1.0-alpha.12",
53
+ "@storybook/csf-plugin": "10.1.0-alpha.14",
54
+ "@vitest/mocker": "3.2.4",
52
55
  "ts-dedent": "^2.0.0"
53
56
  },
54
57
  "devDependencies": {
@@ -63,7 +66,7 @@
63
66
  "vite": "^7.0.4"
64
67
  },
65
68
  "peerDependencies": {
66
- "storybook": "^10.1.0-alpha.12",
69
+ "storybook": "^10.1.0-alpha.14",
67
70
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0"
68
71
  },
69
72
  "publishConfig": {
package/preset.js ADDED
@@ -0,0 +1 @@
1
+ export * from './dist/preset.js';