@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
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/preset.ts","../src/viteStorybookRendererFallbackPlugin.ts","../src/viteStorybookAstroRendererPlugin.ts","../src/vitePluginAstroBuildPrerender.ts","../src/vitePluginAstroBuildShared.ts","../src/productionRenderRuntime.ts","../src/storySsrVite.ts","../src/vitePluginAstroBuildServer.ts","../src/vitePluginAstro.ts","../src/vite/sanitizeConfigPlugin.ts","../src/vite/serverAuthPlugin.ts","../src/vite/serverRuntimePlugin.ts","../src/vitePluginAstroToolbarFallback.ts"],"sourcesContent":["import { dirname } from 'node:path';\nimport type { StorybookConfigVite, FrameworkOptions } from './types.ts';\nimport { vitePluginStorybookAstroMiddleware } from './viteStorybookAstroMiddlewarePlugin.ts';\nimport { viteStorybookRendererFallbackPlugin } from './viteStorybookRendererFallbackPlugin.ts';\nimport { viteStorybookAstroRendererPlugin } from './viteStorybookAstroRendererPlugin.ts';\nimport { vitePluginAstroComponentMarker } from './vitePluginAstroComponentMarker.ts';\nimport { vitePluginAstroBuildPrerender } from './vitePluginAstroBuildPrerender.ts';\nimport { vitePluginAstroBuildServer } from './vitePluginAstroBuildServer.ts';\nimport { vitePluginAstroIntegrationOptsFallback } from './vitePluginAstroIntegrationOptsFallback.ts';\nimport { vitePluginAstroVueFallback } from './vitePluginAstroVueFallback.ts';\nimport { vitePluginAstroToolbarFallback } from './vitePluginAstroToolbarFallback.ts';\nimport { resolveSanitizationOptions } from './lib/sanitization.ts';\nimport { mergeWithAstroConfig } from './vitePluginAstro.ts';\n\nexport const core = {\n builder: '@storybook/builder-vite',\n // Use import.meta.resolve so Storybook receives an absolute file:// URL\n // to the renderer preset rather than a bare package specifier. When\n // package managers like pnpm use strict node_modules isolation, bare\n // specifiers are resolved from the *project root*, where the renderer\n // (a dep of this framework, not the user's project) is not hoisted.\n // The absolute URL is resolved from *this* file's location where the\n // renderer is always accessible as a direct dependency.\n renderer: import.meta.resolve('@storybook-astro/renderer')\n};\n\nexport const viteFinal: StorybookConfigVite['viteFinal'] = async (config, storybookOptions) => {\n const { configType, presets, configDir } = storybookOptions;\n const frameworkOptions = await presets.apply<FrameworkOptions>('frameworkOptions');\n const options = {\n ...frameworkOptions,\n resolveFrom: frameworkOptions.resolveFrom ?? dirname(configDir)\n } satisfies FrameworkOptions;\n\n if (!config.plugins) {\n config.plugins = [];\n }\n\n const integrations = options.integrations ?? [];\n const renderMode = options.renderMode ?? 'server';\n const mode = configType === 'DEVELOPMENT' ? 'development' : 'production';\n const command = configType === 'DEVELOPMENT' ? 'serve' : 'build';\n\n resolveSanitizationOptions(options.sanitization);\n\n config.envPrefix = mergeEnvPrefixes(config.envPrefix, 'STORYBOOK_');\n\n const { vitePlugin: storybookAstroMiddlewarePlugin, viteConfig } =\n await vitePluginStorybookAstroMiddleware(options);\n\n config.plugins.push(\n viteStorybookRendererFallbackPlugin(integrations),\n viteStorybookAstroRendererPlugin({\n mode,\n renderMode,\n server: options.server\n }),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n vitePluginAstroComponentMarker() as any,\n vitePluginAstroIntegrationOptsFallback(),\n vitePluginAstroToolbarFallback(),\n vitePluginAstroVueFallback()\n );\n\n if (configType === 'DEVELOPMENT') {\n config.plugins.push(storybookAstroMiddlewarePlugin, ...viteConfig.plugins);\n } else if (renderMode === 'static') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config.plugins.push(vitePluginAstroBuildPrerender(options) as any);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config.plugins.push(vitePluginAstroBuildServer(options) as any);\n }\n\n if (configType !== 'DEVELOPMENT') {\n config.build = {\n ...(config.build ?? {}),\n manifest: true\n };\n\n config.build.rollupOptions = {\n ...(config.build.rollupOptions ?? {}),\n preserveEntrySignatures: 'strict'\n };\n }\n\n // Add React/ReactDOM aliases for storybook-solidjs compatibility\n if (!config.resolve) {\n config.resolve = {};\n }\n if (!config.resolve.alias) {\n config.resolve.alias = {};\n }\n \n // Ensure React is available for storybook-solidjs\n const aliases = config.resolve.alias as Record<string, string>;\n\n if (!aliases['react']) {\n aliases['react'] = 'react';\n }\n if (!aliases['react-dom']) {\n aliases['react-dom'] = 'react-dom';\n }\n\n const finalConfig = await mergeWithAstroConfig(\n config,\n integrations,\n options.resolveFrom,\n mode,\n command\n );\n\n // Exclude Astro integration packages from dependency optimization because\n // they import virtual modules that esbuild cannot resolve.\n if (!finalConfig.optimizeDeps) {\n finalConfig.optimizeDeps = {};\n }\n if (!finalConfig.optimizeDeps.exclude) {\n finalConfig.optimizeDeps.exclude = [];\n }\n for (const pkg of [\n '@astrojs/vue',\n '@astrojs/vue/client.js',\n '@astrojs/vue/server.js',\n '@astrojs/react',\n '@astrojs/react/client.js',\n '@astrojs/react/server.js',\n '@astrojs/preact',\n '@astrojs/preact/client.js',\n '@astrojs/preact/server.js'\n ]) {\n if (!finalConfig.optimizeDeps.exclude.includes(pkg)) {\n finalConfig.optimizeDeps.exclude.push(pkg);\n }\n }\n // Exclude the renderer from Vite's esbuild pre-bundler so that\n // import.meta.hot is preserved in the preview iframe. When installed\n // via npm (not workspace:*), Vite would otherwise pre-bundle the\n // renderer with esbuild, which strips import.meta.hot and causes the\n // renderer to fall back to fetching astro-prerendered-stories.json\n // (a 404 in dev mode) rather than using the Vite HMR channel.\n if (!finalConfig.optimizeDeps.exclude.includes('@storybook-astro/renderer')) {\n finalConfig.optimizeDeps.exclude.push('@storybook-astro/renderer');\n }\n // fsevents is a macOS-only native chokidar dep with a .node binary that\n // esbuild's prebundler can't load. storybook/internal/preview-api can pass\n // through the transform pipeline twice when used by CSF Next portable\n // stories, producing a duplicate __vite__injectQuery import in the\n // generated chunk; excluding it from prebundling collapses the duplicate.\n for (const pkg of ['fsevents', 'storybook/internal/preview-api']) {\n if (!finalConfig.optimizeDeps.exclude.includes(pkg)) {\n finalConfig.optimizeDeps.exclude.push(pkg);\n }\n }\n // Mark integration virtual modules as external so the dep bundler doesn't\n // try to resolve them (they are Vite virtual modules with no real package).\n // Set both esbuildOptions (Vite ≤7) and rolldownOptions (Vite 8+, Rolldown)\n // so the correct key is populated regardless of Vite version.\n const integrationVirtualModules = [\n 'virtual:@astrojs/vue/app',\n 'virtual:astro:vue-app',\n 'astro:react:opts',\n 'astro:preact:opts',\n 'astro:toolbar:internal'\n ];\n\n // Vite ≤7 (esbuild-based optimizer)\n if (!finalConfig.optimizeDeps.esbuildOptions) {\n finalConfig.optimizeDeps.esbuildOptions = {};\n }\n if (!finalConfig.optimizeDeps.esbuildOptions.external) {\n finalConfig.optimizeDeps.esbuildOptions.external = [];\n }\n for (const mod of integrationVirtualModules) {\n if (!finalConfig.optimizeDeps.esbuildOptions.external.includes(mod)) {\n finalConfig.optimizeDeps.esbuildOptions.external.push(mod);\n }\n }\n\n // Vite 8+ uses Rolldown for dependency optimization.\n const optimizeDepsMut = finalConfig.optimizeDeps as Record<string, unknown>;\n const rolldownOpts = (optimizeDepsMut.rolldownOptions ?? {}) as { external?: string[] };\n\n rolldownOpts.external = Array.from(\n new Set([...(rolldownOpts.external ?? []), ...integrationVirtualModules])\n );\n optimizeDepsMut.rolldownOptions = rolldownOpts;\n\n return finalConfig;\n};\n\nfunction mergeEnvPrefixes(\n existing: string | string[] | undefined,\n additionalPrefix: string\n): string[] {\n const prefixes = Array.isArray(existing) ? existing : existing ? [existing] : [];\n\n return Array.from(new Set([...prefixes, additionalPrefix]));\n}\n","import type { Integration } from './integrations/index.ts';\nimport { createVirtualModule } from './vite/virtualModulePlugin.ts';\n\nexport function viteStorybookRendererFallbackPlugin(integrations: Integration[]) {\n const safeIntegrations = integrations ?? [];\n\n return createVirtualModule({\n pluginName: 'storybook-renderer-fallback',\n virtualModuleId: 'virtual:storybook-renderer-fallback',\n load() {\n return safeIntegrations\n .filter((integration) => integration.storybookEntryPreview)\n .map(\n (integration) =>\n `export * as ${integration.name} from '${integration.storybookEntryPreview}';`\n )\n .join('\\n');\n }\n });\n}\n","import { fileURLToPath } from 'node:url';\nimport type { RenderMode, ServerBuildOptions } from './types.ts';\nimport { createVirtualModule } from './vite/virtualModulePlugin.ts';\n\nconst rendererDevModulePath = fileURLToPath(new URL('./renderer/renderer-dev.js', import.meta.url));\nconst rendererStaticModulePath = fileURLToPath(new URL('./renderer/renderer-static.js', import.meta.url));\nconst rendererServerModulePath = fileURLToPath(new URL('./renderer/renderer-server.js', import.meta.url));\n\nexport function viteStorybookAstroRendererPlugin(options: {\n mode: 'development' | 'production';\n renderMode?: RenderMode;\n server?: ServerBuildOptions;\n}) {\n const pluginName = 'storybook-astro:renderer-module';\n const virtualModuleId = 'virtual:storybook-astro-renderer';\n const isProduction = options.mode === 'production';\n const isStaticMode = options.renderMode === 'static';\n\n return createVirtualModule({\n pluginName,\n virtualModuleId,\n load() {\n if (!isProduction) {\n return `export * from ${JSON.stringify(normalizePath(rendererDevModulePath))};`;\n }\n\n if (isStaticMode) {\n return `export * from ${JSON.stringify(normalizePath(rendererStaticModulePath))};`;\n }\n\n return [\n `import { createServerRenderer } from ${JSON.stringify(normalizePath(rendererServerModulePath))};`,\n `const renderer = createServerRenderer(${JSON.stringify(\n {\n serverUrl: options.server?.serverUrl,\n authToken: options.server?.authToken,\n authHeader: options.server?.authHeader\n },\n null,\n 2\n )});`,\n 'export const render = renderer.render;',\n 'export const init = renderer.init;',\n 'export const applyStyles = renderer.applyStyles;'\n ].join('\\n');\n }\n });\n}\n\nfunction normalizePath(value: string) {\n return value.replace(/\\\\/g, '/');\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport type { Plugin, Rollup } from 'vite';\nimport type { Integration } from './integrations/index.ts';\nimport {\n buildStaticModuleMap,\n emitHydratedComponentEntriesFromAstroFile,\n collectTrackedSpecifiers,\n emitBuildEntrypoints,\n loadVirtualBuildModule,\n resolveVirtualBuildModuleId,\n stripQuery\n} from './vitePluginAstroBuildShared.ts';\nimport {\n createProductionRenderRuntime,\n renderProductionStoryToHtml,\n type ProductionStoryEntry\n} from './productionRenderRuntime.ts';\nimport { resolveRulesConfigFilePath } from './rules-options.ts';\nimport type { FrameworkOptions } from './types.ts';\n\nconst PRERENDERED_STORIES_FILE = 'astro-prerendered-stories.json';\n\ntype StoryIndex = {\n entries?: Record<\n string,\n {\n type?: string;\n id?: string;\n importPath?: string;\n exportName?: string;\n componentPath?: string;\n title?: string;\n name?: string;\n }\n >;\n};\n\nexport function vitePluginAstroBuildPrerender(options: FrameworkOptions): Plugin {\n const integrations = options.integrations ?? [];\n const resolveFrom = options.resolveFrom ?? process.cwd();\n const storyRulesConfigFilePath = resolveRulesConfigFilePath(options.storyRules, resolveFrom);\n const trackedSpecifiers = collectTrackedSpecifiers(integrations);\n const staticEntrypointRefs = new Map<string, string>();\n const componentEntrypointRefs = new Map<string, string>();\n let outDir = resolve(resolveFrom, 'storybook-static');\n\n return {\n name: 'storybook-astro:build-prerender',\n apply: 'build',\n enforce: 'post',\n\n configResolved(config) {\n outDir = resolve(resolveFrom, config.build.outDir ?? 'storybook-static');\n },\n\n async resolveId(this: Rollup.PluginContext, id: string, importer?: string) {\n const importerPath = stripQuery(importer);\n\n if (importerPath?.endsWith('.astro')) {\n await emitHydratedComponentEntriesFromAstroFile({\n pluginContext: this,\n astroFilePath: importerPath,\n resolveFrom,\n componentEntrypointRefs\n });\n }\n\n return resolveVirtualBuildModuleId(id);\n },\n\n load(id: string) {\n return loadVirtualBuildModule(id);\n },\n\n async buildStart(this: Rollup.PluginContext) {\n await emitBuildEntrypoints({\n pluginContext: this,\n integrations,\n resolveFrom,\n trackedSpecifiers,\n staticEntrypointRefs\n });\n },\n\n async writeBundle(\n this: Rollup.PluginContext,\n _outputOptions: Rollup.NormalizedOutputOptions,\n bundle: Rollup.OutputBundle\n ) {\n const staticModuleMap = buildStaticModuleMap(\n this,\n staticEntrypointRefs,\n componentEntrypointRefs\n );\n\n const astroStories = await collectAstroStories(outDir);\n\n if (astroStories.length === 0) {\n await writePrerenderedStoriesFile(outDir, {});\n\n return;\n }\n\n const prerenderedStories = await prerenderAstroStories({\n astroStories,\n integrations,\n sanitization: options.sanitization,\n storyRulesConfigFilePath,\n staticModuleMap,\n trackedSpecifiers,\n resolveFrom,\n bundle\n });\n\n await writePrerenderedStoriesFile(outDir, prerenderedStories);\n }\n };\n}\n\n/** Writes the prerendered Astro story payload consumed by the static renderer. */\nasync function writePrerenderedStoriesFile(outDir: string, payload: Record<string, string>) {\n await mkdir(outDir, { recursive: true });\n await writeFile(resolve(outDir, PRERENDERED_STORIES_FILE), JSON.stringify(payload), 'utf-8');\n}\n\n/** Renders Astro stories during the static build and stores the HTML by story id. */\nasync function prerenderAstroStories(options: {\n astroStories: ProductionStoryEntry[];\n integrations: Integration[];\n sanitization?: FrameworkOptions['sanitization'];\n storyRulesConfigFilePath?: string;\n staticModuleMap: Record<string, string>;\n trackedSpecifiers: Set<string>;\n resolveFrom: string;\n bundle: Rollup.OutputBundle;\n}) {\n const runtime = await createProductionRenderRuntime({\n integrations: options.integrations,\n sanitization: options.sanitization,\n storyRulesConfigFilePath: options.storyRulesConfigFilePath,\n staticModuleMap: options.staticModuleMap,\n trackedSpecifiers: options.trackedSpecifiers,\n resolveFrom: options.resolveFrom\n });\n const assetPathMap = buildAssetPathMap(options.bundle);\n\n try {\n const output: Record<string, string> = {};\n\n for (const story of options.astroStories) {\n const html = await renderProductionStoryToHtml({\n story,\n runtime,\n resolveFrom: options.resolveFrom\n });\n\n if (html !== undefined) {\n output[story.id] = rewriteAssetPaths(html, assetPathMap);\n }\n }\n\n return output;\n } finally {\n await runtime.close();\n }\n}\n\n/** Reads the built Storybook index and keeps only Astro stories that can be prerendered. */\nasync function collectAstroStories(outDir: string): Promise<ProductionStoryEntry[]> {\n const indexFile = resolve(outDir, 'index.json');\n const indexRaw = await readFile(indexFile, 'utf-8');\n const indexJson = JSON.parse(indexRaw) as StoryIndex;\n\n // Static prerender only owns Astro stories. Framework-rendered stories stay\n // with Storybook's normal preview pipeline and are not pre-rendered here.\n return Object.values(indexJson.entries ?? {})\n .filter((entry) => entry.type === 'story' && entry.componentPath?.endsWith('.astro'))\n .map((entry) => {\n if (!entry.id || !entry.importPath || !entry.exportName || !entry.componentPath) {\n throw new Error(`Encountered an invalid Storybook index entry in ${indexFile}.`);\n }\n\n return {\n id: entry.id,\n importPath: entry.importPath,\n componentPath: entry.componentPath,\n exportName: entry.exportName,\n title: entry.title,\n name: entry.name\n };\n });\n}\n\n/** Builds lookup tables that map original asset paths to emitted static asset URLs. */\nfunction buildAssetPathMap(bundle: Rollup.OutputBundle): Map<string, string> {\n const exactMap = new Map<string, string>();\n const stemMap = new Map<string, string>();\n\n for (const chunk of Object.values(bundle)) {\n if (chunk.type !== 'asset') {\n continue;\n }\n\n const asset = chunk as Rollup.OutputAsset;\n\n if (asset.originalFileNames && asset.originalFileNames.length > 0) {\n for (const originalPath of asset.originalFileNames) {\n exactMap.set(originalPath, `/${asset.fileName}`);\n }\n }\n\n // Vite does not populate originalFileNames for image assets processed\n // through its asset pipeline. Build a secondary lookup by the filename\n // stem so /@fs/ URLs in prerendered HTML can still be mapped to their\n // content-hashed output paths. e.g. \"storybook-astro-CfMmZdup.png\" ⟶\n // stem key \"storybook-astro.png\" ⟶ \"/_astro/storybook-astro-CfMmZdup.png\".\n const baseName = asset.fileName.split('/').pop() ?? '';\n const stemMatch = baseName.match(/^(.+)-[A-Za-z0-9]{6,12}\\.(png|jpe?g|gif|webp|svg|avif|ico)$/);\n\n if (stemMatch) {\n stemMap.set(`${stemMatch[1]}.${stemMatch[2]}`, `/${asset.fileName}`);\n }\n }\n\n return { exactMap, stemMap } as unknown as Map<string, string>;\n}\n\n/** Rewrites dev-only /@fs/ asset URLs in prerendered HTML to emitted build asset paths. */\nfunction rewriteAssetPaths(\n html: string,\n assetPathMap: ReturnType<typeof buildAssetPathMap>\n): string {\n const { exactMap, stemMap } = assetPathMap as unknown as {\n exactMap: Map<string, string>;\n stemMap: Map<string, string>;\n };\n\n if (exactMap.size === 0 && stemMap.size === 0) {\n return html;\n }\n\n // Prerendering happens through a Vite SSR server, so image/style URLs can\n // still point at dev-only /@fs/ paths. Rewrite them to the emitted assets.\n return html.replace(/\\/@fs\\/[^\"']+/g, (match) => {\n const pathOnly = match.replace(/\\?.*$/, '');\n const fsPath = pathOnly.slice('/@fs'.length);\n // Handle /@fs//abs/path (double leading slash on Unix)\n const absolutePath = fsPath.startsWith('//') ? fsPath.slice(1) : fsPath;\n\n // Try exact match by originalFileNames first\n const exact = exactMap.get(absolutePath);\n\n if (exact) {\n return exact;\n }\n\n // Fall back to stem-based matching for image assets whose\n // originalFileNames are empty (standard Vite asset pipeline behaviour).\n const baseName = absolutePath.split('/').pop() ?? '';\n const stemHit = stemMap.get(baseName);\n\n if (stemHit) {\n return stemHit;\n }\n\n return match;\n });\n}\n","import { createHash } from 'node:crypto';\nimport { access, copyFile, mkdir, readFile, readdir, stat } from 'node:fs/promises';\nimport { dirname, resolve } from 'node:path';\nimport type { Rollup } from 'vite';\nimport type { Integration } from './integrations/index.ts';\n\n/** Resolves the shared virtual module ids used by both build pipelines. */\nexport function resolveVirtualBuildModuleId(id: string) {\n if (id.startsWith('virtual:astro-static-module/')) {\n return `\\0${id}`;\n }\n\n if (id.startsWith('virtual:astro-component-module/')) {\n return `\\0${id}`;\n }\n}\n\n/** Loads the virtual modules that stand in for tracked runtime and component entrypoints. */\nexport function loadVirtualBuildModule(id: string) {\n if (id.startsWith('\\0virtual:astro-static-module/')) {\n const encodedSpecifier = id.replace('\\0virtual:astro-static-module/', '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n if (isClientEntrypoint(specifier)) {\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join(\n '\\n'\n );\n }\n\n return [`import '${specifier}';`, 'export default undefined;'].join('\\n');\n }\n\n if (id.startsWith('\\0virtual:astro-component-module/')) {\n const withoutPrefix = id.replace('\\0virtual:astro-component-module/', '');\n const encodedSpecifier = withoutPrefix.replace(/\\?.*$/, '');\n const specifier = decodeURIComponent(encodedSpecifier);\n\n return [`export { default } from '${specifier}';`, `export * from '${specifier}';`].join('\\n');\n }\n}\n\n/** Emits build entrypoints for framework client runtimes that Astro stories may reference. */\nexport async function emitBuildEntrypoints(options: {\n pluginContext: Rollup.PluginContext;\n integrations: Integration[];\n resolveFrom: string;\n trackedSpecifiers: Set<string>;\n staticEntrypointRefs: Map<string, string>;\n}) {\n const { pluginContext, integrations, resolveFrom } = options;\n\n // Keep framework client entrypoints in the build so Astro islands can\n // still hydrate after the preview iframe switches to built assets.\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n pluginContext.addWatchFile(entrypoint);\n }\n });\n\n options.trackedSpecifiers.forEach((specifier) => {\n const fileReferenceId = pluginContext.emitFile({\n type: 'chunk',\n id: toStaticVirtualId(specifier),\n name: createEntrypointName(resolveFrom, specifier)\n });\n\n options.staticEntrypointRefs.set(specifier, fileReferenceId);\n });\n}\n\n/** Emits framework component entry chunks for one Astro component file used in the build graph. */\nexport async function emitHydratedComponentEntriesFromAstroFile(options: {\n pluginContext: Rollup.PluginContext;\n astroFilePath: string;\n resolveFrom: string;\n componentEntrypointRefs: Map<string, string>;\n}) {\n const hydratedComponentPaths = await collectHydratedComponentPaths(options.astroFilePath);\n\n for (const resolvedImportPath of hydratedComponentPaths) {\n\n if (options.componentEntrypointRefs.has(resolvedImportPath)) {\n continue;\n }\n\n const fileReferenceId = options.pluginContext.emitFile({\n type: 'chunk',\n id: toComponentChunkId(resolvedImportPath),\n name: createEntrypointName(options.resolveFrom, resolvedImportPath)\n });\n\n options.componentEntrypointRefs.set(resolvedImportPath, fileReferenceId);\n }\n}\n\n/** Collects the framework component files one Astro component hydrates in the browser. */\nexport async function collectHydratedComponentPaths(astroFilePath: string) {\n // Only Astro components create islands, so only their framework imports\n // need standalone client chunks in built Storybook output.\n const localImportSpecifiers = await readLocalImportSpecifiers(astroFilePath);\n const hydratedComponentPaths: string[] = [];\n\n for (const specifier of localImportSpecifiers) {\n const resolvedImportPath = await resolveLocalImportPath(astroFilePath, specifier);\n\n if (!resolvedImportPath) {\n continue;\n }\n\n if (\n !isHydratableSourceFile(resolvedImportPath) ||\n isNonHydratableSourceFile(resolvedImportPath)\n ) {\n continue;\n }\n\n // Only .jsx/.tsx files go through toComponentVirtualId, which emits\n // `export { default } from '<file>'`. A file with no default export\n // crashes Rollup with '\"default\" is not exported'. Svelte/Vue SFCs are\n // passed directly to their compilers, which generate the default export —\n // checking their source for a literal `export default` would falsely\n // exclude them.\n if (/\\.(jsx|tsx)$/.test(resolvedImportPath) && !(await hasDefaultExport(resolvedImportPath))) {\n continue;\n }\n\n hydratedComponentPaths.push(resolvedImportPath);\n }\n\n return hydratedComponentPaths;\n}\n\n/** Collects framework client runtimes that must stay addressable after the preview is built. */\nexport function collectTrackedSpecifiers(integrations: Integration[]) {\n const specifiers = new Set<string>([\n 'astro:scripts/page.js',\n 'astro:scripts/before-hydration.js'\n ]);\n\n integrations.forEach((integration) => {\n const entrypoint = integration.renderer.client?.entrypoint;\n\n if (entrypoint) {\n specifiers.add(entrypoint);\n }\n });\n\n return specifiers;\n}\n\n/** Builds the browser module map used to rewrite source specifiers to built asset URLs. */\nexport function buildStaticModuleMap(\n pluginContext: Rollup.PluginContext,\n staticEntrypointRefs: Map<string, string>,\n componentEntrypointRefs: Map<string, string>\n) {\n const map: Record<string, string> = {};\n\n staticEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n componentEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n\n if (fileName) {\n map[specifier] = toPublicPath(fileName);\n }\n });\n\n return map;\n}\n\n/** Builds the stylesheet map for emitted framework component entry chunks. */\nexport function buildStaticCssMap(\n pluginContext: Rollup.PluginContext,\n bundle: Rollup.OutputBundle,\n componentEntrypointRefs: Map<string, string>\n) {\n const map: Record<string, string[]> = {};\n\n componentEntrypointRefs.forEach((fileReferenceId, specifier) => {\n const fileName = pluginContext.getFileName(fileReferenceId);\n const chunk = fileName ? (bundle[fileName] as Rollup.OutputChunk | undefined) : undefined;\n const importedCss = Array.from(\n (chunk?.viteMetadata?.importedCss ?? new Set<string>()).values()\n );\n\n if (importedCss.length > 0) {\n map[specifier] = importedCss.map((cssFileName) => toPublicPath(cssFileName));\n }\n });\n\n return map;\n}\n\n/** Normalizes one emitted file name to the relative public path used in built HTML. */\nexport function toPublicPath(fileName: string) {\n return `./${fileName}`;\n}\n\nexport function stripQuery(input: string | undefined) {\n return input?.replace(/\\?.*$/, '');\n}\n\n/** Converts a project file path into the stable path used inside the snapshot tree. */\nexport function relativePathFromRoot(resolveFrom: string, filePath: string) {\n return filePath.slice(resolveFrom.length).replace(/^[/\\\\]+/, '');\n}\n\n/** Copies one file or directory tree into the standalone runtime snapshot. */\nexport async function copyPath(sourcePath: string, targetPath: string): Promise<void> {\n const sourceStats = await stat(sourcePath);\n\n if (sourceStats.isDirectory()) {\n await mkdir(targetPath, { recursive: true });\n const entries = await readdir(sourcePath, { withFileTypes: true });\n\n await Promise.all(\n entries.map((entry) =>\n copyPath(resolve(sourcePath, entry.name), resolve(targetPath, entry.name))\n )\n );\n\n return;\n }\n\n await mkdir(dirname(targetPath), { recursive: true });\n await copyFile(sourcePath, targetPath);\n}\n\n/** Maps an original source file path to its location inside the snapshot tree. */\nexport function buildSnapshotFilePath(\n resolveFrom: string,\n filePath: string,\n snapshotDirName: string\n) {\n const normalizedResolveFrom = resolveFrom.replace(/\\\\/g, '/').replace(/\\/$/, '');\n const normalizedFilePath = filePath.replace(/\\\\/g, '/');\n\n if (normalizedFilePath.startsWith(`${normalizedResolveFrom}/`)) {\n return `${snapshotDirName}/${relativePathFromRoot(resolveFrom, filePath)}`.replace(/\\\\/g, '/');\n }\n\n return `${snapshotDirName}/__external/${normalizedFilePath.replace(/^[/\\\\]+/, '')}`.replace(\n /\\\\/g,\n '/'\n );\n}\n\n/** Copies the source files and config files the standalone render server needs at runtime. */\nexport async function copyRuntimeSnapshot(options: {\n resolveFrom: string;\n snapshotRoot: string;\n snapshotDirName: string;\n astroComponents: string[];\n storyRulesConfigFilePath?: string;\n}) {\n // The standalone render server still spins up a Vite SSR runtime, so it\n // needs the exact source/config files that runtime will read from disk.\n const runtimeInputFiles = new Set<string>([\n ...options.astroComponents,\n ...(options.storyRulesConfigFilePath ? [options.storyRulesConfigFilePath] : []),\n ...(await listRuntimeConfigFiles(options.resolveFrom))\n ]);\n const copiedFiles = new Set<string>();\n\n for (const runtimeInputFile of runtimeInputFiles) {\n await copyLocalRuntimeDependencies(runtimeInputFile, options, copiedFiles);\n }\n}\n\n/** Reports whether a JS/TS source file has a default export.\n * Only call for .jsx/.tsx — Svelte and Vue SFCs have no literal `export default`\n * in source, but their compilers generate one. On read error the file is kept,\n * preserving prior behaviour rather than silently dropping a component.\n *\n * The regex scan is intentionally conservative: it can match inside comments\n * or string literals, which produces a false-positive (file kept, Rollup crashes\n * as before) rather than a false-negative (file silently dropped). */\nasync function hasDefaultExport(absPath: string) {\n try {\n const source = await readFile(absPath, 'utf-8');\n\n return /export\\s+default\\b/.test(source) || /export\\s*\\{[^}]*\\bdefault\\b/.test(source);\n } catch {\n return true;\n }\n}\n\nfunction toStaticVirtualId(specifier: string) {\n return `virtual:astro-static-module/${encodeURIComponent(specifier)}`;\n}\n\nfunction toComponentVirtualId(specifier: string) {\n return `virtual:astro-component-module/${encodeURIComponent(specifier)}?component-wrapper`;\n}\n\nfunction toComponentChunkId(specifier: string) {\n return /\\.(svelte|vue)$/.test(specifier) ? specifier : toComponentVirtualId(specifier);\n}\n\nfunction createEntrypointName(resolveFrom: string, specifier: string) {\n const normalizedResolveFrom = resolveFrom.replace(/\\\\/g, '/');\n const normalizedSpecifier = specifier.replace(/\\\\/g, '/');\n const relativeName = normalizedSpecifier.startsWith(`${normalizedResolveFrom}/`)\n ? normalizedSpecifier.slice(normalizedResolveFrom.length + 1)\n : normalizedSpecifier.split('/').slice(-2).join('/');\n const sanitizedName = relativeName.replace(/[^a-zA-Z0-9/_-]/g, '_').replace(/_+/g, '_');\n const hash = createHash('sha1').update(normalizedSpecifier).digest('hex').slice(0, 8);\n\n return `${sanitizedName}-${hash}`;\n}\n\nfunction isClientEntrypoint(specifier: string) {\n return specifier.startsWith('@astrojs/') && specifier.endsWith('/client.js');\n}\n\nfunction isHydratableSourceFile(input: string) {\n return /\\.(jsx|tsx|vue|svelte)$/.test(input);\n}\n\nfunction isNonHydratableSourceFile(input: string) {\n return /\\.stories\\.[jt]sx?$|\\.stories\\.vue$|\\.stories\\.svelte$|\\.(spec|test)\\.[jt]sx?$/.test(\n input\n );\n}\n\n/** Finds project config files that the standalone render server may load through Vite. */\nasync function listRuntimeConfigFiles(resolveFrom: string) {\n const candidates = [\n 'package.json',\n 'tsconfig.json',\n 'tsconfig.base.json',\n 'jsconfig.json',\n 'astro.config.mjs',\n 'astro.config.js',\n 'astro.config.ts',\n 'vite.config.js',\n 'vite.config.ts',\n 'svelte.config.js'\n ];\n const existing: string[] = [];\n\n await Promise.all(\n candidates.map(async (candidate) => {\n const filePath = resolve(resolveFrom, candidate);\n\n try {\n await access(filePath);\n existing.push(filePath);\n } catch {\n return;\n }\n })\n );\n\n return existing;\n}\n\n/** Copies one local source file and follows its local imports into the snapshot. */\nasync function copyLocalRuntimeDependencies(\n sourcePath: string,\n options: {\n resolveFrom: string;\n snapshotRoot: string;\n snapshotDirName: string;\n },\n copiedFiles: Set<string>\n) {\n const normalizedSourcePath = sourcePath.replace(/\\\\/g, '/');\n\n if (copiedFiles.has(normalizedSourcePath)) {\n return;\n }\n\n copiedFiles.add(normalizedSourcePath);\n\n const snapshotRelativePath = buildSnapshotFilePath(\n options.resolveFrom,\n normalizedSourcePath,\n options.snapshotDirName\n );\n\n await copyPath(\n normalizedSourcePath,\n resolve(dirname(options.snapshotRoot), snapshotRelativePath)\n );\n\n // Follow only local imports here. Package dependencies stay external and are\n // resolved by Node/Vite from the deployed install, not copied into snapshot.\n const localImportSpecifiers = await readLocalImportSpecifiers(normalizedSourcePath);\n\n for (const specifier of localImportSpecifiers) {\n const resolvedDependency = await resolveLocalImportPath(normalizedSourcePath, specifier);\n\n if (!resolvedDependency) {\n continue;\n }\n\n await copyLocalRuntimeDependencies(resolvedDependency, options, copiedFiles);\n }\n}\n\n/** Reads local import specifiers from source files that can participate in the SSR runtime. */\nasync function readLocalImportSpecifiers(filePath: string) {\n if (!/\\.(astro|[cm]?[jt]sx?|vue|svelte)$/.test(filePath)) {\n return [];\n }\n\n const source = await readFile(filePath, 'utf-8');\n const matches = source.matchAll(\n /(?:import|export)\\s+(?:[^'\"`]*?\\s+from\\s+)?['\"`]([^'\"`]+)['\"`]|import\\(\\s*['\"`]([^'\"`]+)['\"`]\\s*\\)/g\n );\n\n return Array.from(matches, (match) => match[1] ?? match[2]).filter(\n (specifier): specifier is string => Boolean(specifier) && specifier.startsWith('.')\n );\n}\n\n/** Resolves one relative import the same way the project source tree would on disk. */\nasync function resolveLocalImportPath(importerPath: string, specifier: string) {\n const basePath = resolve(dirname(importerPath), specifier);\n const candidates = [\n basePath,\n `${basePath}.ts`,\n `${basePath}.tsx`,\n `${basePath}.js`,\n `${basePath}.jsx`,\n `${basePath}.mjs`,\n `${basePath}.cjs`,\n `${basePath}.astro`,\n `${basePath}.vue`,\n `${basePath}.svelte`,\n resolve(basePath, 'index.ts'),\n resolve(basePath, 'index.tsx'),\n resolve(basePath, 'index.js'),\n resolve(basePath, 'index.jsx'),\n resolve(basePath, 'index.mjs'),\n resolve(basePath, 'index.cjs'),\n resolve(basePath, 'index.astro'),\n resolve(basePath, 'index.vue'),\n resolve(basePath, 'index.svelte')\n ];\n\n for (const candidate of candidates) {\n try {\n const candidateStats = await stat(candidate);\n\n if (candidateStats.isFile()) {\n return candidate.replace(/\\\\/g, '/');\n }\n } catch {\n continue;\n }\n }\n\n return undefined;\n}\n","import { resolve } from 'node:path';\nimport { createAstroRenderHandler, type HandlerProps } from './astroRenderHandler.ts';\nimport type { Integration } from './integrations/index.ts';\nimport type { SanitizationOptions } from './lib/sanitization.ts';\nimport {\n createClientModuleResolver,\n createProductionAstroContainer,\n createStorySsrViteServer,\n loadRulesConfigModule\n} from './storySsrVite.ts';\n\ntype LoadedStoryModule = Record<string, unknown>;\n\nexport type ProductionRenderRuntime = {\n loadModule: (moduleId: string) => Promise<LoadedStoryModule>;\n renderAstroStory: (data: HandlerProps) => Promise<string>;\n close: () => Promise<void>;\n};\n\nexport type ProductionStoryEntry = {\n id: string;\n importPath: string;\n componentPath: string;\n exportName: string;\n title?: string;\n name?: string;\n};\n\ntype ProductionRenderRuntimeOptions = {\n integrations: Integration[];\n sanitization?: SanitizationOptions;\n storyRulesConfigFilePath?: string;\n staticModuleMap: Record<string, string>;\n trackedSpecifiers: Set<string>;\n resolveFrom: string;\n resolveComponentId?: (id: string) => string;\n};\n\n/** Creates the shared SSR runtime used by both build-time prerendering and the standalone render server. */\nexport async function createProductionRenderRuntime(\n options: ProductionRenderRuntimeOptions\n): Promise<ProductionRenderRuntime> {\n const viteServer = await createStorySsrViteServer({\n integrations: options.integrations,\n trackedSpecifiers: options.trackedSpecifiers,\n resolveFrom: options.resolveFrom\n });\n\n try {\n const rulesConfigModule = await loadRulesConfigModule(\n viteServer,\n options.storyRulesConfigFilePath\n );\n const resolveClientModule = createClientModuleResolver(\n options.integrations,\n options.staticModuleMap\n );\n const astroContainer = await createProductionAstroContainer({\n integrations: options.integrations,\n resolveClientModule,\n viteServer\n });\n\n const loadModule = async (moduleId: string) => {\n return (await viteServer.ssrLoadModule(\n options.resolveComponentId?.(moduleId) ?? moduleId\n )) as LoadedStoryModule;\n };\n const renderAstroStory = createAstroRenderHandler({\n container: astroContainer,\n sanitization: options.sanitization,\n rulesConfigFilePath: options.storyRulesConfigFilePath,\n resolveRulesConfigModule: () => rulesConfigModule,\n loadModule: async (moduleId: string) => {\n const loadedModule = await loadModule(moduleId);\n\n return {\n default: loadedModule.default\n };\n },\n invalidateModuleGraph: () => {\n viteServer.moduleGraph.invalidateAll();\n }\n });\n\n return {\n loadModule,\n renderAstroStory,\n close: () => viteServer.close()\n };\n } catch (error) {\n await viteServer.close();\n throw error;\n }\n}\n\n/** Loads one Astro story module, merges its args, and renders the Astro component to HTML. */\nexport async function renderProductionStoryToHtml(options: {\n story: ProductionStoryEntry;\n runtime: ProductionRenderRuntime;\n resolveFrom: string;\n}) {\n const storyModulePath = resolveProjectImportPath(options.story.importPath, options.resolveFrom);\n const componentPath = resolveProjectImportPath(options.story.componentPath, options.resolveFrom);\n const storyModule = await options.runtime.loadModule(storyModulePath);\n const defaultStoryMeta = isRecord(storyModule.default) ? storyModule.default : {};\n const selectedStoryExport = isRecord(storyModule[options.story.exportName])\n ? storyModule[options.story.exportName]\n : {};\n\n if (typeof defaultStoryMeta.component !== 'function') {\n throw new Error(\n `Unable to prerender story \"${options.story.id}\". Missing default export component in ${options.story.importPath}.`\n );\n }\n\n // Build-time prerender only supports stories that keep the meta-level Astro component.\n if (selectedStoryExport.component && selectedStoryExport.component !== defaultStoryMeta.component) {\n return undefined;\n }\n\n const storyArgs = mergeMetaArgsWithStoryArgs(\n toRecord(defaultStoryMeta.args),\n toRecord(selectedStoryExport.args)\n );\n const { componentArgs, storySlots } = separateStorySlots(storyArgs);\n\n return options.runtime.renderAstroStory({\n component: componentPath,\n args: componentArgs,\n slots: storySlots,\n story: {\n id: options.story.id,\n title: options.story.title,\n name: options.story.name\n }\n });\n}\n\nfunction resolveProjectImportPath(importPath: string, resolveFrom: string) {\n if (importPath.startsWith('./') || importPath.startsWith('../')) {\n return resolve(resolveFrom, importPath);\n }\n\n return importPath;\n}\n\nfunction mergeMetaArgsWithStoryArgs(\n metaArgs: Record<string, unknown> | undefined,\n storyArgs: Record<string, unknown> | undefined\n) {\n return {\n ...(metaArgs ?? {}),\n ...(storyArgs ?? {})\n };\n}\n\nfunction separateStorySlots(storyArgs: Record<string, unknown>) {\n const componentArgs = { ...storyArgs };\n const storySlots = componentArgs.slots;\n\n delete componentArgs.slots;\n\n if (!isRecord(storySlots)) {\n return {\n componentArgs,\n storySlots: {}\n };\n }\n\n return {\n componentArgs,\n storySlots: storySlots as Record<string, string>\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction toRecord(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) {\n return undefined;\n }\n\n return value;\n}\n","import { createRequire } from 'node:module';\nimport { createServer, mergeConfig, type Plugin, type ViteDevServer } from 'vite';\nimport type { experimental_AstroContainer as AstroContainer } from 'astro/container';\nimport { ensureAstroPassthroughImageService } from './astroImageService.ts';\nimport { importAstroConfig } from './importAstroConfig.ts';\nimport type { Integration } from './integrations/index.ts';\nimport { ssrLoadModuleWithFsFallback } from './lib/ssr-load-module-with-fs-fallback.ts';\nimport { resolveStoryModuleMock } from './module-mocks.ts';\nimport { vitePluginAstroFontsFallback } from './vitePluginAstroFontsFallback.ts';\nimport { vitePluginAstroIntegrationOptsFallback } from './vitePluginAstroIntegrationOptsFallback.ts';\nimport { vitePluginAstroRoutesFallback } from './vitePluginAstroRoutesFallback.ts';\nimport { vitePluginAstroVueFallback } from './vitePluginAstroVueFallback.ts';\nimport { vitePluginStoryModuleMocks } from './vitePluginStoryModuleMocks.ts';\n\nexport async function createStorySsrViteServer(options: {\n integrations: Integration[];\n trackedSpecifiers: Set<string>;\n resolveFrom: string;\n}) {\n const { getViteConfig, passthroughImageService } = await importAstroConfig(options.resolveFrom);\n const astroConfig = await getViteConfig(\n { root: options.resolveFrom },\n {\n configFile: false,\n integrations: await Promise.all(\n options.integrations.map((integration) => integration.loadIntegration(options.resolveFrom))\n ),\n image: { service: passthroughImageService() }\n }\n )({\n mode: 'production',\n command: 'serve'\n });\n\n const config = mergeConfig(astroConfig, {\n appType: 'custom',\n server: {\n middlewareMode: true\n },\n ssr: {\n // Keep Astro runtime classes in the Vite SSR graph so containers and\n // components share SlotString/HTMLString instances during prerendering.\n noExternal: /^astro(\\/.+)?$/\n },\n plugins: [\n createProjectAstroResolutionPlugin(options.resolveFrom),\n vitePluginAstroFontsFallback(),\n vitePluginAstroIntegrationOptsFallback(),\n vitePluginAstroVueFallback(),\n vitePluginAstroRoutesFallback(),\n vitePluginStoryModuleMocks(),\n createTrackedSpecifierStubPlugin(options.trackedSpecifiers)\n ]\n });\n\n const viteServer = await createServer(config);\n\n await viteServer.pluginContainer.buildStart({});\n\n return viteServer;\n}\n\nexport async function loadRulesConfigModule(viteServer: ViteDevServer, configFilePath?: string) {\n if (!configFilePath) {\n return undefined;\n }\n\n try {\n return await ssrLoadModuleWithFsFallback(viteServer, configFilePath, {\n fixStacktrace: true\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n throw new Error(\n `Unable to load framework.options.storyRules config module at ${configFilePath}: ${reason}`\n );\n }\n}\n\nexport function createClientModuleResolver(\n integrations: Integration[],\n staticModuleMap: Record<string, string>\n) {\n return function resolveClientModule(specifier: string) {\n if (Object.hasOwn(staticModuleMap, specifier)) {\n return staticModuleMap[specifier];\n }\n\n const normalizedSpecifier = specifier.replace(/\\\\/g, '/').replace(/\\?.*$/, '');\n\n if (Object.hasOwn(staticModuleMap, normalizedSpecifier)) {\n return staticModuleMap[normalizedSpecifier];\n }\n\n for (const integration of integrations) {\n const resolution = integration.resolveClient(specifier);\n\n if (resolution) {\n return resolution;\n }\n }\n };\n}\n\nexport async function createProductionAstroContainer(options: {\n integrations: Integration[];\n resolveClientModule: (specifier: string) => string | undefined;\n viteServer: ViteDevServer;\n}) {\n ensureAstroPassthroughImageService();\n\n // Astro 6's container wraps each slot value in a SlotString, and the\n // rendering pipeline detects raw-HTML slot chunks via `instanceof SlotString`.\n // If the container is loaded by Node's ESM resolver while components are\n // loaded through Vite's SSR graph, the two paths produce different\n // SlotString classes and the instanceof check fails — slot content then\n // takes the escaping code path. Loading the container via the same Vite\n // SSR server keeps the class identity consistent.\n const containerModule = (await options.viteServer.ssrLoadModule('astro/container')) as {\n experimental_AstroContainer: typeof AstroContainer;\n };\n const ViteAstroContainer = containerModule.experimental_AstroContainer;\n\n const container = await ViteAstroContainer.create({\n resolve: async (specifier) => {\n const mockedModule = resolveStoryModuleMock(specifier);\n\n if (mockedModule) {\n return mockedModule;\n }\n\n const resolution = options.resolveClientModule(specifier);\n\n if (resolution) {\n return resolution;\n }\n\n return specifier;\n }\n });\n\n await addContainerRenderers(\n container,\n options.integrations,\n options.resolveClientModule,\n options.viteServer\n );\n\n return container;\n}\n\nexport async function addContainerRenderers(\n container: Awaited<ReturnType<typeof AstroContainer.create>>,\n integrations: Integration[],\n resolveClientModule: (specifier: string) => string | undefined,\n viteServer: ViteDevServer\n) {\n for (const integration of integrations) {\n const serverRenderer = integration.renderer.server;\n\n if (serverRenderer) {\n const serverRendererModule = await viteServer.ssrLoadModule(serverRenderer.entrypoint);\n const renderer = serverRendererModule.default ?? serverRendererModule;\n\n if (integration.name === 'solid' && isRecord(renderer)) {\n container.addServerRenderer({\n name: serverRenderer.name,\n renderer: {\n ...renderer,\n name: serverRenderer.name\n } as never\n });\n } else {\n container.addServerRenderer({\n name: serverRenderer.name,\n renderer\n });\n }\n }\n\n const clientRenderer = integration.renderer.client;\n\n if (clientRenderer) {\n const resolvedEntrypoint =\n resolveClientModule(clientRenderer.entrypoint) ?? clientRenderer.entrypoint;\n\n container.addClientRenderer({\n name: clientRenderer.name,\n entrypoint: resolvedEntrypoint\n });\n }\n }\n}\n\nfunction createProjectAstroResolutionPlugin(resolveFrom: string): Plugin {\n const require = createRequire(import.meta.url);\n\n return {\n name: 'storybook-astro:resolve-project-astro-shared',\n enforce: 'pre',\n resolveId(id: string) {\n if (id !== 'astro' && !id.startsWith('astro/')) {\n return null;\n }\n\n try {\n return require.resolve(id, {\n paths: [resolveFrom]\n });\n } catch {\n return null;\n }\n }\n } satisfies Plugin;\n}\n\nfunction createTrackedSpecifierStubPlugin(trackedSpecifiers: Set<string>): Plugin {\n return {\n name: 'storybook-astro:shared-ssr-stubs',\n resolveId(id: string) {\n if (trackedSpecifiers.has(id)) {\n return `\\0storybook-astro-shared-ssr-stub:${encodeURIComponent(id)}`;\n }\n\n return null;\n },\n load(id: string) {\n if (id.startsWith('\\0storybook-astro-shared-ssr-stub:')) {\n return 'export default undefined;';\n }\n\n return null;\n }\n } satisfies Plugin;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n","import { dirname, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { build, type Rollup } from 'vite';\nimport { resolveRulesConfigFilePath } from './rules-options.ts';\nimport type { FrameworkOptions } from './types.ts';\nimport {\n buildStaticModuleMap,\n buildSnapshotFilePath,\n collectHydratedComponentPaths,\n copyRuntimeSnapshot,\n collectTrackedSpecifiers,\n emitBuildEntrypoints,\n loadVirtualBuildModule,\n resolveVirtualBuildModuleId,\n} from './vitePluginAstroBuildShared.ts';\nimport { mergeWithAstroConfig } from './vitePluginAstro.ts';\nimport { viteAstroContainerRenderersPlugin } from './viteAstroContainerRenderersPlugin.ts';\nimport { sanitizeConfigPlugin } from './vite/sanitizeConfigPlugin.ts';\nimport { serverAuthPlugin } from './vite/serverAuthPlugin.ts';\nimport { serverRuntimePlugin } from './vite/serverRuntimePlugin.ts';\n\nconst moduleRoot = resolve(dirname(fileURLToPath(import.meta.url)), '.');\n// packageRoot works regardless of whether this file is running from src/ or dist/\nconst packageRoot = resolve(moduleRoot, '..');\n\nexport function vitePluginAstroBuildServer(options: FrameworkOptions) {\n const integrations = options.integrations ?? [];\n const resolveFrom = options.resolveFrom ?? process.cwd();\n const trackedSpecifiers = collectTrackedSpecifiers(integrations);\n const staticEntrypointRefs = new Map<string, string>();\n let storybookStaticOutDir = resolve(resolveFrom, 'storybook-static');\n\n return {\n name: 'storybook-astro:build-server',\n apply: 'build',\n enforce: 'post',\n\n configResolved(config: { build: { outDir?: string } }) {\n storybookStaticOutDir = resolve(resolveFrom, config.build.outDir ?? 'storybook-static');\n },\n\n resolveId(id: string) {\n return resolveVirtualBuildModuleId(id);\n },\n\n load(id: string) {\n return loadVirtualBuildModule(id);\n },\n\n async buildStart(this: Rollup.PluginContext) {\n await emitBuildEntrypoints({\n pluginContext: this,\n integrations,\n resolveFrom,\n trackedSpecifiers,\n staticEntrypointRefs\n });\n },\n\n async writeBundle(\n this: Rollup.PluginContext,\n _outputOptions: Rollup.NormalizedOutputOptions\n ) {\n const serverOutDir = resolve(dirname(storybookStaticOutDir), 'storybook-server');\n const snapshotDirName = 'project';\n const astroStories = await collectAstroStories(storybookStaticOutDir, resolveFrom);\n const storyAstroComponentPaths = Array.from(new Set(astroStories.map((story) => story.componentPath)));\n const componentPathMap = buildComponentPathMap(storyAstroComponentPaths, resolveFrom, snapshotDirName);\n const storyRulesConfigFilePath = resolveRulesConfigFilePath(options.storyRules, resolveFrom);\n const trackedModuleMap = buildStaticModuleMap(this, staticEntrypointRefs, new Map());\n const hydratedComponentAssets = await buildHydratedComponentAssets({\n componentPaths: storyAstroComponentPaths,\n integrations,\n resolveFrom,\n outDir: storybookStaticOutDir\n });\n const staticModuleMap = addSnapshotModuleAliases({\n ...trackedModuleMap,\n ...hydratedComponentAssets.staticModuleMap\n }, {\n resolveFrom,\n snapshotRoot: resolve(serverOutDir, snapshotDirName),\n snapshotDirName\n });\n const staticCssMap = hydratedComponentAssets.staticCssMap;\n\n await buildAstroServer({\n integrations,\n sanitization: options.sanitization,\n storyRules: options.storyRules,\n server: options.server,\n outDir: serverOutDir,\n snapshotDirName,\n componentPathMap,\n staticModuleMap,\n staticCssMap,\n trackedSpecifiers: Array.from(trackedSpecifiers),\n resolveFrom\n });\n\n await copyRuntimeSnapshot({\n resolveFrom,\n snapshotRoot: resolve(serverOutDir, snapshotDirName),\n snapshotDirName,\n astroComponents: storyAstroComponentPaths,\n storyRulesConfigFilePath\n });\n }\n };\n}\n\n/** Builds the standalone Astro render server used by server-mode Storybook output. */\nasync function buildAstroServer(options: {\n integrations: NonNullable<FrameworkOptions['integrations']>;\n sanitization?: FrameworkOptions['sanitization'];\n storyRules?: FrameworkOptions['storyRules'];\n server?: FrameworkOptions['server'];\n outDir: string;\n snapshotDirName: string;\n componentPathMap: Record<string, string>;\n staticModuleMap: Record<string, string>;\n staticCssMap: Record<string, string[]>;\n trackedSpecifiers: string[];\n resolveFrom: string;\n}) {\n const buildConfig = {\n root: resolve(packageRoot, 'src/server'),\n ssr: {\n noExternal: /(@astrojs\\/.+|react|react-dom)/\n },\n build: {\n ssr: true,\n outDir: options.outDir,\n emptyOutDir: true,\n sourcemap: true,\n manifest: false,\n rollupOptions: {\n input: resolve(packageRoot, 'src/server/index.ts'),\n treeshake: true\n }\n },\n plugins: [\n sanitizeConfigPlugin(options.sanitization),\n serverAuthPlugin(options.server),\n serverRuntimePlugin({\n integrations: options.integrations,\n storyRules: options.storyRules,\n resolveFrom: options.resolveFrom,\n snapshotDirName: options.snapshotDirName,\n componentPathMap: options.componentPathMap,\n staticModuleMap: options.staticModuleMap,\n staticCssMap: options.staticCssMap,\n trackedSpecifiers: options.trackedSpecifiers\n }),\n viteAstroContainerRenderersPlugin(options.integrations, {\n mode: 'production',\n staticModuleMap: options.staticModuleMap\n })\n ]\n };\n\n const finalConfig = await mergeWithAstroConfig(\n buildConfig,\n options.integrations,\n options.resolveFrom,\n 'production',\n 'build'\n );\n\n await build(finalConfig);\n}\n\n/** Rewrites Astro component module ids so the standalone server loads them from the snapshot tree. */\nfunction buildComponentPathMap(\n astroComponents: string[],\n resolveFrom: string,\n snapshotDirName: string\n) {\n // The built render server loads Astro component modules from the snapshot,\n // not from the original project root that existed during the build.\n return Object.fromEntries(\n astroComponents.map((componentPath) => [\n componentPath,\n buildSnapshotFilePath(resolveFrom, componentPath, snapshotDirName).replace(\n new RegExp(`^${snapshotDirName}/`),\n ''\n )\n ])\n );\n}\n\nasync function collectAstroStories(outDir: string, resolveFrom: string) {\n const indexFile = resolve(outDir, 'index.json');\n const indexRaw = await import('node:fs/promises').then(({ readFile }) => readFile(indexFile, 'utf-8'));\n const indexJson = JSON.parse(indexRaw) as {\n entries?: Record<string, { type?: string; componentPath?: string; importPath?: string; exportName?: string }>\n };\n\n return Object.values(indexJson.entries ?? [])\n .filter((entry) => entry.type === 'story' && entry.componentPath?.endsWith('.astro'))\n .map((entry) => ({\n componentPath: entry.componentPath?.startsWith('./') || entry.componentPath?.startsWith('../')\n ? resolve(resolveFrom, entry.componentPath)\n : entry.componentPath\n }))\n .filter((entry): entry is { componentPath: string } => Boolean(entry.componentPath));\n}\n\nasync function buildHydratedComponentAssets(options: {\n componentPaths: string[];\n integrations: NonNullable<FrameworkOptions['integrations']>;\n resolveFrom: string;\n outDir: string;\n}) {\n const hydratedComponentPaths = Array.from(\n new Set((await Promise.all(options.componentPaths.map((componentPath) => collectHydratedComponentPaths(componentPath)))).flat())\n );\n\n if (hydratedComponentPaths.length === 0) {\n return {\n staticModuleMap: {},\n staticCssMap: {}\n };\n }\n\n const clientEntrypoints = Array.from(\n new Set(\n options.integrations\n .map((integration) => integration.renderer.client?.entrypoint)\n .filter((entrypoint): entrypoint is string => Boolean(entrypoint))\n )\n );\n const entryNames = Object.fromEntries(\n [\n ...hydratedComponentPaths.map((componentPath, index) => [`component-${index}`, componentPath]),\n ...clientEntrypoints.map((entrypoint, index) => [`renderer-${index}`, entrypoint])\n ]\n );\n const buildConfig = {\n root: options.resolveFrom,\n build: {\n write: false,\n outDir: options.outDir,\n emptyOutDir: false,\n manifest: false,\n rollupOptions: {\n input: entryNames,\n preserveEntrySignatures: 'strict',\n output: {\n entryFileNames: '_astro/[name]-[hash].js',\n chunkFileNames: '_astro/[name]-[hash].js',\n assetFileNames: '_astro/[name]-[hash][extname]'\n }\n }\n }\n };\n const finalConfig = await mergeWithAstroConfig(\n buildConfig,\n options.integrations,\n options.resolveFrom,\n 'production',\n 'build'\n );\n const buildOutput = await build(finalConfig);\n const output = Array.isArray(buildOutput) ? buildOutput.flatMap((result) => result.output) : buildOutput.output;\n const staticModuleMap: Record<string, string> = {};\n const staticCssMap: Record<string, string[]> = {};\n\n for (const item of output) {\n await writeBuildOutputFile(options.outDir, item);\n\n if (item.type !== 'chunk' || !item.facadeModuleId) {\n continue;\n }\n\n const normalizedFacadeId = item.facadeModuleId.replace(/\\\\/g, '/');\n const originalInputSpecifier = entryNames[item.name];\n\n staticModuleMap[normalizedFacadeId] = `./${item.fileName}`;\n\n if (originalInputSpecifier && originalInputSpecifier !== normalizedFacadeId) {\n staticModuleMap[originalInputSpecifier] = `./${item.fileName}`;\n }\n\n const importedCss = Array.from((item.viteMetadata?.importedCss ?? new Set<string>()).values());\n\n if (importedCss.length > 0) {\n staticCssMap[normalizedFacadeId] = importedCss.map((fileName) => `./${fileName}`);\n\n if (originalInputSpecifier && originalInputSpecifier !== normalizedFacadeId) {\n staticCssMap[originalInputSpecifier] = importedCss.map((fileName) => `./${fileName}`);\n }\n }\n }\n\n return {\n staticModuleMap,\n staticCssMap\n };\n}\n\nasync function writeBuildOutputFile(outDir: string, item: Rollup.OutputAsset | Rollup.OutputChunk) {\n const outputPath = resolve(outDir, item.fileName);\n\n await mkdir(dirname(outputPath), { recursive: true });\n\n if (item.type === 'asset') {\n await writeFile(outputPath, item.source);\n\n return;\n }\n\n await writeFile(outputPath, item.code);\n}\n\nfunction addSnapshotModuleAliases(\n staticModuleMap: Record<string, string>,\n options: {\n resolveFrom: string;\n snapshotRoot: string;\n snapshotDirName: string;\n }\n) {\n const mapWithSnapshotPaths = { ...staticModuleMap };\n\n for (const [sourcePath, builtPath] of Object.entries(staticModuleMap)) {\n if (!sourcePath.startsWith('/')) {\n continue;\n }\n\n const snapshotPath = resolve(\n dirname(options.snapshotRoot),\n buildSnapshotFilePath(options.resolveFrom, sourcePath, options.snapshotDirName)\n ).replace(/\\\\/g, '/');\n\n mapWithSnapshotPaths[snapshotPath] = builtPath;\n }\n\n return mapWithSnapshotPaths;\n}\n","import { mergeConfig, type InlineConfig } from 'vite';\nimport type { Integration } from './integrations/index.ts';\nimport { importAstroConfig } from './importAstroConfig.ts';\n\nconst ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK = [\n '@astro/plugin-actions',\n '@astrojs/vite-plugin-astro-ssr-manifest',\n 'astro-content-virtual-mod-plugin',\n 'astro:actions',\n 'astro:build:normal',\n 'astro:container',\n 'astro:content-asset-propagation',\n 'astro:content-imports',\n 'astro:content-listen',\n 'astro:dev-toolbar',\n 'astro:head-metadata',\n 'astro:html',\n 'astro:i18n',\n 'astro:integration-container',\n 'astro:jsx',\n 'astro:markdown',\n 'astro:postprocess',\n 'astro:prefetch',\n 'astro:scanner',\n 'astro:scripts:page-ssr',\n 'astro:server',\n 'astro:vite-plugin-env',\n 'astro:vite-plugin-file-url'\n];\n\nexport async function mergeWithAstroConfig(\n config: InlineConfig,\n integrations: Integration[] = [],\n resolveFrom = process.cwd(),\n mode = 'development',\n command: 'build' | 'serve' = 'serve'\n) {\n const { getViteConfig } = await importAstroConfig(resolveFrom);\n const safeIntegrations = integrations ?? [];\n\n const astroConfig = await getViteConfig(\n {},\n {\n configFile: false,\n integrations: await Promise.all(\n safeIntegrations.map((integration) => integration.loadIntegration(resolveFrom))\n )\n }\n )({\n mode,\n command\n });\n\n const filteredPlugins = astroConfig\n .plugins!.flat()\n .filter(\n (plugin) =>\n plugin &&\n 'name' in plugin &&\n !ASTRO_PLUGINS_THAT_ARE_SUPPOSEDLY_NOT_NEEDED_IN_STORYBOOK.includes(plugin.name)\n );\n\n return mergeConfig(config, {\n ...astroConfig,\n plugins: filteredPlugins\n });\n}\n","import type { Plugin } from 'vite';\nimport type { SanitizationOptions } from '../lib/sanitization.ts';\nimport { serializeSanitizationOptions } from '../lib/sanitization.ts';\nimport { createVirtualModule } from './virtualModulePlugin.ts';\n\nexport const SANITIZE_CONFIG_MODULE_ID = 'virtual:storybook-astro/sanitize-config';\n\nexport function sanitizeConfigPlugin(options?: SanitizationOptions): Plugin {\n return createVirtualModule({\n pluginName: 'storybook-astro:sanitize-config',\n virtualModuleId: SANITIZE_CONFIG_MODULE_ID,\n load() {\n const serializedConfig = serializeSanitizationOptions(options);\n\n return `export default ${serializedConfig};`;\n }\n });\n}\n","import type { Plugin } from 'vite';\nimport type { ServerBuildOptions } from '../types.ts';\nimport { createVirtualModule } from './virtualModulePlugin.ts';\n\nexport const SERVER_AUTH_MODULE_ID = 'virtual:storybook-astro/server-auth';\n\nexport function serverAuthPlugin(options?: ServerBuildOptions): Plugin {\n const authToken = normalizeOptionalString(options?.authToken);\n const authHeader = normalizeAuthHeader(options?.authHeader);\n\n return createVirtualModule({\n pluginName: 'storybook-astro:server-auth',\n virtualModuleId: SERVER_AUTH_MODULE_ID,\n load() {\n return [\n `export const storybookAstroServerAuthToken = ${\n authToken ? JSON.stringify(authToken) : 'undefined'\n };`,\n `export const storybookAstroServerAuthHeader = ${JSON.stringify(authHeader)};`\n ].join('\\n');\n }\n });\n}\n\nfunction normalizeOptionalString(value: string | undefined) {\n if (!value) {\n return undefined;\n }\n\n const normalizedValue = value.trim();\n\n return normalizedValue || undefined;\n}\n\nfunction normalizeAuthHeader(value: string | undefined) {\n const normalizedValue = normalizeOptionalString(value);\n\n return (normalizedValue ?? 'authorization').toLowerCase();\n}\n","import { relative } from 'node:path';\nimport type { Integration } from '../integrations/index.ts';\nimport { resolveRulesConfigFilePath } from '../rules-options.ts';\nimport type { FrameworkOptions } from '../types.ts';\nimport { createVirtualModule } from './virtualModulePlugin.ts';\n\nexport const SERVER_RUNTIME_MODULE_ID = 'virtual:storybook-astro/server-runtime';\nconst integrationsModuleId = '@storybook-astro/framework/integrations';\n\nfunction getIntegrationFactoryName(integration: Integration): string {\n return integration.factoryName ?? integration.name;\n}\n\n/** Produces the virtual module that hands the standalone render server its build-time config. */\nexport function serverRuntimePlugin(options: {\n integrations?: FrameworkOptions['integrations'];\n storyRules?: FrameworkOptions['storyRules'];\n resolveFrom: string;\n snapshotDirName: string;\n componentPathMap: Record<string, string>;\n staticModuleMap: Record<string, string>;\n staticCssMap: Record<string, string[]>;\n trackedSpecifiers: string[];\n}) {\n return createVirtualModule({\n pluginName: 'storybook-astro:server-runtime',\n virtualModuleId: SERVER_RUNTIME_MODULE_ID,\n load() {\n const storyRulesConfigFilePath = resolveRulesConfigFilePath(options.storyRules, options.resolveFrom);\n const storyRulesConfigRelativePath = storyRulesConfigFilePath\n ? relative(options.resolveFrom, storyRulesConfigFilePath).replace(/\\\\/g, '/')\n : undefined;\n const integrations = options.integrations ?? [];\n // Keep the generated module small: one config object for plain data,\n // one integrations export for real factory calls.\n const runtimeConfig = {\n snapshotDirName: options.snapshotDirName,\n storyRulesConfigRelativePath,\n componentPathMap: options.componentPathMap,\n staticModuleMap: options.staticModuleMap,\n staticCssMap: options.staticCssMap,\n trackedSpecifiers: options.trackedSpecifiers\n };\n\n return [\n createIntegrationImports(integrations),\n `export const runtimeConfig = ${serializeValue(runtimeConfig)};`,\n `export const integrations = [${createIntegrationFactoryCalls(integrations)}];`\n ].join('\\n');\n }\n });\n}\n\n/** Imports only the integration factories used by this runtime bundle. */\nfunction createIntegrationImports(integrations: Integration[]) {\n const factoryNames = Array.from(new Set(integrations.map(getIntegrationFactoryName)));\n\n if (factoryNames.length === 0) {\n return '';\n }\n\n return `import { ${factoryNames.join(', ')} } from ${JSON.stringify(integrationsModuleId)};`;\n}\n\n/** Recreates the configured integration list inside the generated runtime module. */\nfunction createIntegrationFactoryCalls(integrations: Integration[]) {\n return integrations\n .map((integration) => `${getIntegrationFactoryName(integration)}(${serializeValue(integration.options)})`)\n .join(', ');\n}\n\n/** Serializes plain runtime config values into executable module source. */\nfunction serializeValue(value: unknown): string {\n if (value === undefined) {\n return 'undefined';\n }\n\n if (value === null) {\n return 'null';\n }\n\n if (typeof value === 'string') {\n return JSON.stringify(value);\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return JSON.stringify(value);\n }\n\n if (value instanceof RegExp) {\n return value.toString();\n }\n\n if (Array.isArray(value)) {\n return `[${value.map((entry) => serializeValue(entry)).join(', ')}]`;\n }\n\n if (isRecord(value)) {\n return `{${Object.entries(value)\n .map(([key, entryValue]) => `${JSON.stringify(key)}: ${serializeValue(entryValue)}`)\n .join(', ')}}`;\n }\n\n throw new Error('Unable to serialize Storybook Astro server runtime configuration.');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n","import type { Plugin } from 'vite';\n\nconst TOOLBAR_INTERNAL_STUB = `\nexport const loadDevToolbarApps = async () => [];\n`;\n\n/**\n * Provides a fallback stub for Astro's dev toolbar virtual module.\n *\n * Astro's `astro/dist/runtime/client/dev-toolbar/entrypoint.js` imports\n * from `astro:toolbar:internal`, a virtual module normally provided by\n * Astro's own `vite-plugin-dev-toolbar` Vite plugin. In the Storybook\n * context that plugin is not active, causing esbuild to fail during\n * dependency optimisation when it encounters the unresolvable import.\n *\n * Storybook doesn't use Astro's dev toolbar, so a no-op stub is safe.\n */\nexport function vitePluginAstroToolbarFallback(): Plugin {\n const VIRTUAL_ID = 'astro:toolbar:internal';\n const RESOLVED_ID = '\\0' + VIRTUAL_ID;\n\n return {\n name: 'storybook-astro-toolbar-fallback',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ID) {\n return RESOLVED_ID;\n }\n },\n\n load(id) {\n if (id === RESOLVED_ID) {\n return { code: TOOLBAR_INTERNAL_STUB };\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAAA,gBAAe;;;ACGjB,SAAS,oCAAoC,cAA6B;AAC/E,QAAM,mBAAmB,gBAAgB,CAAC;AAE1C,SAAO,oBAAoB;AAAA,IACzB,YAAY;AAAA,IACZ,iBAAiB;AAAA,IACjB,OAAO;AACL,aAAO,iBACJ,OAAO,CAAC,gBAAgB,YAAY,qBAAqB,EACzD;AAAA,QACC,CAAC,gBACC,eAAe,YAAY,IAAI,UAAU,YAAY,qBAAqB;AAAA,MAC9E,EACC,KAAK,IAAI;AAAA,IACd;AAAA,EACF,CAAC;AACH;;;ACnBA,SAAS,qBAAqB;AAI9B,IAAM,wBAAwB,cAAc,IAAI,IAAI,8BAA8B,YAAY,GAAG,CAAC;AAClG,IAAM,2BAA2B,cAAc,IAAI,IAAI,iCAAiC,YAAY,GAAG,CAAC;AACxG,IAAM,2BAA2B,cAAc,IAAI,IAAI,iCAAiC,YAAY,GAAG,CAAC;AAEjG,SAAS,iCAAiC,SAI9C;AACD,QAAM,aAAa;AACnB,QAAM,kBAAkB;AACxB,QAAM,eAAe,QAAQ,SAAS;AACtC,QAAM,eAAe,QAA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MAAI,CAAC,YAAY,aAAa,gBAAgB;AAC5C,gBAAY,aAAa,iBAAiB,CAAC;AAAA,EAC7C;AACA,MAAI,CAAC,YAAY,aAAa,eAAe,UAAU;AACrD,gBAAY,aAAa,eAAe,WAAW,CAAC;AAAA,EACtD;AACA,aAAW,OAAO,2BAA2B;AAC3C,QAAI,CAAC,YAAY,aAAa,eAAe,SAAS,SAAS,GAAG,GAAG;AACnE,kBAAY,aAAa,eAAe,SAAS,KAAK,GAAG;AAAA,IAC3D;AAAA,EACF;AAGA,QAAM,kBAAkB,YAAY;AACpC,QAAM,eAAgB,gBAAgB,mBAAmB,CAAC;AAE1D,eAAa,WAAW,MAAM;AAAA,IAC5B,oBAAI,IAAI,CAAC,GAAI,aAAa,YAAY,CAAC,GAAI,GAAG,yBAAyB,CAAC;AAAA,EAC1E;AACA,kBAAgB,kBAAkB;AAElC,SAAO;AACT;AAEA,SAAS,iBACP,UACA,kBACU;AACV,QAAM,WAAW,MAAM,QAAQ,QAAQ,IAAI,WAAW,WAAW,CAAC,QAAQ,IAAI,CAAC;AAE/E,SAAO,MAAM,KAAK,oBAAI,IAAI,CAAC,GAAG,UAAU,gBAAgB,CAAC,CAAC;AAC5D;","names":["dirname","mkdir","readFile","resolve","resolve","require","isRecord","resolve","resolve","mkdir","readFile","dirname","resolve","fileURLToPath","mkdir","writeFile","mergeConfig","mergeConfig","isRecord","resolve","dirname","fileURLToPath","collectAstroStories","readFile","mkdir","writeFile","dirname"]}
@@ -6,10 +6,13 @@ async function importAstroConfig(resolveFrom) {
6
6
  const astroConfigEntrypoint = require2.resolve("astro/config", {
7
7
  paths: [resolveFrom]
8
8
  });
9
- return import(pathToFileURL(astroConfigEntrypoint).href);
9
+ return import(
10
+ /* @vite-ignore */
11
+ pathToFileURL(astroConfigEntrypoint).href
12
+ );
10
13
  }
11
14
 
12
15
  export {
13
16
  importAstroConfig
14
17
  };
15
- //# sourceMappingURL=chunk-DNGQBPT7.js.map
18
+ //# sourceMappingURL=chunk-PUTCAN6X.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/importAstroConfig.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\n\nexport async function importAstroConfig(resolveFrom: string) {\n const require = createRequire(import.meta.url);\n const astroConfigEntrypoint = require.resolve('astro/config', {\n paths: [resolveFrom]\n });\n\n return import(pathToFileURL(astroConfigEntrypoint).href);\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAE9B,eAAsB,kBAAkB,aAAqB;AAC3D,QAAMA,WAAU,cAAc,YAAY,GAAG;AAC7C,QAAM,wBAAwBA,SAAQ,QAAQ,gBAAgB;AAAA,IAC5D,OAAO,CAAC,WAAW;AAAA,EACrB,CAAC;AAED,SAAO,OAAO,cAAc,qBAAqB,EAAE;AACrD;","names":["require"]}
1
+ {"version":3,"sources":["../src/importAstroConfig.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { pathToFileURL } from 'node:url';\n\nexport async function importAstroConfig(resolveFrom: string) {\n const require = createRequire(import.meta.url);\n const astroConfigEntrypoint = require.resolve('astro/config', {\n paths: [resolveFrom]\n });\n\n return import(/* @vite-ignore */ pathToFileURL(astroConfigEntrypoint).href);\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAE9B,eAAsB,kBAAkB,aAAqB;AAC3D,QAAMA,WAAU,cAAc,YAAY,GAAG;AAC7C,QAAM,wBAAwBA,SAAQ,QAAQ,gBAAgB;AAAA,IAC5D,OAAO,CAAC,WAAW;AAAA,EACrB,CAAC;AAED,SAAO;AAAA;AAAA,IAA0B,cAAc,qBAAqB,EAAE;AAAA;AACxE;","names":["require"]}
@@ -1,3 +1,9 @@
1
+ import {
2
+ createInlineStoryModuleMock,
3
+ createPathStoryModuleMock,
4
+ withStoryModuleMocks
5
+ } from "./chunk-B5HHF6FC.js";
6
+
1
7
  // src/rules.ts
2
8
  import { dirname, isAbsolute, resolve } from "path";
3
9
  function defineStoryRules(config) {
@@ -13,17 +19,36 @@ async function selectStoryRules(input) {
13
19
  }
14
20
  const uses = Array.isArray(rule.use) ? rule.use : [rule.use];
15
21
  for (const use of uses) {
22
+ const pendingModuleMocks = [];
16
23
  if (typeof use !== "function") {
17
24
  throw new Error('Each story rule "use" entry must be a function.');
18
25
  }
19
26
  const cleanup = await use({
20
27
  story,
21
- mock: (specifier, replacement) => {
28
+ mock: ((specifier, replacementOrFactory) => {
22
29
  const normalizedSpecifier = normalizeMockSpecifier(specifier);
23
- const normalizedReplacement = normalizeMockReplacement(replacement, input.configFilePath);
24
- selection.moduleMocks.set(normalizedSpecifier, normalizedReplacement);
25
- }
30
+ if (typeof replacementOrFactory === "function") {
31
+ pendingModuleMocks.push(
32
+ Promise.resolve(replacementOrFactory()).then((exportsObject) => {
33
+ selection.moduleMocks.set(
34
+ normalizedSpecifier,
35
+ createInlineStoryModuleMock(normalizeMockFactoryResult(exportsObject))
36
+ );
37
+ return void 0;
38
+ })
39
+ );
40
+ return;
41
+ }
42
+ const normalizedReplacement = normalizeMockReplacement(
43
+ replacementOrFactory,
44
+ input.configFilePath
45
+ );
46
+ selection.moduleMocks.set(normalizedSpecifier, createPathStoryModuleMock(normalizedReplacement));
47
+ })
26
48
  });
49
+ if (pendingModuleMocks.length > 0) {
50
+ await Promise.all(pendingModuleMocks);
51
+ }
27
52
  if (cleanup !== void 0) {
28
53
  if (typeof cleanup !== "function") {
29
54
  throw new Error('Story rule "use" must return either nothing or a cleanup function.');
@@ -210,6 +235,12 @@ function normalizeMockReplacement(value, configFilePath) {
210
235
  }
211
236
  return normalizedValue;
212
237
  }
238
+ function normalizeMockFactoryResult(value) {
239
+ if (!isRecord(value)) {
240
+ throw new Error("Story rule mock factory must return an object of module exports.");
241
+ }
242
+ return value;
243
+ }
213
244
  function slugify(input) {
214
245
  return input.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
215
246
  }
@@ -232,55 +263,6 @@ function isRecord(value) {
232
263
  return !Array.isArray(value);
233
264
  }
234
265
 
235
- // src/lib/passthrough-image-service.ts
236
- function installPassthroughImageService() {
237
- if (!globalThis.astroAsset) {
238
- globalThis.astroAsset = {};
239
- }
240
- globalThis.astroAsset.imageService = {
241
- propertiesToHash: ["src"],
242
- validateOptions(options) {
243
- return options;
244
- },
245
- getURL(options) {
246
- const src = options.src;
247
- if (src != null && typeof src === "object" && "src" in src && typeof src.src === "string") {
248
- return src.src;
249
- }
250
- return typeof src === "string" ? src : "";
251
- },
252
- getHTMLAttributes(options) {
253
- const {
254
- src,
255
- width,
256
- height,
257
- format: _format,
258
- quality: _quality,
259
- densities: _densities,
260
- widths: _widths,
261
- formats: _formats,
262
- layout: _layout,
263
- priority: _priority,
264
- fit: _fit,
265
- position: _position,
266
- background: _background,
267
- ...attrs
268
- } = options;
269
- const srcObj = src != null && typeof src === "object" ? src : null;
270
- return {
271
- ...attrs,
272
- width: width ?? srcObj?.width,
273
- height: height ?? srcObj?.height,
274
- loading: attrs.loading ?? "lazy",
275
- decoding: attrs.decoding ?? "async"
276
- };
277
- },
278
- getSrcSet() {
279
- return [];
280
- }
281
- };
282
- }
283
-
284
266
  // src/lib/sanitization.ts
285
267
  import sanitizeHtml from "sanitize-html";
286
268
  var DEFAULT_SANITIZE_HTML_OPTIONS = {
@@ -595,25 +577,205 @@ function isRecord2(value) {
595
577
  return prototype === Object.prototype || prototype === null;
596
578
  }
597
579
 
598
- // src/module-mocks.ts
599
- import { AsyncLocalStorage } from "async_hooks";
600
- var moduleMockStorage = new AsyncLocalStorage();
601
- async function withStoryModuleMocks(moduleMocks, callback) {
602
- return moduleMockStorage.run(moduleMocks, callback);
580
+ // src/storyRulesRuntime.ts
581
+ async function runWithStoryRules(options, callback) {
582
+ const rulesConfigModule = options.resolveRulesConfigModule ? await options.resolveRulesConfigModule() : void 0;
583
+ const selectedRules = await selectStoryRules({
584
+ configModule: rulesConfigModule,
585
+ configFilePath: options.rulesConfigFilePath,
586
+ story: options.story
587
+ });
588
+ if (selectedRules.moduleMocks.size > 0) {
589
+ options.invalidateModuleGraph?.();
590
+ }
591
+ return withStoryRuleCleanups(selectedRules.cleanups, async () => {
592
+ return withStoryModuleMocks(selectedRules.moduleMocks, async () => callback(selectedRules));
593
+ });
594
+ }
595
+
596
+ // src/astroRenderHandler.ts
597
+ function createAstroRenderHandler(options) {
598
+ const sanitizationOptions = resolveSanitizationOptions(options.sanitization);
599
+ const componentCache = /* @__PURE__ */ new Map();
600
+ let renderQueue = Promise.resolve(void 0);
601
+ async function loadPatchedComponent(componentId, useCache = true) {
602
+ if (!useCache) {
603
+ const { default: component } = await options.loadModule(componentId);
604
+ return patchCreateAstroCompat(component);
605
+ }
606
+ if (!componentCache.has(componentId)) {
607
+ componentCache.set(
608
+ componentId,
609
+ (async () => {
610
+ const { default: component } = await options.loadModule(componentId);
611
+ return patchCreateAstroCompat(component);
612
+ })()
613
+ );
614
+ }
615
+ const cachedComponent = componentCache.get(componentId);
616
+ if (!cachedComponent) {
617
+ throw new Error(`Failed to load Astro component: ${componentId}`);
618
+ }
619
+ try {
620
+ return await cachedComponent;
621
+ } catch (error) {
622
+ componentCache.delete(componentId);
623
+ throw error;
624
+ }
625
+ }
626
+ return async function handler(data) {
627
+ const executeRender = async () => {
628
+ return runWithStoryRules(
629
+ {
630
+ story: data.story,
631
+ rulesConfigFilePath: options.rulesConfigFilePath,
632
+ resolveRulesConfigModule: options.resolveRulesConfigModule,
633
+ invalidateModuleGraph: options.invalidateModuleGraph
634
+ },
635
+ async (selectedRules) => {
636
+ const patchedComponent = await loadPatchedComponent(
637
+ data.component,
638
+ selectedRules.moduleMocks.size === 0
639
+ );
640
+ const processedArgs = await processImageMetadata(data.args ?? {});
641
+ const sanitizedPayload = sanitizeRenderPayload(
642
+ {
643
+ args: processedArgs,
644
+ slots: data.slots ?? {}
645
+ },
646
+ sanitizationOptions
647
+ );
648
+ return options.container.renderToString(
649
+ patchedComponent,
650
+ {
651
+ props: sanitizedPayload.args,
652
+ slots: sanitizedPayload.slots
653
+ }
654
+ );
655
+ }
656
+ );
657
+ };
658
+ const resultPromise = renderQueue.then(executeRender, executeRender);
659
+ renderQueue = resultPromise.then(
660
+ () => void 0,
661
+ () => void 0
662
+ );
663
+ return resultPromise;
664
+ };
603
665
  }
604
- function resolveStoryModuleMock(specifier) {
605
- return moduleMockStorage.getStore()?.get(specifier);
666
+ function patchCreateAstroCompat(component) {
667
+ if (typeof component !== "function") {
668
+ throw new Error("Expected Astro component factory to be a function.");
669
+ }
670
+ const originalComponent = component;
671
+ const wrapped = ((result, props, slots) => {
672
+ if (result && typeof result.createAstro === "function") {
673
+ const originalCreateAstro = result.createAstro;
674
+ const runtimeExpectsAstroGlobal = originalCreateAstro.length >= 3;
675
+ result.createAstro = (...args) => {
676
+ if (args.length === 3 && !runtimeExpectsAstroGlobal) {
677
+ return originalCreateAstro(args[1], args[2]);
678
+ }
679
+ return originalCreateAstro(...args);
680
+ };
681
+ }
682
+ return originalComponent(result, props, slots);
683
+ });
684
+ wrapped.isAstroComponentFactory = originalComponent.isAstroComponentFactory;
685
+ wrapped.moduleId = originalComponent.moduleId;
686
+ wrapped.propagation = originalComponent.propagation;
687
+ return wrapped;
688
+ }
689
+ async function processImageMetadata(args) {
690
+ const processed = {};
691
+ for (const [key, value] of Object.entries(args)) {
692
+ if (isImageMetadata(value)) {
693
+ processed[key] = value;
694
+ continue;
695
+ }
696
+ if (Array.isArray(value)) {
697
+ processed[key] = await Promise.all(
698
+ value.map(async (item) => {
699
+ if (isImageMetadata(item)) {
700
+ return item;
701
+ }
702
+ if (isRecord3(item)) {
703
+ return processImageMetadata(item);
704
+ }
705
+ return item;
706
+ })
707
+ );
708
+ continue;
709
+ }
710
+ if (isRecord3(value)) {
711
+ processed[key] = await processImageMetadata(value);
712
+ continue;
713
+ }
714
+ processed[key] = value;
715
+ }
716
+ return processed;
717
+ }
718
+ function isImageMetadata(value) {
719
+ return isRecord3(value) && typeof value.src === "string" && ("width" in value || "height" in value || "format" in value);
720
+ }
721
+ function isRecord3(value) {
722
+ return typeof value === "object" && value !== null;
723
+ }
724
+
725
+ // src/astroImageService.ts
726
+ function ensureAstroPassthroughImageService() {
727
+ if (!globalThis.astroAsset) {
728
+ globalThis.astroAsset = {};
729
+ }
730
+ globalThis.astroAsset.imageService = {
731
+ propertiesToHash: ["src"],
732
+ validateOptions(options) {
733
+ return options;
734
+ },
735
+ getURL(options) {
736
+ const src = options.src;
737
+ if (src != null && typeof src === "object" && "src" in src && typeof src.src === "string") {
738
+ return src.src;
739
+ }
740
+ return typeof src === "string" ? src : "";
741
+ },
742
+ getHTMLAttributes(options) {
743
+ const {
744
+ src,
745
+ width,
746
+ height,
747
+ format,
748
+ quality,
749
+ densities,
750
+ widths,
751
+ formats,
752
+ layout,
753
+ priority,
754
+ fit,
755
+ position,
756
+ background,
757
+ ...attrs
758
+ } = options;
759
+ const srcObject = src != null && typeof src === "object" ? src : null;
760
+ return {
761
+ ...attrs,
762
+ width: width ?? srcObject?.width,
763
+ height: height ?? srcObject?.height,
764
+ loading: attrs.loading ?? "lazy",
765
+ decoding: attrs.decoding ?? "async"
766
+ };
767
+ },
768
+ getSrcSet() {
769
+ return [];
770
+ }
771
+ };
606
772
  }
607
773
 
608
774
  export {
609
775
  defineStoryRules,
610
- selectStoryRules,
611
- withStoryRuleCleanups,
612
- installPassthroughImageService,
613
776
  resolveSanitizationOptions,
614
- sanitizeRenderPayload,
615
777
  serializeSanitizationOptions,
616
- withStoryModuleMocks,
617
- resolveStoryModuleMock
778
+ createAstroRenderHandler,
779
+ ensureAstroPassthroughImageService
618
780
  };
619
- //# sourceMappingURL=chunk-OUEDTRBO.js.map
781
+ //# sourceMappingURL=chunk-TWAO2IQW.js.map