@storybook-astro/framework 1.2.0 → 1.3.0-canary.1

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 (85) hide show
  1. package/dist/{base-IRZo3zgK.d.ts → base-DT67T5pi.d.ts} +1 -0
  2. package/dist/{chunk-T7NWIO5S.js → chunk-2EABPTOY.js} +5 -5
  3. package/dist/{chunk-PJEDXZVN.js → chunk-7YBE4TTI.js} +2 -1
  4. package/dist/chunk-7YBE4TTI.js.map +1 -0
  5. package/dist/{chunk-POHTFYST.js → chunk-AYYMNFI6.js} +104 -6
  6. package/dist/chunk-AYYMNFI6.js.map +1 -0
  7. package/dist/chunk-B5HHF6FC.js +116 -0
  8. package/dist/chunk-B5HHF6FC.js.map +1 -0
  9. package/dist/chunk-H3XZHW6Z.js +1402 -0
  10. package/dist/chunk-H3XZHW6Z.js.map +1 -0
  11. package/dist/{chunk-DNGQBPT7.js → chunk-PUTCAN6X.js} +5 -2
  12. package/dist/{chunk-DNGQBPT7.js.map → chunk-PUTCAN6X.js.map} +1 -1
  13. package/dist/{chunk-OUEDTRBO.js → chunk-TWAO2IQW.js} +229 -67
  14. package/dist/chunk-TWAO2IQW.js.map +1 -0
  15. package/dist/{chunk-4SWPVM6R.js → chunk-WUTCMEF5.js} +2 -2
  16. package/dist/index.d.ts +17 -7
  17. package/dist/index.js +6 -5
  18. package/dist/index.js.map +1 -1
  19. package/dist/integrations/index.d.ts +2 -1
  20. package/dist/integrations/index.js +1 -1
  21. package/dist/middleware.js +18 -131
  22. package/dist/middleware.js.map +1 -1
  23. package/dist/{types-C-jan6Px.d.ts → preset-BvgHg2of.d.ts} +8 -11
  24. package/dist/preset.d.ts +2 -10
  25. package/dist/preset.js +5 -4
  26. package/dist/renderer/renderer-dev.js +62 -0
  27. package/dist/renderer/renderer-dev.js.map +1 -0
  28. package/dist/renderer/renderer-server.js +92 -0
  29. package/dist/renderer/renderer-server.js.map +1 -0
  30. package/dist/renderer/renderer-static.js +54 -0
  31. package/dist/renderer/renderer-static.js.map +1 -0
  32. package/dist/testing.js +12 -11
  33. package/dist/testing.js.map +1 -1
  34. package/dist/{viteStorybookAstroMiddlewarePlugin-2EFKTECT.js → viteStorybookAstroMiddlewarePlugin-UB6ZLJ4B.js} +4 -3
  35. package/dist/vitest/global-setup.js +6 -5
  36. package/dist/vitest/global-setup.js.map +1 -1
  37. package/dist/vitest/index.d.ts +1 -1
  38. package/dist/vitest/index.js +3 -3
  39. package/package.json +14 -43
  40. package/src/astroImageService.ts +57 -0
  41. package/src/astroRenderHandler.ts +203 -0
  42. package/src/importAstroConfig.ts +1 -1
  43. package/src/index.ts +2 -0
  44. package/src/integrations/alpine.ts +1 -0
  45. package/src/integrations/base.ts +6 -0
  46. package/src/middleware.ts +29 -200
  47. package/src/module-mocks.ts +153 -5
  48. package/src/preset.ts +38 -8
  49. package/src/productionRenderRuntime.ts +187 -0
  50. package/src/rules.test.ts +52 -4
  51. package/src/rules.ts +54 -7
  52. package/src/server/index.ts +101 -31
  53. package/src/storyRulesRuntime.ts +34 -0
  54. package/src/storySsrVite.ts +240 -0
  55. package/src/types.ts +0 -9
  56. package/src/virtual.d.ts +17 -3
  57. package/src/vite/{astroFilesVirtualModulePlugin.ts → astroFilesPlugin.ts} +4 -4
  58. package/src/vite/sanitizeConfigPlugin.ts +18 -0
  59. package/src/vite/{storybookAstroServerAuthConfigVirtualModulePlugin.test.ts → serverAuthPlugin.test.ts} +7 -10
  60. package/src/vite/{storybookAstroServerAuthConfigVirtualModulePlugin.ts → serverAuthPlugin.ts} +6 -9
  61. package/src/vite/serverRuntimePlugin.ts +109 -0
  62. package/src/vite/{storybookAstroRulesConfigVirtualModulePlugin.ts → storyRulesPlugin.ts} +6 -7
  63. package/src/vite/{createVirtualModulePlugin.test.ts → virtualModulePlugin.test.ts} +5 -5
  64. package/src/vite/{createVirtualModulePlugin.ts → virtualModulePlugin.ts} +2 -2
  65. package/src/viteAstroContainerRenderersPlugin.ts +72 -2
  66. package/src/vitePluginAstroBuildPrerender.ts +75 -646
  67. package/src/vitePluginAstroBuildServer.ts +217 -165
  68. package/src/vitePluginAstroBuildShared.test.ts +87 -0
  69. package/src/vitePluginAstroBuildShared.ts +465 -0
  70. package/src/vitePluginStoryModuleMocks.ts +29 -0
  71. package/src/viteStorybookAstroMiddlewarePlugin.ts +8 -0
  72. package/src/viteStorybookAstroRendererPlugin.ts +13 -6
  73. package/src/viteStorybookRendererFallbackPlugin.ts +2 -2
  74. package/dist/chunk-OUEDTRBO.js.map +0 -1
  75. package/dist/chunk-PBISP7PA.js +0 -1137
  76. package/dist/chunk-PBISP7PA.js.map +0 -1
  77. package/dist/chunk-PJEDXZVN.js.map +0 -1
  78. package/dist/chunk-POHTFYST.js.map +0 -1
  79. package/dist/node/index.d.ts +0 -10
  80. package/dist/node/index.js +0 -10
  81. package/dist/node/index.js.map +0 -1
  82. package/src/vite/storybookAstroSanitizationConfigVirtualModulePlugin.ts +0 -21
  83. /package/dist/{chunk-T7NWIO5S.js.map → chunk-2EABPTOY.js.map} +0 -0
  84. /package/dist/{chunk-4SWPVM6R.js.map → chunk-WUTCMEF5.js.map} +0 -0
  85. /package/dist/{viteStorybookAstroMiddlewarePlugin-2EFKTECT.js.map → viteStorybookAstroMiddlewarePlugin-UB6ZLJ4B.js.map} +0 -0
@@ -1,1137 +0,0 @@
1
- import {
2
- installPassthroughImageService,
3
- resolveSanitizationOptions,
4
- resolveStoryModuleMock,
5
- sanitizeRenderPayload,
6
- selectStoryRules,
7
- serializeSanitizationOptions,
8
- withStoryModuleMocks,
9
- withStoryRuleCleanups
10
- } from "./chunk-OUEDTRBO.js";
11
- import {
12
- createVirtualModulePlugin,
13
- resolveRulesConfigFilePath,
14
- ssrLoadModuleWithFsFallback,
15
- viteAstroContainerRenderersPlugin,
16
- vitePluginAstroFontsFallback,
17
- vitePluginAstroIntegrationOptsFallback,
18
- vitePluginAstroRoutesFallback,
19
- vitePluginAstroVueFallback,
20
- vitePluginStorybookAstroMiddleware
21
- } from "./chunk-POHTFYST.js";
22
- import {
23
- vitePluginAstroComponentMarker
24
- } from "./chunk-E4LB75JN.js";
25
- import {
26
- importAstroConfig
27
- } from "./chunk-DNGQBPT7.js";
28
-
29
- // src/viteStorybookRendererFallbackPlugin.ts
30
- function viteStorybookRendererFallbackPlugin(integrations) {
31
- const safeIntegrations = integrations ?? [];
32
- return createVirtualModulePlugin({
33
- pluginName: "storybook-renderer-fallback",
34
- virtualModuleId: "virtual:storybook-renderer-fallback",
35
- load() {
36
- return safeIntegrations.filter((integration) => integration.storybookEntryPreview).map(
37
- (integration) => `export * as ${integration.name} from '${integration.storybookEntryPreview}';`
38
- ).join("\n");
39
- }
40
- });
41
- }
42
-
43
- // src/viteStorybookAstroRendererPlugin.ts
44
- var packageName = "@storybook-astro/framework";
45
- function viteStorybookAstroRendererPlugin(options) {
46
- const pluginName = "storybook-astro:renderer-module";
47
- const virtualModuleId = "virtual:storybook-astro-renderer";
48
- const isProduction = options.mode === "production";
49
- const isStaticMode = options.renderMode === "static";
50
- return createVirtualModulePlugin({
51
- pluginName,
52
- virtualModuleId,
53
- load() {
54
- if (!isProduction) {
55
- return `export * from '${packageName}/renderer/renderer-dev.ts';`;
56
- }
57
- if (isStaticMode) {
58
- return `export * from '${packageName}/renderer/renderer-static.ts';`;
59
- }
60
- return [
61
- `import { createServerRenderer } from '${packageName}/renderer/renderer-server.ts';`,
62
- `const renderer = createServerRenderer(${JSON.stringify(
63
- {
64
- serverUrl: options.server?.serverUrl,
65
- authToken: options.server?.authToken,
66
- authHeader: options.server?.authHeader
67
- },
68
- null,
69
- 2
70
- )});`,
71
- "export const render = renderer.render;",
72
- "export const init = renderer.init;",
73
- "export const applyStyles = renderer.applyStyles;"
74
- ].join("\n");
75
- }
76
- });
77
- }
78
-
79
- // src/vitePluginAstroBuildPrerender.ts
80
- import { createRequire } from "module";
81
- import { mkdir, readFile, readdir, writeFile } from "fs/promises";
82
- import { resolve } from "path";
83
- import { createServer, mergeConfig } from "vite";
84
- var PRERENDERED_STORIES_FILE = "astro-prerendered-stories.json";
85
- function vitePluginAstroBuildPrerender(options) {
86
- const integrations = options.integrations ?? [];
87
- const resolveFrom = options.resolveFrom ?? process.cwd();
88
- const storyRulesConfigFilePath = resolveRulesConfigFilePath(options.storyRules, resolveFrom);
89
- const trackedSpecifiers = collectTrackedSpecifiers(integrations);
90
- const staticEntrypointRefs = /* @__PURE__ */ new Map();
91
- const componentEntrypointRefs = /* @__PURE__ */ new Map();
92
- let outDir = resolve(resolveFrom, "storybook-static");
93
- return {
94
- name: "storybook-astro:build-prerender",
95
- apply: "build",
96
- enforce: "post",
97
- configResolved(config) {
98
- outDir = resolve(resolveFrom, config.build.outDir ?? "storybook-static");
99
- },
100
- resolveId(id) {
101
- if (id.startsWith("virtual:astro-static-module/")) {
102
- return `\0${id}`;
103
- }
104
- if (id.startsWith("virtual:astro-component-module/")) {
105
- return `\0${id}`;
106
- }
107
- },
108
- load(id) {
109
- if (id.startsWith("\0virtual:astro-static-module/")) {
110
- const encodedSpecifier = id.replace("\0virtual:astro-static-module/", "");
111
- const specifier = decodeURIComponent(encodedSpecifier);
112
- if (isClientEntrypoint(specifier)) {
113
- return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join("\n");
114
- }
115
- return [`import '${specifier}';`, "export default undefined;"].join("\n");
116
- }
117
- if (id.startsWith("\0virtual:astro-component-module/")) {
118
- const withoutPrefix = id.replace("\0virtual:astro-component-module/", "");
119
- const encodedSpecifier = withoutPrefix.replace(/\?.*$/, "");
120
- const specifier = decodeURIComponent(encodedSpecifier);
121
- return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join("\n");
122
- }
123
- },
124
- async buildStart() {
125
- integrations.forEach((integration) => {
126
- const entrypoint = integration.renderer.client?.entrypoint;
127
- if (entrypoint) {
128
- this.addWatchFile(entrypoint);
129
- }
130
- });
131
- trackedSpecifiers.forEach((specifier) => {
132
- const fileReferenceId = this.emitFile({
133
- type: "chunk",
134
- id: toStaticVirtualId(specifier)
135
- });
136
- staticEntrypointRefs.set(specifier, fileReferenceId);
137
- });
138
- const componentRootPaths = [
139
- resolve(resolveFrom, "src/components"),
140
- ...options.renderMode === "static" && options.componentRoots ? options.componentRoots.map((root) => resolve(resolveFrom, root)) : []
141
- ];
142
- const specifierArrays = await Promise.all(
143
- componentRootPaths.map((root) => collectHydratableSourceModules(root))
144
- );
145
- const specifiers = specifierArrays.flat();
146
- specifiers.forEach((specifier) => {
147
- const chunkId = /\.(svelte|vue)$/.test(specifier) ? specifier : toComponentVirtualId(specifier);
148
- const fileReferenceId = this.emitFile({ type: "chunk", id: chunkId });
149
- componentEntrypointRefs.set(specifier, fileReferenceId);
150
- });
151
- },
152
- async writeBundle(_outputOptions, bundle) {
153
- const staticModuleMap = buildStaticModuleMap(
154
- this,
155
- staticEntrypointRefs,
156
- componentEntrypointRefs
157
- );
158
- const stories = await collectAstroStories(outDir);
159
- if (stories.length === 0) {
160
- await writePrerenderedStoriesFile(outDir, {});
161
- return;
162
- }
163
- const prerenderedStories = await prerenderStories({
164
- stories,
165
- integrations,
166
- sanitization: options.sanitization,
167
- storyRulesConfigFilePath,
168
- staticModuleMap,
169
- trackedSpecifiers,
170
- resolveFrom,
171
- bundle
172
- });
173
- await writePrerenderedStoriesFile(outDir, prerenderedStories);
174
- }
175
- };
176
- }
177
- async function writePrerenderedStoriesFile(outDir, payload) {
178
- await mkdir(outDir, { recursive: true });
179
- await writeFile(resolve(outDir, PRERENDERED_STORIES_FILE), JSON.stringify(payload), "utf-8");
180
- }
181
- async function prerenderStories(options) {
182
- const sanitizationOptions = resolveSanitizationOptions(options.sanitization ?? void 0);
183
- const resolveClientModule = createClientModuleResolver(
184
- options.integrations,
185
- options.staticModuleMap
186
- );
187
- const viteServer = await createStorySsrServer(
188
- options.integrations,
189
- options.trackedSpecifiers,
190
- options.resolveFrom
191
- );
192
- const rulesConfigModule = await loadRulesConfigModule(viteServer, options.storyRulesConfigFilePath);
193
- const assetPathMap = buildAssetPathMap(options.bundle);
194
- installPassthroughImageService();
195
- try {
196
- const containerModule = await viteServer.ssrLoadModule("astro/container");
197
- const AstroContainerRuntime = containerModule.experimental_AstroContainer;
198
- const container = await AstroContainerRuntime.create({
199
- resolve: async (specifier) => {
200
- const mockedModule = resolveStoryModuleMock(specifier);
201
- if (mockedModule) {
202
- return mockedModule;
203
- }
204
- const resolution = resolveClientModule(specifier);
205
- if (resolution) {
206
- return resolution;
207
- }
208
- return specifier;
209
- }
210
- });
211
- await addContainerRenderers(container, options.integrations, resolveClientModule, viteServer);
212
- const output = {};
213
- for (const story of options.stories) {
214
- const selectedRules = await selectStoryRules({
215
- configModule: rulesConfigModule,
216
- configFilePath: options.storyRulesConfigFilePath,
217
- story: {
218
- id: story.id,
219
- title: story.title,
220
- name: story.name
221
- }
222
- });
223
- if (selectedRules.moduleMocks.size > 0) {
224
- viteServer.moduleGraph.invalidateAll();
225
- }
226
- const html = await withStoryRuleCleanups(selectedRules.cleanups, async () => {
227
- return withStoryModuleMocks(selectedRules.moduleMocks, async () => {
228
- const modulePath = resolveImportPath(story.importPath, options.resolveFrom);
229
- const storyModule = await viteServer.ssrLoadModule(modulePath);
230
- const meta = isRecord(storyModule.default) ? storyModule.default : {};
231
- const storyExport = isRecord(storyModule[story.exportName]) ? storyModule[story.exportName] : {};
232
- if (typeof meta.component !== "function") {
233
- throw new Error(
234
- `Unable to prerender story "${story.id}". Missing default export component in ${story.importPath}.`
235
- );
236
- }
237
- if (storyExport.component && storyExport.component !== meta.component) {
238
- return void 0;
239
- }
240
- const mergedArgs = mergeStoryArgs(toRecord(meta.args), toRecord(storyExport.args));
241
- const { args, slots } = separateSlots(mergedArgs);
242
- const processedArgs = await processImageMetadata(args);
243
- const sanitizedPayload = sanitizeRenderPayload(
244
- {
245
- args: processedArgs,
246
- slots
247
- },
248
- sanitizationOptions
249
- );
250
- return container.renderToString(
251
- patchCreateAstroCompat(meta.component),
252
- {
253
- props: sanitizedPayload.args,
254
- slots: sanitizedPayload.slots
255
- }
256
- );
257
- });
258
- });
259
- if (html !== void 0) {
260
- output[story.id] = rewriteAssetPaths(html, assetPathMap);
261
- }
262
- }
263
- return output;
264
- } finally {
265
- await viteServer.close();
266
- }
267
- }
268
- async function createStorySsrServer(integrations, trackedSpecifiers, resolveFrom) {
269
- const { getViteConfig, passthroughImageService } = await importAstroConfig(resolveFrom);
270
- const astroConfig = await getViteConfig(
271
- { root: resolveFrom },
272
- {
273
- configFile: false,
274
- integrations: await Promise.all(
275
- integrations.map((integration) => integration.loadIntegration(resolveFrom))
276
- ),
277
- // Use the passthrough image service so nested components that use <Image>
278
- // from astro:assets render as plain <img> tags without triggering image
279
- // optimization (which fails in the Storybook SSR context).
280
- image: { service: passthroughImageService() }
281
- }
282
- )({
283
- mode: "production",
284
- command: "serve"
285
- });
286
- const config = mergeConfig(astroConfig, {
287
- appType: "custom",
288
- server: {
289
- middlewareMode: true
290
- },
291
- ssr: {
292
- // Force Astro runtime modules to be loaded through Vite's SSR transform
293
- // pipeline rather than being externalized via Node.js native import().
294
- // Without this, the AstroContainer (loaded via ssrLoadModule) and the
295
- // component rendering pipeline may resolve internal classes like
296
- // SlotString/HTMLString from separate module instances, causing
297
- // instanceof checks to fail and slot HTML to be escaped.
298
- noExternal: /^astro(\/.+)?$/
299
- },
300
- plugins: [
301
- createProjectAstroResolutionPlugin(resolveFrom),
302
- vitePluginAstroFontsFallback(),
303
- vitePluginAstroIntegrationOptsFallback(),
304
- vitePluginAstroVueFallback(),
305
- vitePluginAstroRoutesFallback(),
306
- {
307
- name: "storybook-astro:static-prerender-ssr-stubs",
308
- resolveId(id) {
309
- if (trackedSpecifiers.has(id)) {
310
- return `\0storybook-astro-static-prerender-stub:${encodeURIComponent(id)}`;
311
- }
312
- },
313
- load(id) {
314
- if (id.startsWith("\0storybook-astro-static-prerender-stub:")) {
315
- return "export default undefined;";
316
- }
317
- }
318
- }
319
- ]
320
- });
321
- return createServer(config);
322
- }
323
- async function loadRulesConfigModule(viteServer, configFilePath) {
324
- if (!configFilePath) {
325
- return void 0;
326
- }
327
- try {
328
- return await ssrLoadModuleWithFsFallback(viteServer, configFilePath, {
329
- fixStacktrace: true
330
- });
331
- } catch (error) {
332
- const reason = error instanceof Error ? error.message : String(error);
333
- throw new Error(
334
- `Unable to load framework.options.storyRules config module at ${configFilePath}: ${reason}`
335
- );
336
- }
337
- }
338
- async function addContainerRenderers(container, integrations, resolveClientModule, viteServer) {
339
- for (const integration of integrations) {
340
- const serverRenderer = integration.renderer.server;
341
- if (serverRenderer) {
342
- const serverRendererModule = await viteServer.ssrLoadModule(serverRenderer.entrypoint);
343
- const renderer = serverRendererModule.default ?? serverRendererModule;
344
- if (integration.name === "solid" && isRecord(renderer)) {
345
- container.addServerRenderer({
346
- name: serverRenderer.name,
347
- renderer: {
348
- ...renderer,
349
- name: serverRenderer.name
350
- }
351
- });
352
- } else {
353
- container.addServerRenderer({
354
- name: serverRenderer.name,
355
- renderer
356
- });
357
- }
358
- }
359
- const clientRenderer = integration.renderer.client;
360
- if (clientRenderer) {
361
- const resolvedEntrypoint = resolveClientModule(clientRenderer.entrypoint) ?? clientRenderer.entrypoint;
362
- container.addClientRenderer({
363
- name: clientRenderer.name,
364
- entrypoint: resolvedEntrypoint
365
- });
366
- }
367
- }
368
- }
369
- function createClientModuleResolver(integrations, staticModuleMap) {
370
- return function resolveClientModule(specifier) {
371
- if (Object.hasOwn(staticModuleMap, specifier)) {
372
- return staticModuleMap[specifier];
373
- }
374
- const normalizedSpecifier = specifier.replace(/\\/g, "/").replace(/\?.*$/, "");
375
- if (Object.hasOwn(staticModuleMap, normalizedSpecifier)) {
376
- return staticModuleMap[normalizedSpecifier];
377
- }
378
- for (const integration of integrations) {
379
- const resolution = integration.resolveClient(specifier);
380
- if (resolution) {
381
- return resolution;
382
- }
383
- }
384
- };
385
- }
386
- async function collectAstroStories(outDir) {
387
- const indexFile = resolve(outDir, "index.json");
388
- const indexRaw = await readFile(indexFile, "utf-8");
389
- const indexJson = JSON.parse(indexRaw);
390
- return Object.values(indexJson.entries ?? {}).filter((entry) => entry.type === "story" && entry.componentPath?.endsWith(".astro")).map((entry) => {
391
- if (!entry.id || !entry.importPath || !entry.exportName) {
392
- throw new Error(`Encountered an invalid Storybook index entry in ${indexFile}.`);
393
- }
394
- return {
395
- id: entry.id,
396
- importPath: entry.importPath,
397
- exportName: entry.exportName,
398
- title: entry.title,
399
- name: entry.name
400
- };
401
- });
402
- }
403
- function mergeStoryArgs(metaArgs, storyArgs) {
404
- return {
405
- ...metaArgs ?? {},
406
- ...storyArgs ?? {}
407
- };
408
- }
409
- function separateSlots(inputArgs) {
410
- const args = { ...inputArgs };
411
- const slotsCandidate = args.slots;
412
- delete args.slots;
413
- if (!isRecord(slotsCandidate)) {
414
- return {
415
- args,
416
- slots: {}
417
- };
418
- }
419
- return {
420
- args,
421
- slots: slotsCandidate
422
- };
423
- }
424
- function resolveImportPath(importPath, resolveFrom) {
425
- if (importPath.startsWith("./")) {
426
- return resolve(resolveFrom, importPath.slice(2));
427
- }
428
- return resolve(resolveFrom, importPath);
429
- }
430
- function isRecord(value) {
431
- return typeof value === "object" && value !== null;
432
- }
433
- function toRecord(value) {
434
- if (!isRecord(value)) {
435
- return void 0;
436
- }
437
- return value;
438
- }
439
- function collectTrackedSpecifiers(integrations) {
440
- const specifiers = /* @__PURE__ */ new Set(["astro:scripts/page.js", "astro:scripts/before-hydration.js"]);
441
- integrations.forEach((integration) => {
442
- const entrypoint = integration.renderer.client?.entrypoint;
443
- if (entrypoint) {
444
- specifiers.add(entrypoint);
445
- }
446
- });
447
- return specifiers;
448
- }
449
- function buildStaticModuleMap(pluginContext, staticEntrypointRefs, componentEntrypointRefs) {
450
- const map = {};
451
- staticEntrypointRefs.forEach((fileReferenceId, specifier) => {
452
- const fileName = pluginContext.getFileName(fileReferenceId);
453
- if (fileName) {
454
- map[specifier] = toPublicPath(fileName);
455
- }
456
- });
457
- componentEntrypointRefs.forEach((fileReferenceId, specifier) => {
458
- const fileName = pluginContext.getFileName(fileReferenceId);
459
- if (fileName) {
460
- map[specifier] = toPublicPath(fileName);
461
- }
462
- });
463
- return map;
464
- }
465
- function toStaticVirtualId(specifier) {
466
- return `virtual:astro-static-module/${encodeURIComponent(specifier)}`;
467
- }
468
- function toComponentVirtualId(specifier) {
469
- return `virtual:astro-component-module/${encodeURIComponent(specifier)}?component-wrapper`;
470
- }
471
- function isClientEntrypoint(specifier) {
472
- return specifier.startsWith("@astrojs/") && specifier.endsWith("/client.js");
473
- }
474
- function toPublicPath(fileName) {
475
- return `./${fileName}`;
476
- }
477
- function buildAssetPathMap(bundle) {
478
- const exactMap = /* @__PURE__ */ new Map();
479
- const stemMap = /* @__PURE__ */ new Map();
480
- for (const chunk of Object.values(bundle)) {
481
- if (chunk.type !== "asset") {
482
- continue;
483
- }
484
- const asset = chunk;
485
- if (asset.originalFileNames && asset.originalFileNames.length > 0) {
486
- for (const originalPath of asset.originalFileNames) {
487
- exactMap.set(originalPath, `/${asset.fileName}`);
488
- }
489
- }
490
- const baseName = asset.fileName.split("/").pop() ?? "";
491
- const stemMatch = baseName.match(/^(.+)-[A-Za-z0-9]{6,12}\.(png|jpe?g|gif|webp|svg|avif|ico)$/);
492
- if (stemMatch) {
493
- stemMap.set(`${stemMatch[1]}.${stemMatch[2]}`, `/${asset.fileName}`);
494
- }
495
- }
496
- return { exactMap, stemMap };
497
- }
498
- function rewriteAssetPaths(html, assetPathMap) {
499
- const { exactMap, stemMap } = assetPathMap;
500
- if (exactMap.size === 0 && stemMap.size === 0) {
501
- return html;
502
- }
503
- return html.replace(/\/@fs\/[^"']+/g, (match) => {
504
- const pathOnly = match.replace(/\?.*$/, "");
505
- const fsPath = pathOnly.slice("/@fs".length);
506
- const absolutePath = fsPath.startsWith("//") ? fsPath.slice(1) : fsPath;
507
- const exact = exactMap.get(absolutePath);
508
- if (exact) {
509
- return exact;
510
- }
511
- const baseName = absolutePath.split("/").pop() ?? "";
512
- const stemHit = stemMap.get(baseName);
513
- if (stemHit) {
514
- return stemHit;
515
- }
516
- return match;
517
- });
518
- }
519
- async function collectHydratableSourceModules(srcRoot) {
520
- const modules = [];
521
- async function walk(directory) {
522
- let entries;
523
- try {
524
- entries = await readdir(directory, { withFileTypes: true });
525
- } catch {
526
- return;
527
- }
528
- await Promise.all(
529
- entries.map(async (entry) => {
530
- const absolutePath = resolve(directory, entry.name);
531
- if (entry.isDirectory()) {
532
- await walk(absolutePath);
533
- return;
534
- }
535
- if (!entry.isFile()) {
536
- return;
537
- }
538
- const normalizedPath = absolutePath.replace(/\\/g, "/");
539
- if (!isHydratableSourceFile(normalizedPath)) {
540
- return;
541
- }
542
- if (isNonHydratableSourceFile(normalizedPath)) {
543
- return;
544
- }
545
- modules.push(normalizedPath);
546
- })
547
- );
548
- }
549
- await walk(srcRoot);
550
- return modules;
551
- }
552
- function isHydratableSourceFile(input) {
553
- return /\.(jsx|tsx|vue|svelte)$/.test(input);
554
- }
555
- function isNonHydratableSourceFile(input) {
556
- return /\.stories\.[jt]sx?$|\.stories\.vue$|\.stories\.svelte$|\.(spec|test)\.[jt]sx?$/.test(
557
- input
558
- );
559
- }
560
- function patchCreateAstroCompat(component) {
561
- if (typeof component !== "function") {
562
- throw new Error("Expected Astro component factory to be a function.");
563
- }
564
- const originalComponent = component;
565
- const wrapped = ((result, props, slots) => {
566
- if (result && typeof result.createAstro === "function") {
567
- const originalCreateAstro = result.createAstro;
568
- const runtimeExpectsAstroGlobal = originalCreateAstro.length >= 3;
569
- result.createAstro = (...args) => {
570
- if (args.length === 3 && !runtimeExpectsAstroGlobal) {
571
- return originalCreateAstro(args[1], args[2]);
572
- }
573
- return originalCreateAstro(...args);
574
- };
575
- }
576
- return originalComponent(result, props, slots);
577
- });
578
- wrapped.isAstroComponentFactory = originalComponent.isAstroComponentFactory;
579
- wrapped.moduleId = originalComponent.moduleId;
580
- wrapped.propagation = originalComponent.propagation;
581
- return wrapped;
582
- }
583
- async function processImageMetadata(args) {
584
- const processed = {};
585
- for (const [key, value] of Object.entries(args)) {
586
- if (isImageMetadata(value)) {
587
- processed[key] = value;
588
- continue;
589
- }
590
- if (Array.isArray(value)) {
591
- processed[key] = await Promise.all(
592
- value.map(async (item) => {
593
- if (isImageMetadata(item)) {
594
- return item;
595
- }
596
- if (isRecord(item)) {
597
- return processImageMetadata(item);
598
- }
599
- return item;
600
- })
601
- );
602
- continue;
603
- }
604
- if (isRecord(value)) {
605
- processed[key] = await processImageMetadata(value);
606
- continue;
607
- }
608
- processed[key] = value;
609
- }
610
- return processed;
611
- }
612
- function isImageMetadata(value) {
613
- return isRecord(value) && typeof value.src === "string" && ("width" in value || "height" in value || "format" in value);
614
- }
615
- function createProjectAstroResolutionPlugin(resolveFrom) {
616
- const require2 = createRequire(import.meta.url);
617
- return {
618
- name: "storybook-astro:resolve-project-astro-prerender",
619
- enforce: "pre",
620
- resolveId(id) {
621
- if (id !== "astro" && !id.startsWith("astro/")) {
622
- return null;
623
- }
624
- try {
625
- return require2.resolve(id, {
626
- paths: [resolveFrom]
627
- });
628
- } catch {
629
- return null;
630
- }
631
- }
632
- };
633
- }
634
-
635
- // src/vitePluginAstroBuildServer.ts
636
- import { readdir as readdir2 } from "fs/promises";
637
- import { dirname, resolve as resolve2 } from "path";
638
- import { fileURLToPath } from "url";
639
- import { build } from "vite";
640
-
641
- // src/vitePluginAstro.ts
642
- import { mergeConfig as mergeConfig2 } from "vite";
643
- var ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK = [
644
- "@astro/plugin-actions",
645
- "@astrojs/vite-plugin-astro-ssr-manifest",
646
- "astro-content-virtual-mod-plugin",
647
- "astro:actions",
648
- "astro:build:normal",
649
- "astro:container",
650
- "astro:content-asset-propagation",
651
- "astro:content-imports",
652
- "astro:content-listen",
653
- "astro:dev-toolbar",
654
- "astro:head-metadata",
655
- "astro:html",
656
- "astro:i18n",
657
- "astro:integration-container",
658
- "astro:jsx",
659
- "astro:markdown",
660
- "astro:postprocess",
661
- "astro:prefetch",
662
- "astro:scanner",
663
- "astro:scripts:page-ssr",
664
- "astro:server",
665
- "astro:vite-plugin-env",
666
- "astro:vite-plugin-file-url"
667
- ];
668
- async function mergeWithAstroConfig(config, integrations = [], resolveFrom = process.cwd(), mode = "development", command = "serve") {
669
- const { getViteConfig } = await importAstroConfig(resolveFrom);
670
- const safeIntegrations = integrations ?? [];
671
- const astroConfig = await getViteConfig(
672
- {},
673
- {
674
- configFile: false,
675
- integrations: await Promise.all(
676
- safeIntegrations.map((integration) => integration.loadIntegration(resolveFrom))
677
- )
678
- }
679
- )({
680
- mode,
681
- command
682
- });
683
- const filteredPlugins = astroConfig.plugins.flat().filter(
684
- (plugin) => plugin && "name" in plugin && !ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK.includes(plugin.name)
685
- );
686
- return mergeConfig2(config, {
687
- ...astroConfig,
688
- plugins: filteredPlugins
689
- });
690
- }
691
-
692
- // src/vite/astroFilesVirtualModulePlugin.ts
693
- function astroFilesVirtualModulePlugin(astroComponents) {
694
- return createVirtualModulePlugin({
695
- pluginName: "storybook-astro:virtual-astro-files",
696
- virtualModuleId: "virtual:astro-files",
697
- load() {
698
- const imports = astroComponents.reduce((records, file, index) => {
699
- const moduleId = `_astroFile${index}`;
700
- return [
701
- ...records,
702
- {
703
- id: moduleId,
704
- file,
705
- importStatement: `import ${moduleId} from '${file}';`
706
- }
707
- ];
708
- }, []);
709
- return [
710
- imports.map(({ importStatement }) => importStatement).join("\n"),
711
- "export default {",
712
- imports.map(({ file, id }) => `'${file}': ${id}`).join(",\n"),
713
- "};"
714
- ].join("\n");
715
- }
716
- });
717
- }
718
-
719
- // src/vite/storybookAstroRulesConfigVirtualModulePlugin.ts
720
- var STORYBOOK_ASTRO_STORY_RULES_CONFIG_VIRTUAL_MODULE_ID = "virtual:storybook-astro-story-rules-config";
721
- function storybookAstroStoryRulesConfigVirtualModulePlugin(options, resolveFrom = process.cwd()) {
722
- return createVirtualModulePlugin({
723
- pluginName: "storybook-astro:virtual-story-rules-config",
724
- virtualModuleId: STORYBOOK_ASTRO_STORY_RULES_CONFIG_VIRTUAL_MODULE_ID,
725
- load() {
726
- const configFilePath = resolveRulesConfigFilePath(options, resolveFrom);
727
- if (!configFilePath) {
728
- return [
729
- "const storybookAstroStoryRulesConfig = { rules: [] };",
730
- "export default storybookAstroStoryRulesConfig;",
731
- "export const storybookAstroStoryRulesConfigFilePath = undefined;"
732
- ].join("\n");
733
- }
734
- const importPath = JSON.stringify(configFilePath.replace(/\\/g, "/"));
735
- const configPath = JSON.stringify(configFilePath.replace(/\\/g, "/"));
736
- return [
737
- `import * as storybookAstroStoryRulesConfigModule from ${importPath};`,
738
- "export default storybookAstroStoryRulesConfigModule;",
739
- `export const storybookAstroStoryRulesConfigFilePath = ${configPath};`
740
- ].join("\n");
741
- }
742
- });
743
- }
744
-
745
- // src/vite/storybookAstroSanitizationConfigVirtualModulePlugin.ts
746
- var STORYBOOK_ASTRO_SANITIZATION_CONFIG_VIRTUAL_MODULE_ID = "virtual:storybook-astro-sanitization-config";
747
- function storybookAstroSanitizationConfigVirtualModulePlugin(options) {
748
- return createVirtualModulePlugin({
749
- pluginName: "storybook-astro:virtual-sanitization-config",
750
- virtualModuleId: STORYBOOK_ASTRO_SANITIZATION_CONFIG_VIRTUAL_MODULE_ID,
751
- load() {
752
- const serializedConfig = serializeSanitizationOptions(options);
753
- return `export default ${serializedConfig};`;
754
- }
755
- });
756
- }
757
-
758
- // src/vite/storybookAstroServerAuthConfigVirtualModulePlugin.ts
759
- var STORYBOOK_ASTRO_SERVER_AUTH_CONFIG_VIRTUAL_MODULE_ID = "virtual:storybook-astro-server-auth-config";
760
- function storybookAstroServerAuthConfigVirtualModulePlugin(options) {
761
- const authToken = normalizeOptionalString(options?.authToken);
762
- const authHeader = normalizeAuthHeader(options?.authHeader);
763
- return createVirtualModulePlugin({
764
- pluginName: "storybook-astro:virtual-server-auth-config",
765
- virtualModuleId: STORYBOOK_ASTRO_SERVER_AUTH_CONFIG_VIRTUAL_MODULE_ID,
766
- load() {
767
- return [
768
- `export const storybookAstroServerAuthToken = ${authToken ? JSON.stringify(authToken) : "undefined"};`,
769
- `export const storybookAstroServerAuthHeader = ${JSON.stringify(authHeader)};`
770
- ].join("\n");
771
- }
772
- });
773
- }
774
- function normalizeOptionalString(value) {
775
- if (!value) {
776
- return void 0;
777
- }
778
- const normalizedValue = value.trim();
779
- return normalizedValue || void 0;
780
- }
781
- function normalizeAuthHeader(value) {
782
- const normalizedValue = normalizeOptionalString(value);
783
- return (normalizedValue ?? "authorization").toLowerCase();
784
- }
785
-
786
- // src/vitePluginAstroBuildServer.ts
787
- var moduleRoot = resolve2(dirname(fileURLToPath(import.meta.url)), ".");
788
- var packageRoot = resolve2(moduleRoot, "..");
789
- function vitePluginAstroBuildServer(options) {
790
- const integrations = options.integrations ?? [];
791
- const resolveFrom = options.resolveFrom ?? process.cwd();
792
- const storiesMap = /* @__PURE__ */ new Map();
793
- const trackedSpecifiers = collectTrackedSpecifiers2(integrations);
794
- const staticEntrypointRefs = /* @__PURE__ */ new Map();
795
- const componentEntrypointRefs = /* @__PURE__ */ new Map();
796
- let storybookStaticOutDir = resolve2(resolveFrom, "storybook-static");
797
- return {
798
- name: "storybook-astro:build-server",
799
- apply: "build",
800
- enforce: "post",
801
- configResolved(config) {
802
- storybookStaticOutDir = resolve2(resolveFrom, config.build.outDir ?? "storybook-static");
803
- },
804
- resolveId(id, importer) {
805
- if (id.endsWith(".astro") && importer) {
806
- const absoluteAstroPath = resolve2(dirname(importer), id);
807
- if (!storiesMap.has(absoluteAstroPath)) {
808
- storiesMap.set(absoluteAstroPath, /* @__PURE__ */ new Set());
809
- }
810
- storiesMap.get(absoluteAstroPath)?.add(importer);
811
- }
812
- if (id.startsWith("virtual:astro-static-module/")) {
813
- return `\0${id}`;
814
- }
815
- if (id.startsWith("virtual:astro-component-module/")) {
816
- return `\0${id}`;
817
- }
818
- },
819
- load(id) {
820
- if (id.startsWith("\0virtual:astro-static-module/")) {
821
- const encodedSpecifier = id.replace("\0virtual:astro-static-module/", "");
822
- const specifier = decodeURIComponent(encodedSpecifier);
823
- if (isClientEntrypoint2(specifier)) {
824
- return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join("\n");
825
- }
826
- return [`import '${specifier}';`, "export default undefined;"].join("\n");
827
- }
828
- if (id.startsWith("\0virtual:astro-component-module/")) {
829
- const encodedSpecifier = id.replace("\0virtual:astro-component-module/", "");
830
- const specifier = decodeURIComponent(encodedSpecifier);
831
- return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join("\n");
832
- }
833
- },
834
- async buildStart() {
835
- integrations.forEach((integration) => {
836
- const entrypoint = integration.renderer.client?.entrypoint;
837
- if (entrypoint) {
838
- this.addWatchFile(entrypoint);
839
- }
840
- });
841
- trackedSpecifiers.forEach((specifier) => {
842
- const fileReferenceId = this.emitFile({
843
- type: "chunk",
844
- id: toStaticVirtualId2(specifier)
845
- });
846
- staticEntrypointRefs.set(specifier, fileReferenceId);
847
- });
848
- const srcRoot = resolve2(resolveFrom, "src/components");
849
- const specifiers = await collectHydratableSourceModules2(srcRoot);
850
- specifiers.forEach((specifier) => {
851
- const fileReferenceId = this.emitFile({
852
- type: "chunk",
853
- id: toComponentVirtualId2(specifier)
854
- });
855
- componentEntrypointRefs.set(specifier, fileReferenceId);
856
- });
857
- },
858
- async writeBundle() {
859
- const astroComponents = Array.from(storiesMap.keys());
860
- const staticModuleMap = buildStaticModuleMap2(
861
- this,
862
- staticEntrypointRefs,
863
- componentEntrypointRefs
864
- );
865
- const serverOutDir = resolve2(dirname(storybookStaticOutDir), "storybook-server");
866
- await buildAstroServer({
867
- astroComponents,
868
- integrations,
869
- sanitization: options.sanitization,
870
- storyRules: options.storyRules,
871
- server: options.server,
872
- outDir: serverOutDir,
873
- staticModuleMap,
874
- resolveFrom
875
- });
876
- }
877
- };
878
- }
879
- async function buildAstroServer(options) {
880
- const buildConfig = {
881
- root: resolve2(packageRoot, "src/server"),
882
- ssr: {
883
- noExternal: /(@astrojs\/.+|react|react-dom)/
884
- },
885
- build: {
886
- ssr: true,
887
- outDir: options.outDir,
888
- emptyOutDir: true,
889
- sourcemap: true,
890
- manifest: false,
891
- rollupOptions: {
892
- input: resolve2(packageRoot, "src/server/index.ts"),
893
- treeshake: true
894
- }
895
- },
896
- plugins: [
897
- astroFilesVirtualModulePlugin(options.astroComponents),
898
- storybookAstroSanitizationConfigVirtualModulePlugin(options.sanitization),
899
- storybookAstroStoryRulesConfigVirtualModulePlugin(options.storyRules, options.resolveFrom),
900
- storybookAstroServerAuthConfigVirtualModulePlugin(options.server),
901
- viteAstroContainerRenderersPlugin(options.integrations, {
902
- mode: "production",
903
- staticModuleMap: options.staticModuleMap
904
- })
905
- ]
906
- };
907
- const finalConfig = await mergeWithAstroConfig(
908
- buildConfig,
909
- options.integrations,
910
- options.resolveFrom,
911
- "production",
912
- "build"
913
- );
914
- await build(finalConfig);
915
- }
916
- function collectTrackedSpecifiers2(integrations) {
917
- const specifiers = /* @__PURE__ */ new Set(["astro:scripts/page.js", "astro:scripts/before-hydration.js"]);
918
- integrations.forEach((integration) => {
919
- const entrypoint = integration.renderer.client?.entrypoint;
920
- if (entrypoint) {
921
- specifiers.add(entrypoint);
922
- }
923
- });
924
- return specifiers;
925
- }
926
- function buildStaticModuleMap2(pluginContext, staticEntrypointRefs, componentEntrypointRefs) {
927
- const map = {};
928
- staticEntrypointRefs.forEach((fileReferenceId, specifier) => {
929
- const fileName = pluginContext.getFileName(fileReferenceId);
930
- if (fileName) {
931
- map[specifier] = toPublicPath2(fileName);
932
- }
933
- });
934
- componentEntrypointRefs.forEach((fileReferenceId, specifier) => {
935
- const fileName = pluginContext.getFileName(fileReferenceId);
936
- if (fileName) {
937
- map[specifier] = toPublicPath2(fileName);
938
- }
939
- });
940
- return map;
941
- }
942
- function toStaticVirtualId2(specifier) {
943
- return `virtual:astro-static-module/${encodeURIComponent(specifier)}`;
944
- }
945
- function toComponentVirtualId2(specifier) {
946
- return `virtual:astro-component-module/${encodeURIComponent(specifier)}`;
947
- }
948
- function isClientEntrypoint2(specifier) {
949
- return specifier.startsWith("@astrojs/") && specifier.endsWith("/client.js");
950
- }
951
- function toPublicPath2(fileName) {
952
- return `./${fileName}`;
953
- }
954
- async function collectHydratableSourceModules2(srcRoot) {
955
- const modules = [];
956
- async function walk(directory) {
957
- let entries;
958
- try {
959
- entries = await readdir2(directory, { withFileTypes: true });
960
- } catch {
961
- return;
962
- }
963
- await Promise.all(
964
- entries.map(async (entry) => {
965
- const absolutePath = resolve2(directory, entry.name);
966
- if (entry.isDirectory()) {
967
- await walk(absolutePath);
968
- return;
969
- }
970
- if (!entry.isFile()) {
971
- return;
972
- }
973
- const normalizedPath = absolutePath.replace(/\\/g, "/");
974
- if (!isHydratableSourceFile2(normalizedPath)) {
975
- return;
976
- }
977
- if (isNonHydratableSourceFile2(normalizedPath)) {
978
- return;
979
- }
980
- modules.push(normalizedPath);
981
- })
982
- );
983
- }
984
- await walk(srcRoot);
985
- return modules;
986
- }
987
- function isHydratableSourceFile2(input) {
988
- return /\.(jsx|tsx|vue|svelte|js|ts)$/.test(input);
989
- }
990
- function isNonHydratableSourceFile2(input) {
991
- return /\.stories\.[jt]sx?$|\.stories\.vue$|\.stories\.svelte$|\.(spec|test)\.[jt]sx?$/.test(
992
- input
993
- );
994
- }
995
-
996
- // src/vitePluginAstroToolbarFallback.ts
997
- var TOOLBAR_INTERNAL_STUB = `
998
- export const loadDevToolbarApps = async () => [];
999
- `;
1000
- function vitePluginAstroToolbarFallback() {
1001
- const VIRTUAL_ID = "astro:toolbar:internal";
1002
- const RESOLVED_ID = "\0" + VIRTUAL_ID;
1003
- return {
1004
- name: "storybook-astro-toolbar-fallback",
1005
- enforce: "pre",
1006
- resolveId(id) {
1007
- if (id === VIRTUAL_ID) {
1008
- return RESOLVED_ID;
1009
- }
1010
- },
1011
- load(id) {
1012
- if (id === RESOLVED_ID) {
1013
- return { code: TOOLBAR_INTERNAL_STUB };
1014
- }
1015
- }
1016
- };
1017
- }
1018
-
1019
- // src/preset.ts
1020
- var core = {
1021
- builder: "@storybook/builder-vite",
1022
- // Use import.meta.resolve so Storybook receives an absolute file:// URL
1023
- // to the renderer preset rather than a bare package specifier. When
1024
- // package managers like pnpm use strict node_modules isolation, bare
1025
- // specifiers are resolved from the *project root*, where the renderer
1026
- // (a dep of this framework, not the user's project) is not hoisted.
1027
- // The absolute URL is resolved from *this* file's location where the
1028
- // renderer is always accessible as a direct dependency.
1029
- renderer: import.meta.resolve("@storybook-astro/renderer")
1030
- };
1031
- var viteFinal = async (config, { configType, presets }) => {
1032
- const options = await presets.apply("frameworkOptions");
1033
- if (!config.plugins) {
1034
- config.plugins = [];
1035
- }
1036
- const integrations = options.integrations ?? [];
1037
- const resolveFrom = options.resolveFrom ?? process.cwd();
1038
- const renderMode = options.renderMode ?? "server";
1039
- const mode = configType === "DEVELOPMENT" ? "development" : "production";
1040
- const command = configType === "DEVELOPMENT" ? "serve" : "build";
1041
- resolveSanitizationOptions(options.sanitization);
1042
- config.envPrefix = mergeEnvPrefixes(config.envPrefix, "STORYBOOK_");
1043
- const { vitePlugin: storybookAstroMiddlewarePlugin, viteConfig } = await vitePluginStorybookAstroMiddleware(options);
1044
- config.plugins.push(
1045
- viteStorybookRendererFallbackPlugin(integrations),
1046
- viteStorybookAstroRendererPlugin({
1047
- mode,
1048
- renderMode,
1049
- server: options.server
1050
- }),
1051
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1052
- vitePluginAstroComponentMarker(),
1053
- vitePluginAstroIntegrationOptsFallback(),
1054
- vitePluginAstroToolbarFallback(),
1055
- vitePluginAstroVueFallback()
1056
- );
1057
- if (configType === "DEVELOPMENT") {
1058
- config.plugins.push(storybookAstroMiddlewarePlugin, ...viteConfig.plugins);
1059
- } else if (renderMode === "static") {
1060
- config.plugins.push(vitePluginAstroBuildPrerender(options));
1061
- } else {
1062
- config.plugins.push(vitePluginAstroBuildServer(options));
1063
- }
1064
- if (configType !== "DEVELOPMENT") {
1065
- config.build = {
1066
- ...config.build ?? {},
1067
- manifest: true
1068
- };
1069
- config.build.rollupOptions = {
1070
- ...config.build.rollupOptions ?? {},
1071
- preserveEntrySignatures: "strict"
1072
- };
1073
- }
1074
- if (!config.resolve) {
1075
- config.resolve = {};
1076
- }
1077
- if (!config.resolve.alias) {
1078
- config.resolve.alias = {};
1079
- }
1080
- const aliases = config.resolve.alias;
1081
- if (!aliases["react"]) {
1082
- aliases["react"] = "react";
1083
- }
1084
- if (!aliases["react-dom"]) {
1085
- aliases["react-dom"] = "react-dom";
1086
- }
1087
- const finalConfig = await mergeWithAstroConfig(config, integrations, resolveFrom, mode, command);
1088
- if (!finalConfig.optimizeDeps) {
1089
- finalConfig.optimizeDeps = {};
1090
- }
1091
- if (!finalConfig.optimizeDeps.exclude) {
1092
- finalConfig.optimizeDeps.exclude = [];
1093
- }
1094
- for (const pkg of ["@astrojs/vue", "@astrojs/react", "@astrojs/preact"]) {
1095
- if (!finalConfig.optimizeDeps.exclude.includes(pkg)) {
1096
- finalConfig.optimizeDeps.exclude.push(pkg);
1097
- }
1098
- }
1099
- if (!finalConfig.optimizeDeps.exclude.includes("@storybook-astro/renderer")) {
1100
- finalConfig.optimizeDeps.exclude.push("@storybook-astro/renderer");
1101
- }
1102
- const integrationVirtualModules = [
1103
- "virtual:@astrojs/vue/app",
1104
- "virtual:astro:vue-app",
1105
- "astro:react:opts",
1106
- "astro:preact:opts",
1107
- "astro:toolbar:internal"
1108
- ];
1109
- if (!finalConfig.optimizeDeps.esbuildOptions) {
1110
- finalConfig.optimizeDeps.esbuildOptions = {};
1111
- }
1112
- if (!finalConfig.optimizeDeps.esbuildOptions.external) {
1113
- finalConfig.optimizeDeps.esbuildOptions.external = [];
1114
- }
1115
- for (const mod of integrationVirtualModules) {
1116
- if (!finalConfig.optimizeDeps.esbuildOptions.external.includes(mod)) {
1117
- finalConfig.optimizeDeps.esbuildOptions.external.push(mod);
1118
- }
1119
- }
1120
- const optimizeDepsMut = finalConfig.optimizeDeps;
1121
- const rolldownOpts = optimizeDepsMut.rolldownOptions ?? {};
1122
- rolldownOpts.external = Array.from(
1123
- /* @__PURE__ */ new Set([...rolldownOpts.external ?? [], ...integrationVirtualModules])
1124
- );
1125
- optimizeDepsMut.rolldownOptions = rolldownOpts;
1126
- return finalConfig;
1127
- };
1128
- function mergeEnvPrefixes(existing, additionalPrefix) {
1129
- const prefixes = Array.isArray(existing) ? existing : existing ? [existing] : [];
1130
- return Array.from(/* @__PURE__ */ new Set([...prefixes, additionalPrefix]));
1131
- }
1132
-
1133
- export {
1134
- core,
1135
- viteFinal
1136
- };
1137
- //# sourceMappingURL=chunk-PBISP7PA.js.map