@ecopages/core 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +19 -15
  2. package/package.json +13 -4
  3. package/src/adapters/create-app.js +9 -5
  4. package/src/adapters/node/create-app.d.ts +18 -16
  5. package/src/adapters/node/create-app.js +26 -30
  6. package/src/adapters/node/server-adapter.d.ts +26 -9
  7. package/src/adapters/node/server-adapter.js +38 -8
  8. package/src/adapters/shared/hmr/hmr-manager.js +3 -2
  9. package/src/adapters/shared/http/api-request-pipeline.js +2 -2
  10. package/src/adapters/shared/http/dist-file-handler.js +25 -7
  11. package/src/adapters/shared/runtime/render-context.d.ts +2 -1
  12. package/src/adapters/shared/runtime/render-context.js +18 -21
  13. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +4 -3
  14. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +6 -4
  15. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +6 -1
  16. package/src/adapters/shared/runtime/server-request-pipeline.js +11 -10
  17. package/src/adapters/shared/runtime/server-route-handler.js +4 -4
  18. package/src/adapters/shared/runtime/server-static-builder.d.ts +11 -11
  19. package/src/adapters/shared/runtime/server-static-builder.js +37 -18
  20. package/src/assets/app-browser-client-build.js +8 -21
  21. package/src/assets/app-browser-client-manifest.d.ts +1 -4
  22. package/src/assets/app-browser-client-manifest.js +6 -78
  23. package/src/assets/asset-processing-service/processors/script/file-script.processor.d.ts +2 -2
  24. package/src/assets/asset-processing-service/processors/script/file-script.processor.js +2 -2
  25. package/src/assets/browser-asset-output.d.ts +1 -1
  26. package/src/assets/browser-asset-output.js +1 -1
  27. package/src/build/app-build-manifest-runtime.d.ts +11 -1
  28. package/src/build/app-build-manifest-runtime.js +17 -3
  29. package/src/build/cache/pages-unified-graph-build.d.ts +32 -35
  30. package/src/build/cache/pages-unified-graph-build.js +206 -124
  31. package/src/build/cache/server-module-entries.d.ts +35 -0
  32. package/src/build/cache/server-module-entries.js +109 -0
  33. package/src/build/contracts/build-contracts.d.ts +5 -0
  34. package/src/build/contracts/content-virtual-modules.d.ts +9 -3
  35. package/src/build/contracts/content-virtual-modules.js +11 -5
  36. package/src/build/contracts.d.ts +1 -1
  37. package/src/build/contracts.js +1 -1
  38. package/src/build/copy-server-files.d.ts +10 -0
  39. package/src/build/copy-server-files.js +37 -0
  40. package/src/build/preserve-import-meta-transform.d.ts +1 -1
  41. package/src/build/preserve-import-meta-transform.js +1 -1
  42. package/src/build/production-build-id.d.ts +9 -0
  43. package/src/build/production-build-id.js +19 -0
  44. package/src/build/production-dist-complete.d.ts +5 -0
  45. package/src/build/production-dist-complete.js +101 -0
  46. package/src/build/production-route-list.d.ts +26 -0
  47. package/src/build/production-route-list.js +78 -0
  48. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +2 -2
  49. package/src/build/rolldown/rolldown-adapter-helpers.js +56 -4
  50. package/src/build/rolldown/rolldown-build-adapter.js +1 -1
  51. package/src/build/rolldown/rolldown-plugin-bridge.js +2 -2
  52. package/src/build/runtime/build-request-identity.js +2 -1
  53. package/src/build/runtime/build-request-policy.d.ts +3 -2
  54. package/src/build/runtime/build-request-policy.js +5 -3
  55. package/src/build/server/import-view-module.d.ts +11 -0
  56. package/src/build/server/import-view-module.js +21 -0
  57. package/src/build/server/imported-view-plugin.d.ts +16 -0
  58. package/src/build/server/imported-view-plugin.js +59 -0
  59. package/src/build/server/page-module-import.service.d.ts +19 -20
  60. package/src/build/server/page-module-import.service.js +65 -36
  61. package/src/build/server/resolve-static-view.d.ts +9 -0
  62. package/src/build/server/resolve-static-view.js +28 -0
  63. package/src/build/server/route-module-build-cache-registry.d.ts +5 -3
  64. package/src/build/server/route-module-build-cache-registry.js +5 -3
  65. package/src/build/server/server-modules-manifest.d.ts +51 -0
  66. package/src/build/server/server-modules-manifest.js +129 -0
  67. package/src/build/server/view-reference.d.ts +38 -0
  68. package/src/build/server/view-reference.js +112 -0
  69. package/src/build/server-bundle-deploy-manifest.d.ts +9 -9
  70. package/src/build/server-bundle-deploy-manifest.js +24 -28
  71. package/src/build.d.ts +4 -2
  72. package/src/build.js +4 -2
  73. package/src/config/assembly/app-runtime.d.ts +15 -2
  74. package/src/config/assembly/app-runtime.js +3 -1
  75. package/src/config/assembly/finalize-config.js +64 -13
  76. package/src/config/index.d.ts +1 -0
  77. package/src/config/index.js +1 -0
  78. package/src/config/internal-types.d.ts +6 -0
  79. package/src/config/load-eco-config.d.ts +1 -0
  80. package/src/config/load-eco-config.js +11 -2
  81. package/src/config/resolve-eco-config-path.d.ts +2 -1
  82. package/src/config/resolve-eco-config-path.js +21 -15
  83. package/src/config/user-config-types.d.ts +9 -2
  84. package/src/dev/transform-server/dev-transform-server.js +1 -1
  85. package/src/dev/transform-server/dev-transform-vendor-registry.d.ts +29 -6
  86. package/src/dev/transform-server/dev-transform-vendor-registry.js +101 -53
  87. package/src/errors/http-error.d.ts +9 -0
  88. package/src/errors/http-error.js +11 -0
  89. package/src/html/html-transformer.service.d.ts +0 -21
  90. package/src/html/html-transformer.service.js +0 -32
  91. package/src/html-pages/html-page-module.d.ts +19 -0
  92. package/src/html-pages/html-page-module.js +66 -13
  93. package/src/html-pages/html-page-renderer.d.ts +6 -1
  94. package/src/html-pages/html-page-renderer.js +14 -6
  95. package/src/html-pages/html-pages.plugin.d.ts +10 -0
  96. package/src/html-pages/html-pages.plugin.js +7 -1
  97. package/src/index.d.ts +2 -0
  98. package/src/index.js +2 -0
  99. package/src/integration.d.ts +2 -2
  100. package/src/integration.js +1 -1
  101. package/src/islands/island-host.d.ts +1 -2
  102. package/src/islands/island-host.js +1 -2
  103. package/src/page-cache/page-cache-service.d.ts +8 -0
  104. package/src/page-cache/page-cache-service.js +12 -0
  105. package/src/plugins/integration-plugin.d.ts +34 -7
  106. package/src/plugins/integration-plugin.js +14 -2
  107. package/src/plugins/processor.d.ts +18 -1
  108. package/src/plugins/processor.js +20 -1
  109. package/src/plugins/server-dom.d.ts +29 -0
  110. package/src/plugins/server-dom.js +36 -0
  111. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  112. package/src/plugins/tsconfig-import-resolver.js +4 -2
  113. package/src/processor.d.ts +1 -1
  114. package/src/route-renderer/error-pages/error-page-renderer.d.ts +6 -4
  115. package/src/route-renderer/error-pages/error-page-renderer.js +9 -5
  116. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +2 -44
  117. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +14 -89
  118. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +4 -16
  119. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +2 -10
  120. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +3 -5
  121. package/src/route-renderer/orchestration/integration-renderer.d.ts +21 -44
  122. package/src/route-renderer/orchestration/integration-renderer.js +69 -117
  123. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.d.ts +3 -4
  124. package/src/route-renderer/orchestration/ownership-graph/page-client-browser-assets.js +4 -15
  125. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.d.ts +22 -0
  126. package/src/route-renderer/orchestration/ownership-graph/prepared-graph-membership.js +45 -0
  127. package/src/route-renderer/orchestration/page-browser-graph/grouped-graph-build-plan.d.ts +0 -1
  128. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.d.ts +21 -0
  129. package/src/route-renderer/orchestration/page-browser-graph/missing-production-browser-graph.js +31 -0
  130. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +58 -24
  131. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.d.ts +12 -0
  132. package/src/route-renderer/orchestration/page-browser-graph/route-instance-key.js +55 -0
  133. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +4 -3
  134. package/src/router/server/route-registry.d.ts +23 -1
  135. package/src/router/server/route-registry.js +41 -14
  136. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +8 -2
  137. package/src/static-site-generator/production-page-browser-graph-prebuild.js +14 -13
  138. package/src/static-site-generator/static-site-generator.d.ts +19 -3
  139. package/src/static-site-generator/static-site-generator.js +78 -40
  140. package/src/types/build-types.d.ts +6 -0
  141. package/src/types/contracts.d.ts +26 -35
  142. package/src/types/eco-api-types.d.ts +1 -1
  143. package/src/types/public-types.d.ts +1 -0
  144. package/src/types/view-reference.d.ts +31 -0
  145. package/src/types/view-reference.js +15 -0
  146. package/src/utils/additional-watch-paths.d.ts +3 -3
  147. package/src/utils/additional-watch-paths.js +3 -1
  148. package/src/utils/resolve-entry-file.d.ts +4 -2
  149. package/src/utils/resolve-entry-file.js +4 -2
  150. package/src/utils/root-relative-path.d.ts +4 -0
  151. package/src/utils/root-relative-path.js +8 -0
  152. package/src/utils/server-bundle-context.d.ts +14 -0
  153. package/src/utils/server-bundle-context.js +45 -0
  154. package/src/watchers/project-watcher-ignore.d.ts +2 -5
  155. package/src/watchers/project-watcher-ignore.js +2 -5
  156. package/src/watchers/project-watcher.d.ts +9 -7
  157. package/src/watchers/project-watcher.js +100 -52
  158. package/src/watchers/workspace-package-watch-roots.d.ts +4 -4
  159. package/src/watchers/workspace-package-watch-roots.js +41 -25
  160. package/src/build/server/view-module-loader.d.ts +0 -10
  161. package/src/build/server/view-module-loader.js +0 -46
  162. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.d.ts +0 -12
  163. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-merge.utils.js +0 -32
@@ -1,30 +1,34 @@
1
1
  /**
2
- * Unified pages Rolldown graph (Phase A build + Phase C import).
2
+ * Unified production server-module graph.
3
3
  *
4
- * Enabled by default in production builds. Opt out with
5
- * `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0`. Covers all static page template extensions
6
- * registered on the app config.
4
+ * `ecopages build` emits every server entry into `dist/server/` and writes
5
+ * `server-modules.json`. `ecopages start` imports those modules and never compiles.
7
6
  */
8
7
  import path from 'node:path';
9
- import { isEcopagesEnvDisabled } from '../../env.js';
10
- import { isProductionRuntime } from '../../utils/runtime.js';
11
8
  import { pathToFileURL } from 'node:url';
12
9
  import { fileSystem } from '@ecopages/file-system';
10
+ import { isEcopagesEnvDisabled } from '../../env.js';
11
+ import { isProductionRuntime } from '../../utils/runtime.js';
13
12
  import { requireAppRuntime } from '../../utils/app-runtime.js';
13
+ import { setupAppRuntimeIntegrations } from '../app-build-manifest-runtime.js';
14
14
  import { appLogger } from '../../global/app-logger.js';
15
15
  import { findIntegrationForFile } from '../../plugins/find-integration-for-file.js';
16
16
  import { buildOrThrow } from '../runtime/build-queue.js';
17
- import { createServerBuildRequest, resolveAppBuildPlugins } from '../runtime/build-request-policy.js';
18
- import { hashAppConfigFile } from './app-config-hash.js';
19
- import { collectBuildOutputImports, getBuildEntryOutput } from '../build-graph.js';
20
- import { getServerModuleBuildCacheOutdir } from '../server/route-module-build-cache-registry.js';
21
- import { RouteModuleDependencyHasher, resolveRouteModuleDependencyPaths, } from '../server/route-module-dependency-hasher.js';
17
+ import { createServerBuildRequest } from '../runtime/build-request-policy.js';
18
+ import { getBuildEntryOutput } from '../build-graph.js';
19
+ import { contentHash } from '../../utils/content-hash.js';
20
+ import { toRootRelativePath } from '../../utils/root-relative-path.js';
21
+ import { loadProductionServerModules, matchProductionModuleKey, writeProductionServerModulesManifest, } from '../server/server-modules-manifest.js';
22
+ import { getServerBundleOutputPaths } from '../server-bundle-deploy-manifest.js';
23
+ import { ensureProductionBuildId } from '../production-build-id.js';
24
+ import { collectServerModuleEntries, collectSsrScriptPaths, isRolldownServerModuleEntry, } from './server-module-entries.js';
22
25
  /**
23
- * True when the unified graph should build or serve prebuilt page modules.
26
+ * True when a production build should emit the server-modules map.
24
27
  *
25
28
  * @remarks
26
29
  * Enabled by default in production builds. `ECOPAGES_UNIFIED_PAGES_GRAPH=false` or `0` opts out, which the
27
- * bench parity suite uses as its per-page build oracle.
30
+ * bench parity suite uses as its per-page build oracle. Production `ecopages start` still requires
31
+ * the emitted server-modules map from a build that did emit.
28
32
  */
29
33
  export function shouldBuildPagesUnifiedGraph() {
30
34
  return !isEcopagesEnvDisabled('ECOPAGES_UNIFIED_PAGES_GRAPH') && isProductionRuntime();
@@ -32,151 +36,229 @@ export function shouldBuildPagesUnifiedGraph() {
32
36
  /**
33
37
  * @remarks
34
38
  * Pages of an Integration that compiles its own modules (`compilePageModule`), such as
35
- * HTML Pages, are not bundled, so they stay out of the graph.
39
+ * HTML Pages, are not bundled, so they stay out of the Rolldown graph.
36
40
  */
37
41
  export function isPagesUnifiedGraphPage(filePath, appConfig) {
38
42
  const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
39
43
  return owner !== undefined && !owner.compilePageModule;
40
44
  }
41
- function createPagesUnifiedGraphBuildKey(appConfig, outdir) {
42
- const pluginNames = resolveAppBuildPlugins(appConfig, 'server')
43
- .map((plugin) => plugin.name)
44
- .sort()
45
- .join('|');
46
- const templateExtensions = [...appConfig.templatesExt].sort().join('|');
47
- return [
48
- path.resolve(outdir),
49
- hashAppConfigFile(appConfig),
50
- templateExtensions,
51
- pluginNames,
52
- 'node',
53
- 'esm',
54
- 'external-packages',
55
- ].join('::');
56
- }
57
- function readPagesUnifiedGraphManifest(appConfig) {
58
- return requireAppRuntime(appConfig).pagesUnifiedGraphManifest ?? undefined;
59
- }
60
- function sourceDependenciesAreCurrent(manifest) {
61
- return new RouteModuleDependencyHasher().matchesStoredHashes(manifest.dependencyHashes);
62
- }
63
- function writePagesUnifiedGraphManifest(appConfig, manifest) {
64
- requireAppRuntime(appConfig).pagesUnifiedGraphManifest = manifest;
65
- }
66
- function createSafeGraphEntryKey(entryPath, rootDir) {
67
- const relativePath = path.relative(rootDir, entryPath).replace(/\.[^.]+$/u, '');
68
- const safeKey = relativePath.replace(/[^a-zA-Z0-9]+/gu, '-').replace(/^-+|-+$/gu, '');
69
- return safeKey.length > 0 ? safeKey : 'page';
70
- }
71
- /**
72
- * Whether `manifest` was built for this graph setup, every file its outputs import
73
- * still exists, and source hashes still match.
74
- */
75
- function isGraphManifestCurrent(manifest, appConfig, outdir) {
76
- return (manifest.buildKey === createPagesUnifiedGraphBuildKey(appConfig, outdir) &&
77
- manifest.outputImports.every((filePath) => fileSystem.exists(filePath)) &&
78
- sourceDependenciesAreCurrent(manifest));
79
- }
80
45
  /**
46
+ * Readable output stem unique for every source path.
47
+ *
81
48
  * @remarks
82
- * In addition to graph freshness and chunk existence on disk, the manifest must
83
- * match the exact count of active template entries so removing or adding a page
84
- * invalidates the graph.
49
+ * Sanitizing `src/pages/foo-bar` and `src/pages/foo/bar` would otherwise yield
50
+ * the same stem and overwrite one emitted module with the other.
85
51
  */
86
- function isManifestValidForEntries(manifest, appConfig, outdir, entryPaths) {
87
- return (isGraphManifestCurrent(manifest, appConfig, outdir) &&
88
- entryPaths.length === Object.keys(manifest.outputs).length &&
89
- entryPaths.every((entryPath) => {
90
- const outputPath = manifest.outputs[path.resolve(entryPath)];
91
- return outputPath ? fileSystem.exists(outputPath) : false;
92
- }));
52
+ function createSafeGraphEntryKey(entryPath, rootDir) {
53
+ const sourceKey = toRootRelativePath(rootDir, entryPath);
54
+ const relativePath = sourceKey.replace(/\.[^.]+$/u, '');
55
+ const readable = relativePath.replace(/[^a-zA-Z0-9]+/gu, '-').replace(/^-+|-+$/gu, '');
56
+ return `${readable.length > 0 ? readable : 'page'}-${contentHash(sourceKey, 8)}`;
57
+ }
58
+ function uniqueEntryPaths(entryPaths) {
59
+ return [...new Set(entryPaths.map((entryPath) => path.resolve(entryPath)))];
60
+ }
61
+ async function emitCompiledPageModule(appConfig, filePath, outdir) {
62
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
63
+ if (!owner?.compilePageModule) {
64
+ throw new Error(`No compilePageModule implementation for ${filePath}`);
65
+ }
66
+ if (!owner.serializeCompiledPageModule) {
67
+ throw new Error(`No serializeCompiledPageModule implementation for ${filePath}`);
68
+ }
69
+ const compiled = await owner.compilePageModule(filePath, appConfig);
70
+ const { contents } = owner.serializeCompiledPageModule(compiled, { rootDir: appConfig.rootDir, filePath });
71
+ const sourceKey = toRootRelativePath(appConfig.rootDir, filePath);
72
+ const relativePath = `${createSafeGraphEntryKey(filePath, appConfig.rootDir)}-html.json`;
73
+ const outputPath = path.join(outdir, relativePath);
74
+ fileSystem.ensureDir(outdir);
75
+ fileSystem.write(outputPath, contents);
76
+ return { sourceKey, relativePath, outputPath };
77
+ }
78
+ function reviveCompiledPageModuleFromDisk(appConfig, filePath, outputPath) {
79
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
80
+ if (!owner?.reviveCompiledPageModule) {
81
+ throw new Error(`No reviveCompiledPageModule implementation for ${filePath}`);
82
+ }
83
+ return owner.reviveCompiledPageModule(fileSystem.readFileSync(outputPath).toString(), {
84
+ rootDir: appConfig.rootDir,
85
+ filePath,
86
+ });
93
87
  }
94
88
  /**
95
- * {@link isGraphManifestCurrent} for page imports, memoized per manifest.
89
+ * Points `identity.file` at the current app root when the emitted module still
90
+ * names the build machine, so a copied `dist/` does not read that path.
96
91
  *
97
92
  * @remarks
98
- * Page modules can be imported before the static site generator calls
99
- * {@link ensurePagesUnifiedGraphBuilt} (for example while collecting static
100
- * paths), so the import path must not trust a graph this process has already
101
- * invalidated.
93
+ * Relative `dependencies.scripts` resolve from this directory, so the remap
94
+ * keeps the source key. Emitting the module path here breaks the asset
95
+ * pipeline (`./hello.script.ts` would resolve under `dist/server/`).
102
96
  */
103
- function isGraphImportable(manifest, appConfig) {
104
- if (manifest.importable !== undefined)
105
- return manifest.importable;
106
- const current = isGraphManifestCurrent(manifest, appConfig, getServerModuleBuildCacheOutdir(appConfig));
107
- manifest.importable = current;
108
- return current;
97
+ function remapProductionIdentityFile(identity, appConfig) {
98
+ if (!identity?.file) {
99
+ return;
100
+ }
101
+ const manifest = loadProductionServerModules(appConfig);
102
+ if (!manifest) {
103
+ return;
104
+ }
105
+ const key = matchProductionModuleKey(appConfig.rootDir, identity.file, manifest.modules);
106
+ if (key) {
107
+ identity.file = path.resolve(appConfig.rootDir, key);
108
+ }
109
109
  }
110
- /**
111
- * Builds eligible static pages in one Rolldown invocation and records outputs for this process.
112
- */
113
- export async function ensurePagesUnifiedGraphBuilt(options) {
114
- requireAppRuntime(options.appConfig);
115
- if (!shouldBuildPagesUnifiedGraph()) {
116
- return undefined;
110
+ function remapLoadedModuleIdentities(loaded, appConfig) {
111
+ for (const value of Object.values(loaded)) {
112
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) {
113
+ continue;
114
+ }
115
+ const record = value;
116
+ remapProductionIdentityFile(record.config?.identity ?? record.identity, appConfig);
117
117
  }
118
- const eligibleEntryPaths = Array.from(new Set(options.entryPaths
119
- .map((entryPath) => path.resolve(entryPath))
120
- .filter((entryPath) => isPagesUnifiedGraphPage(entryPath, options.appConfig))));
121
- if (eligibleEntryPaths.length === 0) {
122
- return undefined;
118
+ }
119
+ export async function importEmittedServerModule(appConfig, filePath, outputPath) {
120
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
121
+ if (owner?.reviveCompiledPageModule) {
122
+ return reviveCompiledPageModuleFromDisk(appConfig, filePath, outputPath);
123
+ }
124
+ const loaded = (await import(/* @vite-ignore */ pathToFileURL(outputPath).href));
125
+ if (loaded && typeof loaded === 'object') {
126
+ remapLoadedModuleIdentities(loaded, appConfig);
123
127
  }
124
- const outdir = path.resolve(options.outdir);
125
- const existingManifest = options.force ? undefined : readPagesUnifiedGraphManifest(options.appConfig);
126
- if (existingManifest &&
127
- isManifestValidForEntries(existingManifest, options.appConfig, outdir, eligibleEntryPaths)) {
128
- appLogger.debug('Reusing pages unified graph built in this process');
129
- return existingManifest;
128
+ return loaded;
129
+ }
130
+ async function emitRolldownServerModules(appConfig, entryPaths, outdir) {
131
+ if (entryPaths.length === 0) {
132
+ return { modules: {}, outputGraph: {} };
130
133
  }
131
134
  const entryRecord = {};
132
- for (const entryPath of eligibleEntryPaths) {
133
- const entryKey = createSafeGraphEntryKey(entryPath, options.appConfig.rootDir);
134
- entryRecord[entryKey] = entryPath;
135
+ for (const entryPath of entryPaths) {
136
+ entryRecord[createSafeGraphEntryKey(entryPath, appConfig.rootDir)] = entryPath;
135
137
  }
136
138
  appLogger.debugTime('pagesUnifiedGraphBuild');
137
- const buildOptions = createServerBuildRequest(options.appConfig, {
139
+ const buildOptions = createServerBuildRequest(appConfig, {
138
140
  entrypoints: entryRecord,
139
141
  outdir,
140
142
  splitting: true,
143
+ preserveModules: true,
144
+ preserveModulesRoot: appConfig.rootDir,
141
145
  naming: '[name]-[hash].[ext]',
142
146
  });
143
- const buildResult = await buildOrThrow(options.appConfig, buildOptions, 'Pages unified graph build failed').finally(() => appLogger.debugTimeEnd('pagesUnifiedGraphBuild'));
144
- const outputs = {};
145
- const outputImports = new Set();
146
- const dependencyHasher = new RouteModuleDependencyHasher();
147
- const dependencyHashes = {};
148
- for (const entryPath of eligibleEntryPaths) {
149
- const fileHash = fileSystem.hash(entryPath);
150
- const compiledOutput = getBuildEntryOutput(buildResult, entryPath, options.appConfig.rootDir);
147
+ const buildResult = await buildOrThrow(appConfig, buildOptions, 'Pages unified graph build failed').finally(() => appLogger.debugTimeEnd('pagesUnifiedGraphBuild'));
148
+ const modules = {};
149
+ for (const entryPath of entryPaths) {
150
+ const compiledOutput = getBuildEntryOutput(buildResult, entryPath, appConfig.rootDir);
151
151
  if (!compiledOutput) {
152
152
  throw new Error(`Pages unified graph build produced no output for ${entryPath}`);
153
153
  }
154
- outputs[entryPath] = compiledOutput;
155
- for (const importPath of collectBuildOutputImports(buildResult, compiledOutput))
156
- outputImports.add(importPath);
157
- const dependencyModulePaths = resolveRouteModuleDependencyPaths(buildResult, entryPath, options.appConfig.rootDir);
158
- Object.assign(dependencyHashes, dependencyHasher.createDependencyHashes(dependencyModulePaths));
159
- dependencyHashes[path.normalize(entryPath)] = fileHash;
160
- }
161
- const manifest = {
162
- buildKey: createPagesUnifiedGraphBuildKey(options.appConfig, outdir),
163
- outputs,
164
- outputImports: [...outputImports],
165
- dependencyHashes,
154
+ modules[toRootRelativePath(appConfig.rootDir, entryPath)] = toRootRelativePath(outdir, compiledOutput);
155
+ }
156
+ return { modules, outputGraph: buildResult.outputGraph };
157
+ }
158
+ function findEmittedModulePath(outputGraph, sourcePath) {
159
+ const resolvedSource = path.resolve(sourcePath);
160
+ for (const [outputPath, chunk] of Object.entries(outputGraph)) {
161
+ if (chunk.modules.includes(resolvedSource)) {
162
+ return outputPath;
163
+ }
164
+ }
165
+ return undefined;
166
+ }
167
+ async function importEmittedModules(manifest, sourceKeys) {
168
+ const modules = [];
169
+ for (const sourceKey of sourceKeys) {
170
+ const relativePath = manifest.modules[sourceKey];
171
+ if (!relativePath) {
172
+ continue;
173
+ }
174
+ modules.push(await import(/* @vite-ignore */ pathToFileURL(path.join(manifest.outdir, relativePath)).href));
175
+ }
176
+ return modules;
177
+ }
178
+ function assignProductionServerModules(appConfig, manifest) {
179
+ const runtime = requireAppRuntime(appConfig);
180
+ runtime.productionServerModules = manifest;
181
+ }
182
+ /**
183
+ * Emits every production server entry into `outdir` and writes `server-modules.json`.
184
+ *
185
+ * @remarks
186
+ * Imports the emitted Rolldown modules to discover extra `ssr: true` scripts, so
187
+ * Integrations are activated first; Core installs the configured server DOM
188
+ * before their `setup()`. A discovered script already bundled into the first
189
+ * emit maps to that output. Otherwise a second emit adds the scripts; preserved
190
+ * modules keep their output path across both emits, so a module imported after
191
+ * the first emit is not evaluated again from a second copy.
192
+ */
193
+ export async function emitProductionServerModules(options) {
194
+ const appConfig = options.appConfig;
195
+ requireAppRuntime(appConfig);
196
+ await setupAppRuntimeIntegrations({ appConfig });
197
+ const outdir = path.resolve(options.outdir ?? getServerBundleOutputPaths(appConfig).serverOutdir);
198
+ fileSystem.ensureDir(outdir);
199
+ const collected = await collectServerModuleEntries({
200
+ appConfig,
201
+ router: options.router,
202
+ staticRoutes: options.staticRoutes,
203
+ errorPageLoaders: options.errorPageLoaders,
204
+ });
205
+ const rolldownEntries = collected.filter((entryPath) => isRolldownServerModuleEntry(entryPath, appConfig));
206
+ const htmlEntries = collected.filter((entryPath) => !isRolldownServerModuleEntry(entryPath, appConfig));
207
+ const modules = {};
208
+ const initialEmit = await emitRolldownServerModules(appConfig, uniqueEntryPaths(rolldownEntries), outdir);
209
+ Object.assign(modules, initialEmit.modules);
210
+ for (const htmlEntry of uniqueEntryPaths(htmlEntries)) {
211
+ const emitted = await emitCompiledPageModule(appConfig, htmlEntry, outdir);
212
+ modules[emitted.sourceKey] = emitted.relativePath;
213
+ }
214
+ let manifest = {
215
+ outdir,
216
+ buildId: ensureProductionBuildId(appConfig),
217
+ modules,
166
218
  };
167
- writePagesUnifiedGraphManifest(options.appConfig, manifest);
168
- appLogger.debug(`Built pages unified graph for ${eligibleEntryPaths.length} entries`);
219
+ assignProductionServerModules(appConfig, manifest);
220
+ const discoveredScripts = collectSsrScriptPaths(await importEmittedModules(manifest, rolldownEntries.map((entryPath) => toRootRelativePath(appConfig.rootDir, entryPath)))).filter((scriptPath) => fileSystem.exists(scriptPath) && !(toRootRelativePath(appConfig.rootDir, scriptPath) in modules));
221
+ if (discoveredScripts.length > 0) {
222
+ const scriptsToEmit = [];
223
+ for (const scriptPath of discoveredScripts) {
224
+ const existingOutput = findEmittedModulePath(initialEmit.outputGraph, scriptPath);
225
+ if (existingOutput) {
226
+ modules[toRootRelativePath(appConfig.rootDir, scriptPath)] = toRootRelativePath(outdir, existingOutput);
227
+ }
228
+ else {
229
+ scriptsToEmit.push(scriptPath);
230
+ }
231
+ }
232
+ if (scriptsToEmit.length > 0) {
233
+ const emittedModules = await emitRolldownServerModules(appConfig, uniqueEntryPaths([...rolldownEntries, ...scriptsToEmit]), outdir);
234
+ Object.assign(modules, emittedModules.modules);
235
+ }
236
+ manifest = { outdir, buildId: ensureProductionBuildId(appConfig), modules };
237
+ assignProductionServerModules(appConfig, manifest);
238
+ }
239
+ writeProductionServerModulesManifest(manifest);
240
+ appLogger.debug(`Emitted ${Object.keys(modules).length} production server modules`);
169
241
  return manifest;
170
242
  }
243
+ /**
244
+ * Imports the emitted module for `filePath` from the production server-modules map.
245
+ *
246
+ * @remarks
247
+ * Resolves `undefined` when no map was emitted or it does not list the file.
248
+ */
171
249
  export async function importPagesUnifiedGraphModule(appConfig, filePath) {
172
- const manifest = readPagesUnifiedGraphManifest(appConfig);
173
- if (!manifest || !isGraphImportable(manifest, appConfig)) {
250
+ const manifest = loadProductionServerModules(appConfig);
251
+ if (!manifest) {
252
+ return undefined;
253
+ }
254
+ const sourceKey = toRootRelativePath(appConfig.rootDir, filePath);
255
+ const relativePath = manifest.modules[sourceKey];
256
+ if (!relativePath) {
174
257
  return undefined;
175
258
  }
176
- const resolvedFilePath = path.resolve(filePath);
177
- const outputPath = manifest.outputs[resolvedFilePath];
178
- if (!outputPath || !fileSystem.exists(outputPath)) {
259
+ const outputPath = path.join(manifest.outdir, relativePath);
260
+ if (!fileSystem.exists(outputPath)) {
179
261
  return undefined;
180
262
  }
181
- return (await import(/* @vite-ignore */ pathToFileURL(outputPath).href));
263
+ return importEmittedServerModule(appConfig, filePath, outputPath);
182
264
  }
@@ -0,0 +1,35 @@
1
+ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
+ import type { ErrorPageLoaders, StaticRoute } from '../../types/contracts.js';
3
+ export type ServerModuleEntryRouteSource = {
4
+ templateRoutes: readonly {
5
+ filePath: string;
6
+ }[];
7
+ };
8
+ /**
9
+ * True when the file is bundled through Rolldown rather than `compilePageModule`.
10
+ *
11
+ * @remarks
12
+ * Endpoints and `ssr: true` scripts have no Integration owner and still go through
13
+ * Rolldown. HTML Pages and `html.html` compile in process.
14
+ */
15
+ export declare function isRolldownServerModuleEntry(filePath: string, appConfig: EcoPagesAppConfig): boolean;
16
+ /**
17
+ * Collects every production server entry except `ssr: true` scripts, which are
18
+ * discovered from compiled modules after the first graph emit.
19
+ *
20
+ * @remarks
21
+ * Processor `listProductionServerModuleEntries()` files, such as generated content
22
+ * collection modules, join the same map so production start can import them without
23
+ * calling Processor `setup()`. Views imported into the server entry (`ctx.render`,
24
+ * `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
25
+ */
26
+ export declare function collectServerModuleEntries(options: {
27
+ appConfig: EcoPagesAppConfig;
28
+ router: ServerModuleEntryRouteSource;
29
+ staticRoutes?: readonly StaticRoute[];
30
+ errorPageLoaders?: ErrorPageLoaders;
31
+ }): Promise<string[]>;
32
+ /**
33
+ * Walks compiled Page, Layout, and view modules for `ssr: true` script paths.
34
+ */
35
+ export declare function collectSsrScriptPaths(modules: readonly unknown[]): string[];
@@ -0,0 +1,109 @@
1
+ import path from 'node:path';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { getComponentIdentity } from '../../eco/component-identity.js';
4
+ import { isEcoDeclaredComponent } from '../../eco/eco-declared-component.js';
5
+ import { findIntegrationForFile } from '../../plugins/find-integration-for-file.js';
6
+ import { getImportedViewPaths } from '../server/imported-view-plugin.js';
7
+ /**
8
+ * True when the file is bundled through Rolldown rather than `compilePageModule`.
9
+ *
10
+ * @remarks
11
+ * Endpoints and `ssr: true` scripts have no Integration owner and still go through
12
+ * Rolldown. HTML Pages and `html.html` compile in process.
13
+ */
14
+ export function isRolldownServerModuleEntry(filePath, appConfig) {
15
+ const owner = findIntegrationForFile(appConfig.integrations, path.normalize(filePath));
16
+ return !owner?.compilePageModule;
17
+ }
18
+ function addExistingPath(entries, filePath) {
19
+ if (filePath && fileSystem.exists(filePath)) {
20
+ entries.add(path.resolve(filePath));
21
+ }
22
+ }
23
+ function addViewLoader(entries, loader) {
24
+ addExistingPath(entries, loader?.filePath);
25
+ }
26
+ async function collectLayoutFiles(appConfig, entries) {
27
+ const layoutsDir = appConfig.absolutePaths.layoutsDir;
28
+ if (!layoutsDir || !fileSystem.exists(layoutsDir)) {
29
+ return;
30
+ }
31
+ const files = await fileSystem.glob(appConfig.templatesExt.map((extension) => `**/*${extension}`), { cwd: layoutsDir });
32
+ for (const file of files) {
33
+ entries.add(path.resolve(layoutsDir, file));
34
+ }
35
+ }
36
+ /**
37
+ * Collects every production server entry except `ssr: true` scripts, which are
38
+ * discovered from compiled modules after the first graph emit.
39
+ *
40
+ * @remarks
41
+ * Processor `listProductionServerModuleEntries()` files, such as generated content
42
+ * collection modules, join the same map so production start can import them without
43
+ * calling Processor `setup()`. Views imported into the server entry (`ctx.render`,
44
+ * `ctx.renderPartial`) are recorded by the imported-view plugin during that bundle.
45
+ */
46
+ export async function collectServerModuleEntries(options) {
47
+ const entries = new Set();
48
+ const { appConfig } = options;
49
+ for (const route of options.router.templateRoutes) {
50
+ addExistingPath(entries, route.filePath);
51
+ }
52
+ addExistingPath(entries, appConfig.absolutePaths.htmlTemplatePath);
53
+ await collectLayoutFiles(appConfig, entries);
54
+ for (const route of options.staticRoutes ?? []) {
55
+ addViewLoader(entries, route.loader);
56
+ }
57
+ for (const loader of Object.values(options.errorPageLoaders ?? {})) {
58
+ addViewLoader(entries, loader);
59
+ }
60
+ for (const filePath of getImportedViewPaths(appConfig)) {
61
+ addExistingPath(entries, filePath);
62
+ }
63
+ for (const processor of appConfig.processors.values()) {
64
+ for (const entryPath of processor.listProductionServerModuleEntries?.() ?? []) {
65
+ addExistingPath(entries, entryPath);
66
+ }
67
+ }
68
+ return [...entries];
69
+ }
70
+ function addSsrScripts(component, scripts) {
71
+ const identity = getComponentIdentity(component);
72
+ const ownerDir = identity?.file ? path.dirname(identity.file) : undefined;
73
+ if (!ownerDir) {
74
+ return;
75
+ }
76
+ for (const script of component.config?.dependencies?.scripts ?? []) {
77
+ if (typeof script === 'object' && script.ssr && script.src) {
78
+ scripts.add(path.resolve(ownerDir, script.src));
79
+ }
80
+ }
81
+ }
82
+ function collectSsrScriptsFromComponent(component, seen, scripts) {
83
+ if (!component || seen.has(component) || !isEcoDeclaredComponent(component)) {
84
+ return;
85
+ }
86
+ seen.add(component);
87
+ const ecoComponent = component;
88
+ addSsrScripts(ecoComponent, scripts);
89
+ for (const related of ecoComponent.config?.layouts ?? []) {
90
+ collectSsrScriptsFromComponent(related, seen, scripts);
91
+ }
92
+ for (const related of ecoComponent.config?.dependencies?.components ?? []) {
93
+ collectSsrScriptsFromComponent(related, seen, scripts);
94
+ }
95
+ }
96
+ /**
97
+ * Walks compiled Page, Layout, and view modules for `ssr: true` script paths.
98
+ */
99
+ export function collectSsrScriptPaths(modules) {
100
+ const scripts = new Set();
101
+ const seen = new Set();
102
+ for (const module of modules) {
103
+ if (!module || typeof module !== 'object') {
104
+ continue;
105
+ }
106
+ collectSsrScriptsFromComponent(module.default, seen, scripts);
107
+ }
108
+ return [...scripts];
109
+ }
@@ -80,6 +80,8 @@ export interface BuildChunk {
80
80
  dynamicImports: string[];
81
81
  isEntry: boolean;
82
82
  facadeModuleId: string | null;
83
+ /** Absolute source paths of the modules bundled into this chunk; virtual modules are left out. */
84
+ modules: string[];
83
85
  }
84
86
  /** Targets supported by the Ecopages build adapter. */
85
87
  export type BuildTarget = 'browser' | 'node' | 'es3' | 'es5' | 'esnext' | `es${number}` | `chrome${string}` | `edge${string}` | `firefox${string}` | `safari${string}` | `hermes${string}` | `deno${string}` | `ios${string}`;
@@ -108,6 +110,9 @@ export interface BuildOptions {
108
110
  sourcemap?: BuildSourcemap;
109
111
  /** When `false` with a single entrypoint, inlines dynamic imports into one output file. */
110
112
  splitting?: boolean;
113
+ /** Emits one output module per source module so separate server emits can share module identity. */
114
+ preserveModules?: boolean;
115
+ preserveModulesRoot?: string;
111
116
  root?: string;
112
117
  externalPackages?: boolean;
113
118
  /**
@@ -4,11 +4,17 @@ export declare const CONTENT_VIRTUAL_MODULE_PREFIX = "ecopages:content";
4
4
  export declare const CONTENT_VIRTUAL_MODULE_PATTERN: RegExp;
5
5
  /** Matches `ecopages:content/<collection>/server` component resolver specifiers. */
6
6
  export declare const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN: RegExp;
7
- /** Matches browser-only `ecopages:content/<collection>/browser` component loader specifiers. */
8
- export declare const CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN: RegExp;
7
+ /**
8
+ * Matches `ecopages:content/<collection>/component` loader specifiers.
9
+ *
10
+ * @remarks
11
+ * The server graph resolves this specifier to the `/server` module and the Page Browser Graph
12
+ * resolves it to the browser-safe loader, so one import serves both sides.
13
+ */
14
+ export declare const CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN: RegExp;
9
15
  export type ParsedCollectionSpecifier = {
10
16
  collectionName: string;
11
- variant: 'entries' | 'server' | 'browser';
17
+ variant: 'entries' | 'server' | 'component';
12
18
  };
13
19
  export declare function parseCollectionSpecifier(specifier: string): ParsedCollectionSpecifier | null;
14
20
  export declare function isContentServerVirtualModule(specifier: string): boolean;
@@ -4,8 +4,14 @@ export const CONTENT_VIRTUAL_MODULE_PREFIX = 'ecopages:content';
4
4
  export const CONTENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]*$/;
5
5
  /** Matches `ecopages:content/<collection>/server` component resolver specifiers. */
6
6
  export const CONTENT_SERVER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/server$/;
7
- /** Matches browser-only `ecopages:content/<collection>/browser` component loader specifiers. */
8
- export const CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/browser$/;
7
+ /**
8
+ * Matches `ecopages:content/<collection>/component` loader specifiers.
9
+ *
10
+ * @remarks
11
+ * The server graph resolves this specifier to the `/server` module and the Page Browser Graph
12
+ * resolves it to the browser-safe loader, so one import serves both sides.
13
+ */
14
+ export const CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN = /^ecopages:content\/[a-z][a-z0-9-]+\/component$/;
9
15
  export function parseCollectionSpecifier(specifier) {
10
16
  const normalized = specifier.startsWith(`${CONTENT_VIRTUAL_MODULE_PREFIX}/`)
11
17
  ? specifier.slice(`${CONTENT_VIRTUAL_MODULE_PREFIX}/`.length)
@@ -21,10 +27,10 @@ export function parseCollectionSpecifier(specifier) {
21
27
  variant: 'server',
22
28
  };
23
29
  }
24
- if (normalized.endsWith('/browser')) {
30
+ if (normalized.endsWith('/component')) {
25
31
  return {
26
- collectionName: normalized.slice(0, -'/browser'.length),
27
- variant: 'browser',
32
+ collectionName: normalized.slice(0, -'/component'.length),
33
+ variant: 'component',
28
34
  };
29
35
  }
30
36
  return {
@@ -1,4 +1,4 @@
1
1
  export type * from './contracts/build-contracts.js';
2
2
  export type * from './contracts/build-types.js';
3
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './contracts/content-virtual-modules.js';
3
+ export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, type ParsedCollectionSpecifier, } from './contracts/content-virtual-modules.js';
4
4
  export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
@@ -1,2 +1,2 @@
1
- export { CONTENT_BROWSER_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './contracts/content-virtual-modules.js';
1
+ export { CONTENT_COMPONENT_VIRTUAL_MODULE_PATTERN, CONTENT_SERVER_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PATTERN, CONTENT_VIRTUAL_MODULE_PREFIX, isContentServerVirtualModule, parseCollectionSpecifier, } from './contracts/content-virtual-modules.js';
2
2
  export { isServerOnlyModuleSpecifier } from './contracts/server-only-specifier.js';
@@ -0,0 +1,10 @@
1
+ import type { EcoPagesAppConfig } from '../config/internal-types.js';
2
+ /**
3
+ * Copies `serverFiles` globs into `dist/server/` under each file's basename.
4
+ *
5
+ * @remarks
6
+ * Production `import.meta.dirname` is the emitted module directory, so declared
7
+ * files land next to those modules. Two matches that share a basename fail the
8
+ * build.
9
+ */
10
+ export declare function copyDeclaredServerFiles(appConfig: EcoPagesAppConfig): Promise<void>;