vite-plugin-storybook-nextjs 0.0.13--canary.8.d70ae00.0 → 0.0.13--canary.8.c64d6ac.0

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.
Files changed (44) hide show
  1. package/dist/index.cjs +934 -0
  2. package/dist/index.d.cts +12 -0
  3. package/dist/index.js +61 -90
  4. package/dist/mocks/storybook.global.cjs +69 -0
  5. package/dist/mocks/storybook.global.d.cts +2 -0
  6. package/dist/mocks/storybook.global.js +40 -17
  7. package/dist/plugins/next-image/alias/image-context.cjs +8 -0
  8. package/dist/plugins/next-image/alias/image-context.d.cts +13 -0
  9. package/dist/plugins/next-image/alias/image-default-loader.cjs +40 -0
  10. package/dist/plugins/next-image/alias/image-default-loader.d.cts +5 -0
  11. package/dist/plugins/next-image/alias/next-image.cjs +53 -0
  12. package/dist/plugins/next-image/alias/next-image.d.cts +30 -0
  13. package/dist/plugins/next-image/alias/next-image.d.ts +1 -1
  14. package/dist/plugins/next-image/alias/next-legacy-image.cjs +27 -0
  15. package/dist/plugins/next-image/alias/next-legacy-image.d.cts +6 -0
  16. package/dist/plugins/next-mocks/alias/cache/index.d.ts +16 -0
  17. package/dist/plugins/next-mocks/alias/cache/index.js +18 -0
  18. package/dist/plugins/next-mocks/alias/headers/cookies.d.ts +14 -0
  19. package/dist/plugins/next-mocks/alias/headers/cookies.js +72 -0
  20. package/dist/plugins/next-mocks/alias/headers/headers.d.ts +21 -0
  21. package/dist/plugins/next-mocks/alias/headers/headers.js +38 -0
  22. package/dist/plugins/next-mocks/alias/headers/index.d.ts +11 -0
  23. package/dist/plugins/next-mocks/alias/headers/index.js +70 -0
  24. package/dist/plugins/next-mocks/alias/navigation/index.d.ts +38 -0
  25. package/dist/plugins/next-mocks/alias/navigation/index.js +74 -0
  26. package/dist/plugins/next-mocks/alias/router/index.d.ts +45 -0
  27. package/dist/plugins/next-mocks/alias/router/index.js +108 -0
  28. package/dist/plugins/next-mocks/alias/rsc/server-only.d.ts +3 -0
  29. package/dist/plugins/next-mocks/alias/rsc/server-only.js +4 -0
  30. package/package.json +21 -17
  31. /package/dist/{cache → plugins/next-mocks/alias/cache}/index.cjs +0 -0
  32. /package/dist/{cache → plugins/next-mocks/alias/cache}/index.d.cts +0 -0
  33. /package/dist/{headers → plugins/next-mocks/alias/headers}/cookies.cjs +0 -0
  34. /package/dist/{headers → plugins/next-mocks/alias/headers}/cookies.d.cts +0 -0
  35. /package/dist/{headers → plugins/next-mocks/alias/headers}/headers.cjs +0 -0
  36. /package/dist/{headers → plugins/next-mocks/alias/headers}/headers.d.cts +0 -0
  37. /package/dist/{headers → plugins/next-mocks/alias/headers}/index.cjs +0 -0
  38. /package/dist/{headers → plugins/next-mocks/alias/headers}/index.d.cts +0 -0
  39. /package/dist/{navigation → plugins/next-mocks/alias/navigation}/index.cjs +0 -0
  40. /package/dist/{navigation → plugins/next-mocks/alias/navigation}/index.d.cts +0 -0
  41. /package/dist/{router → plugins/next-mocks/alias/router}/index.cjs +0 -0
  42. /package/dist/{router → plugins/next-mocks/alias/router}/index.d.cts +0 -0
  43. /package/dist/{rsc → plugins/next-mocks/alias/rsc}/server-only.cjs +0 -0
  44. /package/dist/{rsc → plugins/next-mocks/alias/rsc}/server-only.d.cts +0 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,934 @@
1
+ 'use strict';
2
+
3
+ var path = require('path');
4
+ var module$1 = require('module');
5
+ var defineEnvPlugin_js = require('next/dist/build/webpack/plugins/define-env-plugin.js');
6
+ var fs3 = require('fs');
7
+ var env = require('@next/env');
8
+ var Log = require('next/dist/build/output/log.js');
9
+ var index_js = require('next/dist/build/swc/index.js');
10
+ var constants_js = require('next/dist/shared/lib/constants.js');
11
+ var fs2 = require('fs/promises');
12
+ var fetchCssFromGoogleFonts_js = require('next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts.js');
13
+ var getFontAxes_js = require('next/dist/compiled/@next/font/dist/google/get-font-axes.js');
14
+ var getGoogleFontsUrl_js = require('next/dist/compiled/@next/font/dist/google/get-google-fonts-url.js');
15
+ var validateGoogleFontFunctionCall_js = require('next/dist/compiled/@next/font/dist/google/validate-google-font-function-call.js');
16
+ var loaderUtils = require('next/dist/compiled/loader-utils3/index.js');
17
+ var validateLocalFontFunctionCall_js = require('next/dist/compiled/@next/font/dist/local/validate-local-font-function-call.js');
18
+ var tsDedent = require('ts-dedent');
19
+ var loadJsConfig = require('next/dist/build/load-jsconfig.js');
20
+ var findPagesDir_js = require('next/dist/lib/find-pages-dir.js');
21
+ var utils_js = require('next/dist/build/utils.js');
22
+ var options_js = require('next/dist/build/swc/options.js');
23
+ var loadConfig = require('next/dist/server/config.js');
24
+ var os = require('os');
25
+ var querystring = require('querystring');
26
+ var imageSizeOf = require('image-size');
27
+
28
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
29
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
30
+
31
+ var path__default = /*#__PURE__*/_interopDefault(path);
32
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
33
+ var Log__default = /*#__PURE__*/_interopDefault(Log);
34
+ var fs2__default = /*#__PURE__*/_interopDefault(fs2);
35
+ var loaderUtils__default = /*#__PURE__*/_interopDefault(loaderUtils);
36
+ var loadJsConfig__default = /*#__PURE__*/_interopDefault(loadJsConfig);
37
+ var loadConfig__default = /*#__PURE__*/_interopDefault(loadConfig);
38
+ var imageSizeOf__default = /*#__PURE__*/_interopDefault(imageSizeOf);
39
+
40
+ // src/index.ts
41
+ var nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
42
+ async function loadEnvironmentConfig(dir, dev) {
43
+ return env.loadEnvConfig(dir, dev, Log__default.default);
44
+ }
45
+ async function loadSWCBindingsEagerly(nextConfig) {
46
+ await index_js.loadBindings(nextConfig?.experimental?.useWasmBinary);
47
+ if (index_js.lockfilePatchPromise.cur) {
48
+ await index_js.lockfilePatchPromise.cur;
49
+ }
50
+ }
51
+ function shouldOutputCommonJs(filename) {
52
+ return filename.endsWith(".cjs") || nextDistPath.test(filename);
53
+ }
54
+ async function loadClosestPackageJson(dir, attempts = 1) {
55
+ if (attempts > 5) {
56
+ throw new Error("Can't resolve main package.json file");
57
+ }
58
+ const mainPath = attempts === 1 ? ["."] : new Array(attempts).fill("..");
59
+ try {
60
+ const file = await fs3__default.default.promises.readFile(
61
+ path.join(dir, ...mainPath, "package.json"),
62
+ "utf8"
63
+ );
64
+ return JSON.parse(file);
65
+ } catch (e) {
66
+ return loadClosestPackageJson(dir, attempts + 1);
67
+ }
68
+ }
69
+
70
+ // src/plugins/next-env/plugin.ts
71
+ function vitePluginNextEnv(rootDir, nextConfigResolver) {
72
+ let envConfig;
73
+ let isDev;
74
+ const resolvedDir = path.resolve(rootDir);
75
+ return {
76
+ name: "vite-plugin-storybook-nextjs-env",
77
+ enforce: "pre",
78
+ async config(config, env) {
79
+ isDev = env.mode !== "production";
80
+ envConfig = (await loadEnvironmentConfig(resolvedDir, isDev)).combinedEnv;
81
+ const nextConfig = await nextConfigResolver.promise;
82
+ const publicNextEnvMap = Object.fromEntries(
83
+ Object.entries(envConfig).filter(([key]) => key.startsWith("NEXT_PUBLIC_")).map(([key, value]) => {
84
+ return [`process.env.${key}`, JSON.stringify(value)];
85
+ })
86
+ );
87
+ const finalConfig = {
88
+ ...config.define,
89
+ ...publicNextEnvMap,
90
+ ...defineEnvPlugin_js.getDefineEnv({
91
+ isTurbopack: false,
92
+ config: nextConfig,
93
+ isClient: true,
94
+ isEdgeServer: false,
95
+ isNodeOrEdgeCompilation: false,
96
+ isNodeServer: false,
97
+ clientRouterFilters: void 0,
98
+ dev: isDev,
99
+ middlewareMatchers: void 0,
100
+ hasRewrites: false,
101
+ distDir: nextConfig.distDir,
102
+ fetchCacheKeyPrefix: nextConfig?.experimental?.fetchCacheKeyPrefix
103
+ })
104
+ };
105
+ delete process.env.__NEXT_IMAGE_OPTS;
106
+ delete finalConfig["process.env.__NEXT_IMAGE_OPTS"];
107
+ return {
108
+ define: finalConfig,
109
+ test: {
110
+ deps: {
111
+ optimizer: {
112
+ ssr: {
113
+ include: ["next"]
114
+ }
115
+ }
116
+ }
117
+ }
118
+ };
119
+ }
120
+ };
121
+ }
122
+ var cssCache = /* @__PURE__ */ new Map();
123
+ async function getFontFaceDeclarations(options) {
124
+ const {
125
+ fontFamily,
126
+ weights,
127
+ styles,
128
+ selectedVariableAxes,
129
+ display,
130
+ variable
131
+ } = validateGoogleFontFunctionCall_js.validateGoogleFontFunctionCall(options.fontFamily, options.props);
132
+ const fontAxes = getFontAxes_js.getFontAxes(
133
+ fontFamily,
134
+ weights,
135
+ styles,
136
+ selectedVariableAxes
137
+ );
138
+ const url = getGoogleFontsUrl_js.getGoogleFontsUrl(fontFamily, fontAxes, display);
139
+ try {
140
+ const hasCachedCSS = cssCache.has(url);
141
+ const fontFaceCSS = hasCachedCSS ? cssCache.get(url) : await fetchCssFromGoogleFonts_js.fetchCSSFromGoogleFonts(url, fontFamily, true).catch(() => null);
142
+ if (!hasCachedCSS) {
143
+ cssCache.set(url, fontFaceCSS);
144
+ } else {
145
+ cssCache.delete(url);
146
+ }
147
+ if (fontFaceCSS === null) {
148
+ throw new Error(
149
+ `Failed to fetch \`${fontFamily}\` from Google Fonts with URL: \`${url}\``
150
+ );
151
+ }
152
+ return {
153
+ id: loaderUtils__default.default.getHashDigest(url, "md5", "hex", 6),
154
+ fontFamily,
155
+ fontFaceCSS,
156
+ weights,
157
+ styles,
158
+ variable
159
+ };
160
+ } catch (error) {
161
+ throw new Error(
162
+ `Failed to fetch \`${fontFamily}\` from Google Fonts with URL: \`${url}\``
163
+ );
164
+ }
165
+ }
166
+ var getPlaceholderFontUrl = (refId) => `__%%import.meta.ROLLUP_FILE_URL_${refId}%%__`;
167
+ getPlaceholderFontUrl.regexp = /__%%import\.meta\.ROLLUP_FILE_URL_(.*?)%%__/g;
168
+ async function getFontFaceDeclarations2(options) {
169
+ const localFontSrc = options.props.metaSrc;
170
+ const {
171
+ weight,
172
+ style,
173
+ variable,
174
+ declarations = []
175
+ } = validateLocalFontFunctionCall_js.validateLocalFontFunctionCall("", options.props);
176
+ const id = `font-${loaderUtils__default.default.getHashDigest(
177
+ Buffer.from(JSON.stringify(localFontSrc)),
178
+ "md5",
179
+ "hex",
180
+ 6
181
+ )}`;
182
+ const fontDeclarations = declarations.map(
183
+ ({ prop, value }) => `${prop}: ${value};`
184
+ ).join("\n");
185
+ const getFontFaceCSS = () => {
186
+ if (localFontSrc) {
187
+ if ("fontReferenceId" in localFontSrc) {
188
+ return tsDedent.dedent`@font-face {
189
+ font-family: ${id};
190
+ src: url(${localFontSrc.fontReferenceId ? getPlaceholderFontUrl(localFontSrc.fontReferenceId) : `/@fs${localFontSrc.fontPath}`})
191
+ ${fontDeclarations}
192
+ }`;
193
+ }
194
+ return localFontSrc.map((font) => {
195
+ return tsDedent.dedent`@font-face {
196
+ font-family: ${id};
197
+ src: url(${font.path.fontReferenceId ? getPlaceholderFontUrl(font.path.fontReferenceId) : `/@fs${font.path.fontPath}`});
198
+ ${font.weight ? `font-weight: ${font.weight};` : ""}
199
+ ${font.style ? `font-style: ${font.style};` : ""}
200
+ ${fontDeclarations}
201
+ }`;
202
+ }).join("");
203
+ }
204
+ return "";
205
+ };
206
+ return {
207
+ id,
208
+ fontFamily: id,
209
+ fontFaceCSS: getFontFaceCSS(),
210
+ weights: weight ? [weight] : [],
211
+ styles: style ? [style] : [],
212
+ variable
213
+ };
214
+ }
215
+
216
+ // src/plugins/next-font/utils/get-css-meta.ts
217
+ function getCSSMeta(options) {
218
+ const className = getClassName(options);
219
+ const style = getStylesObj(options);
220
+ const variableClassName = `__variable_${className}`;
221
+ const classNamesCSS = `
222
+ .${className} {
223
+ font-family: ${options.fontFamily};
224
+ ${isNextCSSPropertyValid(options.styles) ? `font-style: ${options.styles[0]};` : ""}
225
+ ${isNextCSSPropertyValid(options.weights) ? `font-weight: ${options.weights[0]};` : ""}
226
+ }
227
+
228
+ ${options.variable ? `.${variableClassName} { ${options.variable}: '${options.fontFamily}'; }` : ""}
229
+ `;
230
+ const fontFaceCSS = `${changeFontDisplayToSwap(options.fontFaceCSS)}`;
231
+ return {
232
+ className,
233
+ fontFaceCSS,
234
+ classNamesCSS,
235
+ style,
236
+ ...options.variable ? { variableClassName } : {}
237
+ };
238
+ }
239
+ function getClassName({ styles, weights, fontFamily }) {
240
+ const font = fontFamily.replaceAll(" ", "-").toLowerCase();
241
+ const style = isNextCSSPropertyValid(styles) ? styles[0] : null;
242
+ const weight = isNextCSSPropertyValid(weights) ? weights[0] : null;
243
+ return `${font}${style ? `-${style}` : ""}${weight ? `-${weight}` : ""}`;
244
+ }
245
+ function getStylesObj({ styles, weights, fontFamily }) {
246
+ return {
247
+ fontFamily,
248
+ ...isNextCSSPropertyValid(styles) ? { fontStyle: styles[0] } : {},
249
+ ...isNextCSSPropertyValid(weights) ? { fontWeight: weights[0] } : {}
250
+ };
251
+ }
252
+ function isNextCSSPropertyValid(prop) {
253
+ return prop.length === 1 && prop[0] !== "variable";
254
+ }
255
+ function changeFontDisplayToSwap(css) {
256
+ return css.replaceAll("font-display: optional;", "font-display: block;");
257
+ }
258
+ function setFontDeclarationsInHead({
259
+ id,
260
+ fontFaceCSS,
261
+ classNamesCSS
262
+ }) {
263
+ const regex = new RegExp(getPlaceholderFontUrl.regexp);
264
+ const fontPaths = fontFaceCSS.matchAll(regex);
265
+ const fontPathsImportUrls = [];
266
+ if (fontPaths) {
267
+ for (const match of fontFaceCSS.matchAll(regex)) {
268
+ fontPathsImportUrls.push({
269
+ id: match[1],
270
+ path: match[0].replaceAll(/__%%|%%__/g, "")
271
+ });
272
+ }
273
+ }
274
+ return tsDedent.dedent`
275
+ const fontPaths = [${fontPathsImportUrls.map((fontPath) => `{id: '${fontPath.id}', path: ${fontPath.path}}`).join(", ")}];
276
+ if (!document.getElementById('id-${id}')) {
277
+ let fontDeclarations = \`${fontFaceCSS}\`;
278
+ fontPaths.forEach((fontPath, i) => {
279
+ fontDeclarations = fontDeclarations.replace('__%%import.meta.ROLLUP_FILE_URL_' + fontPath.id + '%%__', fontPath.path.toString());
280
+ });
281
+ const style = document.createElement('style');
282
+ style.setAttribute('id', 'font-face-${id}');
283
+ style.innerHTML = fontDeclarations;
284
+ document.head.appendChild(style);
285
+
286
+ const classNamesCSS = \`${classNamesCSS}\`;
287
+ const classNamesStyle = document.createElement('style');
288
+ classNamesStyle.setAttribute('id', 'classnames-${id}');
289
+ classNamesStyle.innerHTML = classNamesCSS;
290
+ document.head.appendChild(classNamesStyle);
291
+ }
292
+ `;
293
+ }
294
+
295
+ // src/plugins/next-font/plugin.ts
296
+ var includePattern = /next(\\|\/|\\\\).*(\\|\/|\\\\)target\.css.*$/;
297
+ var virtualModuleId = "virtual:next-font";
298
+ function vitePluginNextFont() {
299
+ let devMode = true;
300
+ return {
301
+ name: "vite-plugin-storybook-nextjs-font",
302
+ enforce: "pre",
303
+ async config(config, env) {
304
+ devMode = env.mode !== "production";
305
+ return config;
306
+ },
307
+ async resolveId(source, importer) {
308
+ const cwd = process.cwd();
309
+ if (!includePattern.test(source) || !importer) {
310
+ return null;
311
+ }
312
+ const [sourceWithoutQuery, rawQuery] = source.split("?");
313
+ const queryParams = JSON.parse(rawQuery);
314
+ const fontOptions = {
315
+ filename: queryParams.path ?? "",
316
+ fontFamily: queryParams.import ?? "",
317
+ props: queryParams.arguments?.[0] ?? {},
318
+ source: importer
319
+ };
320
+ if (fontOptions.source.endsWith("html")) {
321
+ return null;
322
+ }
323
+ let fontFaceDeclaration;
324
+ const pathSep = path__default.default.sep;
325
+ if (sourceWithoutQuery.endsWith(
326
+ ["next", "font", "google", "target.css"].join(pathSep)
327
+ )) {
328
+ fontFaceDeclaration = await getFontFaceDeclarations(fontOptions);
329
+ }
330
+ if (sourceWithoutQuery.endsWith(
331
+ ["next", "font", "local", "target.css"].join(pathSep)
332
+ )) {
333
+ const importerDirPath = path__default.default.dirname(fontOptions.filename);
334
+ const emitFont = async (importerRelativeFontPath) => {
335
+ const fontExtension = path__default.default.extname(importerRelativeFontPath);
336
+ const fontBaseName = path__default.default.basename(
337
+ importerRelativeFontPath,
338
+ fontExtension
339
+ );
340
+ const fontPath = path__default.default.join(importerDirPath, importerRelativeFontPath);
341
+ if (devMode) {
342
+ return {
343
+ fontPath: path__default.default.join(cwd, fontPath),
344
+ fontReferenceId: void 0
345
+ };
346
+ }
347
+ try {
348
+ const fontData = await fs2__default.default.readFile(fontPath);
349
+ const fontReferenceId = this.emitFile({
350
+ name: `${fontBaseName}${fontExtension}`,
351
+ type: "asset",
352
+ source: fontData
353
+ });
354
+ return { fontReferenceId, fontPath };
355
+ } catch (err) {
356
+ console.error(`Could not read font file ${fontPath}:`, err);
357
+ return void 0;
358
+ }
359
+ };
360
+ const loaderOptions = {
361
+ ...fontOptions
362
+ };
363
+ if (loaderOptions) {
364
+ if (typeof fontOptions.props.src === "string") {
365
+ const font = await emitFont(fontOptions.props.src);
366
+ loaderOptions.props.metaSrc = font;
367
+ } else {
368
+ loaderOptions.props.metaSrc = (await Promise.all(
369
+ (fontOptions.props.src ?? []).map(async (fontSrc) => {
370
+ const font = await emitFont(fontSrc.path);
371
+ if (!font) {
372
+ return void 0;
373
+ }
374
+ return {
375
+ ...fontSrc,
376
+ path: font
377
+ };
378
+ })
379
+ )).filter((font) => font !== void 0);
380
+ }
381
+ }
382
+ fontFaceDeclaration = await getFontFaceDeclarations2(loaderOptions);
383
+ }
384
+ return {
385
+ id: `${virtualModuleId}?${rawQuery}`,
386
+ meta: {
387
+ fontFaceDeclaration
388
+ }
389
+ };
390
+ },
391
+ load(id) {
392
+ const [source] = id.split("?");
393
+ if (source !== virtualModuleId) {
394
+ return void 0;
395
+ }
396
+ const moduleInfo = this.getModuleInfo(id);
397
+ const fontFaceDeclaration = moduleInfo?.meta?.fontFaceDeclaration;
398
+ if (typeof fontFaceDeclaration !== "undefined") {
399
+ const cssMeta = getCSSMeta(fontFaceDeclaration);
400
+ return `
401
+ ${setFontDeclarationsInHead({
402
+ fontFaceCSS: cssMeta.fontFaceCSS,
403
+ id: fontFaceDeclaration.id,
404
+ classNamesCSS: cssMeta.classNamesCSS
405
+ })}
406
+
407
+ export default {
408
+ className: "${cssMeta.className}",
409
+ style: ${JSON.stringify(cssMeta.style)}
410
+ ${cssMeta.variableClassName ? `, variable: "${cssMeta.variableClassName}"` : ""}
411
+ }
412
+ `;
413
+ }
414
+ return "export default {}";
415
+ }
416
+ };
417
+ }
418
+
419
+ // src/utils/swc/styles.ts
420
+ function getStyledComponentsOptions(styledComponentsConfig, development) {
421
+ if (!styledComponentsConfig) {
422
+ return null;
423
+ }
424
+ if (typeof styledComponentsConfig === "object") {
425
+ return {
426
+ ...styledComponentsConfig,
427
+ displayName: styledComponentsConfig.displayName ?? Boolean(development)
428
+ };
429
+ }
430
+ return {
431
+ displayName: Boolean(development)
432
+ };
433
+ }
434
+ function getEmotionOptions(emotionConfig, development) {
435
+ if (!emotionConfig) {
436
+ return null;
437
+ }
438
+ let autoLabel = !!development;
439
+ switch (typeof emotionConfig === "object" && emotionConfig.autoLabel) {
440
+ case "never":
441
+ autoLabel = false;
442
+ break;
443
+ case "always":
444
+ autoLabel = true;
445
+ break;
446
+ }
447
+ return {
448
+ enabled: true,
449
+ autoLabel,
450
+ sourcemap: development,
451
+ ...typeof emotionConfig === "object" && {
452
+ importMap: emotionConfig.importMap,
453
+ labelFormat: emotionConfig.labelFormat,
454
+ sourcemap: development && emotionConfig.sourceMap
455
+ }
456
+ };
457
+ }
458
+
459
+ // src/utils/swc/options.ts
460
+ var require2 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)));
461
+ var regeneratorRuntimePath = require2.resolve(
462
+ "next/dist/compiled/regenerator-runtime"
463
+ );
464
+ function getBaseSWCOptions({
465
+ filename,
466
+ development,
467
+ hasReactRefresh,
468
+ globalWindow,
469
+ esm,
470
+ modularizeImports,
471
+ swcPlugins,
472
+ compilerOptions,
473
+ resolvedBaseUrl,
474
+ jsConfig,
475
+ swcCacheDir
476
+ }) {
477
+ const parserConfig = options_js.getParserOptions({ filename, jsConfig });
478
+ const paths = jsConfig?.compilerOptions?.paths;
479
+ const enableDecorators = Boolean(
480
+ jsConfig?.compilerOptions?.experimentalDecorators
481
+ );
482
+ const emitDecoratorMetadata = Boolean(
483
+ jsConfig?.compilerOptions?.emitDecoratorMetadata
484
+ );
485
+ const useDefineForClassFields = Boolean(
486
+ jsConfig?.compilerOptions?.useDefineForClassFields
487
+ );
488
+ const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options]) => [require2.resolve(name), options]);
489
+ return {
490
+ jsc: {
491
+ ...resolvedBaseUrl && paths ? {
492
+ baseUrl: resolvedBaseUrl.baseUrl,
493
+ paths
494
+ } : {},
495
+ externalHelpers: false,
496
+ parser: parserConfig,
497
+ experimental: {
498
+ keepImportAttributes: true,
499
+ emitAssertForImportAttributes: true,
500
+ plugins,
501
+ cacheRoot: swcCacheDir
502
+ },
503
+ transform: {
504
+ legacyDecorator: enableDecorators,
505
+ decoratorMetadata: emitDecoratorMetadata,
506
+ useDefineForClassFields,
507
+ react: {
508
+ importSource: jsConfig?.compilerOptions?.jsxImportSource ?? (compilerOptions?.emotion ? "@emotion/react" : "react"),
509
+ runtime: "automatic",
510
+ pragmaFrag: "React.Fragment",
511
+ throwIfNamespace: true,
512
+ development: !!development,
513
+ useBuiltins: true,
514
+ refresh: !!hasReactRefresh
515
+ },
516
+ optimizer: {
517
+ simplify: false,
518
+ // TODO: Figuring out for what globals are exactly used for
519
+ globals: {
520
+ typeofs: {
521
+ window: globalWindow ? "object" : "undefined"
522
+ },
523
+ envs: {
524
+ NODE_ENV: development ? '"development"' : '"production"'
525
+ }
526
+ }
527
+ },
528
+ regenerator: {
529
+ importPath: regeneratorRuntimePath
530
+ }
531
+ }
532
+ },
533
+ sourceMaps: true,
534
+ removeConsole: compilerOptions?.removeConsole,
535
+ reactRemoveProperties: false,
536
+ // Map the k-v map to an array of pairs.
537
+ modularizeImports: modularizeImports ? Object.fromEntries(
538
+ Object.entries(modularizeImports).map(([mod, config]) => [
539
+ mod,
540
+ {
541
+ ...config,
542
+ transform: typeof config.transform === "string" ? config.transform : Object.entries(config.transform).map(([key, value]) => [
543
+ key,
544
+ value
545
+ ])
546
+ }
547
+ ])
548
+ ) : void 0,
549
+ relay: compilerOptions?.relay,
550
+ // Always transform styled-jsx and error when `client-only` condition is triggered
551
+ styledJsx: {},
552
+ // Disable css-in-js libs (without client-only integration) transform on server layer for server components
553
+ emotion: getEmotionOptions(compilerOptions?.emotion, development),
554
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
555
+ styledComponents: getStyledComponentsOptions(
556
+ compilerOptions?.styledComponents,
557
+ development
558
+ ),
559
+ serverComponents: void 0,
560
+ serverActions: void 0,
561
+ // For app router we prefer to bundle ESM,
562
+ // On server side of pages router we prefer CJS.
563
+ preferEsm: esm
564
+ };
565
+ }
566
+
567
+ // src/utils/swc/transform.ts
568
+ var getVitestSWCTransformConfig = ({
569
+ filename,
570
+ inputSourceMap,
571
+ isServerEnvironment,
572
+ loadedJSConfig,
573
+ nextDirectories,
574
+ nextConfig,
575
+ rootDir,
576
+ isDev,
577
+ isEsmProject
578
+ }) => {
579
+ const baseOptions = getBaseSWCOptions({
580
+ filename,
581
+ development: isDev,
582
+ hasReactRefresh: false,
583
+ globalWindow: !isServerEnvironment,
584
+ modularizeImports: nextConfig.modularizeImports,
585
+ jsConfig: loadedJSConfig.jsConfig,
586
+ resolvedBaseUrl: loadedJSConfig.resolvedBaseUrl,
587
+ swcPlugins: nextConfig.experimental.swcPlugins,
588
+ compilerOptions: nextConfig?.compilerOptions,
589
+ esm: isEsmProject,
590
+ swcCacheDir: path__default.default.join(
591
+ rootDir,
592
+ nextConfig.distDir ?? ".next",
593
+ "cache",
594
+ "swc"
595
+ )
596
+ });
597
+ const useCjsModules = shouldOutputCommonJs(filename);
598
+ const isPageFile = nextDirectories.pagesDir ? filename.startsWith(nextDirectories.pagesDir) : false;
599
+ return {
600
+ ...baseOptions,
601
+ fontLoaders: {
602
+ fontLoaders: ["next/font/local", "next/font/google"],
603
+ relativeFilePathFromRoot: path__default.default.relative(rootDir, filename)
604
+ },
605
+ cjsRequireOptimizer: {
606
+ packages: {
607
+ "next/server": {
608
+ transforms: {
609
+ NextRequest: "next/dist/server/web/spec-extension/request",
610
+ NextResponse: "next/dist/server/web/spec-extension/response",
611
+ ImageResponse: "next/dist/server/web/spec-extension/image-response",
612
+ userAgentFromString: "next/dist/server/web/spec-extension/user-agent",
613
+ userAgent: "next/dist/server/web/spec-extension/user-agent"
614
+ }
615
+ }
616
+ }
617
+ },
618
+ ...isServerEnvironment ? {
619
+ env: {
620
+ targets: {
621
+ // Targets the current version of Node.js
622
+ node: process.versions.node
623
+ }
624
+ }
625
+ } : {
626
+ env: {
627
+ targets: utils_js.getSupportedBrowsers(rootDir, isDev)
628
+ }
629
+ },
630
+ module: {
631
+ type: isEsmProject && !useCjsModules ? "es6" : "commonjs"
632
+ },
633
+ disableNextSsg: !isPageFile,
634
+ disablePageConfig: true,
635
+ isPageFile,
636
+ pagesDir: nextDirectories.pagesDir,
637
+ appDir: nextDirectories.appDir,
638
+ isDevelopment: isDev,
639
+ isServerCompiler: isServerEnvironment,
640
+ inputSourceMap: inputSourceMap && typeof inputSourceMap === "object" ? JSON.stringify(inputSourceMap) : void 0,
641
+ sourceFileName: filename,
642
+ filename
643
+ };
644
+ };
645
+
646
+ // src/utils/typescript.ts
647
+ var isDefined = (value) => value !== void 0;
648
+
649
+ // src/plugins/next-swc/plugin.ts
650
+ var excluded = /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|virtual:)[\\/]/g;
651
+ var included = /\.((c|m)?(j|t)sx?)$/;
652
+ function vitePluginNextSwc(rootDir, nextConfigResolver) {
653
+ let loadedJSConfig;
654
+ let nextDirectories;
655
+ let isServerEnvironment;
656
+ let isDev;
657
+ let isEsmProject;
658
+ const resolvedDir = path.resolve(rootDir);
659
+ return {
660
+ name: "vite-plugin-storybook-nextjs-swc",
661
+ enforce: "pre",
662
+ async config(config, env) {
663
+ const nextConfig = await nextConfigResolver.promise;
664
+ nextDirectories = findPagesDir_js.findPagesDir(resolvedDir);
665
+ loadedJSConfig = await loadJsConfig__default.default(resolvedDir, nextConfig);
666
+ isDev = env.mode !== "production";
667
+ await loadClosestPackageJson(resolvedDir);
668
+ isEsmProject = true;
669
+ await loadSWCBindingsEagerly(nextConfig);
670
+ const serverWatchIgnored = config.server?.watch?.ignored;
671
+ const isServerWatchIgnoredArray = Array.isArray(serverWatchIgnored);
672
+ if (config.test?.environment === "node" || config.test?.environment === "edge-runtime" || config.test?.browser?.enabled !== false) {
673
+ isServerEnvironment = true;
674
+ }
675
+ return {
676
+ // esbuild: {
677
+ // // We will use Next.js custom SWC transpiler instead of Vite's build-in esbuild
678
+ // exclude: [/node_modules/, /.m?(t|j)sx?/],
679
+ // },
680
+ server: {
681
+ watch: {
682
+ ignored: [
683
+ ...isServerWatchIgnoredArray ? serverWatchIgnored : [serverWatchIgnored],
684
+ "/.next/"
685
+ ].filter(isDefined)
686
+ }
687
+ }
688
+ };
689
+ },
690
+ async transform(code, id) {
691
+ if (!excluded.test(id) && included.test(id)) {
692
+ const inputSourceMap = this.getCombinedSourcemap();
693
+ const output = await index_js.transform(
694
+ code,
695
+ getVitestSWCTransformConfig({
696
+ filename: id,
697
+ inputSourceMap,
698
+ isServerEnvironment,
699
+ loadedJSConfig,
700
+ nextConfig: await nextConfigResolver.promise,
701
+ nextDirectories,
702
+ rootDir,
703
+ isDev,
704
+ isEsmProject
705
+ })
706
+ );
707
+ return output;
708
+ }
709
+ }
710
+ };
711
+ }
712
+
713
+ // src/polyfills/promise-with-resolvers.ts
714
+ if (typeof Promise.withResolvers === "undefined") {
715
+ Promise.withResolvers = () => {
716
+ let resolve4;
717
+ let reject;
718
+ const promise = new Promise((res, rej) => {
719
+ resolve4 = res;
720
+ reject = rej;
721
+ });
722
+ return { promise, resolve: resolve4, reject };
723
+ };
724
+ }
725
+
726
+ // src/utils.ts
727
+ var VITEST_PLUGIN_NAME = "vite-plugin-storybook-nextjs";
728
+ var isVitestEnv = process.env.VITEST === "true";
729
+
730
+ // src/plugins/next-image/plugin.ts
731
+ var includePattern2 = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/;
732
+ var excludeImporterPattern = /\.(css|scss|sass)$/;
733
+ var virtualImage = "virtual:next-image";
734
+ var virtualNextImage = "virtual:next/image";
735
+ var virtualNextLegacyImage = "virtual:next/legacy/image";
736
+ var sharp;
737
+ var require3 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)));
738
+ try {
739
+ sharp = require3("sharp");
740
+ if (sharp && sharp.concurrency() > 1) {
741
+ const divisor = process.env.NODE_ENV === "development" ? 4 : 2;
742
+ sharp.concurrency(Math.floor(Math.max(os.cpus().length / divisor, 1)));
743
+ }
744
+ } catch (e) {
745
+ console.warn(
746
+ "You have to install sharp in order to use image optimization features in Next.js. AVIF support is also disabled."
747
+ );
748
+ }
749
+ var getEntryPoint = (subPath, env) => require3.resolve(`${VITEST_PLUGIN_NAME}/${env}/mocks/${subPath}`);
750
+ var getAlias = (env) => ({
751
+ "sb-original/default-loader": getEntryPoint("image-default-loader", env),
752
+ "sb-original/image-context": getEntryPoint("image-context", env)
753
+ });
754
+ function vitePluginNextImage(nextConfigResolver) {
755
+ let isBrowser = !isVitestEnv;
756
+ return {
757
+ name: "vite-plugin-storybook-nextjs-image",
758
+ enforce: "pre",
759
+ async config(config, env) {
760
+ if (config.test?.browser?.enabled === true) {
761
+ isBrowser = true;
762
+ }
763
+ return {
764
+ resolve: {
765
+ alias: getAlias(isBrowser ? "browser" : "node")
766
+ }
767
+ };
768
+ },
769
+ async resolveId(id, importer) {
770
+ const [source, queryA] = id.split("?");
771
+ if (queryA === "ignore") {
772
+ return null;
773
+ }
774
+ if (includePattern2.test(source) && !excludeImporterPattern.test(importer ?? "") && !importer?.startsWith(virtualImage)) {
775
+ const isAbsolute = path__default.default.isAbsolute(id);
776
+ const imagePath = importer ? isAbsolute ? source : path__default.default.join(path__default.default.dirname(importer), source) : source;
777
+ return `${virtualImage}?imagePath=${imagePath}`;
778
+ }
779
+ if (id === "next/image" && importer !== virtualNextImage) {
780
+ return virtualNextImage;
781
+ }
782
+ if (id === "next/legacy/image" && importer !== virtualNextLegacyImage) {
783
+ return virtualNextLegacyImage;
784
+ }
785
+ return null;
786
+ },
787
+ async load(id) {
788
+ const aliasEnv = isBrowser ? "browser" : "node";
789
+ if (virtualNextImage === id) {
790
+ return (await fs3__default.default.promises.readFile(
791
+ require3.resolve(`${VITEST_PLUGIN_NAME}/${aliasEnv}/mocks/image`)
792
+ )).toString("utf-8");
793
+ }
794
+ if (virtualNextLegacyImage === id) {
795
+ return (await fs3__default.default.promises.readFile(
796
+ require3.resolve(
797
+ `${VITEST_PLUGIN_NAME}/${aliasEnv}/mocks/legacy-image`
798
+ )
799
+ )).toString("utf-8");
800
+ }
801
+ const [source, query] = id.split("?");
802
+ if (virtualImage === source) {
803
+ const imagePath = querystring.decode(query).imagePath;
804
+ const nextConfig = await nextConfigResolver.promise;
805
+ const extension = path__default.default.extname(imagePath);
806
+ try {
807
+ if (nextConfig.images?.disableStaticImages) {
808
+ return tsDedent.dedent`
809
+ import image from "${imagePath}?ignore";
810
+ export default image;
811
+ `;
812
+ }
813
+ const imageData = await fs3__default.default.promises.readFile(imagePath);
814
+ let width;
815
+ let height;
816
+ if (extension === ".avif" && sharp) {
817
+ const transformer = sharp(Buffer.from(imageData));
818
+ const result = await transformer.metadata();
819
+ width = result.width;
820
+ height = result.height;
821
+ } else {
822
+ const result = imageSizeOf__default.default(imageData);
823
+ width = result.width;
824
+ height = result.height;
825
+ }
826
+ return tsDedent.dedent`
827
+ import src from "${imagePath}?ignore";
828
+ export default {
829
+ src,
830
+ height: ${height},
831
+ width: ${width},
832
+ blurDataURL: src
833
+ };
834
+ `;
835
+ } catch (err) {
836
+ console.error(`Could not read font file ${imagePath}:`, err);
837
+ return void 0;
838
+ }
839
+ }
840
+ return null;
841
+ }
842
+ };
843
+ }
844
+ var require4 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)));
845
+ var getEntryPoint2 = (subPath, env) => require4.resolve(`${VITEST_PLUGIN_NAME}/${env}/mocks/${subPath}`);
846
+ var getAlias2 = (env) => ({
847
+ "next/headers": getEntryPoint2("headers", env),
848
+ "@storybook/nextjs/headers.mock": getEntryPoint2("headers", env),
849
+ "next/navigation": getEntryPoint2("navigation", env),
850
+ "@storybook/nextjs/navigation.mock": getEntryPoint2("navigation", env),
851
+ "next/router": getEntryPoint2("router", env),
852
+ "@storybook/nextjs/router.mock": getEntryPoint2("router", env),
853
+ "next/cache": getEntryPoint2("cache", env),
854
+ "@storybook/nextjs/cache.mock": getEntryPoint2("cache", env),
855
+ "server-only": getEntryPoint2("server-only", env),
856
+ "@opentelemetry/api": require4.resolve(
857
+ "next/dist/compiled/@opentelemetry/api/index.js"
858
+ )
859
+ });
860
+ var vitePluginNextMocks = () => ({
861
+ name: "vite-plugin-next-mocks",
862
+ config: (env) => {
863
+ const aliasEnv = isVitestEnv && env.test?.browser?.enabled !== true ? "node" : "browser";
864
+ return {
865
+ resolve: {
866
+ alias: getAlias2(aliasEnv)
867
+ }
868
+ };
869
+ }
870
+ });
871
+
872
+ // src/index.ts
873
+ var require5 = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.src || new URL('out.js', document.baseURI).href)));
874
+ function VitePlugin({ dir = process.cwd() } = {}) {
875
+ const resolvedDir = path.resolve(dir);
876
+ const nextConfigResolver = Promise.withResolvers();
877
+ return [
878
+ {
879
+ name: "vite-plugin-storybook-nextjs",
880
+ enforce: "pre",
881
+ async config(config, env) {
882
+ const phase = env.mode === "development" ? constants_js.PHASE_DEVELOPMENT_SERVER : env.mode === "test" ? constants_js.PHASE_TEST : constants_js.PHASE_PRODUCTION_BUILD;
883
+ nextConfigResolver.resolve(await loadConfig__default.default(phase, resolvedDir));
884
+ return {
885
+ ...!isVitestEnv && {
886
+ resolve: {
887
+ alias: {
888
+ react: "next/dist/compiled/react",
889
+ "react-dom": "next/dist/compiled/react-dom"
890
+ }
891
+ }
892
+ },
893
+ test: {
894
+ alias: {
895
+ "react/jsx-dev-runtime": require5.resolve(
896
+ "next/dist/compiled/react/jsx-dev-runtime.js"
897
+ ),
898
+ "react/jsx-runtime": require5.resolve(
899
+ "next/dist/compiled/react/jsx-runtime.js"
900
+ ),
901
+ react: require5.resolve("next/dist/compiled/react"),
902
+ "react-dom/test-utils": require5.resolve(
903
+ "next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js"
904
+ ),
905
+ "react-dom/cjs/react-dom.development.js": require5.resolve(
906
+ "next/dist/compiled/react-dom/cjs/react-dom.development.js"
907
+ ),
908
+ "react-dom/client": require5.resolve(
909
+ "next/dist/compiled/react-dom/client.js"
910
+ ),
911
+ "react-dom": require5.resolve("next/dist/compiled/react-dom")
912
+ }
913
+ }
914
+ };
915
+ },
916
+ configResolved(config) {
917
+ if (!config.test?.browser?.enabled) {
918
+ config.test.setupFiles = [
919
+ require5.resolve("./mocks/storybook.global.js"),
920
+ ...config.test?.setupFiles ?? []
921
+ ];
922
+ }
923
+ }
924
+ },
925
+ vitePluginNextFont(),
926
+ vitePluginNextSwc(dir, nextConfigResolver),
927
+ vitePluginNextEnv(dir, nextConfigResolver),
928
+ vitePluginNextImage(nextConfigResolver),
929
+ vitePluginNextMocks()
930
+ ];
931
+ }
932
+ var src_default = VitePlugin;
933
+
934
+ module.exports = src_default;