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

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 (179) hide show
  1. package/README.md +50 -32
  2. package/package.json +50 -4
  3. package/src/adapters/README.md +3 -1
  4. package/src/adapters/abstract/application-adapter.d.ts +28 -6
  5. package/src/adapters/abstract/application-adapter.js +58 -5
  6. package/src/adapters/abstract/segment-path-matcher.js +56 -38
  7. package/src/adapters/abstract/server-adapter.d.ts +14 -0
  8. package/src/adapters/abstract/server-adapter.js +10 -0
  9. package/src/adapters/bun/create-app.d.ts +8 -4
  10. package/src/adapters/bun/create-app.js +64 -37
  11. package/src/adapters/bun/server-adapter.d.ts +6 -2
  12. package/src/adapters/bun/server-adapter.js +14 -1
  13. package/src/adapters/create-app.d.ts +62 -7
  14. package/src/adapters/create-app.js +61 -5
  15. package/src/adapters/node/create-app.d.ts +5 -5
  16. package/src/adapters/node/create-app.js +18 -5
  17. package/src/adapters/node/runtime-host.js +9 -4
  18. package/src/adapters/node/server-adapter.d.ts +5 -1
  19. package/src/adapters/node/server-adapter.js +16 -1
  20. package/src/adapters/shared/http/explicit-static-route-matcher.js +5 -2
  21. package/src/adapters/shared/http/fs-server-response-factory.d.ts +2 -8
  22. package/src/adapters/shared/http/fs-server-response-factory.js +5 -30
  23. package/src/adapters/shared/http/fs-server-response-matcher.d.ts +24 -24
  24. package/src/adapters/shared/http/fs-server-response-matcher.js +59 -83
  25. package/src/adapters/shared/runtime/application-adapter.d.ts +1 -0
  26. package/src/adapters/shared/runtime/application-adapter.js +12 -0
  27. package/src/adapters/shared/runtime/bind-runtime-server.d.ts +17 -0
  28. package/src/adapters/shared/runtime/bind-runtime-server.js +50 -0
  29. package/src/adapters/shared/runtime/port-manager-default-prompt.d.ts +6 -0
  30. package/src/adapters/shared/runtime/port-manager-default-prompt.js +41 -0
  31. package/src/adapters/shared/runtime/port-manager.d.ts +3 -3
  32. package/src/adapters/shared/runtime/port-manager.js +14 -45
  33. package/src/adapters/shared/runtime/server-adapter.d.ts +14 -5
  34. package/src/adapters/shared/runtime/server-adapter.js +22 -30
  35. package/src/adapters/shared/runtime/server-route-handler.js +11 -3
  36. package/src/adapters/shared/runtime/server-static-builder.d.ts +9 -3
  37. package/src/adapters/shared/runtime/server-static-builder.js +59 -37
  38. package/src/build/README.md +4 -0
  39. package/src/build/cache/server-entry-build-cache.d.ts +24 -1
  40. package/src/build/cache/server-entry-build-cache.js +125 -8
  41. package/src/build/contracts/content-virtual-modules.d.ts +3 -1
  42. package/src/build/contracts/content-virtual-modules.js +8 -0
  43. package/src/build/rolldown/rolldown-adapter-helpers.js +41 -25
  44. package/src/build/rolldown/rolldown-plugin-bridge.js +25 -21
  45. package/src/build/runtime/build-request-policy.js +1 -1
  46. package/src/build/server-bundle-publication.d.ts +14 -0
  47. package/src/build/server-bundle-publication.js +49 -0
  48. package/src/config/README.md +17 -2
  49. package/src/config/apply-user-config.d.ts +6 -0
  50. package/src/config/apply-user-config.js +67 -0
  51. package/src/config/config-builder.d.ts +10 -1
  52. package/src/config/config-builder.js +51 -10
  53. package/src/config/constants.d.ts +4 -0
  54. package/src/config/constants.js +4 -0
  55. package/src/config/define-config.d.ts +9 -0
  56. package/src/config/define-config.js +10 -0
  57. package/src/config/index.d.ts +5 -0
  58. package/src/config/index.js +4 -0
  59. package/src/config/is-finalized-app-config.d.ts +6 -0
  60. package/src/config/is-finalized-app-config.js +11 -0
  61. package/src/config/load-eco-config.d.ts +21 -0
  62. package/src/config/load-eco-config.js +100 -0
  63. package/src/config/resolve-eco-config-path.d.ts +23 -0
  64. package/src/config/resolve-eco-config-path.js +47 -0
  65. package/src/config/server-config-bundle.d.ts +25 -0
  66. package/src/config/server-config-bundle.js +148 -0
  67. package/src/config/user-config-types.d.ts +164 -0
  68. package/src/config/user-config-types.js +1 -0
  69. package/src/css-imports.d.ts +4 -0
  70. package/src/declarations.d.ts +11 -5
  71. package/src/dev/README.md +6 -0
  72. package/src/dev/development-restart-watch-paths.d.ts +13 -0
  73. package/src/dev/development-restart-watch-paths.js +37 -0
  74. package/src/dev/development-restart.d.ts +13 -0
  75. package/src/dev/development-restart.js +21 -0
  76. package/src/dev/transform-server/dev-transform-server.d.ts +6 -0
  77. package/src/dev/transform-server/dev-transform-server.js +16 -5
  78. package/src/eco/README.md +73 -5
  79. package/src/eco/component-identity.d.ts +3 -2
  80. package/src/eco/component-identity.js +5 -2
  81. package/src/eco/discovered-dependencies.d.ts +45 -0
  82. package/src/eco/discovered-dependencies.js +87 -0
  83. package/src/eco/eco.js +6 -0
  84. package/src/eco/eco.types.d.ts +18 -2
  85. package/src/eco/lazy-injector-map.js +57 -41
  86. package/src/eco/page-dependency-contributions.d.ts +19 -0
  87. package/src/eco/page-dependency-contributions.js +52 -0
  88. package/src/errors/http-error-page-contract.d.ts +77 -0
  89. package/src/errors/http-error-page-contract.js +106 -0
  90. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -0
  91. package/src/hmr/strategies/js-hmr-strategy.js +24 -16
  92. package/src/index.browser.d.ts +3 -0
  93. package/src/index.browser.js +3 -0
  94. package/src/index.d.ts +4 -1
  95. package/src/index.js +4 -1
  96. package/src/islands/README.md +5 -1
  97. package/src/plugins/README.md +8 -1
  98. package/src/plugins/component-import-discovery.d.ts +19 -0
  99. package/src/plugins/component-import-discovery.js +241 -0
  100. package/src/plugins/eco-component-meta-plugin.d.ts +3 -1
  101. package/src/plugins/eco-component-meta-plugin.js +118 -16
  102. package/src/plugins/processor.d.ts +10 -2
  103. package/src/plugins/processor.js +4 -0
  104. package/src/plugins/tsconfig-import-resolver.d.ts +3 -1
  105. package/src/plugins/tsconfig-import-resolver.js +4 -2
  106. package/src/route-renderer/GRAPH.md +1 -1
  107. package/src/route-renderer/README.md +15 -2
  108. package/src/{adapters/shared/http/explicit-static-render-preparation.d.ts → route-renderer/explicit-view-render-preparation.d.ts} +3 -3
  109. package/src/route-renderer/orchestration/custom-element-scripts/README.md +9 -0
  110. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preload-invalidation.d.ts +16 -0
  111. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preload-invalidation.js +34 -0
  112. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preloader.d.ts +80 -0
  113. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-script-preloader.js +190 -0
  114. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-server-module-importer.d.ts +17 -0
  115. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-server-module-importer.js +41 -0
  116. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-ssr-preload-entrypoint.d.ts +10 -0
  117. package/src/route-renderer/orchestration/custom-element-scripts/custom-element-ssr-preload-entrypoint.js +46 -0
  118. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.d.ts +7 -2
  119. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +2 -0
  120. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +11 -2
  121. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +10 -2
  122. package/src/route-renderer/orchestration/integration-renderer.d.ts +9 -5
  123. package/src/route-renderer/orchestration/integration-renderer.js +42 -29
  124. package/src/route-renderer/orchestration/ownership-graph/component-graph-collectors.d.ts +2 -5
  125. package/src/route-renderer/orchestration/ownership-graph/component-graph-collectors.js +2 -68
  126. package/src/route-renderer/orchestration/ownership-graph/component-graph.js +55 -39
  127. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.d.ts +6 -0
  128. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +59 -36
  129. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +8 -10
  130. package/src/route-renderer/orchestration/string-markup-renderer.d.ts +1 -1
  131. package/src/route-renderer/orchestration/string-markup-renderer.js +2 -1
  132. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +6 -2
  133. package/src/route-renderer/page-loading/component-dependency-collection.js +113 -68
  134. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +41 -28
  135. package/src/route-renderer/page-loading/file-scoped-dependency-components.d.ts +10 -3
  136. package/src/route-renderer/page-loading/file-scoped-dependency-components.js +62 -25
  137. package/src/route-renderer/page-loading/page-dependency-bundling.js +14 -8
  138. package/src/route-renderer/page-loading/resolved-page-dependencies.d.ts +1 -2
  139. package/src/route-renderer/page-loading/resolved-page-dependencies.js +8 -7
  140. package/src/route-renderer/route-renderer.d.ts +9 -0
  141. package/src/route-renderer/route-renderer.js +18 -0
  142. package/src/router/README.md +7 -1
  143. package/src/router/server/route-registry.d.ts +13 -0
  144. package/src/router/server/route-registry.js +46 -32
  145. package/src/services/README.md +5 -0
  146. package/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.d.ts +36 -9
  147. package/src/services/assets/asset-processing-service/browser-runtime-entry-resolution.js +122 -37
  148. package/src/services/assets/asset-processing-service/browser-runtime-entry.factory.d.ts +2 -0
  149. package/src/services/assets/asset-processing-service/browser-runtime-entry.factory.js +13 -2
  150. package/src/services/assets/asset-processing-service/page-package.js +42 -39
  151. package/src/services/error-pages/README.md +9 -0
  152. package/src/services/error-pages/default-error-pages.d.ts +44 -0
  153. package/src/services/error-pages/default-error-pages.js +207 -0
  154. package/src/services/error-pages/error-page-renderer.d.ts +58 -0
  155. package/src/services/error-pages/error-page-renderer.js +146 -0
  156. package/src/services/error-pages/semantic-error-page-exporter.d.ts +23 -0
  157. package/src/services/error-pages/semantic-error-page-exporter.js +35 -0
  158. package/src/services/invalidation/development-invalidation.service.d.ts +7 -1
  159. package/src/services/invalidation/development-invalidation.service.js +35 -3
  160. package/src/services/module-loading/README.md +16 -13
  161. package/src/services/module-loading/app-server-module-transpiler.service.js +2 -0
  162. package/src/services/module-loading/collection-server-module-build.service.d.ts +1 -0
  163. package/src/services/module-loading/collection-server-module-build.service.js +5 -2
  164. package/src/services/module-loading/page-module-import.service.d.ts +8 -0
  165. package/src/services/module-loading/page-module-import.service.js +62 -28
  166. package/src/services/module-loading/route-module-dependency-hasher.js +13 -1
  167. package/src/services/module-loading/view-module-loader.d.ts +10 -0
  168. package/src/services/module-loading/view-module-loader.js +46 -0
  169. package/src/services/validation/schema-validation-service.d.ts +1 -0
  170. package/src/services/validation/schema-validation-service.js +23 -36
  171. package/src/static-site-generator/README.md +6 -1
  172. package/src/static-site-generator/static-site-generator.d.ts +7 -2
  173. package/src/static-site-generator/static-site-generator.js +90 -49
  174. package/src/types/internal-types.d.ts +6 -1
  175. package/src/types/public-types.d.ts +32 -22
  176. package/src/utils/parse-cli-args.js +29 -22
  177. package/src/watchers/project-watcher.d.ts +14 -1
  178. package/src/watchers/project-watcher.js +85 -34
  179. /package/src/{adapters/shared/http/explicit-static-render-preparation.js → route-renderer/explicit-view-render-preparation.js} +0 -0
@@ -1,5 +1,5 @@
1
1
  import { createServer as createNetServer } from 'node:net';
2
- import { createInterface } from 'node:readline';
2
+ import { createClackDefaultPrompt } from './port-manager-default-prompt.js';
3
3
  /**
4
4
  * Detects whether a thrown error indicates the requested port is already in
5
5
  * use.
@@ -53,42 +53,12 @@ export function isPortAvailable(port, hostname = '127.0.0.1') {
53
53
  tester.listen(port, hostname);
54
54
  });
55
55
  }
56
- function createDefaultPrompt(stdin, stdout) {
57
- return async (message, timeoutMs) => {
58
- stdout.write(`${message} `);
59
- return await new Promise((resolve) => {
60
- const rl = createInterface({ input: stdin, output: undefined, terminal: false });
61
- let settled = false;
62
- const finish = (value) => {
63
- if (settled) {
64
- return;
65
- }
66
- settled = true;
67
- clearTimeout(timer);
68
- rl.close();
69
- stdout.write('\n');
70
- resolve(value);
71
- };
72
- const timer = setTimeout(() => finish(true), timeoutMs);
73
- rl.once('line', (line) => {
74
- const answer = line.trim().toLowerCase();
75
- if (answer === '' || answer === 'y' || answer === 'yes') {
76
- finish(true);
77
- }
78
- else {
79
- finish(false);
80
- }
81
- });
82
- rl.once('close', () => finish(true));
83
- });
84
- };
85
- }
86
- const PREVIEW_PORT_RELEASE_RACE_RETRIES = 2;
87
- const PREVIEW_PORT_FALLBACK_ATTEMPTS = 20;
88
- const PREVIEW_PORT_RELEASE_RACE_DELAY_MS = 100;
89
- const PREVIEW_PORT_AUTO_APPROVE_MS = 10_000;
56
+ const PORT_RELEASE_RACE_RETRIES = 2;
57
+ const PORT_FALLBACK_ATTEMPTS = 20;
58
+ const PORT_RELEASE_RACE_DELAY_MS = 100;
59
+ const PORT_AUTO_APPROVE_MS = 10_000;
90
60
  /**
91
- * Owns preview-port assignment: probing, race-release retries, fallback, and
61
+ * Owns server-port assignment: probing, race-release retries, fallback, and
92
62
  * an optional interactive auto-approve prompt.
93
63
  *
94
64
  * @remarks
@@ -109,10 +79,10 @@ export class PortManager {
109
79
  this.startOnPort = options.startOnPort;
110
80
  this.warn = options.warn;
111
81
  this.probePort = options.probePort ?? isPortAvailable;
112
- this.maxPortOffset = options.maxPortOffset ?? PREVIEW_PORT_FALLBACK_ATTEMPTS - 1;
113
- this.releaseRaceRetries = options.releaseRaceRetries ?? PREVIEW_PORT_RELEASE_RACE_RETRIES;
114
- this.releaseRaceDelayMs = options.releaseRaceDelayMs ?? PREVIEW_PORT_RELEASE_RACE_DELAY_MS;
115
- this.autoApproveMs = options.autoApproveMs ?? PREVIEW_PORT_AUTO_APPROVE_MS;
82
+ this.maxPortOffset = options.maxPortOffset ?? PORT_FALLBACK_ATTEMPTS - 1;
83
+ this.releaseRaceRetries = options.releaseRaceRetries ?? PORT_RELEASE_RACE_RETRIES;
84
+ this.releaseRaceDelayMs = options.releaseRaceDelayMs ?? PORT_RELEASE_RACE_DELAY_MS;
85
+ this.autoApproveMs = options.autoApproveMs ?? PORT_AUTO_APPROVE_MS;
116
86
  this.interactive =
117
87
  typeof options.interactive === 'boolean'
118
88
  ? options.interactive
@@ -121,14 +91,14 @@ export class PortManager {
121
91
  this.prompt = options.prompt;
122
92
  }
123
93
  else if (this.interactive) {
124
- this.prompt = createDefaultPrompt(process.stdin, process.stdout);
94
+ this.prompt = createClackDefaultPrompt();
125
95
  }
126
96
  else {
127
97
  this.prompt = undefined;
128
98
  }
129
99
  }
130
100
  /**
131
- * Binds the preview server to the preferred port.
101
+ * Binds a server to the preferred port.
132
102
  *
133
103
  * @remarks
134
104
  * When the preferred port is free, binds it directly — no prompt, no
@@ -149,7 +119,6 @@ export class PortManager {
149
119
  if (firstAttempt.status === 'factory-refused') {
150
120
  return null;
151
121
  }
152
- // firstAttempt.status === 'port-in-use'
153
122
  await this.shouldFallback(preferredPort, options.allowPortFallback, firstAttempt.error);
154
123
  return await this.fallForward(preferredPort);
155
124
  }
@@ -158,7 +127,7 @@ export class PortManager {
158
127
  const nextFree = await this.findNextFreePort(preferredPort);
159
128
  const nextFreeSuffix = typeof nextFree === 'number' ? ` (next free: ${nextFree})` : '';
160
129
  const autoApproveHint = `auto-yes in ${Math.round(this.autoApproveMs / 1000)}s`;
161
- const message = `[@ecopages/core] Port ${preferredPort} is already in use${nextFreeSuffix}. Bind there instead? [Y/n] (${autoApproveHint})`;
130
+ const message = `Port ${preferredPort} is already in use${nextFreeSuffix}. Bind to the next free port instead? (${autoApproveHint})`;
162
131
  const accepted = await this.prompt(message, this.autoApproveMs);
163
132
  if (!accepted) {
164
133
  throw error;
@@ -174,7 +143,7 @@ export class PortManager {
174
143
  const candidatePort = preferredPort + offset;
175
144
  const attempt = await this.tryPort(candidatePort);
176
145
  if (attempt.status === 'bound') {
177
- this.warn?.(`Port ${preferredPort} is in use; preview serving on port ${attempt.boundPort} instead. Pin the preview port with --port or ECOPAGES_PORT when a fixed binding is required.`);
146
+ this.warn?.(`Port ${preferredPort} is in use; serving on port ${attempt.boundPort} instead. Pin the port with --port or ECOPAGES_PORT when a fixed binding is required.`);
178
147
  return attempt.boundPort;
179
148
  }
180
149
  }
@@ -8,7 +8,7 @@ import { ServerStaticBuilder } from './server-static-builder.js';
8
8
  import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
9
9
  import { ServerRouteHandler } from './server-route-handler.js';
10
10
  import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
11
- import type { ApiHandler, CacheInvalidator, ErrorHandler, IHmrManager, RenderContext, StaticRoute } from '../../../types/public-types.js';
11
+ import type { ApiHandler, CacheInvalidator, ErrorHandler, IHmrManager, RenderContext, StaticRoute, ErrorPageLoaders } from '../../../types/public-types.js';
12
12
  type SharedHmrAssetManager = IHmrManager;
13
13
  type SharedRequestContext<TServer = unknown> = {
14
14
  apiHandlers: ApiHandler[];
@@ -28,17 +28,24 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
28
28
  protected hostOwnsDevClient: boolean;
29
29
  private devStaticRoutePrewarmStarted;
30
30
  private sharedPageCacheService;
31
+ /** Propagates the actual listening port to every binding-dependent service. */
32
+ applyBoundPort(input: {
33
+ port: number;
34
+ runtimeOrigin: string;
35
+ }): void;
31
36
  /**
32
37
  * Warms declared static paths after the final watch-mode response pipeline exists.
33
38
  */
34
39
  protected startDevStaticRoutePrewarmWhenReady(): Promise<void>;
35
40
  protected initializeSharedRouteHandling(options: {
36
41
  staticRoutes: StaticRoute[];
42
+ errorPageLoaders?: ErrorPageLoaders;
37
43
  hmrManager?: SharedHmrAssetManager;
38
44
  }): Promise<void>;
39
45
  private ensureRouteRendererFactory;
40
46
  protected createSharedWatchRefreshCallback(options: {
41
47
  staticRoutes: StaticRoute[];
48
+ errorPageLoaders?: ErrorPageLoaders;
42
49
  hmrManager?: SharedHmrAssetManager;
43
50
  onRoutesReady?: () => Promise<void> | void;
44
51
  onError?: (error: Error) => Promise<void> | void;
@@ -60,12 +67,14 @@ export declare abstract class SharedServerAdapter<TOptions extends ServerAdapter
60
67
  * 1. How to render React/Lit pages via `RouteRendererFactory`
61
68
  * 2. How to match logical routes to physical filesystem artifacts via `FileSystemResponseMatcher`
62
69
  * 3. Whether to serve the response from the embedded `PageCacheService` or generate it fresh on the fly.
63
- *
64
- * @param staticRoutes - A map of explicitly served static assets.
65
- * @param hmrManager - The runtime-specific Hot Module Replacement orchestrator (if watching).
66
70
  */
67
- protected configureSharedResponseHandlers(staticRoutes: StaticRoute[], hmrManager?: IHmrManager): void;
71
+ protected configureSharedResponseHandlers(options: {
72
+ staticRoutes: StaticRoute[];
73
+ hmrManager?: IHmrManager;
74
+ errorPageLoaders?: ErrorPageLoaders;
75
+ }): void;
68
76
  private createSharedResponseHandlerDependencies;
77
+ private createSharedPageCacheServiceFromConfig;
69
78
  private getOrCreateSharedPageCacheService;
70
79
  protected getCacheService(): CacheInvalidator | null;
71
80
  protected getRenderContext(): RenderContext;
@@ -37,6 +37,12 @@ export class SharedServerAdapter extends AbstractServerAdapter {
37
37
  hostOwnsDevClient = false;
38
38
  devStaticRoutePrewarmStarted = false;
39
39
  sharedPageCacheService;
40
+ /** Propagates the actual listening port to every binding-dependent service. */
41
+ applyBoundPort(input) {
42
+ super.applyBoundPort(input);
43
+ this.routeRendererFactory?.setRuntimeOrigin(input.runtimeOrigin);
44
+ this.staticBuilder?.setRuntimeBinding(input);
45
+ }
40
46
  /**
41
47
  * Warms declared static paths after the final watch-mode response pipeline exists.
42
48
  */
@@ -72,7 +78,7 @@ export class SharedServerAdapter extends AbstractServerAdapter {
72
78
  async initializeSharedRouteHandling(options) {
73
79
  this.ensureRouteRendererFactory();
74
80
  await this.initSharedRouter();
75
- this.configureSharedResponseHandlers(options.staticRoutes, options.hmrManager);
81
+ this.configureSharedResponseHandlers(options);
76
82
  }
77
83
  ensureRouteRendererFactory() {
78
84
  if (this.routeRendererFactory) {
@@ -89,6 +95,7 @@ export class SharedServerAdapter extends AbstractServerAdapter {
89
95
  try {
90
96
  await this.initializeSharedRouteHandling({
91
97
  staticRoutes: options.staticRoutes,
98
+ errorPageLoaders: options.errorPageLoaders,
92
99
  hmrManager: options.hmrManager,
93
100
  });
94
101
  if (options.onRoutesReady) {
@@ -147,22 +154,19 @@ export class SharedServerAdapter extends AbstractServerAdapter {
147
154
  * 1. How to render React/Lit pages via `RouteRendererFactory`
148
155
  * 2. How to match logical routes to physical filesystem artifacts via `FileSystemResponseMatcher`
149
156
  * 3. Whether to serve the response from the embedded `PageCacheService` or generate it fresh on the fly.
150
- *
151
- * @param staticRoutes - A map of explicitly served static assets.
152
- * @param hmrManager - The runtime-specific Hot Module Replacement orchestrator (if watching).
153
157
  */
154
- configureSharedResponseHandlers(staticRoutes, hmrManager) {
158
+ configureSharedResponseHandlers(options) {
155
159
  this.ensureRouteRendererFactory();
156
- const { fileSystemResponseMatcher, explicitStaticRouteMatcher } = this.createSharedResponseHandlerDependencies(staticRoutes);
160
+ const { fileSystemResponseMatcher, explicitStaticRouteMatcher } = this.createSharedResponseHandlerDependencies(options.staticRoutes, options.errorPageLoaders);
157
161
  this.fileSystemResponseMatcher = fileSystemResponseMatcher;
158
162
  this.routeHandler = new ServerRouteHandler({
159
163
  router: this.router,
160
164
  fileSystemResponseMatcher: this.fileSystemResponseMatcher,
161
165
  explicitStaticRouteMatcher,
162
- hmrManager,
166
+ hmrManager: options.hmrManager,
163
167
  });
164
168
  }
165
- createSharedResponseHandlerDependencies(staticRoutes) {
169
+ createSharedResponseHandlerDependencies(staticRoutes, errorPageLoaders) {
166
170
  const fileSystemResponseFactory = new FileSystemServerResponseFactory({
167
171
  options: {
168
172
  watchMode: !!this.options?.watch,
@@ -174,6 +178,7 @@ export class SharedServerAdapter extends AbstractServerAdapter {
174
178
  assetPrefix: path.join(this.appConfig.rootDir, this.appConfig.distDir),
175
179
  router: this.router,
176
180
  routeRendererFactory: this.routeRendererFactory,
181
+ errorPageLoaders,
177
182
  fileSystemResponseFactory,
178
183
  cacheService,
179
184
  defaultCacheStrategy: this.appConfig.cache?.defaultStrategy ?? 'static',
@@ -190,36 +195,23 @@ export class SharedServerAdapter extends AbstractServerAdapter {
190
195
  : undefined,
191
196
  };
192
197
  }
193
- getOrCreateSharedPageCacheService() {
194
- if (this.sharedPageCacheService !== undefined) {
195
- return this.sharedPageCacheService;
196
- }
198
+ createSharedPageCacheServiceFromConfig() {
197
199
  const cacheConfig = this.appConfig.cache;
198
200
  const watch = Boolean(this.options?.watch);
199
- if (watch) {
200
- if (cacheConfig?.enabled === false) {
201
- this.sharedPageCacheService = null;
202
- registerAppPageCacheService(this.appConfig, null);
203
- return null;
204
- }
205
- const store = cacheConfig?.store === 'memory' || !cacheConfig?.store
206
- ? new MemoryCacheStore({ maxEntries: cacheConfig?.maxEntries })
207
- : cacheConfig.store;
208
- const service = new PageCacheService({ store, enabled: true });
209
- this.sharedPageCacheService = service;
210
- registerAppPageCacheService(this.appConfig, service);
211
- return service;
212
- }
213
- const isCacheEnabled = cacheConfig?.enabled ?? true;
201
+ const isCacheEnabled = watch ? cacheConfig?.enabled !== false : (cacheConfig?.enabled ?? true);
214
202
  if (!isCacheEnabled) {
215
- this.sharedPageCacheService = null;
216
- registerAppPageCacheService(this.appConfig, null);
217
203
  return null;
218
204
  }
219
205
  const store = cacheConfig?.store === 'memory' || !cacheConfig?.store
220
206
  ? new MemoryCacheStore({ maxEntries: cacheConfig?.maxEntries })
221
207
  : cacheConfig.store;
222
- const service = new PageCacheService({ store, enabled: true });
208
+ return new PageCacheService({ store, enabled: true });
209
+ }
210
+ getOrCreateSharedPageCacheService() {
211
+ if (this.sharedPageCacheService !== undefined) {
212
+ return this.sharedPageCacheService;
213
+ }
214
+ const service = this.createSharedPageCacheServiceFromConfig();
223
215
  this.sharedPageCacheService = service;
224
216
  registerAppPageCacheService(this.appConfig, service);
225
217
  return service;
@@ -40,7 +40,15 @@ export class ServerRouteHandler {
40
40
  const pathname = new URL(request.url).pathname;
41
41
  const explicitMatch = this.explicitStaticRouteMatcher?.match(request.url);
42
42
  if (explicitMatch) {
43
- return await this.explicitStaticRouteMatcher.handleMatch(explicitMatch);
43
+ try {
44
+ return await this.explicitStaticRouteMatcher.handleMatch(explicitMatch);
45
+ }
46
+ catch (error) {
47
+ if (error instanceof Response) {
48
+ return error;
49
+ }
50
+ return await this.fileSystemResponseMatcher.renderServerError(pathname, error);
51
+ }
44
52
  }
45
53
  const fsMatch = !pathname.includes('.') && this.router.matchRequest(request.url);
46
54
  return await (fsMatch
@@ -59,8 +67,8 @@ export class ServerRouteHandler {
59
67
  * @throws HttpError for standard HTTP errors
60
68
  */
61
69
  async handleNoMatch(request) {
70
+ const pathname = new URL(request.url).pathname;
62
71
  try {
63
- const pathname = new URL(request.url).pathname;
64
72
  return await this.fileSystemResponseMatcher.handleNoMatch(pathname);
65
73
  }
66
74
  catch (error) {
@@ -71,7 +79,7 @@ export class ServerRouteHandler {
71
79
  this.hmrManager?.broadcast({ type: 'error', message: error.message });
72
80
  appLogger.error('Error handling no match:', error);
73
81
  }
74
- return new Response('Internal Server Error', { status: 500 });
82
+ return await this.fileSystemResponseMatcher.renderServerError(pathname, error);
75
83
  }
76
84
  }
77
85
  }
@@ -1,6 +1,6 @@
1
1
  import type { EcoPagesAppConfig, IHmrManager } from '../../../types/internal-types.js';
2
2
  import type { EcoBuildPlugin } from '../../../build/contracts/build-types.js';
3
- import type { StaticRoute } from '../../../types/public-types.js';
3
+ import type { ErrorPageLoaders, StaticRoute } from '../../../types/public-types.js';
4
4
  import type { RouteRegistry } from '../../../router/server/route-registry.js';
5
5
  import type { StaticSiteGenerator } from '../../../static-site-generator/static-site-generator.js';
6
6
  import type { StaticGenerationRendererResolver } from '../../../route-renderer/route-renderer.js';
@@ -43,14 +43,19 @@ export interface ServerStaticBuilderLogger {
43
43
  export declare class ServerStaticBuilder {
44
44
  private readonly appConfig;
45
45
  private readonly staticSiteGenerator;
46
- private readonly serveOptions;
47
- private readonly runtimeOrigin;
46
+ private serveOptions;
47
+ private runtimeOrigin;
48
48
  private readonly needsServerBundle;
49
49
  private readonly logger;
50
50
  private readonly entryFile;
51
51
  private readonly hmrManager?;
52
52
  private readonly onRuntimePlugin?;
53
53
  constructor({ appConfig, staticSiteGenerator, serveOptions, runtimeOrigin, needsServerBundle, logger, entryFile, hmrManager, onRuntimePlugin, }: ServerStaticBuilderParams);
54
+ /** Keeps build-time URLs aligned with the server's actual listening port. */
55
+ setRuntimeBinding(input: {
56
+ port: number;
57
+ runtimeOrigin: string;
58
+ }): void;
54
59
  private prepareExportDirectory;
55
60
  private refreshRuntimeAssets;
56
61
  /**
@@ -82,5 +87,6 @@ export declare class ServerStaticBuilder {
82
87
  router: RouteRegistry;
83
88
  routeRendererFactory: StaticGenerationRendererResolver;
84
89
  staticRoutes?: StaticRoute[];
90
+ errorPageLoaders?: ErrorPageLoaders;
85
91
  }): Promise<void>;
86
92
  }
@@ -2,12 +2,14 @@ import path from 'node:path';
2
2
  import { fileSystem } from '@ecopages/file-system';
3
3
  import { DEFAULT_ECOPAGES_HOSTNAME, DEFAULT_ECOPAGES_PORT } from '../../../config/constants.js';
4
4
  import { appLogger } from '../../../global/app-logger.js';
5
- import { build, getAppBuildAdapter, setupAppRuntimePlugins } from '../../../build/build-adapter.js';
5
+ import { build, setupAppRuntimePlugins } from '../../../build/build-adapter.js';
6
+ import { createServerBundleStagingDirectory, publishServerBundleDirectory, removeServerBundleStagingDirectory, resolvePublishedServerBundlePaths, } from '../../../build/server-bundle-publication.js';
6
7
  import { createServerBuildRequest } from '../../../build/runtime/build-request-policy.js';
7
8
  import { requireBuildRuntime } from '../../../build/runtime/build-runtime.js';
8
9
  import { attachHmrToIntegrations } from './runtime-server-lifecycle.js';
9
- import { getServerBundleOutputPaths, lookupServerEntryBuildCache, recordServerEntryBuildCache, writeServerBundleDeployManifest, } from '../../../build/cache/server-entry-build-cache.js';
10
+ import { getServerBundleOutputPaths, lookupServerEntryBuildCache, recordServerEntryBuildCache, SERVER_BUNDLE_MANIFEST_FILENAME, writeServerBundleDeployManifest, } from '../../../build/cache/server-entry-build-cache.js';
10
11
  import { clearProductionBuildCaches, shouldResetStaticExportDirectory, } from '../../../static-site-generator/static-build-invalidation.js';
12
+ import { assertCanBundleServerConfig, bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME, } from '../../../config/server-config-bundle.js';
11
13
  import { resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
12
14
  /**
13
15
  * Handles static site generation.
@@ -33,6 +35,11 @@ export class ServerStaticBuilder {
33
35
  this.hmrManager = hmrManager;
34
36
  this.onRuntimePlugin = onRuntimePlugin;
35
37
  }
38
+ /** Keeps build-time URLs aligned with the server's actual listening port. */
39
+ setRuntimeBinding(input) {
40
+ this.serveOptions = { ...this.serveOptions, port: input.port };
41
+ this.runtimeOrigin = input.runtimeOrigin;
42
+ }
36
43
  prepareExportDirectory(force) {
37
44
  if (force) {
38
45
  clearProductionBuildCaches(this.appConfig);
@@ -87,56 +94,70 @@ export class ServerStaticBuilder {
87
94
  * @throws If the build adapter is unavailable, is host-owned, or bundling fails.
88
95
  */
89
96
  async bundleServerEntry(options) {
90
- const buildAdapter = getAppBuildAdapter(this.appConfig);
91
- if (buildAdapter.ownership === 'vite-host') {
92
- throw new Error('Cannot bundle the server entry file: build ownership is "vite-host". ' +
93
- 'The host runtime is expected to produce its own server bundle.');
94
- }
97
+ assertCanBundleServerConfig(this.appConfig);
95
98
  const entryPath = path.isAbsolute(this.entryFile)
96
99
  ? this.entryFile
97
100
  : path.join(this.appConfig.rootDir, this.entryFile);
98
101
  if (!fileSystem.exists(entryPath)) {
99
102
  throw new Error(`Cannot bundle server entry: file "${this.entryFile}" not found in "${this.appConfig.rootDir}".`);
100
103
  }
101
- const { serverOutdir, serverEntryPath } = getServerBundleOutputPaths(this.appConfig);
104
+ const { serverOutdir } = getServerBundleOutputPaths(this.appConfig);
102
105
  const cached = lookupServerEntryBuildCache({
103
106
  appConfig: this.appConfig,
104
107
  entryPath,
105
108
  force: options?.force,
106
109
  });
107
110
  if (cached) {
108
- const hasBundle = cached.outputPaths.some((outputPath) => path.resolve(outputPath) === path.resolve(serverEntryPath) && fileSystem.exists(outputPath));
109
- if (hasBundle) {
110
- this.logger.info('Reusing cached server entry bundle');
111
- writeServerBundleDeployManifest(this.appConfig, serverEntryPath);
112
- return;
113
- }
111
+ this.logger.info('Reusing cached server entry bundle');
112
+ return;
114
113
  }
115
114
  this.logger.info('Bundling server entry file...');
116
- const buildOptions = createServerBuildRequest(this.appConfig, {
117
- profile: 'server-entry',
118
- entrypoints: [entryPath],
119
- outdir: serverOutdir,
120
- naming: SERVER_BUNDLE_FILENAME,
121
- sourcemap: 'hidden',
122
- });
123
- const result = await build(buildOptions, requireBuildRuntime(this.appConfig).getProfile('server-entry'));
124
- if (!result.success) {
125
- const errorMessages = result.logs.map((log) => log.message).join('\n');
126
- throw new Error(`Failed to bundle server entry file:\n${errorMessages}`);
115
+ const stagingDir = createServerBundleStagingDirectory(serverOutdir);
116
+ try {
117
+ const configBundle = await bundleEcoConfigModule(this.appConfig, {
118
+ outputDir: stagingDir,
119
+ runtimeDir: serverOutdir,
120
+ });
121
+ const stagedServerEntryPath = path.join(stagingDir, SERVER_BUNDLE_FILENAME);
122
+ const buildOptions = createServerBuildRequest(this.appConfig, {
123
+ profile: 'server-entry',
124
+ entrypoints: [entryPath],
125
+ outdir: stagingDir,
126
+ naming: SERVER_BUNDLE_FILENAME,
127
+ sourcemap: 'hidden',
128
+ });
129
+ const result = await build(buildOptions, requireBuildRuntime(this.appConfig).getProfile('server-entry'));
130
+ if (!result.success) {
131
+ const errorMessages = result.logs.map((log) => log.message).join('\n');
132
+ throw new Error(`Failed to bundle server entry file:\n${errorMessages}`);
133
+ }
134
+ writeServerBundleDeployManifest(this.appConfig, stagedServerEntryPath, {
135
+ sourceConfigPath: this.appConfig.absolutePaths.config,
136
+ emittedConfigModule: configBundle ? EMITTED_ECO_CONFIG_FILENAME : undefined,
137
+ outputDir: stagingDir,
138
+ });
139
+ const stagedOutputPaths = [
140
+ ...(result.outputs.length > 0
141
+ ? result.outputs.map((output) => output.path)
142
+ : fileSystem.exists(stagedServerEntryPath)
143
+ ? [stagedServerEntryPath]
144
+ : []),
145
+ ...(configBundle ? [configBundle.emittedConfigPath] : []),
146
+ path.join(stagingDir, SERVER_BUNDLE_MANIFEST_FILENAME),
147
+ ];
148
+ const outputPaths = resolvePublishedServerBundlePaths(stagedOutputPaths, stagingDir, serverOutdir);
149
+ publishServerBundleDirectory(stagingDir, serverOutdir);
150
+ recordServerEntryBuildCache({
151
+ appConfig: this.appConfig,
152
+ entryPath,
153
+ buildResult: result,
154
+ configBuildResult: configBundle?.buildResult,
155
+ outputPaths,
156
+ });
157
+ }
158
+ finally {
159
+ removeServerBundleStagingDirectory(stagingDir);
127
160
  }
128
- const outputPaths = result.outputs.length > 0
129
- ? result.outputs.map((output) => output.path)
130
- : fileSystem.exists(serverEntryPath)
131
- ? [serverEntryPath]
132
- : [];
133
- recordServerEntryBuildCache({
134
- appConfig: this.appConfig,
135
- entryPath,
136
- buildResult: result,
137
- outputPaths,
138
- });
139
- writeServerBundleDeployManifest(this.appConfig, serverEntryPath);
140
161
  this.logger.info('Server entry file bundled successfully');
141
162
  }
142
163
  /**
@@ -159,6 +180,7 @@ export class ServerStaticBuilder {
159
180
  baseUrl,
160
181
  routeRendererFactory: dependencies.routeRendererFactory,
161
182
  staticRoutes: dependencies.staticRoutes,
183
+ errorPageLoaders: dependencies.errorPageLoaders,
162
184
  force,
163
185
  preserveExportDirectory,
164
186
  });
@@ -45,6 +45,7 @@ build/
45
45
  app-build-manifest-runtime.ts contributor collection at startup
46
46
  contracts/ EcoBuildPlugin, BuildOptions, AppBuildManifest
47
47
  runtime/ profiles, executors, request policy/identity
48
+ server-bundle-publication.ts staged server/config artifact publication
48
49
  rolldown/ bundler adapter, plugin bridge, output normalization
49
50
  cache/ persisted caches, fingerprints, unified pages graph
50
51
  browser/ client runtime rewrites, JSX ownership, Lit worker guard
@@ -60,6 +61,7 @@ build/
60
61
  - `rolldown/rolldown-plugin-bridge.ts`: `EcoBuildPlugin[]` → bundler-plugin translation.
61
62
  - `runtime/serialized-build-executor.ts`: FIFO queue primitive.
62
63
  - `cache/server-entry-build-cache.ts`: production server-entry bundle cache (`.eco/.server-entry/.build-cache.json` + `dist/.server/manifest.json`).
64
+ - `server-bundle-publication.ts`: stages the server entry, emitted config, and deploy manifest together, then publishes the complete directory with rollback.
63
65
  - `cache/cache-constants.ts`: shared `.build-cache.json` filename for persisted production caches.
64
66
  - `*.test.ts`: regression coverage colocated with each module.
65
67
 
@@ -176,6 +178,8 @@ Two persisted cache layers accelerate production builds. Both use `.build-cache.
176
178
 
177
179
  `requireBuildRuntime(appConfig).getProfile('server-entry')` serves server-entry bundling. `clearProductionBuildCaches()` wipes both manifest trees, resets in-memory route-module state, and clears `buildRuntime`.
178
180
 
181
+ Server-entry cache hits require every recorded runtime artifact. Cache misses build the server entry and emitted config in a sibling staging directory; the deploy manifest joins that generation before the directory is published. A failed build therefore leaves the previous server generation intact.
182
+
179
183
  The route-module registry (`route-module-build-cache-registry.ts`) shares one `RouteModuleBuildCache` per `(app, outdir)` pair. Legacy `.server-route-modules` outdirs are still read for migration but new writes go to `.server-modules`.
180
184
 
181
185
  ## Unified pages graph
@@ -6,11 +6,22 @@ export interface ServerBundleDeployManifest {
6
6
  serverEntry: string;
7
7
  distDir: string;
8
8
  builtAt: number;
9
+ /** Canonical source config path compiled into the server bundle. */
10
+ sourceConfigPath?: string;
11
+ /** Relative source config path from project root. */
12
+ sourceConfigRelativePath?: string;
13
+ /** Deployed config module path relative to the server bundle directory. */
14
+ emittedConfigModule?: string;
15
+ /** Content hash of the source config file when built. */
16
+ configHash?: string;
17
+ /** Content hash of the emitted production config artifact. */
18
+ emittedConfigHash?: string;
9
19
  }
10
20
  export interface ServerEntryBuildCacheManifest {
11
21
  invalidationVersion: string;
12
22
  entryPath: string;
13
23
  entryHash: string;
24
+ configHash: string;
14
25
  buildInputsFingerprint: string;
15
26
  buildKey: string;
16
27
  outputPaths: string[];
@@ -28,7 +39,18 @@ export declare function getServerBundleOutputPaths(appConfig: EcoPagesAppConfig)
28
39
  manifestPath: string;
29
40
  };
30
41
  export declare function readServerEntryBuildCacheManifest(appConfig: EcoPagesAppConfig): ServerEntryBuildCacheManifest | undefined;
31
- export declare function writeServerBundleDeployManifest(appConfig: EcoPagesAppConfig, serverEntryPath: string): void;
42
+ export declare function writeServerBundleDeployManifest(appConfig: EcoPagesAppConfig, serverEntryPath: string, options?: Pick<ServerBundleDeployManifest, 'sourceConfigPath' | 'emittedConfigModule'> & {
43
+ outputDir?: string;
44
+ }): void;
45
+ export declare function readServerBundleDeployManifest(appConfig: EcoPagesAppConfig): ServerBundleDeployManifest | undefined;
46
+ /**
47
+ * @remarks
48
+ * Production `start` must not load a different config than the one compiled into the bundle.
49
+ */
50
+ export declare function assertProductionConfigIdentity(appConfigOrCwd: EcoPagesAppConfig | string, requestedConfigPath: string | undefined, options?: {
51
+ isExplicitOverride?: boolean;
52
+ }): void;
53
+ export declare function readServerBundleDeployManifestFromDir(cwd?: string): ServerBundleDeployManifest | undefined;
32
54
  export declare function lookupServerEntryBuildCache(options: {
33
55
  appConfig: EcoPagesAppConfig;
34
56
  entryPath: string;
@@ -38,6 +60,7 @@ export declare function recordServerEntryBuildCache(options: {
38
60
  appConfig: EcoPagesAppConfig;
39
61
  entryPath: string;
40
62
  buildResult: BuildResult;
63
+ configBuildResult?: BuildResult;
41
64
  outputPaths: string[];
42
65
  }): void;
43
66
  export declare function resolveProductionServerEntry(cwd?: string): string | undefined;