astro 2.5.5 → 2.5.6

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 (46) hide show
  1. package/dist/@types/astro.d.ts +3 -2
  2. package/dist/assets/services/service.js +6 -0
  3. package/dist/assets/utils/emitAsset.d.ts +1 -3
  4. package/dist/assets/utils/emitAsset.js +4 -15
  5. package/dist/assets/vite-plugin-assets.js +5 -5
  6. package/dist/content/runtime-assets.d.ts +1 -2
  7. package/dist/content/runtime-assets.js +2 -3
  8. package/dist/content/runtime.js +1 -1
  9. package/dist/content/types-generator.js +9 -5
  10. package/dist/content/utils.d.ts +2 -2
  11. package/dist/content/utils.js +4 -4
  12. package/dist/content/vite-plugin-content-imports.js +113 -150
  13. package/dist/content/vite-plugin-content-virtual-mod.d.ts +3 -3
  14. package/dist/content/vite-plugin-content-virtual-mod.js +7 -3
  15. package/dist/core/app/index.d.ts +0 -2
  16. package/dist/core/app/index.js +5 -7
  17. package/dist/core/app/types.d.ts +3 -2
  18. package/dist/core/build/generate.js +16 -11
  19. package/dist/core/build/graph.js +3 -2
  20. package/dist/core/build/internal.d.ts +8 -4
  21. package/dist/core/build/internal.js +19 -1
  22. package/dist/core/build/plugins/plugin-css.js +9 -14
  23. package/dist/core/build/plugins/plugin-middleware.d.ts +0 -1
  24. package/dist/core/build/plugins/plugin-middleware.js +3 -16
  25. package/dist/core/build/plugins/plugin-pages.d.ts +10 -0
  26. package/dist/core/build/plugins/plugin-pages.js +40 -24
  27. package/dist/core/build/plugins/plugin-ssr.d.ts +2 -2
  28. package/dist/core/build/plugins/plugin-ssr.js +46 -20
  29. package/dist/core/build/static-build.js +18 -5
  30. package/dist/core/build/types.d.ts +2 -2
  31. package/dist/core/config/schema.d.ts +170 -170
  32. package/dist/core/constants.js +1 -1
  33. package/dist/core/dev/dev.js +1 -1
  34. package/dist/core/errors/errors-data.d.ts +57 -8
  35. package/dist/core/errors/errors-data.js +57 -12
  36. package/dist/core/messages.js +2 -2
  37. package/dist/core/render/dev/index.js +1 -2
  38. package/dist/prerender/routing.d.ts +13 -0
  39. package/dist/prerender/routing.js +49 -0
  40. package/dist/runtime/server/astro-global.js +11 -1
  41. package/dist/runtime/server/index.d.ts +1 -1
  42. package/dist/runtime/server/index.js +9 -1
  43. package/dist/runtime/server/render/astro/instance.js +3 -0
  44. package/dist/runtime/server/scripts.js +1 -1
  45. package/dist/vite-plugin-astro-server/route.js +3 -11
  46. package/package.json +4 -4
@@ -19,8 +19,6 @@ import {
19
19
  import { matchRoute } from "../routing/match.js";
20
20
  import { deserializeManifest } from "./common.js";
21
21
  const clientLocalsSymbol = Symbol.for("astro.locals");
22
- const pagesVirtualModuleId = "@astrojs-pages-virtual-entry";
23
- const resolvedPagesVirtualModuleId = "\0" + pagesVirtualModuleId;
24
22
  const responseSentSymbol = Symbol.for("astro.responseSent");
25
23
  class App {
26
24
  #env;
@@ -115,13 +113,15 @@ class App {
115
113
  if (routeData.route === "/404") {
116
114
  defaultStatus = 404;
117
115
  }
118
- let mod = await this.#manifest.pageMap.get(routeData.component)();
116
+ let page = await this.#manifest.pageMap.get(routeData.component)();
117
+ let mod = await page.page();
119
118
  if (routeData.type === "page") {
120
119
  let response = await this.#renderPage(request, routeData, mod, defaultStatus);
121
120
  if (response.status === 500 || response.status === 404) {
122
121
  const errorPageData = matchRoute("/" + response.status, this.#manifestData);
123
122
  if (errorPageData && errorPageData.route !== routeData.route) {
124
- mod = await this.#manifest.pageMap.get(errorPageData.component)();
123
+ page = await this.#manifest.pageMap.get(errorPageData.component)();
124
+ mod = await page.page();
125
125
  try {
126
126
  let errorResponse = await this.#renderPage(
127
127
  request,
@@ -265,7 +265,5 @@ class App {
265
265
  }
266
266
  export {
267
267
  App,
268
- deserializeManifest,
269
- pagesVirtualModuleId,
270
- resolvedPagesVirtualModuleId
268
+ deserializeManifest
271
269
  };
@@ -1,5 +1,6 @@
1
1
  import type { MarkdownRenderingOptions } from '@astrojs/markdown-remark';
2
- import type { AstroMiddlewareInstance, ComponentInstance, RouteData, SerializedRouteData, SSRComponentMetadata, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
2
+ import type { AstroMiddlewareInstance, RouteData, SerializedRouteData, SSRComponentMetadata, SSRLoadedRenderer, SSRResult } from '../../@types/astro';
3
+ import type { SinglePageBuiltModule } from '../build/types';
3
4
  export type ComponentPath = string;
4
5
  export type StylesheetAsset = {
5
6
  type: 'inline';
@@ -24,7 +25,7 @@ export interface RouteInfo {
24
25
  export type SerializedRouteInfo = Omit<RouteInfo, 'routeData'> & {
25
26
  routeData: SerializedRouteData;
26
27
  };
27
- type ImportComponentInstance = () => Promise<ComponentInstance>;
28
+ type ImportComponentInstance = () => Promise<SinglePageBuiltModule>;
28
29
  export interface SSRManifest {
29
30
  adapterName: string;
30
31
  routes: RouteInfo[];
@@ -6,7 +6,10 @@ import {
6
6
  generateImage as generateImageInternal,
7
7
  getStaticImageList
8
8
  } from "../../assets/generate.js";
9
- import { hasPrerenderedPages } from "../../core/build/internal.js";
9
+ import {
10
+ eachPageDataFromEntryPoint,
11
+ hasPrerenderedPages
12
+ } from "../../core/build/internal.js";
10
13
  import {
11
14
  prependForwardSlash,
12
15
  removeLeadingForwardSlash,
@@ -30,7 +33,7 @@ import { createRequest } from "../request.js";
30
33
  import { matchRoute } from "../routing/match.js";
31
34
  import { getOutputFilename } from "../util.js";
32
35
  import { getOutDirWithinCwd, getOutFile, getOutFolder } from "./common.js";
33
- import { cssOrder, eachPageData, getPageDataByComponent, mergeInlineCss } from "./internal.js";
36
+ import { cssOrder, getPageDataByComponent, mergeInlineCss } from "./internal.js";
34
37
  import { getTimeStat } from "./util.js";
35
38
  function shouldSkipDraft(pageModule, settings) {
36
39
  var _a;
@@ -66,17 +69,20 @@ async function generatePages(opts, internals) {
66
69
  const verb = ssr ? "prerendering" : "generating";
67
70
  info(opts.logging, null, `
68
71
  ${bgGreen(black(` ${verb} static routes `))}`);
69
- const ssrEntryURL = new URL("./" + serverEntry + `?time=${Date.now()}`, outFolder);
70
- const ssrEntry = await import(ssrEntryURL.toString());
71
72
  const builtPaths = /* @__PURE__ */ new Set();
72
73
  if (ssr) {
73
- for (const pageData of eachPageData(internals)) {
74
- if (pageData.route.prerender)
75
- await generatePage(opts, internals, pageData, ssrEntry, builtPaths);
74
+ for (const [pageData, filePath] of eachPageDataFromEntryPoint(internals)) {
75
+ if (pageData.route.prerender) {
76
+ const ssrEntryURLPage = new URL("./" + filePath + `?time=${Date.now()}`, outFolder);
77
+ const ssrEntryPage = await import(ssrEntryURLPage.toString());
78
+ await generatePage(opts, internals, pageData, ssrEntryPage, builtPaths);
79
+ }
76
80
  }
77
81
  } else {
78
- for (const pageData of eachPageData(internals)) {
79
- await generatePage(opts, internals, pageData, ssrEntry, builtPaths);
82
+ for (const [pageData, filePath] of eachPageDataFromEntryPoint(internals)) {
83
+ const ssrEntryURLPage = new URL("./" + filePath + `?time=${Date.now()}`, outFolder);
84
+ const ssrEntryPage = await import(ssrEntryURLPage.toString());
85
+ await generatePage(opts, internals, pageData, ssrEntryPage, builtPaths);
80
86
  }
81
87
  }
82
88
  if (opts.settings.config.experimental.assets) {
@@ -108,14 +114,13 @@ async function generateImage(opts, transform, path) {
108
114
  info(opts.logging, null, ` ${green("\u25B6")} ${path} ${dim(statsText)} ${dim(timeIncrease)}`);
109
115
  }
110
116
  async function generatePage(opts, internals, pageData, ssrEntry, builtPaths) {
111
- var _a;
112
117
  let timeStart = performance.now();
113
118
  const renderers = ssrEntry.renderers;
114
119
  const pageInfo = getPageDataByComponent(internals, pageData.route.component);
115
120
  const linkIds = [];
116
121
  const scripts = (pageInfo == null ? void 0 : pageInfo.hoistedScript) ?? null;
117
122
  const styles = pageData.styles.sort(cssOrder).map(({ sheet }) => sheet).reduce(mergeInlineCss, []);
118
- const pageModulePromise = (_a = ssrEntry.pageMap) == null ? void 0 : _a.get(pageData.component);
123
+ const pageModulePromise = ssrEntry.page;
119
124
  const middleware = ssrEntry.middleware;
120
125
  if (!pageModulePromise) {
121
126
  throw new Error(
@@ -1,4 +1,4 @@
1
- import { resolvedPagesVirtualModuleId } from "../app/index.js";
1
+ import { ASTRO_PAGE_RESOLVED_MODULE_ID } from "./plugins/plugin-pages.js";
2
2
  function* walkParentInfos(id, ctx, until, depth = 0, order = 0, seen = /* @__PURE__ */ new Set(), childId = "") {
3
3
  seen.add(id);
4
4
  const info = ctx.getModuleInfo(id);
@@ -25,7 +25,8 @@ function* walkParentInfos(id, ctx, until, depth = 0, order = 0, seen = /* @__PUR
25
25
  }
26
26
  }
27
27
  function moduleIsTopLevelPage(info) {
28
- return info.importers[0] === resolvedPagesVirtualModuleId || info.dynamicImporters[0] == resolvedPagesVirtualModuleId;
28
+ var _a, _b;
29
+ return ((_a = info.importers[0]) == null ? void 0 : _a.includes(ASTRO_PAGE_RESOLVED_MODULE_ID)) || ((_b = info.dynamicImporters[0]) == null ? void 0 : _b.includes(ASTRO_PAGE_RESOLVED_MODULE_ID));
29
30
  }
30
31
  function* getTopLevelPages(id, ctx) {
31
32
  for (const res of walkParentInfos(id, ctx)) {
@@ -1,13 +1,16 @@
1
1
  import type { Rollup } from 'vite';
2
- import type { PageBuildData, StylesheetAsset, ViteID } from './types';
3
2
  import type { SSRResult } from '../../@types/astro';
4
3
  import type { PageOptions } from '../../vite-plugin-astro/types';
4
+ import type { PageBuildData, StylesheetAsset, ViteID } from './types';
5
5
  export interface BuildInternals {
6
6
  /**
7
- * The module ids of all CSS chunks, used to deduplicate CSS assets between
8
- * SSR build and client build in vite-plugin-css.
7
+ * Each CSS module is named with a chunk id derived from the Astro pages they
8
+ * are used in by default. It's easy to crawl this relation in the SSR build as
9
+ * the Astro pages are the entrypoint, but not for the client build as hydratable
10
+ * components are the entrypoint instead. This map is used as a cache from the SSR
11
+ * build so the client can pick up the same information and use the same chunk ids.
9
12
  */
10
- cssChunkModuleIds: Set<string>;
13
+ cssModuleToChunkIdMap: Map<string, string>;
11
14
  hoistedScriptIdToHoistedMap: Map<string, Set<string>>;
12
15
  hoistedScriptIdToPagesMap: Map<string, Set<string>>;
13
16
  entrySpecifierToBundleMap: Map<string, string>;
@@ -76,6 +79,7 @@ export declare function getPageDataByComponent(internals: BuildInternals, compon
76
79
  export declare function getPageDataByViteID(internals: BuildInternals, viteid: ViteID): PageBuildData | undefined;
77
80
  export declare function hasPageDataByViteID(internals: BuildInternals, viteid: ViteID): boolean;
78
81
  export declare function eachPageData(internals: BuildInternals): Generator<PageBuildData, void, undefined>;
82
+ export declare function eachPageDataFromEntryPoint(internals: BuildInternals): Generator<[PageBuildData, string]>;
79
83
  export declare function hasPrerenderedPages(internals: BuildInternals): boolean;
80
84
  interface OrderInfo {
81
85
  depth: number;
@@ -1,10 +1,11 @@
1
1
  import { prependForwardSlash, removeFileExtension } from "../path.js";
2
2
  import { viteID } from "../util.js";
3
+ import { ASTRO_PAGE_EXTENSION_POST_PATTERN, ASTRO_PAGE_MODULE_ID } from "./plugins/plugin-pages.js";
3
4
  function createBuildInternals() {
4
5
  const hoistedScriptIdToHoistedMap = /* @__PURE__ */ new Map();
5
6
  const hoistedScriptIdToPagesMap = /* @__PURE__ */ new Map();
6
7
  return {
7
- cssChunkModuleIds: /* @__PURE__ */ new Set(),
8
+ cssModuleToChunkIdMap: /* @__PURE__ */ new Map(),
8
9
  hoistedScriptIdToHoistedMap,
9
10
  hoistedScriptIdToPagesMap,
10
11
  entrySpecifierToBundleMap: /* @__PURE__ */ new Map(),
@@ -82,6 +83,22 @@ function hasPageDataByViteID(internals, viteid) {
82
83
  function* eachPageData(internals) {
83
84
  yield* internals.pagesByComponent.values();
84
85
  }
86
+ function* eachPageDataFromEntryPoint(internals) {
87
+ for (const [entryPoint, filePath] of internals.entrySpecifierToBundleMap) {
88
+ if (entryPoint.includes(ASTRO_PAGE_MODULE_ID)) {
89
+ const [, pageName] = entryPoint.split(":");
90
+ const pageData = internals.pagesByComponent.get(
91
+ `${pageName.replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".")}`
92
+ );
93
+ if (!pageData) {
94
+ throw new Error(
95
+ "Build failed. Astro couldn't find the emitted page from " + pageName + " pattern"
96
+ );
97
+ }
98
+ yield [pageData, filePath];
99
+ }
100
+ }
101
+ }
85
102
  function hasPrerenderedPages(internals) {
86
103
  for (const pageData of eachPageData(internals)) {
87
104
  if (pageData.route.prerender) {
@@ -140,6 +157,7 @@ export {
140
157
  createBuildInternals,
141
158
  cssOrder,
142
159
  eachPageData,
160
+ eachPageDataFromEntryPoint,
143
161
  getPageDataByComponent,
144
162
  getPageDataByViteID,
145
163
  getPageDatasByChunk,
@@ -37,28 +37,28 @@ function rollupPluginAstroBuildCSS(options) {
37
37
  const pagesToPropagatedCss = {};
38
38
  const cssBuildPlugin = {
39
39
  name: "astro:rollup-plugin-build-css",
40
- transform(_, id) {
41
- if (options.target === "client" && internals.cssChunkModuleIds.has(id)) {
42
- return "";
43
- }
44
- },
45
40
  outputOptions(outputOptions) {
46
- if (options.target === "client")
47
- return;
48
41
  const assetFileNames = outputOptions.assetFileNames;
49
42
  const namingIncludesHash = assetFileNames == null ? void 0 : assetFileNames.toString().includes("[hash]");
50
43
  const createNameForParentPages = namingIncludesHash ? assetName.shortHashedName : assetName.createSlugger(settings);
51
44
  extendManualChunks(outputOptions, {
52
45
  after(id, meta) {
53
46
  if (isBuildableCSSRequest(id)) {
47
+ if (options.target === "client") {
48
+ return internals.cssModuleToChunkIdMap.get(id);
49
+ }
54
50
  for (const [pageInfo] of walkParentInfos(id, {
55
51
  getModuleInfo: meta.getModuleInfo
56
52
  })) {
57
53
  if (new URL(pageInfo.id, "file://").searchParams.has(PROPAGATED_ASSET_FLAG)) {
58
- return createNameHash(id, [id]);
54
+ const chunkId2 = createNameHash(id, [id]);
55
+ internals.cssModuleToChunkIdMap.set(id, chunkId2);
56
+ return chunkId2;
59
57
  }
60
58
  }
61
- return createNameForParentPages(id, meta);
59
+ const chunkId = createNameForParentPages(id, meta);
60
+ internals.cssModuleToChunkIdMap.set(id, chunkId);
61
+ return chunkId;
62
62
  }
63
63
  }
64
64
  });
@@ -72,11 +72,6 @@ function rollupPluginAstroBuildCSS(options) {
72
72
  const meta = chunk.viteMetadata;
73
73
  if (meta.importedCss.size < 1)
74
74
  continue;
75
- if (options.target === "server") {
76
- for (const id of Object.keys(chunk.modules)) {
77
- internals.cssChunkModuleIds.add(id);
78
- }
79
- }
80
75
  if (options.target === "client") {
81
76
  for (const id of Object.keys(chunk.modules)) {
82
77
  for (const pageData of getParentClientOnlys(id, this, internals)) {
@@ -3,6 +3,5 @@ import type { BuildInternals } from '../internal.js';
3
3
  import type { AstroBuildPlugin } from '../plugin';
4
4
  import type { StaticBuildOptions } from '../types';
5
5
  export declare const MIDDLEWARE_MODULE_ID = "@astro-middleware";
6
- export declare const RESOLVED_MIDDLEWARE_MODULE_ID = "\0@astro-middleware";
7
6
  export declare function vitePluginMiddleware(opts: StaticBuildOptions, _internals: BuildInternals): VitePlugin;
8
7
  export declare function pluginMiddleware(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
@@ -1,8 +1,6 @@
1
1
  import { MIDDLEWARE_PATH_SEGMENT_NAME } from "../../constants.js";
2
2
  import { addRollupInput } from "../add-rollup-input.js";
3
3
  const MIDDLEWARE_MODULE_ID = "@astro-middleware";
4
- const RESOLVED_MIDDLEWARE_MODULE_ID = "\0@astro-middleware";
5
- let inputs = /* @__PURE__ */ new Set();
6
4
  function vitePluginMiddleware(opts, _internals) {
7
5
  return {
8
6
  name: "@astro/plugin-middleware",
@@ -11,24 +9,14 @@ function vitePluginMiddleware(opts, _internals) {
11
9
  return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
12
10
  }
13
11
  },
14
- resolveId(id) {
12
+ async resolveId(id) {
15
13
  if (id === MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
16
- return RESOLVED_MIDDLEWARE_MODULE_ID;
17
- }
18
- },
19
- async load(id) {
20
- if (id === RESOLVED_MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
21
- const imports = [];
22
- const exports = [];
23
- let middlewareId = await this.resolve(
14
+ const middlewareId = await this.resolve(
24
15
  `${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
25
16
  );
26
17
  if (middlewareId) {
27
- imports.push(`import { onRequest } from "${middlewareId.id}"`);
28
- exports.push(`export { onRequest }`);
18
+ return middlewareId.id;
29
19
  }
30
- const result = [imports.join("\n"), exports.join("\n")];
31
- return result.join("\n");
32
20
  }
33
21
  }
34
22
  };
@@ -47,7 +35,6 @@ function pluginMiddleware(opts, internals) {
47
35
  }
48
36
  export {
49
37
  MIDDLEWARE_MODULE_ID,
50
- RESOLVED_MIDDLEWARE_MODULE_ID,
51
38
  pluginMiddleware,
52
39
  vitePluginMiddleware
53
40
  };
@@ -1,4 +1,14 @@
1
1
  import { type BuildInternals } from '../internal.js';
2
2
  import type { AstroBuildPlugin } from '../plugin';
3
3
  import type { StaticBuildOptions } from '../types';
4
+ export declare const ASTRO_PAGE_MODULE_ID = "@astro-page:";
5
+ export declare const ASTRO_PAGE_RESOLVED_MODULE_ID = "\0@astro-page:";
6
+ export declare const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
7
+ /**
8
+ * 1. We add a fixed prefix, which is used as virtual module naming convention;
9
+ * 2. We replace the dot that belongs extension with an arbitrary string.
10
+ *
11
+ * @param path
12
+ */
13
+ export declare function getVirtualModulePageNameFromPath(path: string): string;
4
14
  export declare function pluginPages(opts: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
@@ -1,44 +1,56 @@
1
- import { pagesVirtualModuleId, resolvedPagesVirtualModuleId } from "../../app/index.js";
1
+ import { extname } from "node:path";
2
2
  import { addRollupInput } from "../add-rollup-input.js";
3
- import { eachPageData } from "../internal.js";
4
3
  import { MIDDLEWARE_MODULE_ID } from "./plugin-middleware.js";
5
4
  import { RENDERERS_MODULE_ID } from "./plugin-renderers.js";
5
+ const ASTRO_PAGE_MODULE_ID = "@astro-page:";
6
+ const ASTRO_PAGE_RESOLVED_MODULE_ID = "\0@astro-page:";
7
+ const ASTRO_PAGE_EXTENSION_POST_PATTERN = "@_@";
8
+ function getVirtualModulePageNameFromPath(path) {
9
+ const extension = extname(path);
10
+ return `${ASTRO_PAGE_MODULE_ID}${path.replace(
11
+ extension,
12
+ extension.replace(".", ASTRO_PAGE_EXTENSION_POST_PATTERN)
13
+ )}`;
14
+ }
6
15
  function vitePluginPages(opts, internals) {
7
16
  return {
8
17
  name: "@astro/plugin-build-pages",
9
18
  options(options) {
10
19
  if (opts.settings.config.output === "static") {
11
- return addRollupInput(options, [pagesVirtualModuleId]);
20
+ const inputs = /* @__PURE__ */ new Set();
21
+ for (const path of Object.keys(opts.allPages)) {
22
+ inputs.add(getVirtualModulePageNameFromPath(path));
23
+ }
24
+ return addRollupInput(options, Array.from(inputs));
12
25
  }
13
26
  },
14
27
  resolveId(id) {
15
- if (id === pagesVirtualModuleId) {
16
- return resolvedPagesVirtualModuleId;
28
+ if (id.startsWith(ASTRO_PAGE_MODULE_ID)) {
29
+ return "\0" + id;
17
30
  }
18
31
  },
19
32
  async load(id) {
20
- if (id === resolvedPagesVirtualModuleId) {
21
- let importMap = "";
33
+ if (id.startsWith(ASTRO_PAGE_RESOLVED_MODULE_ID)) {
22
34
  const imports = [];
23
35
  const exports = [];
24
- const content = [];
25
- let i = 0;
26
- imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
27
- exports.push(`export { renderers };`);
28
- for (const pageData of eachPageData(internals)) {
29
- const variable = `_page${i}`;
30
- imports.push(
31
- `const ${variable} = () => import(${JSON.stringify(pageData.moduleSpecifier)});`
32
- );
33
- importMap += `[${JSON.stringify(pageData.component)}, ${variable}],`;
34
- i++;
35
- }
36
- if (opts.settings.config.experimental.middleware) {
37
- imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}";`);
38
- exports.push(`export const middleware = _middleware;`);
36
+ const pageName = id.slice(ASTRO_PAGE_RESOLVED_MODULE_ID.length);
37
+ const pageData = internals.pagesByComponent.get(
38
+ `${pageName.replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".")}`
39
+ );
40
+ if (pageData) {
41
+ const resolvedPage = await this.resolve(pageData.moduleSpecifier);
42
+ if (resolvedPage) {
43
+ imports.push(`const page = () => import(${JSON.stringify(pageData.moduleSpecifier)});`);
44
+ exports.push(`export { page }`);
45
+ imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
46
+ exports.push(`export { renderers };`);
47
+ if (opts.settings.config.experimental.middleware) {
48
+ imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}";`);
49
+ exports.push(`export const middleware = _middleware;`);
50
+ }
51
+ return `${imports.join("\n")}${exports.join("\n")}`;
52
+ }
39
53
  }
40
- content.push(`export const pageMap = new Map([${importMap}]);`);
41
- return `${imports.join("\n")}${content.join("\n")}${exports.join("\n")}`;
42
54
  }
43
55
  }
44
56
  };
@@ -56,5 +68,9 @@ function pluginPages(opts, internals) {
56
68
  };
57
69
  }
58
70
  export {
71
+ ASTRO_PAGE_EXTENSION_POST_PATTERN,
72
+ ASTRO_PAGE_MODULE_ID,
73
+ ASTRO_PAGE_RESOLVED_MODULE_ID,
74
+ getVirtualModulePageNameFromPath,
59
75
  pluginPages
60
76
  };
@@ -1,6 +1,6 @@
1
- import type { StaticBuildOptions } from '../types';
2
1
  import { type BuildInternals } from '../internal.js';
3
2
  import type { AstroBuildPlugin } from '../plugin';
4
- export declare const virtualModuleId = "@astrojs-ssr-virtual-entry";
3
+ import type { StaticBuildOptions } from '../types';
4
+ export declare const SSR_VIRTUAL_MODULE_ID = "@astrojs-ssr-virtual-entry";
5
5
  export declare function injectManifest(buildOpts: StaticBuildOptions, internals: BuildInternals): Promise<string>;
6
6
  export declare function pluginSSR(options: StaticBuildOptions, internals: BuildInternals): AstroBuildPlugin;
@@ -3,49 +3,74 @@ import { fileURLToPath } from "url";
3
3
  import { runHookBuildSsr } from "../../../integrations/index.js";
4
4
  import { isHybridOutput } from "../../../prerender/utils.js";
5
5
  import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from "../../../vite-plugin-scripts/index.js";
6
- import { pagesVirtualModuleId } from "../../app/index.js";
7
6
  import { joinPaths, prependForwardSlash } from "../../path.js";
8
7
  import { serializeRouteData } from "../../routing/index.js";
9
8
  import { addRollupInput } from "../add-rollup-input.js";
10
9
  import { getOutFile, getOutFolder } from "../common.js";
11
10
  import { cssOrder, mergeInlineCss } from "../internal.js";
11
+ import { MIDDLEWARE_MODULE_ID } from "./plugin-middleware.js";
12
+ import { getVirtualModulePageNameFromPath } from "./plugin-pages.js";
12
13
  import { RENDERERS_MODULE_ID } from "./plugin-renderers.js";
13
- const virtualModuleId = "@astrojs-ssr-virtual-entry";
14
- const resolvedVirtualModuleId = "\0" + virtualModuleId;
14
+ const SSR_VIRTUAL_MODULE_ID = "@astrojs-ssr-virtual-entry";
15
+ const RESOLVED_SSR_VIRTUAL_MODULE_ID = "\0" + SSR_VIRTUAL_MODULE_ID;
15
16
  const manifestReplace = "@@ASTRO_MANIFEST_REPLACE@@";
16
17
  const replaceExp = new RegExp(`['"](${manifestReplace})['"]`, "g");
17
- function vitePluginSSR(internals, adapter, config) {
18
+ function vitePluginSSR(internals, adapter, options) {
18
19
  return {
19
20
  name: "@astrojs/vite-plugin-astro-ssr",
20
21
  enforce: "post",
21
22
  options(opts) {
22
- return addRollupInput(opts, [virtualModuleId]);
23
+ return addRollupInput(opts, [SSR_VIRTUAL_MODULE_ID]);
23
24
  },
24
25
  resolveId(id) {
25
- if (id === virtualModuleId) {
26
- return resolvedVirtualModuleId;
26
+ if (id === SSR_VIRTUAL_MODULE_ID) {
27
+ return RESOLVED_SSR_VIRTUAL_MODULE_ID;
27
28
  }
28
29
  },
29
- load(id) {
30
+ async load(id) {
30
31
  var _a;
31
- if (id === resolvedVirtualModuleId) {
32
- let middleware = "";
32
+ if (id === RESOLVED_SSR_VIRTUAL_MODULE_ID) {
33
+ const {
34
+ settings: { config },
35
+ allPages
36
+ } = options;
37
+ const imports = [];
38
+ const contents = [];
39
+ const exports = [];
40
+ let middleware;
33
41
  if (((_a = config.experimental) == null ? void 0 : _a.middleware) === true) {
34
- middleware = "middleware: _main.middleware";
42
+ imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}"`);
43
+ middleware = "middleware: _middleware";
35
44
  }
36
- return `import * as adapter from '${adapter.serverEntrypoint}';
45
+ let i = 0;
46
+ const pageMap = [];
47
+ for (const path of Object.keys(allPages)) {
48
+ const virtualModuleName = getVirtualModulePageNameFromPath(path);
49
+ let module = await this.resolve(virtualModuleName);
50
+ if (module) {
51
+ const variable = `_page${i}`;
52
+ imports.push(`const ${variable} = () => import("${virtualModuleName}");`);
53
+ const pageData = internals.pagesByComponent.get(path);
54
+ if (pageData) {
55
+ pageMap.push(`[${JSON.stringify(pageData.component)}, ${variable}]`);
56
+ }
57
+ i++;
58
+ }
59
+ }
60
+ contents.push(`const pageMap = new Map([${pageMap.join(",")}]);`);
61
+ exports.push(`export { pageMap }`);
62
+ const content = `import * as adapter from '${adapter.serverEntrypoint}';
37
63
  import { renderers } from '${RENDERERS_MODULE_ID}';
38
- import * as _main from '${pagesVirtualModuleId}';
39
64
  import { deserializeManifest as _deserializeManifest } from 'astro/app';
40
65
  import { _privateSetManifestDontUseThis } from 'astro:ssr-manifest';
41
66
  const _manifest = Object.assign(_deserializeManifest('${manifestReplace}'), {
42
- pageMap: _main.pageMap,
43
- renderers: _main.renderers,
67
+ pageMap,
68
+ renderers,
44
69
  ${middleware}
45
70
  });
46
71
  _privateSetManifestDontUseThis(_manifest);
47
72
  const _args = ${adapter.args ? JSON.stringify(adapter.args) : "undefined"};
48
- export * from '${pagesVirtualModuleId}';
73
+
49
74
  ${adapter.exports ? `const _exports = adapter.createExports(_manifest, _args);
50
75
  ${adapter.exports.map((name) => {
51
76
  if (name === "default") {
@@ -60,6 +85,7 @@ const _start = 'start';
60
85
  if(_start in adapter) {
61
86
  adapter[_start](_manifest, _args);
62
87
  }`;
88
+ return `${imports.join("\n")}${contents.join("\n")}${content}${exports.join("\n")}`;
63
89
  }
64
90
  return void 0;
65
91
  },
@@ -73,7 +99,7 @@ if(_start in adapter) {
73
99
  if (chunk.type === "asset") {
74
100
  continue;
75
101
  }
76
- if (chunk.modules[resolvedVirtualModuleId]) {
102
+ if (chunk.modules[RESOLVED_SSR_VIRTUAL_MODULE_ID]) {
77
103
  internals.ssrEntryChunk = chunk;
78
104
  delete bundle[chunkName];
79
105
  }
@@ -196,7 +222,7 @@ function pluginSSR(options, internals) {
196
222
  build: "ssr",
197
223
  hooks: {
198
224
  "build:before": () => {
199
- let vitePlugin = ssr ? vitePluginSSR(internals, options.settings.adapter, options.settings.config) : void 0;
225
+ let vitePlugin = ssr ? vitePluginSSR(internals, options.settings.adapter, options) : void 0;
200
226
  return {
201
227
  enforce: "after-user-plugins",
202
228
  vitePlugin
@@ -217,7 +243,7 @@ function pluginSSR(options, internals) {
217
243
  };
218
244
  }
219
245
  export {
246
+ SSR_VIRTUAL_MODULE_ID,
220
247
  injectManifest,
221
- pluginSSR,
222
- virtualModuleId
248
+ pluginSSR
223
249
  };
@@ -16,7 +16,6 @@ import { isModeServerWithNoAdapter } from "../../core/util.js";
16
16
  import { runHookBuildSetup } from "../../integrations/index.js";
17
17
  import { isHybridOutput } from "../../prerender/utils.js";
18
18
  import { PAGE_SCRIPT_ID } from "../../vite-plugin-scripts/index.js";
19
- import { resolvedPagesVirtualModuleId } from "../app/index.js";
20
19
  import { AstroError, AstroErrorData } from "../errors/index.js";
21
20
  import { info } from "../logger/core.js";
22
21
  import { getOutDirWithinCwd } from "./common.js";
@@ -24,8 +23,12 @@ import { generatePages } from "./generate.js";
24
23
  import { trackPageData } from "./internal.js";
25
24
  import { createPluginContainer } from "./plugin.js";
26
25
  import { registerAllPlugins } from "./plugins/index.js";
27
- import { RESOLVED_MIDDLEWARE_MODULE_ID } from "./plugins/plugin-middleware.js";
26
+ import {
27
+ ASTRO_PAGE_EXTENSION_POST_PATTERN,
28
+ ASTRO_PAGE_RESOLVED_MODULE_ID
29
+ } from "./plugins/plugin-pages.js";
28
30
  import { RESOLVED_RENDERERS_MODULE_ID } from "./plugins/plugin-renderers.js";
31
+ import { SSR_VIRTUAL_MODULE_ID } from "./plugins/plugin-ssr.js";
29
32
  import { getTimeStat } from "./util.js";
30
33
  async function viteBuild(opts) {
31
34
  var _a, _b, _c;
@@ -129,10 +132,17 @@ async function ssrBuild(opts, internals, input, container) {
129
132
  assetFileNames: `${settings.config.build.assets}/[name].[hash][extname]`,
130
133
  ...(_e = (_d = viteConfig.build) == null ? void 0 : _d.rollupOptions) == null ? void 0 : _e.output,
131
134
  entryFileNames(chunkInfo) {
132
- if (chunkInfo.facadeModuleId === resolvedPagesVirtualModuleId) {
133
- return opts.buildConfig.serverEntry;
134
- } else if (chunkInfo.facadeModuleId === RESOLVED_MIDDLEWARE_MODULE_ID) {
135
+ var _a2, _b2;
136
+ if ((_a2 = chunkInfo.facadeModuleId) == null ? void 0 : _a2.startsWith(ASTRO_PAGE_RESOLVED_MODULE_ID)) {
137
+ return makeAstroPageEntryPointFileName(chunkInfo.facadeModuleId);
138
+ } else if (
139
+ // checks if the path of the module we have middleware, e.g. middleware.js / middleware/index.js
140
+ ((_b2 = chunkInfo.facadeModuleId) == null ? void 0 : _b2.includes("middleware")) && // checks if the file actually export the `onRequest` function
141
+ chunkInfo.exports.includes("onRequest")
142
+ ) {
135
143
  return "middleware.mjs";
144
+ } else if (chunkInfo.facadeModuleId === SSR_VIRTUAL_MODULE_ID) {
145
+ return opts.settings.config.build.serverEntry;
136
146
  } else if (chunkInfo.facadeModuleId === RESOLVED_RENDERERS_MODULE_ID) {
137
147
  return "renderers.mjs";
138
148
  } else {
@@ -315,6 +325,9 @@ async function ssrMoveAssets(opts) {
315
325
  removeEmptyDirs(serverAssets);
316
326
  }
317
327
  }
328
+ function makeAstroPageEntryPointFileName(facadeModuleId) {
329
+ return `${facadeModuleId.replace(ASTRO_PAGE_RESOLVED_MODULE_ID, "").replace("src/", "").replaceAll("[", "_").replaceAll("]", "_").replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, ".")}.mjs`;
330
+ }
318
331
  export {
319
332
  staticBuild,
320
333
  viteBuild
@@ -44,8 +44,8 @@ export interface StaticBuildOptions {
44
44
  teardownCompiler: boolean;
45
45
  }
46
46
  type ImportComponentInstance = () => Promise<ComponentInstance>;
47
- export interface SingleFileBuiltModule {
48
- pageMap: Map<ComponentPath, ImportComponentInstance>;
47
+ export interface SinglePageBuiltModule {
48
+ page: ImportComponentInstance;
49
49
  middleware: AstroMiddlewareInstance<unknown>;
50
50
  renderers: SSRLoadedRenderer[];
51
51
  }