@ecopages/core 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/README.md +2 -2
  2. package/package.json +14 -4
  3. package/src/adapters/node/create-app.d.ts +5 -5
  4. package/src/adapters/node/create-app.js +1 -1
  5. package/src/adapters/node/server-adapter.d.ts +1 -0
  6. package/src/adapters/node/server-adapter.js +4 -1
  7. package/src/adapters/shared/hmr/hmr-manager.d.ts +2 -0
  8. package/src/adapters/shared/hmr/hmr-manager.js +8 -4
  9. package/src/adapters/shared/http/api-request-pipeline.d.ts +16 -3
  10. package/src/adapters/shared/http/api-request-pipeline.js +23 -16
  11. package/src/adapters/shared/http/define-api-handler.d.ts +8 -8
  12. package/src/adapters/shared/http/explicit-static-route-matcher.js +8 -4
  13. package/src/adapters/shared/http/file-route-middleware-pipeline.d.ts +10 -11
  14. package/src/adapters/shared/http/file-route-middleware-pipeline.js +5 -6
  15. package/src/adapters/shared/http/fs-server-response-matcher.js +12 -4
  16. package/src/adapters/shared/http/run-middleware-chain.d.ts +29 -2
  17. package/src/adapters/shared/http/run-middleware-chain.js +108 -10
  18. package/src/adapters/shared/runtime/render-context.d.ts +2 -0
  19. package/src/adapters/shared/runtime/render-context.js +6 -21
  20. package/src/adapters/shared/runtime/server-request-pipeline.d.ts +2 -2
  21. package/src/adapters/shared/runtime/server-request-pipeline.js +4 -3
  22. package/src/adapters/shared/runtime/server-static-builder.js +4 -1
  23. package/src/adapters/shared/runtime/unattached-scripts.d.ts +17 -0
  24. package/src/adapters/shared/runtime/unattached-scripts.js +57 -0
  25. package/src/adapters/shared/ws/node-http-websocket-upgrades.js +3 -2
  26. package/src/adapters/shared/ws/ws-pattern-matcher.d.ts +14 -1
  27. package/src/adapters/shared/ws/ws-pattern-matcher.js +14 -13
  28. package/src/assets/app-browser-client-build.js +3 -0
  29. package/src/assets/asset-processing-service/asset-processing.service.d.ts +9 -0
  30. package/src/assets/asset-processing-service/asset-processing.service.js +19 -0
  31. package/src/assets/asset-processing-service/processed-asset-ledger.d.ts +16 -2
  32. package/src/assets/asset-processing-service/processed-asset-ledger.js +31 -3
  33. package/src/build/build-graph.d.ts +19 -2
  34. package/src/build/build-graph.js +19 -18
  35. package/src/build/cache/pages-unified-graph-build.d.ts +4 -6
  36. package/src/build/cache/pages-unified-graph-build.js +14 -51
  37. package/src/build/cache/server-module-entries.d.ts +5 -9
  38. package/src/build/cache/server-module-entries.js +5 -58
  39. package/src/build/contracts/build-contracts.d.ts +15 -0
  40. package/src/build/contracts.d.ts +1 -1
  41. package/src/build/contracts.js +1 -1
  42. package/src/build/production-asset-ledger.d.ts +1 -1
  43. package/src/build/production-asset-ledger.js +4 -2
  44. package/src/build/rolldown/file-role-grammar-plugin.d.ts +11 -0
  45. package/src/build/rolldown/file-role-grammar-plugin.js +32 -0
  46. package/src/build/rolldown/rolldown-adapter-helpers.d.ts +11 -0
  47. package/src/build/rolldown/rolldown-adapter-helpers.js +79 -10
  48. package/src/build/rolldown/ssr-script-entries-plugin.d.ts +31 -0
  49. package/src/build/rolldown/ssr-script-entries-plugin.js +104 -0
  50. package/src/build/runtime/build-request-policy.js +4 -1
  51. package/src/build/server/server-modules-manifest.d.ts +6 -1
  52. package/src/build/server/server-modules-manifest.js +10 -1
  53. package/src/build/server/view-reference.d.ts +9 -0
  54. package/src/build/server/view-reference.js +11 -0
  55. package/src/build.d.ts +3 -1
  56. package/src/build.js +3 -1
  57. package/src/cli.d.ts +14 -0
  58. package/src/cli.js +14 -0
  59. package/src/config/assembly/app-runtime.d.ts +13 -0
  60. package/src/config/assembly/app-runtime.js +2 -0
  61. package/src/config/assembly/finalize-config.js +13 -8
  62. package/src/config/internal-types.d.ts +0 -12
  63. package/src/config/resolve-eco-config-path.d.ts +2 -0
  64. package/src/config/resolve-eco-config-path.js +2 -1
  65. package/src/config/server-config-bundle.d.ts +0 -1
  66. package/src/config/server-config-bundle.js +1 -1
  67. package/src/config/user-config-types.d.ts +0 -12
  68. package/src/declarations.d.ts +2 -0
  69. package/src/dev/invalidation/development-invalidation.service.d.ts +0 -2
  70. package/src/dev/invalidation/development-invalidation.service.js +1 -11
  71. package/src/dev/transform-server/dev-transform-vendor-registry.js +33 -19
  72. package/src/eco/discovered-dependencies.d.ts +5 -0
  73. package/src/eco/discovered-dependencies.js +9 -0
  74. package/src/eco/eco.browser.js +6 -26
  75. package/src/eco/eco.js +24 -16
  76. package/src/eco/migration-docs.d.ts +7 -0
  77. package/src/eco/migration-docs.js +7 -0
  78. package/src/eco/page-data-hooks.d.ts +27 -0
  79. package/src/eco/page-data-hooks.js +64 -0
  80. package/src/eco/page-layout-normalization.d.ts +2 -2
  81. package/src/hmr/client/hmr-runtime.js +1 -1
  82. package/src/hmr/strategies/js-hmr-strategy.d.ts +0 -2
  83. package/src/hmr/strategies/server-rendered-template-hmr-strategy.d.ts +2 -1
  84. package/src/hmr/strategies/server-rendered-template-hmr-strategy.js +4 -3
  85. package/src/html/html-rewriter.d.ts +9 -7
  86. package/src/html/html-rewriter.js +26 -41
  87. package/src/html/html-transformer.service.d.ts +2 -2
  88. package/src/html/html-transformer.service.js +21 -15
  89. package/src/html-pages/html-page-module-scripts.js +2 -1
  90. package/src/html-pages/html-pages.plugin.d.ts +1 -1
  91. package/src/html-pages/html-pages.plugin.js +1 -1
  92. package/src/index.d.ts +1 -0
  93. package/src/index.js +1 -0
  94. package/src/integration.d.ts +2 -2
  95. package/src/integration.js +2 -2
  96. package/src/islands/island-host.d.ts +16 -5
  97. package/src/islands/island-host.js +8 -1
  98. package/src/middleware/create-middleware.d.ts +41 -0
  99. package/src/middleware/create-middleware.js +72 -0
  100. package/src/plugins/component-import-discovery.d.ts +14 -1
  101. package/src/plugins/component-import-discovery.js +36 -16
  102. package/src/plugins/eco-component-meta-plugin.d.ts +38 -0
  103. package/src/plugins/eco-component-meta-plugin.js +208 -44
  104. package/src/plugins/ecopages-virtual-imports.d.ts +15 -0
  105. package/src/plugins/ecopages-virtual-imports.js +25 -0
  106. package/src/plugins/integration-plugin.d.ts +1 -1
  107. package/src/plugins/integration-plugin.js +1 -1
  108. package/src/plugins/tsconfig-import-resolver.d.ts +2 -0
  109. package/src/plugins/tsconfig-import-resolver.js +7 -5
  110. package/src/route-renderer/error-pages/error-page-renderer.js +32 -3
  111. package/src/route-renderer/explicit-view-render-preparation.d.ts +28 -3
  112. package/src/route-renderer/explicit-view-render-preparation.js +63 -11
  113. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.d.ts +15 -5
  114. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.js +27 -15
  115. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.d.ts +24 -9
  116. package/src/route-renderer/orchestration/foreign-child/foreign-subtree-execution.service.js +73 -50
  117. package/src/route-renderer/orchestration/integration-renderer.d.ts +42 -11
  118. package/src/route-renderer/orchestration/integration-renderer.js +83 -43
  119. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.builder.js +0 -3
  120. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +36 -11
  121. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +74 -62
  122. package/src/route-renderer/page-declaration.d.ts +25 -0
  123. package/src/route-renderer/page-declaration.js +39 -0
  124. package/src/route-renderer/page-loading/component-declarations.d.ts +65 -0
  125. package/src/route-renderer/page-loading/component-declarations.js +77 -0
  126. package/src/route-renderer/page-loading/component-dependency-collection.d.ts +4 -16
  127. package/src/route-renderer/page-loading/component-dependency-collection.js +36 -105
  128. package/src/route-renderer/page-loading/declared-asset-collection.d.ts +19 -14
  129. package/src/route-renderer/page-loading/declared-asset-collection.js +66 -67
  130. package/src/route-renderer/page-loading/dependency-resolver.d.ts +18 -10
  131. package/src/route-renderer/page-loading/dependency-resolver.js +58 -99
  132. package/src/route-renderer/page-loading/lazy-entry-collection.d.ts +19 -26
  133. package/src/route-renderer/page-loading/lazy-entry-collection.js +53 -64
  134. package/src/route-renderer/page-loading/module-declaration-aggregation.d.ts +17 -3
  135. package/src/route-renderer/page-loading/module-declaration-aggregation.js +14 -13
  136. package/src/route-renderer/page-loading/page-module-loader.d.ts +31 -12
  137. package/src/route-renderer/page-loading/page-module-loader.js +66 -35
  138. package/src/route-renderer/page-loading/resolved-page-dependencies.js +14 -9
  139. package/src/router/server/pages-dir.d.ts +7 -0
  140. package/src/router/server/pages-dir.js +7 -0
  141. package/src/router/server/route-registry.d.ts +22 -10
  142. package/src/router/server/route-registry.js +54 -23
  143. package/src/router/server/segment-path-matcher.d.ts +29 -5
  144. package/src/router/server/segment-path-matcher.js +22 -19
  145. package/src/static-site-generator/production-page-browser-graph-prebuild.d.ts +2 -2
  146. package/src/static-site-generator/production-page-browser-graph-prebuild.js +5 -5
  147. package/src/static-site-generator/static-site-generator.d.ts +17 -2
  148. package/src/static-site-generator/static-site-generator.js +52 -18
  149. package/src/types/contracts.d.ts +216 -160
  150. package/src/types/eco-api-types.d.ts +86 -51
  151. package/src/types/locals-brand.d.ts +9 -0
  152. package/src/types/locals-brand.js +9 -0
  153. package/src/types/middleware-types.d.ts +143 -0
  154. package/src/types/middleware-types.js +1 -0
  155. package/src/types/public-types.d.ts +3 -2
  156. package/src/utils/file-roles.d.ts +48 -0
  157. package/src/utils/file-roles.js +85 -0
  158. package/src/utils/node-builtin.d.ts +10 -0
  159. package/src/utils/node-builtin.js +13 -0
  160. package/src/watchers/project-watcher.js +2 -2
  161. package/src/build/contracts/server-only-specifier.d.ts +0 -8
  162. package/src/build/contracts/server-only-specifier.js +0 -11
  163. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.d.ts +0 -5
  164. package/src/route-renderer/orchestration/route-pipeline/marker-artifact.utils.js +0 -11
  165. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.d.ts +0 -4
  166. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.js +0 -30
  167. package/src/route-renderer/page-loading/ecopages-virtual-imports.d.ts +0 -12
  168. package/src/route-renderer/page-loading/ecopages-virtual-imports.js +0 -100
  169. package/src/utils/endpoint-file-extensions.d.ts +0 -11
  170. package/src/utils/endpoint-file-extensions.js +0 -13
  171. package/src/utils/locals-utils.d.ts +0 -15
  172. package/src/utils/locals-utils.js +0 -34
@@ -1,17 +1,115 @@
1
1
  /**
2
2
  * Runs an onion middleware chain and invokes the terminal handler when the chain completes.
3
+ *
4
+ * @remarks
5
+ * Each stage receives its own `next`, which continues the chain exactly once. A second call throws before the
6
+ * chain advances, even from inside a later stage: a shared cursor would let a stage that calls `next` twice resume
7
+ * the chain after a guard that had already answered, running everything behind the guard, including the terminal
8
+ * handler, a second time. `next` also throws once its stage has returned or thrown, so a stage that answered cannot
9
+ * start the rest of the chain later, from a timer or a callback.
10
+ *
11
+ * A stage continues with `next(locals)`. The chain defines each own key it provides on `context.locals` before the
12
+ * next stage runs, so a later stage and the handler read it, and a later key overrides an earlier one. Keys are
13
+ * defined, not assigned, so a `__proto__` key is a plain local and cannot replace the prototype of the store. A
14
+ * provided key is typed for everything after it, so when a stage continues, every key an earlier stage provided
15
+ * must still hold its value: a plain function that wrote or deleted one would leave readers with a value their
16
+ * types do not describe, so its `next` throws instead.
17
+ *
18
+ * A stage answers with whatever it returns: the response `next` resolved with, edited, or another response that
19
+ * wraps or replaces it, as an outer stage adding headers to an immutable redirect must. A stage that returns before
20
+ * the rest of the chain it started settles, or throws, waits for that rest before its own result or error
21
+ * propagates, so the handler never runs after the request has been answered.
22
+ *
23
+ * When the rest of the chain fails, the stage decides only if it looked at the promise `next` returned: awaited it,
24
+ * returned it, or called `then`, `catch` or `finally` on it. Then its own result stands, so
25
+ * `try { await next() } catch { return fallback }` answers with the fallback. A stage that never looked at that
26
+ * promise, as in `next(); return new Response('ok')`, did not handle the failure, so the chain rethrows it once the
27
+ * stage has returned, even when the failure comes after. A stage that throws propagates its own error instead.
3
28
  */
4
29
  export async function runMiddlewareChain(middleware, context, terminal) {
5
- if (middleware.length === 0) {
6
- return terminal();
7
- }
8
- let index = 0;
9
- const executeNext = async () => {
10
- if (index < middleware.length) {
11
- const current = middleware[index++];
12
- return await current(context, executeNext);
30
+ const provided = new Map();
31
+ const runFrom = async (position) => {
32
+ if (position >= middleware.length) {
33
+ return terminal();
34
+ }
35
+ let finished = false;
36
+ let started = false;
37
+ let continuation;
38
+ let restSettled;
39
+ let restFailure;
40
+ const next = (locals) => {
41
+ if (finished) {
42
+ throw new Error(`[ecopages] Middleware stage ${position} called next() after it returned. Call next() before the stage returns, and return the response it resolves with.`);
43
+ }
44
+ if (started) {
45
+ throw new Error(`[ecopages] Middleware stage ${position} called next() more than once. A stage may continue the chain a single time.`);
46
+ }
47
+ started = true;
48
+ assertProvidedLocalsKept(context.locals, provided, position);
49
+ if (locals) {
50
+ defineLocals(context.locals, locals);
51
+ for (const [key, value] of Object.entries(locals))
52
+ provided.set(key, value);
53
+ }
54
+ const rest = runFrom(position + 1);
55
+ restSettled = rest.then(() => undefined, (error) => {
56
+ restFailure = { error };
57
+ });
58
+ continuation = new ContinuationPromise(rest);
59
+ return continuation;
60
+ };
61
+ let response;
62
+ try {
63
+ response = await middleware[position](context, next);
64
+ }
65
+ finally {
66
+ finished = true;
67
+ await restSettled;
68
+ }
69
+ if (restFailure && !continuation?.observed) {
70
+ throw restFailure.error;
13
71
  }
14
- return terminal();
72
+ return response;
15
73
  };
16
- return executeNext();
74
+ return runFrom(0);
75
+ }
76
+ /**
77
+ * The promise a stage's `next` returns, which records whether the stage looked at it.
78
+ *
79
+ * @remarks
80
+ * A `Promise` subclass and not an own `then` on a plain promise: `await` reads `then` only on a promise whose
81
+ * `constructor` is not `Promise`, and `catch` and `finally` call `then`, so overriding `then` sees `await`,
82
+ * `return next()` from an async stage, `Promise.resolve(next())` and `Promise.all([next()])` alike. The species is
83
+ * `Promise`, so the promises `then` derives are plain and do not count. The constructor attaches a handler that
84
+ * does not count as looking, so a promise the stage dropped does not also surface as an unhandled rejection: the
85
+ * chain reports that failure itself.
86
+ */
87
+ class ContinuationPromise extends Promise {
88
+ static get [Symbol.species]() {
89
+ return Promise;
90
+ }
91
+ #observed = false;
92
+ constructor(rest) {
93
+ super((resolve) => resolve(rest));
94
+ super.then(undefined, () => undefined);
95
+ }
96
+ get observed() {
97
+ return this.#observed;
98
+ }
99
+ then(onfulfilled, onrejected) {
100
+ this.#observed = true;
101
+ return super.then(onfulfilled, onrejected);
102
+ }
103
+ }
104
+ function assertProvidedLocalsKept(locals, provided, position) {
105
+ for (const [key, value] of provided) {
106
+ if (!Object.is(Object.getOwnPropertyDescriptor(locals, key)?.value, value)) {
107
+ throw new Error(`[ecopages] Middleware stage ${position} changed the local "${key}" that an earlier stage provided with next(). Make the stage with createMiddleware and pass the new value to next({ ${key} }) instead of writing ctx.locals.`);
108
+ }
109
+ }
110
+ }
111
+ function defineLocals(locals, provided) {
112
+ for (const [key, value] of Object.entries(provided)) {
113
+ Object.defineProperty(locals, key, { value, writable: true, enumerable: true, configurable: true });
114
+ }
17
115
  }
@@ -4,6 +4,8 @@ export interface CreateRenderContextOptions {
4
4
  integrations: AnyIntegrationPlugin[];
5
5
  ensureIntegrationReady?: (integrationName: string) => Promise<void>;
6
6
  importServerModule?: (filePath: string) => Promise<unknown>;
7
+ /** App root; with it, an imported view must declare its Page with a literal `eco.page()` call in its own file. */
8
+ rootDir?: string;
7
9
  }
8
10
  /**
9
11
  * Creates a render context for route handlers.
@@ -1,22 +1,8 @@
1
+ import { assertViewDeclaredIn } from '../../../route-renderer/page-declaration.js';
1
2
  import { isViewReference } from '../../../types/view-reference.js';
2
3
  import { getComponentOwner } from '../../../eco/component-identity.js';
3
4
  import { invariant } from '../../../utils/invariant.js';
4
5
  import { createBodyResponse } from '../http/create-body-response.js';
5
- /**
6
- * Merges request locals into component props as a dedicated 'locals' property.
7
- * This prevents naming conflicts and maintains type safety by keeping locals
8
- * separate from other props.
9
- *
10
- * @param props - The original component props
11
- * @param locals - Optional request-scoped locals from middleware
12
- * @returns Props with locals merged in, or original props if no locals provided
13
- */
14
- function mergePropsWithLocals(props, locals) {
15
- if (!locals || typeof props !== 'object' || props === null) {
16
- return props;
17
- }
18
- return { ...props, locals };
19
- }
20
6
  function createExplicitViewContext(scope, renderOptions, partial) {
21
7
  return {
22
8
  partial,
@@ -57,22 +43,21 @@ export function createRenderContext(options) {
57
43
  invariant(!!options.importServerModule, 'Imported views need the server-module loader.');
58
44
  const module = (await options.importServerModule(view.filePath));
59
45
  invariant(!!module.default, `View module ${view.filePath} has no default export.`);
46
+ if (options.rootDir) {
47
+ assertViewDeclaredIn(view.filePath, module.default, options.rootDir);
48
+ }
60
49
  return module.default;
61
50
  };
62
51
  const renderContext = {
63
52
  async render(view, props, renderOptions) {
64
- const locals = this?.locals;
65
- const mergedProps = mergePropsWithLocals(props ?? {}, locals);
66
53
  const resolvedView = await resolveView(view);
67
54
  const renderer = await getRendererForView(resolvedView);
68
- return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, false));
55
+ return renderer.renderExplicitView(resolvedView, props ?? {}, createExplicitViewContext(this, renderOptions, false));
69
56
  },
70
57
  async renderPartial(view, props, renderOptions) {
71
- const locals = this?.locals;
72
- const mergedProps = mergePropsWithLocals(props, locals);
73
58
  const resolvedView = await resolveView(view);
74
59
  const renderer = await getRendererForView(resolvedView);
75
- return renderer.renderExplicitView(resolvedView, mergedProps, createExplicitViewContext(this, renderOptions, true));
60
+ return renderer.renderExplicitView(resolvedView, props, createExplicitViewContext(this, renderOptions, true));
76
61
  },
77
62
  json(data, responseOptions) {
78
63
  return createBodyResponse('json', data, {
@@ -5,11 +5,11 @@ import { RouteRegistry } from '../../../router/server/route-registry.js';
5
5
  import type { StaticGenerationRoute } from '../../../router/server/route-registry.js';
6
6
  import { FileSystemResponseMatcher } from '../http/fs-server-response-matcher.js';
7
7
  import { ServerRouteHandler } from './server-route-handler.js';
8
- import { ApiRequestPipeline } from '../http/api-request-pipeline.js';
8
+ import { ApiRequestPipeline, type ApiRoutes } from '../http/api-request-pipeline.js';
9
9
  import { type EndpointRequestContext, type EndpointRouteHandlerOptions } from '../http/endpoint-route-handler.js';
10
10
  import type { ApiHandler, CacheInvalidator, ErrorHandler, RenderContext, StaticRoute, ErrorPageLoaders } from '../../../types/contracts.js';
11
11
  export type ServerRequestContext<TServer = unknown> = {
12
- apiHandlers: ApiHandler[];
12
+ apiRoutes: ApiRoutes;
13
13
  errorHandler?: ErrorHandler<Request, TServer>;
14
14
  serverInstance?: TServer;
15
15
  };
@@ -119,6 +119,7 @@ export class ServerRequestPipeline {
119
119
  pageModuleAdapter: this.createRouteRegistryPageModuleAdapter(),
120
120
  });
121
121
  await this.router.init();
122
+ this.runtime.router = this.router;
122
123
  startupTrace.markPhaseEnd('route-registry');
123
124
  }
124
125
  createRouteRegistryPageModuleAdapter() {
@@ -131,8 +132,7 @@ export class ServerRequestPipeline {
131
132
  const page = module.default;
132
133
  const pageComponent = page;
133
134
  return {
134
- staticPaths: pageComponent?.staticPaths,
135
- staticProps: pageComponent?.staticProps,
135
+ paths: pageComponent?.paths,
136
136
  cache: pageComponent?.cache,
137
137
  };
138
138
  },
@@ -214,6 +214,7 @@ export class ServerRequestPipeline {
214
214
  getRenderContext() {
215
215
  return createRenderContext({
216
216
  integrations: this.appConfig.integrations,
217
+ rootDir: this.appConfig.rootDir,
217
218
  ensureIntegrationReady: (integrationName) => ensureIntegrationRuntimeReady({ appConfig: this.appConfig, integrationName }),
218
219
  importServerModule: (filePath) => this.importServerModule(path.resolve(this.appConfig.rootDir, filePath)),
219
220
  });
@@ -239,7 +240,7 @@ export class ServerRequestPipeline {
239
240
  return await hmrManager.injectDevClientRuntimes(withUncachedDevHtml(response));
240
241
  }
241
242
  async tryHandleSharedApiRequest(request, context, parsedPathSegments) {
242
- return await this.apiRequestPipeline.tryHandle(request, context.apiHandlers, context.serverInstance, context.errorHandler, parsedPathSegments);
243
+ return await this.apiRequestPipeline.tryHandle(request, context.apiRoutes, context.serverInstance, context.errorHandler, parsedPathSegments);
243
244
  }
244
245
  /**
245
246
  * Resolves an error that escaped {@link handleSharedRequest} with the same
@@ -14,11 +14,13 @@ import { writeProductionAssetLedger } from '../../../build/production-asset-ledg
14
14
  import { getPrebuiltHtmlPageModuleScriptUrls } from '../../../html-pages/html-page-module-scripts.js';
15
15
  import { writeProductionRouteList } from '../../../build/production-route-list.js';
16
16
  import { getServerBundleOutputPaths, writeServerBundleDeployManifest, } from '../../../build/server-bundle-deploy-manifest.js';
17
- import { bundleEcoConfigModule, EMITTED_ECO_CONFIG_FILENAME } from '../../../config/server-config-bundle.js';
17
+ import { bundleEcoConfigModule } from '../../../config/server-config-bundle.js';
18
+ import { EMITTED_ECO_CONFIG_FILENAME } from '../../../config/resolve-eco-config-path.js';
18
19
  import { CLIENT_OUTPUT_DIR, resolveEntryFile, SERVER_BUNDLE_FILENAME } from '../../../utils/resolve-entry-file.js';
19
20
  import { createServerBundleLoaderSource, SERVER_BUNDLE_IMPLEMENTATION_FILENAME, } from '../../../utils/server-bundle-context.js';
20
21
  import { copyRuntimePublicDirIfChanged } from './copy-runtime-public-dir.js';
21
22
  import { readEndpointHandlers } from '../http/endpoint-route-handler.js';
23
+ import { warnAboutUnattachedScripts } from './unattached-scripts.js';
22
24
  import { emitProductionServerModules, shouldBuildPagesUnifiedGraph, } from '../../../build/cache/pages-unified-graph-build.js';
23
25
  /**
24
26
  * Handles static site generation.
@@ -194,6 +196,7 @@ export class ServerStaticBuilder {
194
196
  router: dependencies.router,
195
197
  staticRoutes: dependencies.staticRoutes,
196
198
  errorPageLoaders: dependencies.errorPageLoaders,
199
+ onServerSources: (sources) => warnAboutUnattachedScripts(this.appConfig, sources),
197
200
  });
198
201
  }
199
202
  writeProductionRouteList(this.appConfig, dependencies.router.templateRoutes);
@@ -0,0 +1,17 @@
1
+ import type { EcoPagesAppConfig } from '../../../config/internal-types.js';
2
+ /**
3
+ * Lists the `.script` files under `srcDir` that nothing attaches to a page.
4
+ *
5
+ * @remarks
6
+ * A script is attached when a literal `dependencies.scripts` entry in a module of the server build names it, an
7
+ * HTML Page or the Html shell loads it with `<script src>`, or an attached script imports it. A module of the
8
+ * server build that imports a script also counts, since that script is then part of the build. A `src` computed at
9
+ * runtime is not found, and neither is a declaration in an MDX file, so such a script is listed here.
10
+ *
11
+ * @param serverModules Source files of the server build, whose declarations are read.
12
+ */
13
+ export declare function findUnattachedScripts(appConfig: EcoPagesAppConfig, serverModules: readonly string[]): Promise<string[]>;
14
+ /**
15
+ * Warns once per `.script` file that {@link findUnattachedScripts} lists.
16
+ */
17
+ export declare function warnAboutUnattachedScripts(appConfig: EcoPagesAppConfig, serverModules: readonly string[]): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import { appLogger } from '../../../global/app-logger.js';
2
+ import { fileSystem } from '@ecopages/file-system';
3
+ import { path } from '@ecopages/file-system/path';
4
+ import { collectHtmlPageModuleScriptBuildInputs, scanModuleScript, } from '../../../html-pages/html-page-module-scripts.js';
5
+ import { FILE_ROLE_SUFFIXES } from '../../../utils/file-roles.js';
6
+ import { findDeclaredScripts, scriptModuleLanguage } from '../../../build/rolldown/ssr-script-entries-plugin.js';
7
+ const SCRIPT_SUFFIXES = FILE_ROLE_SUFFIXES.filter((suffix) => suffix.startsWith('.script.'));
8
+ /**
9
+ * Lists the `.script` files under `srcDir` that nothing attaches to a page.
10
+ *
11
+ * @remarks
12
+ * A script is attached when a literal `dependencies.scripts` entry in a module of the server build names it, an
13
+ * HTML Page or the Html shell loads it with `<script src>`, or an attached script imports it. A module of the
14
+ * server build that imports a script also counts, since that script is then part of the build. A `src` computed at
15
+ * runtime is not found, and neither is a declaration in an MDX file, so such a script is listed here.
16
+ *
17
+ * @param serverModules Source files of the server build, whose declarations are read.
18
+ */
19
+ export async function findUnattachedScripts(appConfig, serverModules) {
20
+ const { srcDir } = appConfig.absolutePaths;
21
+ const patterns = SCRIPT_SUFFIXES.map((suffix) => `**/*${suffix}`);
22
+ const scripts = (await fileSystem.glob(patterns, { cwd: srcDir })).map((file) => path.resolve(srcDir, file));
23
+ if (scripts.length === 0)
24
+ return [];
25
+ const attached = new Set();
26
+ const roots = new Set();
27
+ for (const file of serverModules) {
28
+ attached.add(path.resolve(file));
29
+ const lang = scriptModuleLanguage(file);
30
+ if (!lang || !fileSystem.exists(file))
31
+ continue;
32
+ const code = fileSystem.readFileSync(file).toString();
33
+ if (!code.includes('scripts'))
34
+ continue;
35
+ for (const { src } of findDeclaredScripts(file, code, lang))
36
+ roots.add(path.resolve(path.dirname(file), src));
37
+ }
38
+ const html = collectHtmlPageModuleScriptBuildInputs(appConfig);
39
+ for (const script of html.scripts)
40
+ roots.add(path.resolve(script));
41
+ for (const file of html.files)
42
+ attached.add(path.resolve(file));
43
+ for (const root of roots) {
44
+ attached.add(root);
45
+ for (const file of scanModuleScript(appConfig, root).files)
46
+ attached.add(file);
47
+ }
48
+ return scripts.filter((script) => !attached.has(script)).sort();
49
+ }
50
+ /**
51
+ * Warns once per `.script` file that {@link findUnattachedScripts} lists.
52
+ */
53
+ export async function warnAboutUnattachedScripts(appConfig, serverModules) {
54
+ for (const script of await findUnattachedScripts(appConfig, serverModules)) {
55
+ appLogger.warn(`${path.relative(appConfig.rootDir, script)} is a browser script, but no dependencies.scripts entry or HTML <script src> attaches it, so it ships nowhere. Check the declaration's path, or delete the file.`);
56
+ }
57
+ }
@@ -3,7 +3,7 @@ import { WebSocketServer } from 'ws';
3
3
  import { HttpError } from '../../../errors/http-error.js';
4
4
  import { appLogger } from '../../../global/app-logger.js';
5
5
  import { parseSearchParams } from '../../../router/server/parse-search-params.js';
6
- import { findWebSocketRoute } from './ws-pattern-matcher.js';
6
+ import { compileWebSocketRoutes, findWebSocketRoute } from './ws-pattern-matcher.js';
7
7
  import { createEcopagesSocket, invokeWebSocketHandlerHook, toWebSocketCloseInfo } from './websocket-lifecycle.js';
8
8
  const attachedUpgradeServers = new WeakSet();
9
9
  function adaptNodeWebSocket(ws, kind, params, search, context) {
@@ -88,6 +88,7 @@ export function attachNodeHttpWebSocketUpgrades(server, options) {
88
88
  }
89
89
  attachedUpgradeServers.add(server);
90
90
  const userWss = new WebSocketServer({ noServer: true });
91
+ const websocketRoutes = compileWebSocketRoutes(options.websocketHandlers);
91
92
  server.on('upgrade', (req, socket, head) => {
92
93
  if (options.preflight?.(req, socket, head)) {
93
94
  return;
@@ -95,7 +96,7 @@ export function attachNodeHttpWebSocketUpgrades(server, options) {
95
96
  const url = new URL(req.url ?? '/', options.runtimeOrigin);
96
97
  let wsMatch;
97
98
  try {
98
- wsMatch = findWebSocketRoute(options.websocketHandlers, url.pathname);
99
+ wsMatch = findWebSocketRoute(websocketRoutes, url.pathname);
99
100
  }
100
101
  catch (error) {
101
102
  if (!HttpError.isHttpError(error) || error.status !== 400) {
@@ -1,7 +1,20 @@
1
1
  import type { EcopagesWebSocketHandler } from '../../../types/contracts.js';
2
+ import { type SegmentPattern } from '../../../router/server/segment-path-matcher.js';
2
3
  export type WebSocketRouteMatch = {
3
4
  handler: EcopagesWebSocketHandler<unknown, Record<string, string>>;
4
5
  params: Record<string, string>;
5
6
  kind: string;
6
7
  };
7
- export declare function findWebSocketRoute(handlers: Map<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>, pathname: string): WebSocketRouteMatch | null;
8
+ /**
9
+ * WebSocket handlers with their patterns parsed, in registration order.
10
+ *
11
+ * @remarks Build it with {@link compileWebSocketRoutes} once the handlers are known, so an upgrade only
12
+ * compares path segments.
13
+ */
14
+ export type CompiledWebSocketRoutes = ReadonlyArray<{
15
+ pattern: string;
16
+ compiled: SegmentPattern<'websocket'>;
17
+ handler: EcopagesWebSocketHandler<unknown, Record<string, string>>;
18
+ }>;
19
+ export declare function compileWebSocketRoutes(handlers: ReadonlyMap<string, EcopagesWebSocketHandler<unknown, Record<string, string>>>): CompiledWebSocketRoutes;
20
+ export declare function findWebSocketRoute(routes: CompiledWebSocketRoutes, pathname: string): WebSocketRouteMatch | null;
@@ -1,20 +1,21 @@
1
- import { matchParsedSegmentPath, parseSegmentPath, scoreSegmentPathPattern, } from '../../../router/server/segment-path-matcher.js';
2
- export function findWebSocketRoute(handlers, pathname) {
1
+ import { compileSegmentPattern, matchParsedSegmentPath, parseSegmentPath, } from '../../../router/server/segment-path-matcher.js';
2
+ export function compileWebSocketRoutes(handlers) {
3
+ return [...handlers].map(([pattern, handler]) => ({
4
+ pattern,
5
+ compiled: compileSegmentPattern(pattern, 'websocket'),
6
+ handler,
7
+ }));
8
+ }
9
+ export function findWebSocketRoute(routes, pathname) {
3
10
  const pathSegments = parseSegmentPath(pathname);
4
11
  let best = null;
5
- let index = 0;
6
- for (const [pattern, handler] of handlers) {
7
- const params = matchParsedSegmentPath(pattern, pathSegments, 'websocket');
8
- if (params === null) {
9
- index += 1;
12
+ for (const { pattern, compiled, handler } of routes) {
13
+ const params = matchParsedSegmentPath(compiled, pathSegments);
14
+ if (params === null)
10
15
  continue;
16
+ if (best === null || compiled.score > best.score) {
17
+ best = { score: compiled.score, match: { handler, params, kind: pattern } };
11
18
  }
12
- const score = scoreSegmentPathPattern(pattern, 'websocket');
13
- const match = { handler, params, kind: pattern };
14
- if (best === null || score > best.score || (score === best.score && index < best.index)) {
15
- best = { score, match, index };
16
- }
17
- index += 1;
18
19
  }
19
20
  return best?.match ?? null;
20
21
  }
@@ -10,6 +10,8 @@ import { requireAppRuntime } from '../utils/app-runtime.js';
10
10
  import { BrowserBundleService } from './browser-bundle.service.js';
11
11
  import { getAssetDependencyKey, getDeclaredDependencyKey } from './asset-processing-service/asset-dependency-keys.js';
12
12
  import { isBundleableScript } from './asset-processing-service/bundleable-script.js';
13
+ /** Source bytes from which an installed package gets a chunk of its own in the app-wide build. */
14
+ const PACKAGE_CHUNK_MIN_SIZE = 10 * 1024;
13
15
  function hash(value) {
14
16
  return contentHash(value, 16);
15
17
  }
@@ -195,6 +197,7 @@ async function executeAppBrowserBuild(appConfig, buildEntries, htmlEntryNames) {
195
197
  splitting: true,
196
198
  naming: '[name]-[hash].[ext]',
197
199
  minify: group.options.minify ?? true,
200
+ packageChunks: { minSize: PACKAGE_CHUNK_MIN_SIZE },
198
201
  });
199
202
  assertBuildSucceeded(result, '[ecopages] Could not build the app browser client');
200
203
  for (const { path: output } of result.outputs) {
@@ -79,6 +79,15 @@ export declare class AssetProcessingService {
79
79
  * compiled or written; a dependency the ledger does not record is an error.
80
80
  */
81
81
  processDependencies(deps: AssetDefinition[], integration: AssetProcessingIntegration | undefined): Promise<ProcessedAsset[]>;
82
+ /**
83
+ * Processes `deps`, then returns the outputs the asset ledger records for them in declaration order.
84
+ *
85
+ * @remarks
86
+ * This is the order a sealed `ecopages start` returns, so an output recorded from it renders the same in the
87
+ * build and in start. A dependency processing skipped, such as a missing file, is left out until start, where
88
+ * it is an error.
89
+ */
90
+ processDependenciesInDeclarationOrder(deps: AssetDefinition[], integration: AssetProcessingIntegration | undefined): Promise<ProcessedAsset[]>;
82
91
  /**
83
92
  * Returns the emitted form of `dep` the production build recorded, if any.
84
93
  *
@@ -150,6 +150,25 @@ export class AssetProcessingService {
150
150
  await this.optimizeDependencies(results);
151
151
  return [...prebuilt, ...results];
152
152
  }
153
+ /**
154
+ * Processes `deps`, then returns the outputs the asset ledger records for them in declaration order.
155
+ *
156
+ * @remarks
157
+ * This is the order a sealed `ecopages start` returns, so an output recorded from it renders the same in the
158
+ * build and in start. A dependency processing skipped, such as a missing file, is left out until start, where
159
+ * it is an error.
160
+ */
161
+ async processDependenciesInDeclarationOrder(deps, integration) {
162
+ const processed = await this.processDependencies(deps, integration);
163
+ if (requireAppRuntime(this.config).processedAssets.isSealed)
164
+ return processed;
165
+ return prepareAssetDependencies(deps, integration, this.config.rootDir).flatMap((dep) => {
166
+ const recorded = this.lookupRecordedAsset(dep);
167
+ return recorded
168
+ ? [finalizeProcessedAsset(recorded, (asset) => this.resolveProcessedAssetSrcUrl(asset))]
169
+ : [];
170
+ });
171
+ }
153
172
  /**
154
173
  * Returns the emitted form of `dep` the production build recorded, if any.
155
174
  *
@@ -14,6 +14,8 @@ export type SerializedProcessedAssetLedger = {
14
14
  entries: LedgerEntry[];
15
15
  /** Every file the app-wide browser build emitted, chunks included; absent when no browser build ran. */
16
16
  browserOutputs?: string[];
17
+ /** The processed shell Dependencies of each route shell, by {@link ProcessedAssetLedger.recordShell} key. */
18
+ shells?: Record<string, LedgerProcessedAsset[]>;
17
19
  };
18
20
  /**
19
21
  * The emitted form of every dependency one production build processed or bundled, by dependency key.
@@ -27,6 +29,7 @@ export type SerializedProcessedAssetLedger = {
27
29
  */
28
30
  export declare class ProcessedAssetLedger {
29
31
  private readonly entries;
32
+ private readonly shells;
30
33
  private browserOutputs;
31
34
  private sealed;
32
35
  private readonly rootDir;
@@ -45,12 +48,23 @@ export declare class ProcessedAssetLedger {
45
48
  /** Records the files one app-wide browser build emitted, which marks the ledger as holding that build. */
46
49
  recordBrowserOutputs(filepaths: readonly string[]): void;
47
50
  /**
48
- * Forgets the app-wide browser build, so a retried production build records only its own outputs.
51
+ * Records the processed Dependencies of one route shell: its Html template, Layouts and Page.
52
+ *
53
+ * @remarks
54
+ * `key` names the Page and Html template, which fix the shell. The build records each shell the first time it
55
+ * prepares a route of that Page, and every later preparation, in the build or in `ecopages start`, reads it.
56
+ */
57
+ recordShell(key: string, assets: ProcessedAsset[]): void;
58
+ /** Returns the processed Dependencies recorded for one route shell. */
59
+ lookupShell(key: string): ProcessedAsset[] | undefined;
60
+ /**
61
+ * Forgets the app-wide browser build and the recorded shells, so a retried production build records only its
62
+ * own outputs.
49
63
  *
50
64
  * @remarks
51
65
  * Recorded dependencies stay: the next build records the ones it bundles again under the same keys.
52
66
  */
53
- clearBrowserOutputs(): void;
67
+ clearBuildOutputs(): void;
54
68
  /** Returns the recorded asset with paths resolved against the current app root. */
55
69
  lookup(dep: AssetDefinition): ProcessedAsset | undefined;
56
70
  /** Names `dep` in error messages: its app-root relative file, import path or content name. */
@@ -12,6 +12,7 @@ import { getAssetDependencyKey } from './asset-dependency-keys.js';
12
12
  */
13
13
  export class ProcessedAssetLedger {
14
14
  entries = new Map();
15
+ shells = new Map();
15
16
  browserOutputs;
16
17
  sealed = false;
17
18
  rootDir;
@@ -45,13 +46,29 @@ export class ProcessedAssetLedger {
45
46
  this.browserOutputs.add(this.relative(filepath));
46
47
  }
47
48
  /**
48
- * Forgets the app-wide browser build, so a retried production build records only its own outputs.
49
+ * Records the processed Dependencies of one route shell: its Html template, Layouts and Page.
50
+ *
51
+ * @remarks
52
+ * `key` names the Page and Html template, which fix the shell. The build records each shell the first time it
53
+ * prepares a route of that Page, and every later preparation, in the build or in `ecopages start`, reads it.
54
+ */
55
+ recordShell(key, assets) {
56
+ this.shells.set(key, assets);
57
+ }
58
+ /** Returns the processed Dependencies recorded for one route shell. */
59
+ lookupShell(key) {
60
+ return this.shells.get(key);
61
+ }
62
+ /**
63
+ * Forgets the app-wide browser build and the recorded shells, so a retried production build records only its
64
+ * own outputs.
49
65
  *
50
66
  * @remarks
51
67
  * Recorded dependencies stay: the next build records the ones it bundles again under the same keys.
52
68
  */
53
- clearBrowserOutputs() {
69
+ clearBuildOutputs() {
54
70
  this.browserOutputs = undefined;
71
+ this.shells.clear();
55
72
  }
56
73
  /** Returns the recorded asset with paths resolved against the current app root. */
57
74
  lookup(dep) {
@@ -70,13 +87,24 @@ export class ProcessedAssetLedger {
70
87
  const entries = [...this.entries]
71
88
  .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
72
89
  .map(([key, asset]) => ({ key, asset }));
73
- return this.browserOutputs ? { entries, browserOutputs: [...this.browserOutputs].sort() } : { entries };
90
+ const shells = Object.fromEntries([...this.shells]
91
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
92
+ .map(([key, assets]) => [key, assets.map((asset) => this.toPortable(asset))]));
93
+ return {
94
+ entries,
95
+ ...(this.browserOutputs ? { browserOutputs: [...this.browserOutputs].sort() } : {}),
96
+ ...(this.shells.size > 0 ? { shells } : {}),
97
+ };
74
98
  }
75
99
  restore(ledger) {
76
100
  this.entries.clear();
77
101
  for (const { key, asset } of ledger.entries)
78
102
  this.entries.set(key, asset);
79
103
  this.browserOutputs = ledger.browserOutputs ? new Set(ledger.browserOutputs) : undefined;
104
+ this.shells.clear();
105
+ for (const [key, assets] of Object.entries(ledger.shells ?? {})) {
106
+ this.shells.set(key, assets.map((asset) => this.toAbsolute(asset)));
107
+ }
80
108
  }
81
109
  relative(filepath) {
82
110
  return path.relative(this.rootDir, path.resolve(this.rootDir, filepath));
@@ -3,6 +3,24 @@ import type { BuildOptions, BuildSuccess } from './build-adapter.js';
3
3
  * Absolute path for an entry as the caller passed it, without resolving symlinks.
4
4
  */
5
5
  export declare function resolveBuildEntryPath(entry: string, root: string): string;
6
+ /**
7
+ * One requested build entry with its symlink-resolved paths.
8
+ */
9
+ export type RequestedBuildEntry = {
10
+ name: string;
11
+ entry: string;
12
+ resolved: string;
13
+ entryReal: string | undefined;
14
+ resolvedReal: string | undefined;
15
+ };
16
+ /**
17
+ * Resolves every requested entry and its real paths once, for repeated {@link recordBuildEntryOutput} calls.
18
+ *
19
+ * @remarks
20
+ * Real-path lookups touch the filesystem, so recording one build's chunks against freshly resolved entries
21
+ * would repeat them for every chunk and entry.
22
+ */
23
+ export declare function resolveRequestedBuildEntries(entrypoints: BuildOptions['entrypoints'], root: string): RequestedBuildEntry[];
6
24
  /**
7
25
  * Records every spelling a caller may use to look up one entry's output.
8
26
  *
@@ -14,8 +32,7 @@ export declare function resolveBuildEntryPath(entry: string, root: string): stri
14
32
  export declare function recordBuildEntryOutput(entryOutputs: Record<string, string>, outputPath: string, options: {
15
33
  facadeModuleId: string;
16
34
  chunkName?: string;
17
- entrypoints: BuildOptions['entrypoints'];
18
- root: string;
35
+ requestedEntries: RequestedBuildEntry[];
19
36
  }): void;
20
37
  /**
21
38
  * Finds the emitted file for an entry using the path or name the caller passed.