@ecopages/core 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/README.md +2 -2
  2. package/package.json +3 -3
  3. package/src/adapters/node/create-app.d.ts +29 -11
  4. package/src/adapters/node/create-app.js +78 -67
  5. package/src/adapters/node/dev-session.js +0 -1
  6. package/src/adapters/node/http-request-bridge.d.ts +4 -0
  7. package/src/adapters/node/http-request-bridge.js +9 -1
  8. package/src/adapters/node/runtime-host.d.ts +23 -6
  9. package/src/adapters/node/runtime-host.js +27 -8
  10. package/src/adapters/node/server-adapter.d.ts +10 -35
  11. package/src/adapters/node/server-adapter.js +21 -58
  12. package/src/adapters/shared/hmr/hmr-manager.d.ts +9 -5
  13. package/src/adapters/shared/hmr/hmr-manager.js +38 -54
  14. package/src/adapters/shared/http/api-request-pipeline.d.ts +3 -12
  15. package/src/adapters/shared/http/api-request-pipeline.js +7 -7
  16. package/src/adapters/shared/http/dist-file-handler.d.ts +16 -0
  17. package/src/adapters/shared/http/dist-file-handler.js +172 -0
  18. package/src/adapters/shared/http/explicit-static-route-matcher.js +2 -1
  19. package/src/adapters/shared/http/fs-server-response-matcher.js +3 -2
  20. package/src/adapters/shared/runtime/bind-runtime-server.d.ts +5 -7
  21. package/src/adapters/shared/runtime/bind-runtime-server.js +5 -11
  22. package/src/adapters/shared/runtime/port-manager.d.ts +2 -11
  23. package/src/adapters/shared/runtime/port-manager.js +3 -28
  24. package/src/adapters/shared/runtime/runtime-server-lifecycle.d.ts +6 -9
  25. package/src/adapters/shared/runtime/runtime-server-lifecycle.js +2 -5
  26. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +1 -3
  27. package/src/adapters/shared/runtime/server-request-pipeline.js +1 -5
  28. package/src/adapters/shared/runtime/server-static-builder.d.ts +3 -3
  29. package/src/adapters/shared/runtime/server-static-builder.js +3 -3
  30. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +2 -1
  31. package/src/adapters/shared/ws/websocket-lifecycle.d.ts +5 -6
  32. package/src/adapters/shared/ws/websocket-lifecycle.js +1 -2
  33. package/src/build/build-adapter.d.ts +2 -19
  34. package/src/build/build-adapter.js +0 -21
  35. package/src/build/cache/cache-keys.d.ts +0 -3
  36. package/src/build/cache/cache-keys.js +0 -14
  37. package/src/build/cache/pages-unified-graph-build.js +2 -17
  38. package/src/build/contracts/build-contracts.d.ts +0 -3
  39. package/src/build/rolldown/rolldown-build-adapter.d.ts +0 -1
  40. package/src/build/rolldown/rolldown-build-adapter.js +1 -2
  41. package/src/build/rolldown/rolldown-build-invocation-metrics.d.ts +1 -2
  42. package/src/build/rolldown/rolldown-build-invocation-metrics.js +5 -12
  43. package/src/build/runtime/build-queue.d.ts +8 -13
  44. package/src/build/runtime/build-queue.js +6 -17
  45. package/src/build/server/app-module-loader.service.d.ts +1 -1
  46. package/src/build/server/app-module-loader.service.js +0 -2
  47. package/src/build/server/page-module-import.service.d.ts +2 -3
  48. package/src/build/server/page-module-import.service.js +3 -4
  49. package/src/build/server-bundle-deploy-manifest.d.ts +5 -0
  50. package/src/build/server-bundle-deploy-manifest.js +15 -1
  51. package/src/build.d.ts +2 -2
  52. package/src/build.js +2 -2
  53. package/src/config/assembly/app-runtime.d.ts +2 -2
  54. package/src/config/assembly/app-runtime.js +2 -2
  55. package/src/config/assembly/finalize-config.d.ts +4 -4
  56. package/src/config/assembly/finalize-config.js +4 -5
  57. package/src/config/internal-types.d.ts +0 -7
  58. package/src/config/user-config-types.d.ts +0 -4
  59. package/src/diagnostics/request-pipeline-metrics.d.ts +3 -3
  60. package/src/diagnostics/request-pipeline-metrics.js +4 -4
  61. package/src/errors/http-error.d.ts +2 -2
  62. package/src/errors/http-error.js +4 -4
  63. package/src/hmr/client/hmr-runtime.js +16 -7
  64. package/src/hmr/client/module-update.d.ts +7 -0
  65. package/src/hmr/client/module-update.js +21 -4
  66. package/src/hmr/hmr-strategy.d.ts +0 -3
  67. package/src/hmr/hmr-strategy.js +0 -3
  68. package/src/hmr/strategies/js-hmr-strategy.d.ts +2 -3
  69. package/src/hmr/strategies/js-hmr-strategy.js +3 -6
  70. package/src/plugins/alias-resolver-cache.d.ts +4 -3
  71. package/src/plugins/alias-resolver-cache.js +4 -3
  72. package/src/plugins/eco-component-meta-plugin.d.ts +10 -1
  73. package/src/plugins/eco-component-meta-plugin.js +66 -10
  74. package/src/plugins/foreign-jsx-override-plugin.js +2 -1
  75. package/src/route-renderer/error-pages/default-error-pages.js +2 -1
  76. package/src/route-renderer/orchestration/document-shell/document-shell-render.service.js +1 -1
  77. package/src/route-renderer/orchestration/foreign-child/render-session.d.ts +0 -1
  78. package/src/route-renderer/orchestration/integration-renderer.d.ts +10 -5
  79. package/src/route-renderer/orchestration/integration-renderer.js +13 -14
  80. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.d.ts +1 -6
  81. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph-session.js +0 -6
  82. package/src/route-renderer/orchestration/page-browser-graph/page-browser-graph.service.js +10 -32
  83. package/src/route-renderer/page-loading/page-module-loader.js +1 -1
  84. package/src/route-renderer/route-renderer.d.ts +2 -5
  85. package/src/route-renderer/route-renderer.js +2 -4
  86. package/src/router/client/link-navigation-policy.d.ts +4 -1
  87. package/src/router/client/link-navigation-policy.js +20 -6
  88. package/src/router/server/route-registry.d.ts +0 -1
  89. package/src/router/server/route-registry.js +2 -11
  90. package/src/router/server/segment-path-matcher.d.ts +12 -0
  91. package/src/router/server/segment-path-matcher.js +30 -0
  92. package/src/static-site-generator/static-site-generator.d.ts +0 -5
  93. package/src/static-site-generator/static-site-generator.js +2 -15
  94. package/src/types/contracts.d.ts +17 -27
  95. package/src/types/public-types.d.ts +1 -1
  96. package/src/utils/format-error-chain.d.ts +9 -0
  97. package/src/utils/format-error-chain.js +20 -0
  98. package/src/utils/invariant.d.ts +6 -1
  99. package/src/utils/invariant.js +7 -2
  100. package/src/watchers/project-watcher.d.ts +20 -1
  101. package/src/watchers/project-watcher.js +40 -9
  102. package/src/watchers/workspace-package-watch-roots.js +5 -5
  103. package/src/adapters/README.md +0 -58
  104. package/src/adapters/shared/hmr/hmr-manager.test-helpers.d.ts +0 -28
  105. package/src/adapters/shared/hmr/hmr-manager.test-helpers.js +0 -53
  106. package/src/adapters/shared/runtime/runtime-host.d.ts +0 -15
  107. package/src/adapters/shared/runtime/runtime-host.js +0 -1
  108. package/src/assets/README.md +0 -35
  109. package/src/build/README.md +0 -298
  110. package/src/build/server/README.md +0 -50
  111. package/src/cache/README.md +0 -5
  112. package/src/client/README.md +0 -5
  113. package/src/client/navigation-scripts/navigation-scripts.test.browser.d.ts +0 -1
  114. package/src/client/navigation-scripts/navigation-scripts.test.browser.js +0 -111
  115. package/src/client/scroll.test.browser.d.ts +0 -1
  116. package/src/client/scroll.test.browser.js +0 -31
  117. package/src/client/view-transitions.test.browser.d.ts +0 -1
  118. package/src/client/view-transitions.test.browser.js +0 -53
  119. package/src/config/README.md +0 -58
  120. package/src/config/constants.d.ts +0 -1
  121. package/src/config/constants.js +0 -1
  122. package/src/dev/README.md +0 -61
  123. package/src/dev/invalidation/README.md +0 -11
  124. package/src/dev-toolbar/README.md +0 -66
  125. package/src/diagnostics/README.md +0 -11
  126. package/src/eco/README.md +0 -776
  127. package/src/errors/README.md +0 -5
  128. package/src/global/README.md +0 -5
  129. package/src/hmr/README.md +0 -64
  130. package/src/hmr/client/build-error-overlay.test.browser.d.ts +0 -1
  131. package/src/hmr/client/build-error-overlay.test.browser.js +0 -48
  132. package/src/hmr/client/hmr-runtime.test.browser.d.ts +0 -1
  133. package/src/hmr/client/hmr-runtime.test.browser.js +0 -32
  134. package/src/hmr/entrypoint-dependency-graph.d.ts +0 -12
  135. package/src/hmr/entrypoint-dependency-graph.js +0 -27
  136. package/src/hmr/hmr-file-change-prep.d.ts +0 -9
  137. package/src/hmr/hmr-file-change-prep.js +0 -11
  138. package/src/html/README.md +0 -15
  139. package/src/html-pages/README.md +0 -104
  140. package/src/islands/README.md +0 -44
  141. package/src/page-cache/README.md +0 -17
  142. package/src/plugins/README.md +0 -53
  143. package/src/route-renderer/GRAPH.md +0 -142
  144. package/src/route-renderer/README.md +0 -160
  145. package/src/route-renderer/error-pages/README.md +0 -11
  146. package/src/route-renderer/orchestration/custom-element-scripts/README.md +0 -15
  147. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.d.ts +0 -39
  148. package/src/route-renderer/orchestration/integration-renderer.test-fixtures.js +0 -94
  149. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.d.ts +0 -35
  150. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.test-fixtures.js +0 -69
  151. package/src/router/README.md +0 -160
  152. package/src/router/client/link-intent.test.browser.d.ts +0 -1
  153. package/src/router/client/link-intent.test.browser.js +0 -33
  154. package/src/router/client/link-navigation-policy.test.browser.d.ts +0 -1
  155. package/src/router/client/link-navigation-policy.test.browser.js +0 -142
  156. package/src/router/client/navigation-commit.test.browser.d.ts +0 -1
  157. package/src/router/client/navigation-commit.test.browser.js +0 -116
  158. package/src/router/client/navigation-document.test.browser.d.ts +0 -1
  159. package/src/router/client/navigation-document.test.browser.js +0 -77
  160. package/src/router/client/navigation-head.test.browser.d.ts +0 -1
  161. package/src/router/client/navigation-head.test.browser.js +0 -101
  162. package/src/router/client/navigation-lifecycle.test.browser.d.ts +0 -1
  163. package/src/router/client/navigation-lifecycle.test.browser.js +0 -97
  164. package/src/router/client/navigation-view-transition.test.browser.d.ts +0 -1
  165. package/src/router/client/navigation-view-transition.test.browser.js +0 -189
  166. package/src/router/client/staged-stylesheets.test-fixtures.d.ts +0 -18
  167. package/src/router/client/staged-stylesheets.test-fixtures.js +0 -31
  168. package/src/static-site-generator/README.md +0 -67
  169. package/src/static-site-generator/static-site-generator.test-utils.d.ts +0 -2
  170. package/src/static-site-generator/static-site-generator.test-utils.js +0 -41
  171. package/src/types/README.md +0 -5
  172. package/src/utils/README.md +0 -7
  173. package/src/validation/README.md +0 -9
  174. package/src/watchers/README.md +0 -15
  175. package/src/watchers/project-watcher.test-helpers.d.ts +0 -60
  176. package/src/watchers/project-watcher.test-helpers.js +0 -108
package/README.md CHANGED
@@ -21,7 +21,7 @@ The important ownership rules are:
21
21
 
22
22
  - Core runtime mode and `ECOPAGES_*` settings are read through `src/env.ts`. Its typed accessors define the supported variable names, parse `true` and `1` as enabled and `false` and `0` as disabled, and provide the runtime-mode helpers used by core, integrations and Processors. The user-facing settings are documented in the [CLI reference](../ecopages/README.md#environment--runtime-options).
23
23
 
24
- - Every `loadEcoPagesConfig()` call imports the config module through the module cache, then finalizes a distinct app config and `AppRuntime`. Build state, HTML Page warnings, custom-element preload scopes, and request-pipeline metrics stay with that runtime; pure memo caches remain shared. Server startup refreshes the app's build queue via `installBuildQueue(appConfig)`.
24
+ - Every `loadEcoPagesConfig()` call imports the config module through the module cache, then finalizes a distinct app config and `AppRuntime`. Build state, HTML Page warnings, custom-element preload scopes, and request-pipeline metrics stay with that runtime; pure memo caches remain shared. Each runtime keeps the one build queue finalization created.
25
25
  - Build requests declare server or browser environment independently of scheduling. Integrations and Processors contribute one environment-selected plugin list; config rejects duplicate names within an environment. Core's own transforms preserve source locations and the bridge composes chained maps. See [Build Layer](src/build/README.md) and [Plugin Contracts](src/plugins/README.md) for migration.
26
26
  - Component identity attribution is one build plugin, shared by server, browser, and HMR compilation paths: after a lexical `eco.` gate, it uses Oxc to wrap supported factory options with `bindComponentIdentity()`, which factories retain as `config.identity`.
27
27
  - Component ownership follows `config.integration`, then `config.identity.integration`, then the inherited owner through the exported `getComponentOwner()` helper. Integration plugins opt into page-owned asset bundling with `bundlesPageDependencies`; React and Ecopages JSX enable it. Bundling only combines consecutive eligible assets so custom-attribute files keep their declared order.
@@ -90,7 +90,7 @@ The manager/orchestration layer is core-owned, but framework-specific strategies
90
90
 
91
91
  ### Practical Summary
92
92
 
93
- - Config finalization seeds one app-owned `AppRuntime` (build adapter, build manifest, build queue, build-input index, and module caches); the HMR manager owns the concrete per-app dependency graph. Server startup refreshes the build queue.
93
+ - Config finalization seeds one app-owned `AppRuntime` (build adapter, build manifest, build queue, build-input index, and module caches); the HMR manager records the imports of each served browser module in that build-input index. Server startup refreshes the build queue.
94
94
  - `BrowserBundleService` is the shared browser build seam used by HMR and asset-oriented browser output paths; callers choose the `build` or `hmr` scheduling lane explicitly.
95
95
  - `AppModuleLoader` is created once per app runtime and supplies the app root and shared build queue for server-side source loading, including HMR metadata imports.
96
96
  - `RouteRegistry` gives exact and dynamic Pages priority over catch-alls, selects the most specific matching catch-all prefix, and shares segment matching and one-time URL decoding with API, explicit, and WebSocket routes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/core",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Core package for Ecopages",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -21,7 +21,7 @@
21
21
  },
22
22
  "dependencies": {
23
23
  "@clack/prompts": "^1.7.0",
24
- "@ecopages/file-system": "0.3.0",
24
+ "@ecopages/file-system": "0.3.1",
25
25
  "@ecopages/logger": "^0.2.3",
26
26
  "@ecopages/scripts-injector": "^0.1.5",
27
27
  "@jridgewell/remapping": "^2.3.5",
@@ -35,7 +35,7 @@
35
35
  "ws": "^8.20.1"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/dev-toolbar": "0.3.0"
38
+ "@ecopages/dev-toolbar": "0.3.1"
39
39
  },
40
40
  "peerDependenciesMeta": {
41
41
  "@ecopages/dev-toolbar": {
@@ -2,10 +2,8 @@ import type { EcoPagesAppConfig } from '../../config/internal-types.js';
2
2
  import type { ApiHandler, ApiHandlerContext, ErrorHandler, Middleware, RouteGroupBuilder, RouteOptions, ViewLoader, ErrorPageLoaders, ErrorPageTemplateProps, EcopagesRouteInfo, EcopagesWebSocketHandler } from '../../types/contracts.js';
3
3
  import { type HttpErrorPageStatus } from '../../errors/http-error-page-contract.js';
4
4
  import type { ReturnParseCliArgs } from '../../utils/parse-cli-args.js';
5
- import type { RuntimeHost } from '../shared/runtime/runtime-host.js';
6
- import { type NodeRuntimeServeOptions } from './runtime-host.js';
7
- import { type NodeServerAdapter, type NodeServerAdapterParams } from './server-adapter.js';
8
- import type { NodeServerInstance } from './server-adapter.js';
5
+ import { type RuntimeHost } from './runtime-host.js';
6
+ import { NodeServerAdapter, type NodeServerAdapterParams, type NodeServerInstance } from './server-adapter.js';
9
7
  export interface AppStartInfo {
10
8
  origin: string;
11
9
  /**
@@ -24,9 +22,13 @@ export type EcopagesAppRuntimeOptions = {
24
22
  serverOptions?: Record<string, unknown>;
25
23
  cliArgs: ReturnParseCliArgs;
26
24
  };
25
+ /**
26
+ * @remarks
27
+ * Tests pass a fake runtime host and server adapter to drive the app lifecycle in isolation.
28
+ */
27
29
  export type EcopagesAppDependencies = {
28
- runtimeHost: RuntimeHost<NodeServerInstance, NodeRuntimeServeOptions>;
29
- createServerAdapter?: (params: NodeServerAdapterParams) => NodeServerAdapter | Promise<NodeServerAdapter>;
30
+ runtimeHost: RuntimeHost;
31
+ createServerAdapter?: (params: NodeServerAdapterParams) => Promise<NodeServerAdapter>;
30
32
  };
31
33
  /**
32
34
  * Handler function type for route handlers
@@ -52,7 +54,7 @@ export declare class EcopagesApp implements AsyncDisposable {
52
54
  private onAppStartCallback?;
53
55
  private readonly runtimeLabel;
54
56
  private readonly runtimeHost;
55
- private readonly serverAdapterFactory;
57
+ private readonly createServerAdapter;
56
58
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
57
59
  serverAdapter: NodeServerAdapter | undefined;
58
60
  private lifecycle;
@@ -117,7 +119,7 @@ export declare class EcopagesApp implements AsyncDisposable {
117
119
  * and routes lifecycle events to `handler`.
118
120
  *
119
121
  * Supports dynamic segments via `:param` syntax. The handler receives
120
- * typed `params` and `search` fields, and a typed `context` produced by
122
+ * typed `params` and `search` fields (a query key repeated in the URL is an array in `search`), and a typed `context` produced by
121
123
  * the optional `context()` factory.
122
124
  *
123
125
  * One pattern registration matches infinite path variations. For example,
@@ -130,7 +132,8 @@ export declare class EcopagesApp implements AsyncDisposable {
130
132
  * ```typescript
131
133
  * app.websocket<ChatContext, { roomId: string }>('/ws/chat/:roomId', {
132
134
  * async context({ params, search }) {
133
- * return { username: search.username ?? 'anonymous', roomId: params.roomId };
135
+ * const username = Array.isArray(search.username) ? search.username[0] : search.username;
136
+ * return { username: username ?? 'anonymous', roomId: params.roomId };
134
137
  * },
135
138
  * onConnect(socket) {
136
139
  * socket.send(`Welcome to room ${socket.context.roomId}`);
@@ -163,16 +166,29 @@ export declare class EcopagesApp implements AsyncDisposable {
163
166
  * ```
164
167
  */
165
168
  onError(handler: ErrorHandler<Request, unknown>): this;
166
- private createServerAdapter;
167
169
  private resolveRuntimeAssetSetup;
168
- private initializeServerAdapter;
170
+ private initializeSession;
169
171
  /**
170
172
  * Boot the server. When `onAppStart` is passed, it runs once the runtime can take traffic.
173
+ *
174
+ * @remarks
175
+ * Resolves without a server when `stop()` is called before startup finishes;
176
+ * that startup does not continue.
171
177
  */
172
178
  start(onAppStart?: OnAppStartCallback): Promise<NodeServerInstance | void>;
173
179
  private bootServer;
180
+ /**
181
+ * Whether `stop()` has not yet claimed `session`.
182
+ *
183
+ * @remarks
184
+ * `stop()` always replaces the lifecycle, so startup work re-checks this after
185
+ * each await and abandons a session that is being stopped.
186
+ */
187
+ private isActive;
188
+ /** Resolves `undefined` when `stop()` is called before the session is ready. */
174
189
  private getReadySession;
175
190
  private runStartup;
191
+ private releaseFailedStartup;
176
192
  private logServerStarted;
177
193
  private notifyListening;
178
194
  /**
@@ -188,6 +204,8 @@ export declare class EcopagesApp implements AsyncDisposable {
188
204
  *
189
205
  * @remarks
190
206
  * Shutdown releases the bound HTTP server and adapter-owned runtime resources.
207
+ * During startup it waits for the step in flight, which then stops, and
208
+ * releases whatever that step created.
191
209
  */
192
210
  stop(force?: boolean): Promise<void>;
193
211
  private disposeSession;
@@ -8,7 +8,7 @@ import { resolveRuntimeBinding } from '../shared/runtime/runtime-app-bootstrap.j
8
8
  import { bindRuntimeServer } from '../shared/runtime/bind-runtime-server.js';
9
9
  import { NodeHttpRequestBridge } from './http-request-bridge.js';
10
10
  import { NodeRuntimeHost } from './runtime-host.js';
11
- import { createNodeServerAdapter } from './server-adapter.js';
11
+ import { NodeServerAdapter } from './server-adapter.js';
12
12
  import { resolveAppStartRoutes } from '../../utils/ecopages-route-info.js';
13
13
  import { requireAppRuntime } from '../../utils/app-runtime.js';
14
14
  import { createViewModuleLoader } from '../../build/server/view-module-loader.js';
@@ -47,7 +47,7 @@ export class EcopagesApp {
47
47
  onAppStartCallback;
48
48
  runtimeLabel;
49
49
  runtimeHost;
50
- serverAdapterFactory;
50
+ createServerAdapter;
51
51
  /** @remarks Initialized by the first `fetch()` or `start()` call and exposed for host-level request middleware. */
52
52
  serverAdapter;
53
53
  lifecycle = { phase: 'idle' };
@@ -57,8 +57,8 @@ export class EcopagesApp {
57
57
  this.serverOptions = options.serverOptions || {};
58
58
  this.cliArgs = options.cliArgs;
59
59
  this.runtimeHost = dependencies.runtimeHost;
60
- this.serverAdapterFactory =
61
- dependencies.createServerAdapter ?? ((params) => createNodeServerAdapter(params, this.runtimeHost));
60
+ this.createServerAdapter =
61
+ dependencies.createServerAdapter ?? (async (params) => new NodeServerAdapter(params));
62
62
  startupTrace.markConfigReady();
63
63
  }
64
64
  register(path, method, handler, options) {
@@ -217,7 +217,7 @@ export class EcopagesApp {
217
217
  * and routes lifecycle events to `handler`.
218
218
  *
219
219
  * Supports dynamic segments via `:param` syntax. The handler receives
220
- * typed `params` and `search` fields, and a typed `context` produced by
220
+ * typed `params` and `search` fields (a query key repeated in the URL is an array in `search`), and a typed `context` produced by
221
221
  * the optional `context()` factory.
222
222
  *
223
223
  * One pattern registration matches infinite path variations. For example,
@@ -230,7 +230,8 @@ export class EcopagesApp {
230
230
  * ```typescript
231
231
  * app.websocket<ChatContext, { roomId: string }>('/ws/chat/:roomId', {
232
232
  * async context({ params, search }) {
233
- * return { username: search.username ?? 'anonymous', roomId: params.roomId };
233
+ * const username = Array.isArray(search.username) ? search.username[0] : search.username;
234
+ * return { username: username ?? 'anonymous', roomId: params.roomId };
234
235
  * },
235
236
  * onConnect(socket) {
236
237
  * socket.send(`Welcome to room ${socket.context.roomId}`);
@@ -284,9 +285,6 @@ export class EcopagesApp {
284
285
  this.errorHandler = handler;
285
286
  return this;
286
287
  }
287
- createServerAdapter(params) {
288
- return Promise.resolve(this.serverAdapterFactory(params));
289
- }
290
288
  resolveRuntimeAssetSetup() {
291
289
  const { build, preview, serveOnly } = this.cliArgs;
292
290
  if (preview && serveOnly) {
@@ -294,7 +292,7 @@ export class EcopagesApp {
294
292
  }
295
293
  return build || preview ? 'export' : 'start';
296
294
  }
297
- async initializeServerAdapter() {
295
+ async initializeSession() {
298
296
  const binding = resolveRuntimeBinding({
299
297
  cliArgs: this.cliArgs,
300
298
  serverOptions: this.serverOptions,
@@ -303,6 +301,7 @@ export class EcopagesApp {
303
301
  runtime.origin = binding.runtimeOrigin;
304
302
  const serverAdapter = await this.createServerAdapter({
305
303
  runtime,
304
+ runtimeHost: this.runtimeHost,
306
305
  appConfig: this.appConfig,
307
306
  apiHandlers: this.apiHandlers,
308
307
  staticRoutes: this.staticRoutes,
@@ -327,10 +326,14 @@ export class EcopagesApp {
327
326
  }
328
327
  throw error;
329
328
  }
330
- return serverAdapter;
329
+ return { adapter: serverAdapter, server: undefined, allowPortFallback: binding.allowPortFallback };
331
330
  }
332
331
  /**
333
332
  * Boot the server. When `onAppStart` is passed, it runs once the runtime can take traffic.
333
+ *
334
+ * @remarks
335
+ * Resolves without a server when `stop()` is called before startup finishes;
336
+ * that startup does not continue.
334
337
  */
335
338
  async start(onAppStart) {
336
339
  if (onAppStart) {
@@ -340,12 +343,12 @@ export class EcopagesApp {
340
343
  }
341
344
  async bootServer() {
342
345
  const session = await this.getReadySession();
346
+ if (!session || !this.isActive(session))
347
+ return;
343
348
  const current = this.lifecycle;
344
- if (current.phase === 'starting')
345
- return (await current.ready).server;
346
- if (current.phase === 'stopping') {
347
- await current.stopped;
348
- return await this.bootServer();
349
+ if (current.phase === 'starting') {
350
+ await current.ready;
351
+ return this.isActive(session) ? session.server : undefined;
349
352
  }
350
353
  if (session.server)
351
354
  return session.server;
@@ -362,25 +365,40 @@ export class EcopagesApp {
362
365
  this.lifecycle = { phase: 'ready', session };
363
366
  throw error;
364
367
  }
365
- return session.server;
368
+ return this.isActive(session) ? session.server : undefined;
369
+ }
370
+ /**
371
+ * Whether `stop()` has not yet claimed `session`.
372
+ *
373
+ * @remarks
374
+ * `stop()` always replaces the lifecycle, so startup work re-checks this after
375
+ * each await and abandons a session that is being stopped.
376
+ */
377
+ isActive(session) {
378
+ const current = this.lifecycle;
379
+ return (current.phase === 'ready' || current.phase === 'starting') && current.session === session;
366
380
  }
381
+ /** Resolves `undefined` when `stop()` is called before the session is ready. */
367
382
  async getReadySession() {
368
383
  const current = this.lifecycle;
369
384
  if (current.phase === 'ready')
370
385
  return current.session;
371
- if (current.phase === 'starting')
372
- return await current.ready;
386
+ if (current.phase === 'starting') {
387
+ const session = await current.ready;
388
+ return this.isActive(session) ? session : undefined;
389
+ }
373
390
  if (current.phase === 'stopping') {
374
391
  await current.stopped;
375
392
  return await this.getReadySession();
376
393
  }
377
- const ready = this.initializeServerAdapter().then((adapter) => ({ adapter, server: undefined }));
394
+ const ready = this.initializeSession();
378
395
  const starting = { phase: 'starting', ready };
379
396
  this.lifecycle = starting;
380
397
  try {
381
398
  const session = await ready;
382
- if (this.lifecycle === starting)
383
- this.lifecycle = { phase: 'ready', session };
399
+ if (this.lifecycle !== starting)
400
+ return undefined;
401
+ this.lifecycle = { phase: 'ready', session };
384
402
  this.serverAdapter = session.adapter;
385
403
  return session;
386
404
  }
@@ -406,53 +424,54 @@ export class EcopagesApp {
406
424
  await this.notifyListening(previewOrigin);
407
425
  return;
408
426
  }
409
- const serveOptions = session.adapter.getServerOptions();
410
- const binding = resolveRuntimeBinding({
411
- cliArgs: this.cliArgs,
412
- serverOptions: this.serverOptions,
413
- });
414
427
  startupTrace.beginServerListen();
415
428
  const bindingResult = await bindRuntimeServer(this.runtimeHost, {
416
- startOptions: {
417
- serveOptions: {
418
- ...serveOptions,
419
- handleRequest: async (request) => await session.adapter.handleServerRequest(request),
420
- },
429
+ serveOptions: {
430
+ ...session.adapter.getServerOptions(),
431
+ handleRequest: async (request) => await session.adapter.handleServerRequest(request),
421
432
  },
422
- allowPortFallback: binding.allowPortFallback,
433
+ allowPortFallback: session.allowPortFallback,
423
434
  usePortManager: this.cliArgs.dev,
424
435
  });
425
436
  session.server = bindingResult.server;
437
+ if (!this.isActive(session))
438
+ return;
426
439
  session.adapter.applyBoundPort(bindingResult);
427
440
  try {
428
441
  await session.adapter.completeInitialization(session.server);
429
442
  }
430
443
  catch (error) {
431
- const errors = [error];
432
- const failedServer = session.server;
433
- session.server = undefined;
434
- try {
435
- await this.runtimeHost.stop(failedServer, { force: true });
436
- }
437
- catch (stopError) {
438
- errors.push(stopError);
439
- }
440
- try {
441
- await session.adapter.dispose();
442
- }
443
- catch (disposeError) {
444
- errors.push(disposeError);
445
- }
446
- if (this.serverAdapter === session.adapter)
447
- this.serverAdapter = undefined;
448
- if (this.lifecycle.phase === 'starting')
449
- this.lifecycle = { phase: 'stopped' };
450
- if (errors.length > 1)
451
- throw new AggregateError(errors, 'Server startup and cleanup failed');
452
- throw error;
444
+ await this.releaseFailedStartup(session, error);
453
445
  }
446
+ if (!this.isActive(session))
447
+ return;
454
448
  await this.notifyListening(requireAppRuntime(this.appConfig).origin);
455
449
  }
450
+ async releaseFailedStartup(session, error) {
451
+ const errors = [error];
452
+ const failedServer = session.server;
453
+ session.server = undefined;
454
+ try {
455
+ if (failedServer)
456
+ await this.runtimeHost.stop(failedServer, { force: true });
457
+ }
458
+ catch (stopError) {
459
+ errors.push(stopError);
460
+ }
461
+ try {
462
+ await session.adapter.dispose();
463
+ }
464
+ catch (disposeError) {
465
+ errors.push(disposeError);
466
+ }
467
+ if (this.serverAdapter === session.adapter)
468
+ this.serverAdapter = undefined;
469
+ if (this.lifecycle.phase === 'starting')
470
+ this.lifecycle = { phase: 'stopped' };
471
+ if (errors.length > 1)
472
+ throw new AggregateError(errors, 'Server startup and cleanup failed');
473
+ throw error;
474
+ }
456
475
  logServerStarted(origin) {
457
476
  appLogger.info(formatRuntimeServerStartedMessage(this.runtimeLabel, origin));
458
477
  }
@@ -500,6 +519,8 @@ export class EcopagesApp {
500
519
  *
501
520
  * @remarks
502
521
  * Shutdown releases the bound HTTP server and adapter-owned runtime resources.
522
+ * During startup it waits for the step in flight, which then stops, and
523
+ * releases whatever that step created.
503
524
  */
504
525
  stop(force = true) {
505
526
  const current = this.lifecycle;
@@ -514,18 +535,7 @@ export class EcopagesApp {
514
535
  return stopped;
515
536
  }
516
537
  async disposeSession(current, force) {
517
- let session = current.session;
518
- if (current.phase === 'starting') {
519
- try {
520
- session ??= await current.ready;
521
- }
522
- catch {
523
- if (!session) {
524
- this.lifecycle = { phase: 'stopped' };
525
- return;
526
- }
527
- }
528
- }
538
+ const session = current.phase === 'starting' ? await current.ready.catch(() => current.session) : current.session;
529
539
  const errors = [];
530
540
  if (session?.server) {
531
541
  const activeServer = session.server;
@@ -563,6 +573,7 @@ export class EcopagesApp {
563
573
  */
564
574
  async fetch(request) {
565
575
  const session = await this.getReadySession();
576
+ invariant(session !== undefined, 'The app was stopped before it could handle the request.');
566
577
  return session.adapter.handleRequest(request);
567
578
  }
568
579
  createDevelopmentRestartHandler() {
@@ -90,7 +90,6 @@ export class DevSession {
90
90
  appConfig: this.options.appConfig,
91
91
  hmrManager: this.hmrManager,
92
92
  bridge: this.bridge,
93
- stopPreviewServer: async () => { },
94
93
  });
95
94
  }
96
95
  catch (error) {
@@ -52,6 +52,10 @@ export declare class NodeHttpRequestBridge {
52
52
  * as server-sent events. The bridge therefore forwards the `ReadableStream`
53
53
  * directly into the Node writable response instead of materializing an
54
54
  * intermediate `ArrayBuffer`.
55
+ *
56
+ * `Headers.forEach` yields every `Set-Cookie` value as a separate entry, so
57
+ * writing them one by one would let each overwrite the previous. They are
58
+ * collected with `getSetCookie()` and written as a single array value.
55
59
  */
56
60
  sendNodeResponse(res: ServerResponse, response: Response): Promise<void>;
57
61
  }
@@ -178,12 +178,20 @@ export class NodeHttpRequestBridge {
178
178
  * as server-sent events. The bridge therefore forwards the `ReadableStream`
179
179
  * directly into the Node writable response instead of materializing an
180
180
  * intermediate `ArrayBuffer`.
181
+ *
182
+ * `Headers.forEach` yields every `Set-Cookie` value as a separate entry, so
183
+ * writing them one by one would let each overwrite the previous. They are
184
+ * collected with `getSetCookie()` and written as a single array value.
181
185
  */
182
186
  async sendNodeResponse(res, response) {
183
187
  res.statusCode = response.status;
184
188
  response.headers.forEach((value, key) => {
185
- res.setHeader(key, value);
189
+ if (key !== 'set-cookie')
190
+ res.setHeader(key, value);
186
191
  });
192
+ const setCookies = response.headers.getSetCookie();
193
+ if (setCookies.length > 0)
194
+ res.setHeader('set-cookie', setCookies);
187
195
  if (!response.body) {
188
196
  res.end();
189
197
  return;
@@ -1,5 +1,4 @@
1
1
  import { createServer, type Server as NodeServerInstance } from 'node:http';
2
- import type { RuntimeHost, RuntimeHostStartOptions } from '../shared/runtime/runtime-host.js';
3
2
  import { NodeHttpRequestBridge } from './http-request-bridge.js';
4
3
  type NodeServerFactory = typeof createServer;
5
4
  export type NodeRuntimeServeOptions = {
@@ -7,6 +6,13 @@ export type NodeRuntimeServeOptions = {
7
6
  hostname?: string;
8
7
  handleRequest(request: Request): Promise<Response>;
9
8
  };
9
+ /**
10
+ * The transport surface `EcopagesApp` and `NodeServerAdapter` use.
11
+ *
12
+ * @remarks
13
+ * Tests pass a fake with this shape to run the app lifecycle without binding a port.
14
+ */
15
+ export type RuntimeHost = Pick<NodeRuntimeHost, 'start' | 'stop' | 'getOrigin'>;
10
16
  /**
11
17
  * Node runtime host that binds the shared Web-request pipeline onto a concrete
12
18
  * Node HTTP server.
@@ -16,12 +22,19 @@ export type NodeRuntimeServeOptions = {
16
22
  * requests through `NodeHttpRequestBridge`, and handling socket-level failures.
17
23
  * Routing and rendering remain in the shared server adapter.
18
24
  */
19
- export declare class NodeRuntimeHost implements RuntimeHost<NodeServerInstance, NodeRuntimeServeOptions> {
25
+ export declare class NodeRuntimeHost {
20
26
  private readonly requestBridge;
21
27
  private readonly serverFactory;
22
28
  /**
23
- * Creates a Node runtime host with injectable request bridging and server
24
- * creation seams for tests and alternate hosts.
29
+ * Every open socket per started server, including upgraded WebSocket sockets.
30
+ *
31
+ * @remarks
32
+ * `closeAllConnections()` stops tracking a socket once it is upgraded, yet
33
+ * `server.close()` still waits for it, so a forced stop destroys these too.
34
+ */
35
+ private readonly sockets;
36
+ /**
37
+ * Creates a Node runtime host; tests inject the request bridge and server factory.
25
38
  */
26
39
  constructor(requestBridge: NodeHttpRequestBridge, serverFactory?: NodeServerFactory);
27
40
  /**
@@ -33,10 +46,14 @@ export declare class NodeRuntimeHost implements RuntimeHost<NodeServerInstance,
33
46
  * failures here (the response write, or an uninitialised adapter) are logged
34
47
  * with their stack and answered with 500.
35
48
  */
36
- start(options: RuntimeHostStartOptions<NodeRuntimeServeOptions>): Promise<NodeServerInstance>;
49
+ start(serveOptions: NodeRuntimeServeOptions): Promise<NodeServerInstance>;
37
50
  /**
38
51
  * Stops the Node HTTP server and, by default, force-closes any remaining open
39
- * connections.
52
+ * connections, WebSocket connections included.
53
+ *
54
+ * @remarks
55
+ * With `force: false` the returned promise waits until every connection ends
56
+ * on its own, so an open WebSocket keeps it pending.
40
57
  */
41
58
  stop(server: NodeServerInstance, options?: {
42
59
  force?: boolean;
@@ -16,8 +16,15 @@ export class NodeRuntimeHost {
16
16
  requestBridge;
17
17
  serverFactory;
18
18
  /**
19
- * Creates a Node runtime host with injectable request bridging and server
20
- * creation seams for tests and alternate hosts.
19
+ * Every open socket per started server, including upgraded WebSocket sockets.
20
+ *
21
+ * @remarks
22
+ * `closeAllConnections()` stops tracking a socket once it is upgraded, yet
23
+ * `server.close()` still waits for it, so a forced stop destroys these too.
24
+ */
25
+ sockets = new WeakMap();
26
+ /**
27
+ * Creates a Node runtime host; tests inject the request bridge and server factory.
21
28
  */
22
29
  constructor(requestBridge, serverFactory = createServer) {
23
30
  this.requestBridge = requestBridge;
@@ -32,15 +39,15 @@ export class NodeRuntimeHost {
32
39
  * failures here (the response write, or an uninitialised adapter) are logged
33
40
  * with their stack and answered with 500.
34
41
  */
35
- async start(options) {
36
- const hostname = String(options.serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME);
37
- const port = Number(options.serveOptions.port ?? DEFAULT_ECOPAGES_PORT);
42
+ async start(serveOptions) {
43
+ const hostname = String(serveOptions.hostname ?? DEFAULT_ECOPAGES_HOSTNAME);
44
+ const port = Number(serveOptions.port ?? DEFAULT_ECOPAGES_PORT);
38
45
  let server;
39
46
  server = this.serverFactory(async (req, res) => {
40
47
  try {
41
- const runtimeOrigin = this.getOrigin(server, options.serveOptions);
48
+ const runtimeOrigin = this.getOrigin(server, serveOptions);
42
49
  const webRequest = this.requestBridge.createWebRequest(req, runtimeOrigin);
43
- const response = await options.serveOptions.handleRequest(webRequest);
50
+ const response = await serveOptions.handleRequest(webRequest);
44
51
  await this.requestBridge.sendNodeResponse(res, response);
45
52
  }
46
53
  catch (error) {
@@ -52,6 +59,12 @@ export class NodeRuntimeHost {
52
59
  res.end('Internal Server Error');
53
60
  }
54
61
  });
62
+ const sockets = new Set();
63
+ this.sockets.set(server, sockets);
64
+ server.on('connection', (socket) => {
65
+ sockets.add(socket);
66
+ socket.once('close', () => sockets.delete(socket));
67
+ });
55
68
  await new Promise((resolve, reject) => {
56
69
  server.once('error', reject);
57
70
  server.listen(port, hostname, () => {
@@ -63,7 +76,11 @@ export class NodeRuntimeHost {
63
76
  }
64
77
  /**
65
78
  * Stops the Node HTTP server and, by default, force-closes any remaining open
66
- * connections.
79
+ * connections, WebSocket connections included.
80
+ *
81
+ * @remarks
82
+ * With `force: false` the returned promise waits until every connection ends
83
+ * on its own, so an open WebSocket keeps it pending.
67
84
  */
68
85
  async stop(server, options) {
69
86
  await new Promise((resolve, reject) => {
@@ -76,6 +93,8 @@ export class NodeRuntimeHost {
76
93
  });
77
94
  if (options?.force ?? true) {
78
95
  server.closeAllConnections();
96
+ for (const socket of this.sockets.get(server) ?? [])
97
+ socket.destroy();
79
98
  }
80
99
  });
81
100
  }