vite-plugin-storybook-nextjs 0.0.3--canary.253ba44.0 → 0.0.4--canary.fb0538a.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 (29) hide show
  1. package/dist/index.d.ts +12 -0
  2. package/dist/index.js +218 -216
  3. package/dist/mocks/storybook.global.d.ts +2 -0
  4. package/dist/mocks/storybook.global.js +15 -0
  5. package/dist/plugins/next-image/alias/image-context.d.ts +13 -0
  6. package/dist/plugins/next-image/alias/image-context.js +1 -1
  7. package/dist/plugins/next-image/alias/image-default-loader.d.ts +5 -0
  8. package/dist/plugins/next-image/alias/next-image.d.ts +30 -0
  9. package/dist/plugins/next-image/alias/next-legacy-image.d.ts +6 -0
  10. package/dist/plugins/next-mocks/alias/cache/index.d.ts +16 -0
  11. package/dist/plugins/next-mocks/alias/cache/index.js +18 -0
  12. package/dist/plugins/next-mocks/alias/headers/cookies.d.ts +14 -0
  13. package/dist/plugins/next-mocks/alias/headers/cookies.js +34 -0
  14. package/dist/plugins/next-mocks/alias/headers/headers.d.ts +21 -0
  15. package/dist/plugins/next-mocks/alias/headers/headers.js +38 -0
  16. package/dist/plugins/next-mocks/alias/headers/index.d.ts +10 -0
  17. package/dist/plugins/next-mocks/alias/headers/index.js +71 -0
  18. package/dist/plugins/next-mocks/alias/navigation/index.d.ts +30 -0
  19. package/dist/plugins/next-mocks/alias/navigation/index.js +65 -0
  20. package/dist/plugins/next-mocks/alias/router/index.d.ts +45 -0
  21. package/dist/plugins/next-mocks/alias/router/index.js +108 -0
  22. package/dist/plugins/next-mocks/alias/rsc/server-only.d.ts +3 -0
  23. package/dist/plugins/next-mocks/alias/rsc/server-only.js +4 -0
  24. package/package.json +8 -4
  25. package/dist/index.cjs +0 -960
  26. package/dist/plugins/next-image/alias/image-context.cjs +0 -8
  27. package/dist/plugins/next-image/alias/image-default-loader.cjs +0 -40
  28. package/dist/plugins/next-image/alias/next-image.cjs +0 -53
  29. package/dist/plugins/next-image/alias/next-legacy-image.cjs +0 -27
package/dist/index.js CHANGED
@@ -1,25 +1,27 @@
1
1
  import path, { resolve, join } from 'node:path';
2
- import { getDefineEnv } from 'next/dist/build/webpack/plugins/define-env-plugin';
3
- import { loadEnvConfig } from '@next/env';
4
- import Log from 'next/dist/build/output/log';
5
- import { transform, loadBindings, lockfilePatchPromise } from 'next/dist/build/swc';
6
- import loadConfig from 'next/dist/server/config';
7
- import { PHASE_TEST, CONFIG_FILES } from 'next/dist/shared/lib/constants';
8
- import fs from 'node:fs/promises';
9
- import { fetchCSSFromGoogleFonts } from 'next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts';
10
- import { getFontAxes } from 'next/dist/compiled/@next/font/dist/google/get-font-axes';
11
- import { getGoogleFontsUrl } from 'next/dist/compiled/@next/font/dist/google/get-google-fonts-url';
12
- import { validateGoogleFontFunctionCall } from 'next/dist/compiled/@next/font/dist/google/validate-google-font-function-call';
13
- import loaderUtils from 'next/dist/compiled/loader-utils3';
14
- import { validateLocalFontFunctionCall } from 'next/dist/compiled/@next/font/dist/local/validate-local-font-function-call';
15
- import dedent3, { dedent } from 'ts-dedent';
16
- import loadJsConfig from 'next/dist/build/load-jsconfig';
17
- import { findPagesDir } from 'next/dist/lib/find-pages-dir';
18
- import { getSupportedBrowsers } from 'next/dist/build/utils';
19
- import { getParserOptions } from 'next/dist/build/swc/options';
20
- import fs2 from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import { getDefineEnv } from 'next/dist/build/webpack/plugins/define-env-plugin.js';
4
+ import fs3 from 'node:fs';
5
+ import nextEnv from '@next/env';
6
+ import Log from 'next/dist/build/output/log.js';
7
+ import { transform, loadBindings, lockfilePatchPromise } from 'next/dist/build/swc/index.js';
8
+ import { PHASE_DEVELOPMENT_SERVER, PHASE_TEST, PHASE_PRODUCTION_BUILD } from 'next/dist/shared/lib/constants.js';
9
+ import fs2 from 'node:fs/promises';
10
+ import { fetchCSSFromGoogleFonts } from 'next/dist/compiled/@next/font/dist/google/fetch-css-from-google-fonts.js';
11
+ import { getFontAxes } from 'next/dist/compiled/@next/font/dist/google/get-font-axes.js';
12
+ import { getGoogleFontsUrl } from 'next/dist/compiled/@next/font/dist/google/get-google-fonts-url.js';
13
+ import { validateGoogleFontFunctionCall } from 'next/dist/compiled/@next/font/dist/google/validate-google-font-function-call.js';
14
+ import loaderUtils from 'next/dist/compiled/loader-utils3/index.js';
15
+ import { validateLocalFontFunctionCall } from 'next/dist/compiled/@next/font/dist/local/validate-local-font-function-call.js';
16
+ import { dedent } from 'ts-dedent';
17
+ import loadJsConfig from 'next/dist/build/load-jsconfig.js';
18
+ import { findPagesDir } from 'next/dist/lib/find-pages-dir.js';
19
+ import { getSupportedBrowsers } from 'next/dist/build/utils.js';
20
+ import { getParserOptions } from 'next/dist/build/swc/options.js';
21
+ import loadConfig from 'next/dist/server/config.js';
21
22
  import { cpus } from 'node:os';
22
- import { fileURLToPath, URL } from 'node:url';
23
+ import { decode } from 'node:querystring';
24
+ import { fileURLToPath, URL as URL$1 } from 'node:url';
23
25
  import imageSizeOf from 'image-size';
24
26
 
25
27
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
@@ -28,16 +30,9 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
28
30
  if (typeof require !== "undefined") return require.apply(this, arguments);
29
31
  throw Error('Dynamic require of "' + x + '" is not supported');
30
32
  });
33
+ var { loadEnvConfig } = nextEnv;
31
34
  var nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
32
- async function getConfig(dir) {
33
- const conf = await loadConfig(PHASE_TEST, dir);
34
- return conf;
35
- }
36
- async function getConfigPaths(dir) {
37
- return CONFIG_FILES.map((file) => join(dir, file));
38
- }
39
- async function loadEnvironmentConfig(dir) {
40
- const dev = false;
35
+ async function loadEnvironmentConfig(dir, dev) {
41
36
  return loadEnvConfig(dir, dev, Log);
42
37
  }
43
38
  async function loadSWCBindingsEagerly(nextConfig) {
@@ -49,43 +44,69 @@ async function loadSWCBindingsEagerly(nextConfig) {
49
44
  function shouldOutputCommonJs(filename) {
50
45
  return filename.endsWith(".cjs") || nextDistPath.test(filename);
51
46
  }
47
+ async function loadClosestPackageJson(dir, attempts = 1) {
48
+ if (attempts > 5) {
49
+ throw new Error("Can't resolve main package.json file");
50
+ }
51
+ const mainPath = attempts === 1 ? ["."] : new Array(attempts).fill("..");
52
+ try {
53
+ const file = await fs3.promises.readFile(
54
+ join(dir, ...mainPath, "package.json"),
55
+ "utf8"
56
+ );
57
+ return JSON.parse(file);
58
+ } catch (e) {
59
+ return loadClosestPackageJson(dir, attempts + 1);
60
+ }
61
+ }
52
62
 
53
63
  // src/plugins/next-env/plugin.ts
54
- function vitePluginNextConfig(rootDir) {
55
- let nextConfig;
64
+ function vitePluginNextEnv(rootDir, nextConfigResolver) {
56
65
  let envConfig;
57
66
  let isDev;
58
67
  const resolvedDir = resolve(rootDir);
59
68
  return {
60
- name: "vite-plugin-storybook-nextjs-swc",
69
+ name: "vite-plugin-storybook-nextjs-env",
70
+ enforce: "pre",
61
71
  async config(config, env) {
62
- nextConfig = await getConfig(resolvedDir);
63
- envConfig = (await loadEnvironmentConfig(resolvedDir)).combinedEnv;
64
- isDev = env.mode === "development";
72
+ isDev = env.mode !== "production";
73
+ envConfig = (await loadEnvironmentConfig(resolvedDir, isDev)).combinedEnv;
74
+ const nextConfig = await nextConfigResolver.promise;
65
75
  const publicNextEnvMap = Object.fromEntries(
66
76
  Object.entries(envConfig).filter(([key]) => key.startsWith("NEXT_PUBLIC_")).map(([key, value]) => {
67
77
  return [`process.env.${key}`, JSON.stringify(value)];
68
78
  })
69
79
  );
80
+ const finalConfig = {
81
+ ...config.define,
82
+ ...publicNextEnvMap,
83
+ ...getDefineEnv({
84
+ isTurbopack: false,
85
+ config: nextConfig,
86
+ isClient: true,
87
+ isEdgeServer: false,
88
+ isNodeOrEdgeCompilation: false,
89
+ isNodeServer: false,
90
+ clientRouterFilters: void 0,
91
+ dev: isDev,
92
+ middlewareMatchers: void 0,
93
+ hasRewrites: false,
94
+ distDir: nextConfig.distDir,
95
+ fetchCacheKeyPrefix: nextConfig?.experimental?.fetchCacheKeyPrefix
96
+ })
97
+ };
98
+ delete process.env.__NEXT_IMAGE_OPTS;
99
+ delete finalConfig["process.env.__NEXT_IMAGE_OPTS"];
70
100
  return {
71
- ...config,
72
- define: {
73
- ...config.define,
74
- ...publicNextEnvMap,
75
- ...getDefineEnv({
76
- isTurbopack: false,
77
- config: nextConfig,
78
- isClient: true,
79
- isEdgeServer: false,
80
- isNodeOrEdgeCompilation: false,
81
- isNodeServer: false,
82
- clientRouterFilters: void 0,
83
- dev: isDev,
84
- middlewareMatchers: void 0,
85
- hasRewrites: false,
86
- distDir: nextConfig.distDir,
87
- fetchCacheKeyPrefix: nextConfig?.experimental?.fetchCacheKeyPrefix
88
- })
101
+ define: finalConfig,
102
+ test: {
103
+ deps: {
104
+ optimizer: {
105
+ ssr: {
106
+ include: ["next"]
107
+ }
108
+ }
109
+ }
89
110
  }
90
111
  };
91
112
  }
@@ -159,14 +180,14 @@ async function getFontFaceDeclarations2(options) {
159
180
  if ("fontReferenceId" in localFontSrc) {
160
181
  return dedent`@font-face {
161
182
  font-family: ${id};
162
- src: url(${localFontSrc.fontReferenceId ? getPlaceholderFontUrl(localFontSrc.fontReferenceId) : `.${localFontSrc.fontPath}`})
183
+ src: url(${localFontSrc.fontReferenceId ? getPlaceholderFontUrl(localFontSrc.fontReferenceId) : `/@fs${localFontSrc.fontPath}`})
163
184
  ${fontDeclarations}
164
185
  }`;
165
186
  }
166
187
  return localFontSrc.map((font) => {
167
188
  return dedent`@font-face {
168
189
  font-family: ${id};
169
- src: url(${font.path.fontReferenceId ? getPlaceholderFontUrl(font.path.fontReferenceId) : `.${font.path.fontPath}`});
190
+ src: url(${font.path.fontReferenceId ? getPlaceholderFontUrl(font.path.fontReferenceId) : `/@fs${font.path.fontPath}`});
170
191
  ${font.weight ? `font-weight: ${font.weight};` : ""}
171
192
  ${font.style ? `font-style: ${font.style};` : ""}
172
193
  ${fontDeclarations}
@@ -243,7 +264,7 @@ function setFontDeclarationsInHead({
243
264
  });
244
265
  }
245
266
  }
246
- return dedent3`
267
+ return dedent`
247
268
  const fontPaths = [${fontPathsImportUrls.map((fontPath) => `{id: '${fontPath.id}', path: ${fontPath.path}}`).join(", ")}];
248
269
  if (!document.getElementById('id-${id}')) {
249
270
  let fontDeclarations = \`${fontFaceCSS}\`;
@@ -267,53 +288,17 @@ function setFontDeclarationsInHead({
267
288
  // src/plugins/next-font/plugin.ts
268
289
  var includePattern = /next(\\|\/|\\\\).*(\\|\/|\\\\)target\.css.*$/;
269
290
  var virtualModuleId = "virtual:next-font";
270
- function configureNextFont() {
291
+ function vitePluginNextFont() {
271
292
  let devMode = true;
272
- const fontAssetPaths = /* @__PURE__ */ new Map();
273
293
  return {
274
- name: "configure-next-font",
294
+ name: "vite-plugin-storybook-nextjs-font",
295
+ enforce: "pre",
275
296
  async config(config, env) {
276
- devMode = env.mode === "development";
297
+ devMode = env.mode !== "production";
277
298
  return config;
278
299
  },
279
- configureServer(server) {
280
- server.middlewares.use(async (req, res, next) => {
281
- if (req.url && fontAssetPaths.has(req.url)) {
282
- const fontAbsoluteAssetPath = fontAssetPaths.get(req.url);
283
- const fontFileExtension = path.extname(fontAbsoluteAssetPath);
284
- try {
285
- const fontData = await fs.readFile(fontAbsoluteAssetPath);
286
- switch (fontFileExtension) {
287
- case ".woff":
288
- res.setHeader("Content-Type", "font/woff");
289
- break;
290
- case ".woff2":
291
- res.setHeader("Content-Type", "font/woff2");
292
- break;
293
- case ".ttf":
294
- res.setHeader("Content-Type", "font/ttf");
295
- break;
296
- case ".otf":
297
- res.setHeader("Content-Type", "font/otf");
298
- break;
299
- default:
300
- res.setHeader("Content-Type", "font");
301
- }
302
- res.end(fontData);
303
- } catch (e) {
304
- console.error(
305
- `Could not read font file ${fontAbsoluteAssetPath}:`,
306
- e
307
- );
308
- res.statusCode = 404;
309
- res.end();
310
- }
311
- } else {
312
- next();
313
- }
314
- });
315
- },
316
300
  async resolveId(source, importer) {
301
+ const cwd = process.cwd();
317
302
  if (!includePattern.test(source) || !importer) {
318
303
  return null;
319
304
  }
@@ -347,14 +332,13 @@ function configureNextFont() {
347
332
  );
348
333
  const fontPath = path.join(importerDirPath, importerRelativeFontPath);
349
334
  if (devMode) {
350
- fontAssetPaths.set(importerRelativeFontPath, fontPath);
351
335
  return {
352
- fontPath: importerRelativeFontPath,
336
+ fontPath: path.join(cwd, fontPath),
353
337
  fontReferenceId: void 0
354
338
  };
355
339
  }
356
340
  try {
357
- const fontData = await fs.readFile(fontPath);
341
+ const fontData = await fs2.readFile(fontPath);
358
342
  const fontReferenceId = this.emitFile({
359
343
  name: `${fontBaseName}${fontExtension}`,
360
344
  type: "asset",
@@ -466,7 +450,8 @@ function getEmotionOptions(emotionConfig, development) {
466
450
  }
467
451
 
468
452
  // src/utils/swc/options.ts
469
- var regeneratorRuntimePath = __require.resolve(
453
+ var require2 = createRequire(import.meta.url);
454
+ var regeneratorRuntimePath = require2.resolve(
470
455
  "next/dist/compiled/regenerator-runtime"
471
456
  );
472
457
  function getBaseSWCOptions({
@@ -493,7 +478,7 @@ function getBaseSWCOptions({
493
478
  const useDefineForClassFields = Boolean(
494
479
  jsConfig?.compilerOptions?.useDefineForClassFields
495
480
  );
496
- const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options]) => [__require.resolve(name), options]);
481
+ const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options]) => [require2.resolve(name), options]);
497
482
  return {
498
483
  jsc: {
499
484
  ...resolvedBaseUrl && paths ? {
@@ -538,7 +523,7 @@ function getBaseSWCOptions({
538
523
  }
539
524
  }
540
525
  },
541
- sourceMaps: "inline",
526
+ sourceMaps: true,
542
527
  removeConsole: compilerOptions?.removeConsole,
543
528
  reactRemoveProperties: false,
544
529
  // Map the k-v map to an array of pairs.
@@ -581,12 +566,12 @@ var getVitestSWCTransformConfig = ({
581
566
  nextDirectories,
582
567
  nextConfig,
583
568
  rootDir,
584
- isDev
569
+ isDev,
570
+ isEsmProject
585
571
  }) => {
586
- const esm = true;
587
572
  const baseOptions = getBaseSWCOptions({
588
573
  filename,
589
- development: false,
574
+ development: isDev,
590
575
  hasReactRefresh: false,
591
576
  globalWindow: !isServerEnvironment,
592
577
  modularizeImports: nextConfig.modularizeImports,
@@ -594,7 +579,7 @@ var getVitestSWCTransformConfig = ({
594
579
  resolvedBaseUrl: loadedJSConfig.resolvedBaseUrl,
595
580
  swcPlugins: nextConfig.experimental.swcPlugins,
596
581
  compilerOptions: nextConfig?.compilerOptions,
597
- esm,
582
+ esm: isEsmProject,
598
583
  swcCacheDir: path.join(
599
584
  rootDir,
600
585
  nextConfig.distDir ?? ".next",
@@ -603,6 +588,7 @@ var getVitestSWCTransformConfig = ({
603
588
  )
604
589
  });
605
590
  const useCjsModules = shouldOutputCommonJs(filename);
591
+ const isPageFile = nextDirectories.pagesDir ? filename.startsWith(nextDirectories.pagesDir) : false;
606
592
  return {
607
593
  ...baseOptions,
608
594
  fontLoaders: {
@@ -635,12 +621,15 @@ var getVitestSWCTransformConfig = ({
635
621
  }
636
622
  },
637
623
  module: {
638
- type: esm && !useCjsModules ? "es6" : "commonjs"
624
+ type: isEsmProject && !useCjsModules ? "es6" : "commonjs"
639
625
  },
640
- disableNextSsg: true,
626
+ disableNextSsg: !isPageFile,
641
627
  disablePageConfig: true,
628
+ isPageFile,
642
629
  pagesDir: nextDirectories.pagesDir,
643
630
  appDir: nextDirectories.appDir,
631
+ isDevelopment: isDev,
632
+ isServerCompiler: isServerEnvironment,
644
633
  inputSourceMap: inputSourceMap && typeof inputSourceMap === "object" ? JSON.stringify(inputSourceMap) : void 0,
645
634
  sourceFileName: filename,
646
635
  filename
@@ -658,15 +647,18 @@ function vitePluginNextSwc(rootDir, nextConfigResolver) {
658
647
  let nextDirectories;
659
648
  let isServerEnvironment;
660
649
  let isDev;
650
+ let isEsmProject;
661
651
  const resolvedDir = resolve(rootDir);
662
652
  return {
663
653
  name: "vite-plugin-storybook-nextjs-swc",
654
+ enforce: "pre",
664
655
  async config(config, env) {
665
656
  const nextConfig = await nextConfigResolver.promise;
666
657
  nextDirectories = findPagesDir(resolvedDir);
667
- loadedJSConfig = await loadJsConfig(resolvedDir, nextConfig);
668
- (await loadEnvironmentConfig(resolvedDir)).combinedEnv;
669
- isDev = env.mode === "development";
658
+ loadedJSConfig = await loadJsConfig.default(resolvedDir, nextConfig);
659
+ isDev = env.mode !== "production";
660
+ await loadClosestPackageJson(resolvedDir);
661
+ isEsmProject = true;
670
662
  await loadSWCBindingsEagerly(nextConfig);
671
663
  const serverWatchIgnored = config.server?.watch?.ignored;
672
664
  const isServerWatchIgnoredArray = Array.isArray(serverWatchIgnored);
@@ -679,10 +671,10 @@ function vitePluginNextSwc(rootDir, nextConfigResolver) {
679
671
  "@opentelemetry/api": "next/dist/compiled/@opentelemetry/api"
680
672
  }
681
673
  },
682
- esbuild: {
683
- // We will use Next.js custom SWC transpiler instead of Vite's build-in esbuild
684
- exclude: [/node_modules/, /.m?(t|j)sx?/]
685
- },
674
+ // esbuild: {
675
+ // // We will use Next.js custom SWC transpiler instead of Vite's build-in esbuild
676
+ // exclude: [/node_modules/, /.m?(t|j)sx?/],
677
+ // },
686
678
  server: {
687
679
  watch: {
688
680
  ignored: [
@@ -706,7 +698,8 @@ function vitePluginNextSwc(rootDir, nextConfigResolver) {
706
698
  nextConfig: await nextConfigResolver.promise,
707
699
  nextDirectories,
708
700
  rootDir,
709
- isDev
701
+ isDev,
702
+ isEsmProject
710
703
  })
711
704
  );
712
705
  return output;
@@ -749,28 +742,19 @@ try {
749
742
  function vitePluginNextImage(nextConfigResolver) {
750
743
  return {
751
744
  name: "vite-plugin-storybook-nextjs-image",
752
- config(config, env) {
753
- env.mode === "development";
754
- return {
755
- ...config,
756
- resolve: {
757
- ...config.resolve,
758
- alias: {
759
- react: "next/dist/compiled/react",
760
- "react-dom": "next/dist/compiled/react-dom"
761
- }
762
- }
763
- };
745
+ enforce: "pre",
746
+ async config(config, env) {
747
+ return config;
764
748
  },
765
749
  async resolveId(id, importer) {
766
- if (includePattern2.test(id) && !excludeImporterPattern.test(importer ?? "") && !importer?.startsWith(virtualImage)) {
767
- return {
768
- id: `${virtualImage}?${id}`,
769
- meta: {
770
- id,
771
- importer: importer ?? ""
772
- }
773
- };
750
+ const [source, queryA] = id.split("?");
751
+ if (queryA === "ignore") {
752
+ return null;
753
+ }
754
+ if (includePattern2.test(source) && !excludeImporterPattern.test(importer ?? "") && !importer?.startsWith(virtualImage)) {
755
+ const isAbsolute = path.isAbsolute(id);
756
+ const imagePath = importer ? isAbsolute ? source : path.join(path.dirname(importer), source) : source;
757
+ return `${virtualImage}?imagePath=${imagePath}`;
774
758
  }
775
759
  if (id === "next/image" && importer !== virtualNextImage) {
776
760
  return virtualNextImage;
@@ -788,9 +772,9 @@ function vitePluginNextImage(nextConfigResolver) {
788
772
  },
789
773
  async load(id) {
790
774
  if (virtualNextImage === id) {
791
- return (await fs2.promises.readFile(
775
+ return (await fs3.promises.readFile(
792
776
  fileURLToPath(
793
- new URL(
777
+ new URL$1(
794
778
  "./plugins/next-image/alias/next-image.js",
795
779
  import.meta.url
796
780
  )
@@ -798,9 +782,9 @@ function vitePluginNextImage(nextConfigResolver) {
798
782
  )).toString("utf-8");
799
783
  }
800
784
  if (virtualNextLegacyImage === id) {
801
- return (await fs2.promises.readFile(
785
+ return (await fs3.promises.readFile(
802
786
  fileURLToPath(
803
- new URL(
787
+ new URL$1(
804
788
  "./plugins/next-image/alias/next-legacy-image.js",
805
789
  import.meta.url
806
790
  )
@@ -808,9 +792,9 @@ function vitePluginNextImage(nextConfigResolver) {
808
792
  )).toString("utf-8");
809
793
  }
810
794
  if (virtualNextImageDefaultLoader === id) {
811
- return (await fs2.promises.readFile(
795
+ return (await fs3.promises.readFile(
812
796
  fileURLToPath(
813
- new URL(
797
+ new URL$1(
814
798
  "./plugins/next-image/alias/image-default-loader.js",
815
799
  import.meta.url
816
800
  )
@@ -818,34 +802,31 @@ function vitePluginNextImage(nextConfigResolver) {
818
802
  )).toString("utf-8");
819
803
  }
820
804
  if (virtualNextImageContext === id) {
821
- return (await fs2.promises.readFile(
805
+ return (await fs3.promises.readFile(
822
806
  fileURLToPath(
823
- new URL(
807
+ new URL$1(
824
808
  "./plugins/next-image/alias/image-context.js",
825
809
  import.meta.url
826
810
  )
827
811
  )
828
812
  )).toString("utf-8");
829
813
  }
830
- const [source] = id.split("?");
814
+ const [source, query] = id.split("?");
831
815
  if (virtualImage === source) {
832
- const moduleInfo = this.getModuleInfo(id);
833
- const meta = moduleInfo?.meta;
834
- path.basename(id);
816
+ const imagePath = decode(query).imagePath;
835
817
  const nextConfig = await nextConfigResolver.promise;
836
- const extension = meta.id.split(".").pop();
837
- const imagePath = path.join(path.dirname(meta.importer), meta.id);
818
+ const extension = path.extname(imagePath);
838
819
  try {
839
820
  if (nextConfig.images?.disableStaticImages) {
840
- return dedent3`
841
- import image from "${imagePath}";
821
+ return dedent`
822
+ import image from "${imagePath}?ignore";
842
823
  export default image;
843
824
  `;
844
825
  }
845
- const imageData = await fs2.promises.readFile(imagePath);
826
+ const imageData = await fs3.promises.readFile(imagePath);
846
827
  let width;
847
828
  let height;
848
- if (extension === "avif" && sharp) {
829
+ if (extension === ".avif" && sharp) {
849
830
  const transformer = sharp(Buffer.from(imageData));
850
831
  const result = await transformer.metadata();
851
832
  width = result.width;
@@ -855,8 +836,8 @@ function vitePluginNextImage(nextConfigResolver) {
855
836
  width = result.width;
856
837
  height = result.height;
857
838
  }
858
- return dedent3`
859
- import src from "${imagePath}";
839
+ return dedent`
840
+ import src from "${imagePath}?ignore";
860
841
  export default {
861
842
  src,
862
843
  height: ${height},
@@ -873,72 +854,93 @@ function vitePluginNextImage(nextConfigResolver) {
873
854
  }
874
855
  };
875
856
  }
857
+ var dirname = path.dirname(new URL(import.meta.url).pathname);
858
+ var joinDir = (...subPath) => path.join(dirname, "plugins", "next-mocks", "alias", ...subPath);
859
+ var vitePluginNextMocks = () => ({
860
+ name: "vite-plugin-next-mocks",
861
+ config: () => ({
862
+ resolve: {
863
+ alias: {
864
+ "next/headers": joinDir("headers", "index.js"),
865
+ "@storybook/nextjs/headers.mock": joinDir("headers", "index.js"),
866
+ "next/navigation": joinDir("navigation", "index.js"),
867
+ "@storybook/nextjs/navigation.mock": joinDir(
868
+ "navigation",
869
+ "index.js"
870
+ ),
871
+ "next/router": joinDir("router", "index.js"),
872
+ "@storybook/nextjs/router.mock": joinDir("router", "index.js"),
873
+ "next/cache": joinDir("cache", "index.js"),
874
+ "@storybook/nextjs/cache.mock": joinDir("cache", "index.js"),
875
+ "server-only$": joinDir("rsc", "server-only.js")
876
+ }
877
+ }
878
+ })
879
+ });
876
880
 
877
881
  // src/index.ts
882
+ var require3 = createRequire(import.meta.url);
878
883
  function VitePlugin({ dir = process.cwd() } = {}) {
879
884
  const resolvedDir = resolve(dir);
880
885
  const nextConfigResolver = Promise.withResolvers();
881
- const nextFontPlugin = configureNextFont();
882
- const nextSwcPlugin = vitePluginNextSwc(dir, nextConfigResolver);
883
- const nextEnvPlugin = vitePluginNextConfig(dir);
884
- const nextImagePlugin = vitePluginNextImage(nextConfigResolver);
885
- return {
886
- name: "vite-plugin-storybook-nextjs",
887
- async buildStart() {
888
- for (const configPath of await getConfigPaths(resolvedDir)) {
889
- this.addWatchFile(configPath);
890
- }
891
- },
892
- enforce: "pre",
893
- configureServer(server) {
894
- nextFontPlugin.configureServer.call(this, server);
895
- },
896
- async config(config, env) {
897
- nextConfigResolver.resolve(await getConfig(resolvedDir));
898
- const mergedNextSwcConfig = await nextSwcPlugin.config.call(
899
- this,
900
- config,
901
- env
902
- );
903
- const mergedNextEnvConfig = await nextEnvPlugin.config.call(
904
- this,
905
- mergedNextSwcConfig,
906
- env
907
- );
908
- const mergedNextFontConfig = await nextFontPlugin.config.call(
909
- this,
910
- mergedNextEnvConfig,
911
- env
912
- );
913
- const mergedNextImageConfig = await nextImagePlugin.config.call(
914
- this,
915
- mergedNextFontConfig,
916
- env
917
- );
918
- return mergedNextImageConfig;
919
- },
920
- async resolveId(source, importer, options) {
921
- const nextFontResolver = await nextFontPlugin.resolveId.call(
922
- this,
923
- source,
924
- importer
925
- );
926
- if (nextFontResolver) {
927
- return nextFontResolver;
928
- }
929
- return nextImagePlugin.resolveId.call(this, source, importer);
930
- },
931
- load(id) {
932
- const nextFontLoaderResult = nextFontPlugin.load.call(this, id);
933
- if (nextFontLoaderResult) {
934
- return nextFontLoaderResult;
886
+ const isVitestEnv = process.env.VITEST === "true";
887
+ return [
888
+ {
889
+ name: "vite-plugin-storybook-nextjs",
890
+ enforce: "pre",
891
+ async config(config, env) {
892
+ const phase = env.mode === "development" ? PHASE_DEVELOPMENT_SERVER : env.mode === "test" ? PHASE_TEST : PHASE_PRODUCTION_BUILD;
893
+ nextConfigResolver.resolve(
894
+ // @ts-ignore TODO figure out why TypeScript is complaining about this
895
+ await loadConfig.default(phase, resolvedDir)
896
+ );
897
+ return {
898
+ ...!isVitestEnv && {
899
+ resolve: {
900
+ alias: {
901
+ react: "next/dist/compiled/react",
902
+ "react-dom": "next/dist/compiled/react-dom"
903
+ }
904
+ }
905
+ },
906
+ test: {
907
+ alias: {
908
+ "react/jsx-dev-runtime": require3.resolve(
909
+ "next/dist/compiled/react/jsx-dev-runtime.js"
910
+ ),
911
+ "react/jsx-runtime": require3.resolve(
912
+ "next/dist/compiled/react/jsx-runtime.js"
913
+ ),
914
+ react: require3.resolve("next/dist/compiled/react"),
915
+ "react-dom/test-utils": require3.resolve(
916
+ "next/dist/compiled/react-dom/cjs/react-dom-test-utils.production.js"
917
+ ),
918
+ "react-dom/cjs/react-dom.development.js": require3.resolve(
919
+ "next/dist/compiled/react-dom/cjs/react-dom.development.js"
920
+ ),
921
+ "react-dom/client": require3.resolve(
922
+ "next/dist/compiled/react-dom/client.js"
923
+ ),
924
+ "react-dom": require3.resolve("next/dist/compiled/react-dom")
925
+ }
926
+ }
927
+ };
928
+ },
929
+ configResolved(config) {
930
+ if (!config.test?.browser?.enabled) {
931
+ config.test.setupFiles = [
932
+ require3.resolve("./mocks/storybook.global.js"),
933
+ ...config.test?.setupFiles ?? []
934
+ ];
935
+ }
935
936
  }
936
- return nextImagePlugin.load.call(this, id);
937
937
  },
938
- transform(code, id) {
939
- return nextSwcPlugin.transform.call(this, code, id);
940
- }
941
- };
938
+ vitePluginNextFont(),
939
+ vitePluginNextSwc(dir, nextConfigResolver),
940
+ vitePluginNextEnv(dir, nextConfigResolver),
941
+ vitePluginNextImage(nextConfigResolver),
942
+ vitePluginNextMocks()
943
+ ];
942
944
  }
943
945
  var src_default = VitePlugin;
944
946
 
@@ -0,0 +1,2 @@
1
+
2
+ export { }