@ecopages/core 0.2.0-rc.10 → 0.2.0-rc.11

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 (159) hide show
  1. package/README.md +0 -9
  2. package/package.json +3 -144
  3. package/src/adapters/README.md +8 -2
  4. package/src/adapters/abstract/application-adapter.d.ts +6 -32
  5. package/src/adapters/abstract/application-adapter.js +6 -45
  6. package/src/adapters/abstract/ws-pattern-matcher.d.ts +0 -5
  7. package/src/adapters/abstract/ws-pattern-matcher.js +0 -9
  8. package/src/adapters/bun/create-app.d.ts +8 -12
  9. package/src/adapters/bun/create-app.js +13 -55
  10. package/src/adapters/bun/hmr-manager.d.ts +0 -1
  11. package/src/adapters/bun/hmr-manager.js +2 -4
  12. package/src/adapters/bun/server-adapter.d.ts +9 -19
  13. package/src/adapters/bun/server-adapter.js +19 -66
  14. package/src/adapters/bun/static-preview-host.d.ts +1 -0
  15. package/src/adapters/bun/static-preview-host.js +1 -1
  16. package/src/adapters/create-app.d.ts +1 -1
  17. package/src/adapters/create-app.js +2 -1
  18. package/src/adapters/node/create-app.d.ts +4 -8
  19. package/src/adapters/node/create-app.js +7 -12
  20. package/src/adapters/node/runtime-host.d.ts +10 -10
  21. package/src/adapters/node/runtime-host.js +4 -4
  22. package/src/adapters/node/server-adapter-dependencies.d.ts +2 -10
  23. package/src/adapters/node/server-adapter-dependencies.js +8 -13
  24. package/src/adapters/node/server-adapter.d.ts +25 -31
  25. package/src/adapters/node/server-adapter.js +43 -64
  26. package/src/adapters/shared/hmr/shared-hmr-manager.d.ts +0 -4
  27. package/src/adapters/shared/hmr/shared-hmr-manager.js +0 -12
  28. package/src/adapters/shared/http/api-request-pipeline.d.ts +27 -1
  29. package/src/adapters/shared/http/api-request-pipeline.js +31 -16
  30. package/src/adapters/shared/http/fs-server-response-factory.d.ts +0 -1
  31. package/src/adapters/shared/http/fs-server-response-factory.js +0 -3
  32. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.d.ts +1 -3
  33. package/src/adapters/shared/runtime/collect-dev-prewarm-plan.js +1 -4
  34. package/src/adapters/shared/runtime/runtime-app-bootstrap.d.ts +0 -10
  35. package/src/adapters/shared/runtime/runtime-app-bootstrap.js +0 -7
  36. package/src/adapters/shared/runtime/runtime-host.d.ts +5 -2
  37. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +1 -1
  38. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +1 -1
  39. package/src/adapters/shared/runtime/server-adapter.d.ts +13 -0
  40. package/src/adapters/shared/runtime/server-adapter.js +22 -0
  41. package/src/adapters/shared/ws/node-http-websocket-upgrades.d.ts +9 -1
  42. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +8 -2
  43. package/src/build/README.md +5 -6
  44. package/src/build/cache/cache-constants.d.ts +0 -2
  45. package/src/build/cache/cache-constants.js +0 -2
  46. package/src/build/cache/cache-keys.d.ts +0 -2
  47. package/src/build/cache/cache-keys.js +0 -2
  48. package/src/build/cache/output-imports.d.ts +27 -0
  49. package/src/build/cache/output-imports.js +80 -0
  50. package/src/build/cache/pages-unified-graph-build.d.ts +6 -1
  51. package/src/build/cache/pages-unified-graph-build.js +42 -17
  52. package/src/build/cache/production-build-cache.d.ts +2 -2
  53. package/src/build/cache/production-build-cache.js +2 -2
  54. package/src/build/cache/server-entry-build-cache.d.ts +1 -2
  55. package/src/build/cache/server-entry-build-cache.js +4 -5
  56. package/src/build/contracts/build-contracts.d.ts +1 -13
  57. package/src/build/rolldown/runtime-build-output-normalizer.js +3 -6
  58. package/src/build/runtime/build-request-identity.d.ts +2 -6
  59. package/src/build/runtime/build-request-identity.js +2 -8
  60. package/src/build/runtime/deduping-build-executor.d.ts +0 -1
  61. package/src/build/runtime/deduping-build-executor.js +0 -1
  62. package/src/cache/index.d.ts +1 -1
  63. package/src/cache/index.js +1 -1
  64. package/src/cache/module-parse-cache.d.ts +2 -29
  65. package/src/cache/module-parse-cache.js +6 -39
  66. package/src/config/README.md +3 -3
  67. package/src/config/apply-user-config.d.ts +3 -1
  68. package/src/config/apply-user-config.js +3 -2
  69. package/src/config/config-builder.d.ts +1 -0
  70. package/src/config/config-builder.js +2 -2
  71. package/src/config/constants.d.ts +0 -4
  72. package/src/config/constants.js +0 -4
  73. package/src/config/index.d.ts +1 -1
  74. package/src/config/index.js +1 -1
  75. package/src/config/load-eco-config.d.ts +1 -1
  76. package/src/config/load-eco-config.js +18 -11
  77. package/src/config/resolve-eco-config-path.d.ts +9 -0
  78. package/src/config/resolve-eco-config-path.js +11 -0
  79. package/src/config/server-config-bundle.js +2 -2
  80. package/src/config/user-config-types.d.ts +9 -3
  81. package/src/dev/host-runtime.d.ts +0 -1
  82. package/src/dev/host-runtime.js +0 -3
  83. package/src/dev/sc-server.d.ts +4 -1
  84. package/src/dev/sc-server.js +11 -20
  85. package/src/dev/transform-server/dev-transform-import-rewriter.js +2 -2
  86. package/src/hmr/hmr-file-change-prep.d.ts +0 -1
  87. package/src/hmr/hmr-file-change-prep.js +2 -5
  88. package/src/hmr/hmr-strategy.d.ts +3 -8
  89. package/src/hmr/hmr-strategy.js +3 -8
  90. package/src/index.browser.d.ts +1 -2
  91. package/src/index.browser.js +1 -2
  92. package/src/index.d.ts +5 -6
  93. package/src/index.js +5 -6
  94. package/src/islands/island-host.d.ts +0 -9
  95. package/src/islands/island-host.js +1 -13
  96. package/src/plugins/component-import-discovery.js +2 -2
  97. package/src/plugins/eco-component-meta-plugin.js +5 -5
  98. package/src/plugins/integration-plugin.d.ts +0 -1
  99. package/src/plugins/integration-plugin.js +0 -4
  100. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -4
  101. package/src/route-renderer/orchestration/integration-renderer.d.ts +0 -6
  102. package/src/route-renderer/orchestration/integration-renderer.js +1 -11
  103. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +1 -1
  104. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -1
  105. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +1 -1
  106. package/src/services/README.md +1 -1
  107. package/src/services/assets/browser-bundle.service.d.ts +1 -6
  108. package/src/services/error-pages/default-error-pages.d.ts +1 -6
  109. package/src/services/error-pages/default-error-pages.js +0 -8
  110. package/src/services/html/html-rewriter.d.ts +77 -0
  111. package/src/services/html/html-rewriter.js +751 -0
  112. package/src/services/html/html-rewriter.parity.test.bun.d.ts +1 -0
  113. package/src/services/html/html-rewriter.parity.test.bun.js +74 -0
  114. package/src/services/html/html-transformer.service.d.ts +26 -39
  115. package/src/services/html/html-transformer.service.js +81 -153
  116. package/src/services/invalidation/development-invalidation.service.d.ts +2 -19
  117. package/src/services/invalidation/development-invalidation.service.js +1 -39
  118. package/src/services/module-loading/README.md +1 -1
  119. package/src/services/module-loading/app-module-loader.service.d.ts +0 -2
  120. package/src/services/module-loading/app-server-module-transpiler.service.d.ts +1 -1
  121. package/src/services/module-loading/app-server-module-transpiler.service.js +0 -10
  122. package/src/services/module-loading/collection-server-module-build.service.d.ts +0 -1
  123. package/src/services/module-loading/collection-server-module-build.service.js +0 -3
  124. package/src/services/module-loading/host-module-loader-registry.d.ts +0 -1
  125. package/src/services/module-loading/host-module-loader-registry.js +0 -3
  126. package/src/services/module-loading/route-module-build-cache-registry.d.ts +0 -4
  127. package/src/services/module-loading/route-module-build-cache-registry.js +0 -4
  128. package/src/services/module-loading/route-module-build-cache.store.d.ts +3 -0
  129. package/src/services/module-loading/route-module-build-cache.store.js +18 -5
  130. package/src/services/module-loading/route-module-build-manifest.d.ts +6 -1
  131. package/src/services/module-loading/route-module-build-manifest.js +1 -2
  132. package/src/services/module-loading/route-module-dependency-hasher.d.ts +3 -2
  133. package/src/services/module-loading/server-module-transpiler.service.d.ts +1 -15
  134. package/src/services/module-loading/server-module-transpiler.service.js +0 -24
  135. package/src/services/runtime-state/entrypoint-dependency-graph.service.js +0 -12
  136. package/src/services/runtime-state/server-invalidation-state.service.d.ts +4 -2
  137. package/src/services/runtime-state/server-invalidation-state.service.js +7 -14
  138. package/src/types/internal-types.d.ts +0 -38
  139. package/src/types/public-types.d.ts +0 -112
  140. package/src/watchers/project-watcher.d.ts +0 -15
  141. package/src/watchers/project-watcher.js +1 -27
  142. package/src/watchers/project-watcher.test-helpers.d.ts +10 -1
  143. package/src/watchers/project-watcher.test-helpers.js +12 -0
  144. package/src/adapters/abstract/router-adapter.d.ts +0 -26
  145. package/src/adapters/abstract/router-adapter.js +0 -13
  146. package/src/adapters/bun/index.d.ts +0 -2
  147. package/src/adapters/bun/index.js +0 -2
  148. package/src/adapters/index.d.ts +0 -2
  149. package/src/adapters/index.js +0 -2
  150. package/src/eco/eco.utils.d.ts +0 -1
  151. package/src/eco/eco.utils.js +0 -1
  152. package/src/services/cache/index.d.ts +0 -9
  153. package/src/services/cache/index.js +0 -8
  154. package/src/services/html/html-rewriter-provider.service.d.ts +0 -40
  155. package/src/services/html/html-rewriter-provider.service.js +0 -68
  156. package/src/services/module-loading/route-module-build-cache.d.ts +0 -4
  157. package/src/services/module-loading/route-module-build-cache.js +0 -3
  158. package/src/services/runtime-state/dev-graph.service.d.ts +0 -118
  159. package/src/services/runtime-state/dev-graph.service.js +0 -170
@@ -82,6 +82,19 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
82
82
  private tryHandleSharedHmrRequest;
83
83
  private injectSharedHmrHtmlResponse;
84
84
  private tryHandleSharedApiRequest;
85
+ /**
86
+ * Recognises a runtime-specific client disconnect so it answers 499.
87
+ *
88
+ * @remarks
89
+ * Only the Node adapter overrides it: its request bridge raises a dedicated
90
+ * error when the socket closes while the body is read.
91
+ */
92
+ protected isClientAbortError(_error: unknown): boolean;
93
+ /**
94
+ * Resolves an error that escaped {@link handleSharedRequest} with the same
95
+ * precedence as API handler errors, so `app.onError` sees it on every runtime.
96
+ */
97
+ protected handleUnexpectedRequestError(error: unknown, request: Request, context: SharedRequestContext): Promise<Response>;
85
98
  /**
86
99
  * Universally processes an incoming WinterCG Web standard Request.
87
100
  *
@@ -33,6 +33,7 @@ export class SharedServerAdapter extends AbstractServerAdapter {
33
33
  schemaValidator: this.schemaValidator,
34
34
  getRenderContext: () => this.getRenderContext(),
35
35
  getCacheService: () => this.getCacheService(),
36
+ isClientAbort: (error) => this.isClientAbortError(error),
36
37
  });
37
38
  hostOwnsDevClient = false;
38
39
  devStaticRoutePrewarmStarted = false;
@@ -261,6 +262,27 @@ export class SharedServerAdapter extends AbstractServerAdapter {
261
262
  async tryHandleSharedApiRequest(request, context) {
262
263
  return await this.apiRequestPipeline.tryHandle(request, context.apiHandlers, context.serverInstance, context.errorHandler);
263
264
  }
265
+ /**
266
+ * Recognises a runtime-specific client disconnect so it answers 499.
267
+ *
268
+ * @remarks
269
+ * Only the Node adapter overrides it: its request bridge raises a dedicated
270
+ * error when the socket closes while the body is read.
271
+ */
272
+ isClientAbortError(_error) {
273
+ return false;
274
+ }
275
+ /**
276
+ * Resolves an error that escaped {@link handleSharedRequest} with the same
277
+ * precedence as API handler errors, so `app.onError` sees it on every runtime.
278
+ */
279
+ async handleUnexpectedRequestError(error, request, context) {
280
+ return await this.apiRequestPipeline.handleError(error, {
281
+ request,
282
+ serverInstance: context.serverInstance,
283
+ errorHandler: context.errorHandler,
284
+ });
285
+ }
264
286
  /**
265
287
  * Universally processes an incoming WinterCG Web standard Request.
266
288
  *
@@ -12,10 +12,18 @@ export type AttachNodeHttpWebSocketUpgradesOptions = {
12
12
  passthroughUnmatched?: boolean;
13
13
  preflight?: NodeHttpWebSocketUpgradePreflight;
14
14
  };
15
+ /** Upgrade options a host passes when it attaches Ecopages to a server it shares. */
16
+ export type WebSocketUpgradeOptions = Pick<AttachNodeHttpWebSocketUpgradesOptions, 'passthroughUnmatched'>;
15
17
  /**
16
- * Wires Ecopages user WebSocket routes onto a Node HTTP server's `upgrade` event.
18
+ * Wires Ecopages WebSocket upgrades onto a Node HTTP server's `upgrade` event.
17
19
  *
18
20
  * Used by the Node adapter in standalone mode and by host integrations such as
19
21
  * the Vite plugin that embed Ecopages behind a foreign HTTP server.
22
+ *
23
+ * @remarks
24
+ * This is the single owner of the unmatched-upgrade policy: an upgrade claimed
25
+ * by `preflight` (for example `/_hmr`) or a user route is handled here, and
26
+ * anything else is destroyed unless `passthroughUnmatched` leaves it for other
27
+ * listeners on a shared server.
20
28
  */
21
29
  export declare function attachNodeHttpWebSocketUpgrades(server: NodeHttpServer, options: AttachNodeHttpWebSocketUpgradesOptions): void;
@@ -71,13 +71,19 @@ async function setupNodeWebSocketConnection(ws, wsMatch, req, runtimeOrigin, sea
71
71
  });
72
72
  }
73
73
  /**
74
- * Wires Ecopages user WebSocket routes onto a Node HTTP server's `upgrade` event.
74
+ * Wires Ecopages WebSocket upgrades onto a Node HTTP server's `upgrade` event.
75
75
  *
76
76
  * Used by the Node adapter in standalone mode and by host integrations such as
77
77
  * the Vite plugin that embed Ecopages behind a foreign HTTP server.
78
+ *
79
+ * @remarks
80
+ * This is the single owner of the unmatched-upgrade policy: an upgrade claimed
81
+ * by `preflight` (for example `/_hmr`) or a user route is handled here, and
82
+ * anything else is destroyed unless `passthroughUnmatched` leaves it for other
83
+ * listeners on a shared server.
78
84
  */
79
85
  export function attachNodeHttpWebSocketUpgrades(server, options) {
80
- if (options.websocketHandlers.size === 0) {
86
+ if (options.websocketHandlers.size === 0 && !options.preflight) {
81
87
  return;
82
88
  }
83
89
  if (attachedUpgradeServers.has(server)) {
@@ -63,6 +63,7 @@ build/
63
63
  - `cache/server-entry-build-cache.ts`: production server-entry bundle cache (`.eco/.server-entry/.build-cache.json` + `dist/.server/manifest.json`).
64
64
  - `server-bundle-publication.ts`: stages the server entry, emitted config, and deploy manifest together, then publishes the complete directory with rollback.
65
65
  - `cache/cache-constants.ts`: shared `.build-cache.json` filename for persisted production caches.
66
+ - `cache/output-imports.ts`: lists the local files reachable from a compiled module, including shared chunks, so a cached module is reused only while they exist.
66
67
  - `*.test.ts`: regression coverage colocated with each module.
67
68
 
68
69
  ## Default Flow
@@ -139,13 +140,9 @@ App-manifest plugins keep canonical registration order and cannot be silently re
139
140
 
140
141
  ## BuildOptions Caveats
141
142
 
142
- `BuildOptions` is modeled on the bundler's options shape. Most fields map cleanly. The exceptions:
143
+ `BuildOptions` is modeled on the bundler's options shape. Most fields map cleanly. The exception:
143
144
 
144
145
  - `splitting` — when `false` with a single entrypoint, maps to Rolldown `codeSplitting: false` so dynamic imports stay in one file. Multi-entrypoint builds ignore `splitting: false` because Rolldown cannot inline across multiple inputs.
145
- - `bundle` — accepted but ignored. The bundler always bundles.
146
- - `outbase` — accepted but ignored. The adapter derives the base from `options.root` directly.
147
-
148
- These fields are kept in the type so existing call-sites compile. The proper fix is a more focused `BuildOptions` schema in a follow-up.
149
146
 
150
147
  ## Dev / watch path
151
148
 
@@ -191,7 +188,9 @@ Production static exports compile all template pages in one Rolldown invocation
191
188
  | Graph manifest | `.eco/.server-pages-graph/.build-cache.json` |
192
189
  | Chunk outputs | `.eco/.server-modules/` (shared with per-route cache) |
193
190
 
194
- `StaticSiteGenerator` calls `ensurePagesUnifiedGraphBuilt()` before the export loop. `PageModuleImportService` imports prebuilt chunks via `importPagesUnifiedGraphModule()` and falls back to per-page Rolldown on miss. This is separate from production Page Browser Graph prebuild (`production-page-browser-graph-prebuild.ts`), which warms browser assets in `page-browser-graph-session`.
191
+ `StaticSiteGenerator` calls `ensurePagesUnifiedGraphBuilt()` before the export loop. `PageModuleImportService` imports prebuilt chunks via `importPagesUnifiedGraphModule()` and falls back to per-page Rolldown on miss.
192
+
193
+ A persisted graph is reused only when it matches the core package version, the build inputs and the build key, and every local file reachable from its outputs still exists. `importPagesUnifiedGraphModule()` applies the same check, because pages can be imported before the export loop runs. This is separate from production Page Browser Graph prebuild (`production-page-browser-graph-prebuild.ts`), which warms browser assets in `page-browser-graph-session`.
195
194
 
196
195
  `ECOPAGES_ROLLDOWN_BUILD_METRICS=1` enables `rolldown/rolldown-build-invocation-metrics.ts` counters used by bench and parity tests.
197
196
 
@@ -1,4 +1,2 @@
1
1
  /** Filename written beside persisted production build artifacts that store incremental metadata. */
2
2
  export declare const ROUTE_MODULE_BUILD_CACHE_FILENAME = ".build-cache.json";
3
- /** @deprecated Use {@link ROUTE_MODULE_BUILD_CACHE_FILENAME}; server-entry caches share the same filename. */
4
- export declare const SERVER_ENTRY_BUILD_CACHE_FILENAME = ".build-cache.json";
@@ -1,4 +1,2 @@
1
1
  /** Filename written beside persisted production build artifacts that store incremental metadata. */
2
2
  export const ROUTE_MODULE_BUILD_CACHE_FILENAME = '.build-cache.json';
3
- /** @deprecated Use {@link ROUTE_MODULE_BUILD_CACHE_FILENAME}; server-entry caches share the same filename. */
4
- export const SERVER_ENTRY_BUILD_CACHE_FILENAME = ROUTE_MODULE_BUILD_CACHE_FILENAME;
@@ -18,5 +18,3 @@ export declare function createSourceTransformCacheKey(sourceTransforms: BuildOpt
18
18
  * agree within one install; not stable across minifiers or renames.
19
19
  */
20
20
  export declare function hashFunctionIdentity(fn: (...args: never[]) => unknown): string;
21
- /** @deprecated Use {@link hashFunctionIdentity}. */
22
- export declare const hashPluginSetup: typeof hashFunctionIdentity;
@@ -67,5 +67,3 @@ export function hashFunctionIdentity(fn) {
67
67
  }
68
68
  return (hash >>> 0).toString(36);
69
69
  }
70
- /** @deprecated Use {@link hashFunctionIdentity}. */
71
- export const hashPluginSetup = hashFunctionIdentity;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Lists the local files a compiled module imports: relative, absolute and
3
+ * `file:` specifiers in static imports, re-exports and literal dynamic imports.
4
+ *
5
+ * @remarks
6
+ * Persisted build caches record these so a cached module is reused only while
7
+ * the shared chunks and generated modules it loads (for example
8
+ * `.server-collections`) still exist. Uses `parseSync` directly rather than the
9
+ * shared parse cache, so large compiled bundles are not retained in memory.
10
+ */
11
+ export declare function collectLocalImports(code: string, modulePath: string): string[];
12
+ export type LocalImportFileAccess = {
13
+ exists: (filePath: string) => boolean;
14
+ readFile: (filePath: string) => string;
15
+ };
16
+ /**
17
+ * Lists every local file reachable from `modulePath` through local imports.
18
+ *
19
+ * @remarks
20
+ * Direct {@link collectLocalImports} misses shared chunks that a page output
21
+ * only reaches through another chunk. Persisted caches walk this graph so reuse
22
+ * fails when any reachable file is gone. `modulePath` itself is omitted; callers
23
+ * already check that the compiled output exists.
24
+ */
25
+ export declare function collectReachableLocalImports(modulePath: string, fileAccess?: LocalImportFileAccess): string[];
26
+ /** Reads a compiled module from disk and lists its local imports. */
27
+ export declare function readLocalImports(modulePath: string): string[];
@@ -0,0 +1,80 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { fileSystem } from '@ecopages/file-system';
4
+ import { parseSync } from 'oxc-parser';
5
+ /**
6
+ * Lists the local files a compiled module imports: relative, absolute and
7
+ * `file:` specifiers in static imports, re-exports and literal dynamic imports.
8
+ *
9
+ * @remarks
10
+ * Persisted build caches record these so a cached module is reused only while
11
+ * the shared chunks and generated modules it loads (for example
12
+ * `.server-collections`) still exist. Uses `parseSync` directly rather than the
13
+ * shared parse cache, so large compiled bundles are not retained in memory.
14
+ */
15
+ export function collectLocalImports(code, modulePath) {
16
+ const { module } = parseSync(modulePath, code, { lang: 'js', sourceType: 'module' });
17
+ const specifiers = [
18
+ ...module.staticImports.map((entry) => entry.moduleRequest.value),
19
+ ...module.staticExports.flatMap((entry) => entry.entries.map((exportEntry) => exportEntry.moduleRequest?.value)),
20
+ ...module.dynamicImports.map((entry) => readStringLiteral(code.slice(entry.moduleRequest.start, entry.moduleRequest.end))),
21
+ ];
22
+ const directory = path.dirname(modulePath);
23
+ const localImports = new Set();
24
+ for (const specifier of specifiers) {
25
+ const resolved = specifier ? resolveLocalSpecifier(specifier, directory) : undefined;
26
+ if (resolved)
27
+ localImports.add(resolved);
28
+ }
29
+ return [...localImports];
30
+ }
31
+ const defaultLocalImportFileAccess = {
32
+ exists: (filePath) => fileSystem.exists(filePath),
33
+ readFile: (filePath) => fileSystem.readFileSync(filePath),
34
+ };
35
+ /**
36
+ * Lists every local file reachable from `modulePath` through local imports.
37
+ *
38
+ * @remarks
39
+ * Direct {@link collectLocalImports} misses shared chunks that a page output
40
+ * only reaches through another chunk. Persisted caches walk this graph so reuse
41
+ * fails when any reachable file is gone. `modulePath` itself is omitted; callers
42
+ * already check that the compiled output exists.
43
+ */
44
+ export function collectReachableLocalImports(modulePath, fileAccess = defaultLocalImportFileAccess) {
45
+ const reachable = new Set();
46
+ const pending = [modulePath];
47
+ const visited = new Set();
48
+ while (pending.length > 0) {
49
+ const current = pending.pop();
50
+ if (!current || visited.has(current)) {
51
+ continue;
52
+ }
53
+ visited.add(current);
54
+ if (current !== modulePath) {
55
+ reachable.add(current);
56
+ }
57
+ if (current !== modulePath && !fileAccess.exists(current)) {
58
+ continue;
59
+ }
60
+ for (const imported of collectLocalImports(fileAccess.readFile(current), current)) {
61
+ pending.push(imported);
62
+ }
63
+ }
64
+ return [...reachable];
65
+ }
66
+ /** Reads a compiled module from disk and lists its local imports. */
67
+ export function readLocalImports(modulePath) {
68
+ return collectLocalImports(fileSystem.readFileSync(modulePath), modulePath);
69
+ }
70
+ function resolveLocalSpecifier(specifier, directory) {
71
+ const bare = specifier.replace(/[?#].*$/, '');
72
+ if (bare.startsWith('file:'))
73
+ return fileURLToPath(bare);
74
+ if (bare.startsWith('.'))
75
+ return path.resolve(directory, bare);
76
+ return path.isAbsolute(bare) ? bare : undefined;
77
+ }
78
+ function readStringLiteral(source) {
79
+ return /^(['"`])([^'"`$]*)\1$/.exec(source.trim())?.[2];
80
+ }
@@ -9,11 +9,16 @@ import type { EcoPagesAppConfig } from '../../types/internal-types.js';
9
9
  export declare const PAGES_UNIFIED_GRAPH_CACHE_DIR = ".server-pages-graph";
10
10
  export declare const PAGES_UNIFIED_GRAPH_CACHE_FILENAME = ".build-cache.json";
11
11
  export interface PagesUnifiedGraphCacheManifest {
12
- invalidationVersion: string;
12
+ corePackageVersion: string;
13
13
  buildInputsFingerprint: string;
14
14
  buildKey: string;
15
15
  builtAt: number;
16
16
  outputs: Record<string, string>;
17
+ /**
18
+ * Local files reachable from the outputs through local imports, including
19
+ * shared chunks. The graph is reused only while all of them exist.
20
+ */
21
+ outputImports: string[];
17
22
  }
18
23
  export declare function isPagesUnifiedGraphEnabled(): boolean;
19
24
  /** True when the unified graph should build or serve prebuilt page modules. */
@@ -15,8 +15,9 @@ import { createServerBuildRequest, resolveServerAppBuildPlugins } from '../runti
15
15
  import { createBuildInputsFingerprint, hashAppConfigFile } from './build-input-fingerprint.js';
16
16
  import { isProductionCacheManifestCurrent, matchesProductionCacheBuildKey, matchesProductionCacheFingerprint, readProductionCacheManifest, writeProductionCacheManifest, } from './production-build-cache.js';
17
17
  import { getCorePackageVersion } from './cache-keys.js';
18
+ import { collectReachableLocalImports } from './output-imports.js';
18
19
  import { resolveInternalExecutionDir } from '../../utils/resolve-work-dir.js';
19
- import { getSharedRouteModuleBuildCache } from '../../services/module-loading/route-module-build-cache-registry.js';
20
+ import { getServerModuleBuildCacheOutdir, getSharedRouteModuleBuildCache, } from '../../services/module-loading/route-module-build-cache-registry.js';
20
21
  import { resolveRouteModuleDependencyPaths } from '../../services/module-loading/route-module-dependency-hasher.js';
21
22
  export const PAGES_UNIFIED_GRAPH_CACHE_DIR = '.server-pages-graph';
22
23
  export const PAGES_UNIFIED_GRAPH_CACHE_FILENAME = '.build-cache.json';
@@ -95,21 +96,39 @@ function resolveOutputForEntrypoint(entryPath, entryKey, buildResult) {
95
96
  }
96
97
  return undefined;
97
98
  }
99
+ /**
100
+ * Whether `manifest` was written by the current core version, build inputs and graph
101
+ * setup, and every file its outputs import still exists.
102
+ */
103
+ function isGraphManifestCurrent(manifest, appConfig, outdir) {
104
+ return (isProductionCacheManifestCurrent(manifest, getCorePackageVersion()) &&
105
+ matchesProductionCacheFingerprint(manifest, createBuildInputsFingerprint(appConfig)) &&
106
+ matchesProductionCacheBuildKey(manifest, createPagesUnifiedGraphBuildKey(appConfig, outdir)) &&
107
+ manifest.outputImports?.every((filePath) => fileSystem.exists(filePath)) === true);
108
+ }
98
109
  function isManifestValidForEntries(manifest, appConfig, outdir, entryPaths) {
99
- if (!isProductionCacheManifestCurrent(manifest, getCorePackageVersion())) {
100
- return false;
101
- }
102
- if (!matchesProductionCacheFingerprint(manifest, createBuildInputsFingerprint(appConfig))) {
103
- return false;
104
- }
105
- if (!matchesProductionCacheBuildKey(manifest, createPagesUnifiedGraphBuildKey(appConfig, outdir))) {
106
- return false;
107
- }
108
- return entryPaths.every((entryPath) => {
109
- const resolvedEntryPath = path.resolve(entryPath);
110
- const outputPath = manifest.outputs[resolvedEntryPath];
111
- return outputPath ? fileSystem.exists(outputPath) : false;
112
- });
110
+ return (isGraphManifestCurrent(manifest, appConfig, outdir) &&
111
+ entryPaths.every((entryPath) => {
112
+ const outputPath = manifest.outputs[path.resolve(entryPath)];
113
+ return outputPath ? fileSystem.exists(outputPath) : false;
114
+ }));
115
+ }
116
+ const importableGraphs = new WeakMap();
117
+ /**
118
+ * {@link isGraphManifestCurrent} for page imports, memoized per manifest write.
119
+ *
120
+ * @remarks
121
+ * Page modules can be imported before the static site generator calls
122
+ * {@link ensurePagesUnifiedGraphBuilt} (for example while collecting static
123
+ * paths), so the import path must not trust a manifest left by an older build.
124
+ */
125
+ function isGraphImportable(manifest, appConfig) {
126
+ const known = importableGraphs.get(appConfig);
127
+ if (known?.builtAt === manifest.builtAt)
128
+ return known.current;
129
+ const current = isGraphManifestCurrent(manifest, appConfig, getServerModuleBuildCacheOutdir(appConfig));
130
+ importableGraphs.set(appConfig, { builtAt: manifest.builtAt, current });
131
+ return current;
113
132
  }
114
133
  /**
115
134
  * Builds eligible static pages in one Rolldown invocation and seeds route-module disk cache.
@@ -155,6 +174,7 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
155
174
  throw new Error(`Pages unified graph build failed: ${details}`);
156
175
  }
157
176
  const outputs = {};
177
+ const outputImports = new Set();
158
178
  for (const entryPath of eligibleEntryPaths) {
159
179
  const fileHash = fileSystem.hash(entryPath);
160
180
  const entryKey = entryKeysByPath.get(entryPath);
@@ -163,6 +183,9 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
163
183
  throw new Error(`Pages unified graph build produced no output for ${entryPath}`);
164
184
  }
165
185
  outputs[entryPath] = compiledOutput;
186
+ const compiledOutputImports = collectReachableLocalImports(compiledOutput);
187
+ for (const importPath of compiledOutputImports)
188
+ outputImports.add(importPath);
166
189
  routeModuleBuildCache.recordBuild({
167
190
  filePath: entryPath,
168
191
  rootDir: options.appConfig.rootDir,
@@ -172,14 +195,16 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
172
195
  dependencyModulePaths: resolveRouteModuleDependencyPaths(buildResult, entryPath, options.appConfig.rootDir),
173
196
  externalPackages: true,
174
197
  plugins,
198
+ outputImports: compiledOutputImports,
175
199
  });
176
200
  }
177
201
  const manifest = {
178
- invalidationVersion: getCorePackageVersion(),
202
+ corePackageVersion: getCorePackageVersion(),
179
203
  buildInputsFingerprint: createBuildInputsFingerprint(options.appConfig),
180
204
  buildKey: createPagesUnifiedGraphBuildKey(options.appConfig, outdir),
181
205
  builtAt: Date.now(),
182
206
  outputs,
207
+ outputImports: [...outputImports],
183
208
  };
184
209
  writePagesUnifiedGraphManifest(options.appConfig, manifest);
185
210
  appLogger.debug(`Built pages unified graph for ${eligibleEntryPaths.length} entries`);
@@ -187,7 +212,7 @@ export async function ensurePagesUnifiedGraphBuilt(options) {
187
212
  }
188
213
  export async function importPagesUnifiedGraphModule(appConfig, filePath) {
189
214
  const manifest = readPagesUnifiedGraphManifest(appConfig);
190
- if (!manifest) {
215
+ if (!manifest || !isGraphImportable(manifest, appConfig)) {
191
216
  return undefined;
192
217
  }
193
218
  const resolvedFilePath = path.resolve(filePath);
@@ -3,7 +3,7 @@ import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
3
  * Shared manifest fields for persisted production build caches.
4
4
  */
5
5
  export interface ProductionCacheManifestBase {
6
- invalidationVersion?: string;
6
+ /** `getCorePackageVersion()` of the build that wrote the manifest. */
7
7
  corePackageVersion?: string;
8
8
  buildInputsFingerprint?: string;
9
9
  buildKey?: string;
@@ -16,6 +16,6 @@ export declare function getProductionBuildCacheManifestPaths(appConfig: EcoPages
16
16
  export declare function clearPersistedProductionBuildCacheManifests(appConfig: EcoPagesAppConfig): void;
17
17
  export declare function readProductionCacheManifest<T extends ProductionCacheManifestBase>(manifestPath: string): T | undefined;
18
18
  export declare function writeProductionCacheManifest(manifestPath: string, manifest: unknown): void;
19
- export declare function isProductionCacheManifestCurrent(manifest: ProductionCacheManifestBase | undefined, packageVersion: string): boolean;
19
+ export declare function isProductionCacheManifestCurrent(manifest: ProductionCacheManifestBase | undefined, corePackageVersion: string): boolean;
20
20
  export declare function matchesProductionCacheFingerprint(manifest: ProductionCacheManifestBase | undefined, buildInputsFingerprint: string): boolean;
21
21
  export declare function matchesProductionCacheBuildKey(manifest: ProductionCacheManifestBase | undefined, buildKey: string): boolean;
@@ -45,8 +45,8 @@ export function writeProductionCacheManifest(manifestPath, manifest) {
45
45
  fileSystem.ensureDir(path.dirname(manifestPath));
46
46
  fileSystem.write(manifestPath, `${JSON.stringify(manifest, null, '\t')}\n`);
47
47
  }
48
- export function isProductionCacheManifestCurrent(manifest, packageVersion) {
49
- return (manifest?.corePackageVersion ?? manifest?.invalidationVersion) === packageVersion;
48
+ export function isProductionCacheManifestCurrent(manifest, corePackageVersion) {
49
+ return manifest?.corePackageVersion === corePackageVersion;
50
50
  }
51
51
  export function matchesProductionCacheFingerprint(manifest, buildInputsFingerprint) {
52
52
  return manifest?.buildInputsFingerprint === buildInputsFingerprint;
@@ -1,6 +1,5 @@
1
1
  import type { BuildResult } from '../build-adapter.js';
2
2
  import type { EcoPagesAppConfig } from '../../types/internal-types.js';
3
- export { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
4
3
  export declare const SERVER_BUNDLE_MANIFEST_FILENAME = "manifest.json";
5
4
  export interface ServerBundleDeployManifest {
6
5
  serverEntry: string;
@@ -18,7 +17,7 @@ export interface ServerBundleDeployManifest {
18
17
  emittedConfigHash?: string;
19
18
  }
20
19
  export interface ServerEntryBuildCacheManifest {
21
- invalidationVersion: string;
20
+ corePackageVersion: string;
22
21
  entryPath: string;
23
22
  entryHash: string;
24
23
  configHash: string;
@@ -7,14 +7,13 @@ import { createPluginCacheKey, getCorePackageVersion } from './cache-keys.js';
7
7
  import { RouteModuleDependencyHasher, createRouteModuleDependencyHashes, } from '../../services/module-loading/route-module-dependency-hasher.js';
8
8
  import { resolveInternalExecutionDir } from '../../utils/resolve-work-dir.js';
9
9
  import { SERVER_BUNDLE_DIR, SERVER_BUNDLE_FILENAME } from '../../utils/resolve-entry-file.js';
10
- import { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
11
- export { SERVER_ENTRY_BUILD_CACHE_FILENAME } from './cache-constants.js';
10
+ import { ROUTE_MODULE_BUILD_CACHE_FILENAME } from './cache-constants.js';
12
11
  export const SERVER_BUNDLE_MANIFEST_FILENAME = 'manifest.json';
13
12
  function getServerEntryCacheDir(appConfig) {
14
13
  return path.join(resolveInternalExecutionDir(appConfig), '.server-entry');
15
14
  }
16
15
  function getServerEntryCacheManifestPath(appConfig) {
17
- return path.join(getServerEntryCacheDir(appConfig), SERVER_ENTRY_BUILD_CACHE_FILENAME);
16
+ return path.join(getServerEntryCacheDir(appConfig), ROUTE_MODULE_BUILD_CACHE_FILENAME);
18
17
  }
19
18
  function hashDependencyGraph(entryPath, dependencyGraph, hasher, rootDir) {
20
19
  if (!dependencyGraph) {
@@ -55,7 +54,7 @@ export function readServerEntryBuildCacheManifest(appConfig) {
55
54
  return readProductionCacheManifest(getServerEntryCacheManifestPath(appConfig));
56
55
  }
57
56
  function writeServerEntryBuildCacheManifest(appConfig, manifest) {
58
- writeProductionCacheManifest(path.join(getServerEntryCacheDir(appConfig), SERVER_ENTRY_BUILD_CACHE_FILENAME), manifest);
57
+ writeProductionCacheManifest(path.join(getServerEntryCacheDir(appConfig), ROUTE_MODULE_BUILD_CACHE_FILENAME), manifest);
59
58
  }
60
59
  function hashExistingFile(filePath) {
61
60
  return filePath && fileSystem.exists(filePath) ? fileSystem.hash(filePath) : undefined;
@@ -229,7 +228,7 @@ export function recordServerEntryBuildCache(options) {
229
228
  : {};
230
229
  const dependencyHashes = { ...appDependencyHashes, ...configDependencyHashes };
231
230
  const manifest = {
232
- invalidationVersion: getCorePackageVersion(),
231
+ corePackageVersion: getCorePackageVersion(),
233
232
  entryPath,
234
233
  entryHash,
235
234
  configHash,
@@ -34,21 +34,11 @@ export interface BuildResult {
34
34
  *
35
35
  * @remarks
36
36
  * Fields that the adapter can forward are honored. `splitting: false` disables
37
- * Rolldown code splitting for single-entrypoint builds. `bundle` and `outbase`
38
- * are accepted for call-site compatibility but ignored.
37
+ * Rolldown code splitting for single-entrypoint builds.
39
38
  */
40
39
  export interface BuildOptions {
41
40
  entrypoints: string[] | Record<string, string>;
42
41
  outdir?: string;
43
- /**
44
- * Base directory for `[dir]` placeholders in `naming`. Currently
45
- * the bundled adapter derives the base from `root` directly and
46
- * ignores this field.
47
- *
48
- * @deprecated Accepted for call-site compatibility only. Use record-form
49
- * `entrypoints` keys to preserve directory structure.
50
- */
51
- outbase?: string;
52
42
  naming?: string;
53
43
  conditions?: string[];
54
44
  define?: Record<string, string>;
@@ -60,8 +50,6 @@ export interface BuildOptions {
60
50
  /** When `false` with a single entrypoint, inlines dynamic imports into one output file. */
61
51
  splitting?: boolean;
62
52
  root?: string;
63
- /** @deprecated Accepted for call-site compatibility only. */
64
- bundle?: boolean;
65
53
  externalPackages?: boolean;
66
54
  external?: string[];
67
55
  jsx?: {
@@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { pathToFileURL } from 'node:url';
5
+ import { appLogger } from '../../global/app-logger.js';
5
6
  import { isBarePackageImportSpecifier } from '../../plugins/tsconfig-import-resolver.js';
6
7
  const corePackageRequire = createRequire(new URL('../../../package.json', import.meta.url));
7
8
  const appDeclaredPackageCache = new Map();
@@ -201,9 +202,7 @@ function rewriteRuntimeBuildOutputImports(code, rootDir) {
201
202
  });
202
203
  }
203
204
  export function normalizeNodeRuntimeBuildOutputFile(filePath, rootDir) {
204
- if (process.env.ECOPAGES_LOGGER_DEBUG === 'true') {
205
- console.log(`[normalizeNodeRuntimeBuildOutputFile] Checking ${filePath}`);
206
- }
205
+ appLogger.debug(`[normalizeNodeRuntimeBuildOutputFile] Checking ${filePath}`);
207
206
  if (!/\.(?:[cm]?js)$/u.test(filePath)) {
208
207
  return;
209
208
  }
@@ -214,9 +213,7 @@ export function normalizeNodeRuntimeBuildOutputFile(filePath, rootDir) {
214
213
  const code = fileSystem.readFileSync(filePath, 'utf-8');
215
214
  const rewritten = rewriteRuntimeBuildOutputImports(code, rootDir);
216
215
  if (rewritten !== code) {
217
- if (process.env.ECOPAGES_LOGGER_DEBUG === 'true') {
218
- console.log(`[normalizeNodeRuntimeBuildOutputFile] Rewriting ${filePath}`);
219
- }
216
+ appLogger.debug(`[normalizeNodeRuntimeBuildOutputFile] Rewriting ${filePath}`);
220
217
  fileSystem.writeFileSync(filePath, rewritten);
221
218
  }
222
219
  }
@@ -7,11 +7,7 @@ import type { BuildOptions } from '../contracts/build-contracts.js';
7
7
  * are sorted. Plugin, `conditions`, and source-transform order is preserved because
8
8
  * Rolldown hook and `conditionNames` precedence depend on it.
9
9
  *
10
- * Deprecated / ignored adapter fields (`splitting`, `bundle`, `outbase`) still
11
- * participate in the key so requests that differ only on those fields do not
12
- * coalesce. Empty `conditions` / `define` / `external` normalize to the same
13
- * sentinel as `undefined`.
10
+ * Empty `conditions` / `define` / `external` normalize to the same sentinel as
11
+ * `undefined`.
14
12
  */
15
13
  export declare function createBuildRequestIdentity(options: BuildOptions): string;
16
- /** @deprecated Use {@link createBuildRequestIdentity}. */
17
- export declare const createBuildOptionsDedupeKey: typeof createBuildRequestIdentity;
@@ -47,19 +47,15 @@ function normalizeDefine(define) {
47
47
  * are sorted. Plugin, `conditions`, and source-transform order is preserved because
48
48
  * Rolldown hook and `conditionNames` precedence depend on it.
49
49
  *
50
- * Deprecated / ignored adapter fields (`splitting`, `bundle`, `outbase`) still
51
- * participate in the key so requests that differ only on those fields do not
52
- * coalesce. Empty `conditions` / `define` / `external` normalize to the same
53
- * sentinel as `undefined`.
50
+ * Empty `conditions` / `define` / `external` normalize to the same sentinel as
51
+ * `undefined`.
54
52
  */
55
53
  export function createBuildRequestIdentity(options) {
56
54
  return [
57
55
  normalizeEntrypoints(options.entrypoints),
58
56
  options.root ? path.resolve(options.root) : 'root:default',
59
57
  options.outdir ? path.resolve(options.outdir) : 'outdir:default',
60
- options.outbase ? path.resolve(options.outbase) : 'outbase:default',
61
58
  options.splitting ?? 'splitting:default',
62
- options.bundle ?? 'bundle:default',
63
59
  options.externalPackages ?? 'externalPackages:default',
64
60
  options.target ?? 'target:default',
65
61
  options.format ?? 'format:default',
@@ -75,5 +71,3 @@ export function createBuildRequestIdentity(options) {
75
71
  createSourceTransformCacheKey(options.sourceTransforms),
76
72
  ].join('::');
77
73
  }
78
- /** @deprecated Use {@link createBuildRequestIdentity}. */
79
- export const createBuildOptionsDedupeKey = createBuildRequestIdentity;
@@ -1,5 +1,4 @@
1
1
  import type { BuildExecutor, BuildOptions, BuildResult } from '../build-adapter.js';
2
- export { createBuildRequestIdentity, createBuildOptionsDedupeKey } from './build-request-identity.js';
3
2
  /**
4
3
  * In-flight build coalescing wrapper.
5
4
  *
@@ -1,5 +1,4 @@
1
1
  import { createBuildRequestIdentity } from './build-request-identity.js';
2
- export { createBuildRequestIdentity, createBuildOptionsDedupeKey } from './build-request-identity.js';
3
2
  /**
4
3
  * In-flight build coalescing wrapper.
5
4
  *
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @module @ecopages/core/cache
5
5
  */
6
- export { ModuleParseCache, moduleParseCache, cachedParseSync, parseModuleSource, parserLanguageForFile, type ModuleParseOptions, type ParserLanguage, } from './module-parse-cache.js';
6
+ export { parseModuleSource, type ModuleParseOptions } from './module-parse-cache.js';
7
7
  export { recordModuleTransformProfile } from './module-transform-profiler.js';
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @module @ecopages/core/cache
5
5
  */
6
- export { ModuleParseCache, moduleParseCache, cachedParseSync, parseModuleSource, parserLanguageForFile, } from './module-parse-cache.js';
6
+ export { parseModuleSource } from './module-parse-cache.js';
7
7
  export { recordModuleTransformProfile } from './module-transform-profiler.js';