@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,5 +1,18 @@
1
- import type { EcoPageFile, GetMetadata, GetMetadataContext, GetStaticProps, PageMetadataProps, RouteRendererOptions, EcoPageComponent } from '../../types/contracts.js';
1
+ import type { EcoPageFile, GetMetadata, GetMetadataContext, GetProps, GetRequestProps, PageMetadataProps, RouteRendererOptions, EcoPageComponent } from '../../types/contracts.js';
2
2
  import type { EcoPagesAppConfig } from '../../config/internal-types.js';
3
+ /**
4
+ * A Page's `props` hook with the context its Cache Strategy gives it: the request context for a Dynamic Page, the
5
+ * build context for any other.
6
+ */
7
+ export type PagePropsHook = {
8
+ context: 'request';
9
+ run: GetRequestProps<Record<string, unknown>>;
10
+ } | {
11
+ context: 'build';
12
+ run: GetProps<Record<string, unknown>>;
13
+ };
14
+ /** The request a Dynamic Page's `props` hook reads, absent outside a request-time render. */
15
+ type PropsHookRequest = Pick<RouteRendererOptions, 'request' | 'query' | 'locals'>;
3
16
  /**
4
17
  * Loads route page modules and normalizes their data hooks for rendering.
5
18
  *
@@ -27,19 +40,24 @@ export declare class PageModuleLoaderService {
27
40
  bypassCache?: boolean;
28
41
  }): Promise<EcoPageFile>;
29
42
  /**
30
- * Executes the page's static-props hook with Ecopages runtime context.
43
+ * Executes the page's `props` hook with Ecopages runtime context.
31
44
  *
32
45
  * @remarks
33
- * Pages without a static-props hook still return a normalized empty props
46
+ * Pages without a `props` hook still return a normalized empty props
34
47
  * object so downstream render preparation does not branch on hook presence.
48
+ * A Static or revalidating Page's hook receives the build context. A Dynamic
49
+ * Page's hook receives the request context and fails without a `request`.
35
50
  */
36
- getStaticPropsForPage(options: {
37
- getStaticProps?: GetStaticProps<Record<string, unknown>>;
51
+ getPropsForPage(options: PropsHookRequest & {
52
+ getProps?: PagePropsHook;
38
53
  params?: RouteRendererOptions['params'];
54
+ /** The Page file, named when the hook returns a key the route sets. */
55
+ file?: string;
39
56
  }): Promise<{
40
57
  props: Record<string, unknown>;
41
58
  metadata?: PageMetadataProps;
42
59
  }>;
60
+ private bindPropsHook;
43
61
  /**
44
62
  * Builds the final page metadata object for one render request.
45
63
  *
@@ -52,7 +70,7 @@ export declare class PageModuleLoaderService {
52
70
  context: GetMetadataContext;
53
71
  }): Promise<PageMetadataProps>;
54
72
  /**
55
- * Fails when a page module still declares data through the removed module-level exports.
73
+ * Fails when a page module still declares data or its Cache Strategy through the removed module-level exports.
56
74
  *
57
75
  * @remarks
58
76
  * Integrations that cannot call `eco.page(...)`, such as MDX, move their metadata export onto the
@@ -73,7 +91,7 @@ export declare class PageModuleLoaderService {
73
91
  }): Promise<{
74
92
  module: EcoPageFile;
75
93
  Page: EcoPageFile['default'] | EcoPageComponent<any>;
76
- getStaticProps?: GetStaticProps<Record<string, unknown>>;
94
+ getProps?: PagePropsHook;
77
95
  getMetadata?: GetMetadata;
78
96
  integrationSpecificProps: Record<string, unknown>;
79
97
  }>;
@@ -81,14 +99,14 @@ export declare class PageModuleLoaderService {
81
99
  * Resolves the page data needed by the render pipeline.
82
100
  *
83
101
  * @remarks
84
- * Static props are resolved first because page metadata may depend on those
85
- * props. This preserves the same ordering whether data hooks are declared as
86
- * component statics or module exports. Props passed with the render win over
87
- * static props and are visible to metadata; `skipStaticProps` drops the hook.
102
+ * The `props` hook runs first because page metadata may depend on its result.
103
+ * Props passed with the render win over the hook's props and are visible to
104
+ * metadata; `skipPropsHook` drops the hook. A request-time render of a Dynamic
105
+ * Page passes its `request`, which the hook receives with `query` and `locals`.
88
106
  */
89
107
  resolvePageData(options: {
90
108
  pageModule: {
91
- getStaticProps?: GetStaticProps<Record<string, unknown>>;
109
+ getProps?: PagePropsHook;
92
110
  getMetadata?: GetMetadata;
93
111
  };
94
112
  routeOptions: RouteRendererOptions;
@@ -98,3 +116,4 @@ export declare class PageModuleLoaderService {
98
116
  metadata: PageMetadataProps;
99
117
  }>;
100
118
  }
119
+ export {};
@@ -1,8 +1,15 @@
1
1
  import { invariant } from '../../utils/invariant.js';
2
2
  import { requireAppRuntime } from '../../utils/app-runtime.js';
3
3
  import { resolveInternalExecutionDir } from '../../utils/resolve-work-dir.js';
4
+ import { DATA_HOOKS_MIGRATION_URL } from '../../eco/migration-docs.js';
5
+ import { assertNoRouteProps } from '../../eco/page-data-hooks.js';
4
6
  import { HttpError } from '../../errors/http-error.js';
5
- const LEGACY_PAGE_EXPORT_NAMES = ['getStaticPaths', 'getStaticProps', 'getMetadata'];
7
+ const LEGACY_PAGE_EXPORT_NAMES = ['getStaticPaths', 'getStaticProps', 'getMetadata', 'cache'];
8
+ function readPropsHook(page) {
9
+ if (!page.props)
10
+ return undefined;
11
+ return page.cache === 'dynamic' ? { context: 'request', run: page.props } : { context: 'build', run: page.props };
12
+ }
6
13
  /**
7
14
  * Loads route page modules and normalizes their data hooks for rendering.
8
15
  *
@@ -43,32 +50,51 @@ export class PageModuleLoaderService {
43
50
  }
44
51
  }
45
52
  /**
46
- * Executes the page's static-props hook with Ecopages runtime context.
53
+ * Executes the page's `props` hook with Ecopages runtime context.
47
54
  *
48
55
  * @remarks
49
- * Pages without a static-props hook still return a normalized empty props
56
+ * Pages without a `props` hook still return a normalized empty props
50
57
  * object so downstream render preparation does not branch on hook presence.
58
+ * A Static or revalidating Page's hook receives the build context. A Dynamic
59
+ * Page's hook receives the request context and fails without a `request`.
51
60
  */
52
- async getStaticPropsForPage(options) {
53
- const { getStaticProps, params } = options;
54
- return getStaticProps
55
- ? await getStaticProps({
56
- pathname: { params: params ?? {} },
57
- appConfig: this.appConfig,
58
- runtimeOrigin: requireAppRuntime(this.appConfig).origin,
59
- })
60
- .then((data) => data)
61
- .catch((err) => {
62
- if (HttpError.isHttpError(err) || err instanceof Response) {
63
- throw err;
64
- }
65
- const message = err instanceof Error ? err.message : String(err);
66
- throw new Error(`Error fetching static props: ${message}`, { cause: err });
67
- })
68
- : {
69
- props: {},
70
- metadata: undefined,
71
- };
61
+ async getPropsForPage(options) {
62
+ const { getProps } = options;
63
+ if (!getProps) {
64
+ return { props: {}, metadata: undefined };
65
+ }
66
+ const callHook = this.bindPropsHook(getProps, options);
67
+ let props;
68
+ try {
69
+ props = await callHook();
70
+ }
71
+ catch (err) {
72
+ if (HttpError.isHttpError(err) || err instanceof Response) {
73
+ throw err;
74
+ }
75
+ const message = err instanceof Error ? err.message : String(err);
76
+ throw new Error(`Error fetching props: ${message}`, { cause: err });
77
+ }
78
+ assertNoRouteProps(props, options.file ?? 'a Page');
79
+ return { props };
80
+ }
81
+ bindPropsHook(hook, options) {
82
+ const buildContext = {
83
+ params: options.params ?? {},
84
+ appConfig: this.appConfig,
85
+ runtimeOrigin: requireAppRuntime(this.appConfig).origin,
86
+ };
87
+ if (hook.context === 'build')
88
+ return () => hook.run(buildContext);
89
+ const { request, query, locals } = options;
90
+ invariant(request !== undefined, "A Dynamic Page's props hook runs only for a request, and this render has none. Render the Page through a request, or give it another Cache Strategy.");
91
+ const requestContext = {
92
+ ...buildContext,
93
+ request,
94
+ query: query ?? {},
95
+ locals: locals ?? {},
96
+ };
97
+ return () => hook.run(requestContext);
72
98
  }
73
99
  /**
74
100
  * Builds the final page metadata object for one render request.
@@ -92,7 +118,7 @@ export class PageModuleLoaderService {
92
118
  return metadata;
93
119
  }
94
120
  /**
95
- * Fails when a page module still declares data through the removed module-level exports.
121
+ * Fails when a page module still declares data or its Cache Strategy through the removed module-level exports.
96
122
  *
97
123
  * @remarks
98
124
  * Integrations that cannot call `eco.page(...)`, such as MDX, move their metadata export onto the
@@ -102,7 +128,7 @@ export class PageModuleLoaderService {
102
128
  const found = LEGACY_PAGE_EXPORT_NAMES.filter((name) => module[name] !== undefined);
103
129
  if (found.length === 0)
104
130
  return;
105
- throw new Error(`[ecopages] ${file} exports ${found.join(', ')}. Pages declare data through the staticPaths, staticProps and metadata options of eco.page({ ... }); module-level exports are no longer read. Run the migrate-to-eco-page codemod from @ecopages/codemod to migrate this file.`);
131
+ throw new Error(`[ecopages] ${file} exports ${found.join(', ')}. Pages declare data and caching through the paths, props, metadata and cache options of eco.page({ ... }); module-level exports are no longer read. Migration steps: ${DATA_HOOKS_MIGRATION_URL}`);
106
132
  }
107
133
  /**
108
134
  * Loads a page module and resolves the data hooks of its Page component.
@@ -120,7 +146,7 @@ export class PageModuleLoaderService {
120
146
  return {
121
147
  module,
122
148
  Page,
123
- getStaticProps: pageComponent.staticProps,
149
+ getProps: readPropsHook(pageComponent),
124
150
  getMetadata: pageComponent.metadata,
125
151
  integrationSpecificProps,
126
152
  };
@@ -129,19 +155,24 @@ export class PageModuleLoaderService {
129
155
  * Resolves the page data needed by the render pipeline.
130
156
  *
131
157
  * @remarks
132
- * Static props are resolved first because page metadata may depend on those
133
- * props. This preserves the same ordering whether data hooks are declared as
134
- * component statics or module exports. Props passed with the render win over
135
- * static props and are visible to metadata; `skipStaticProps` drops the hook.
158
+ * The `props` hook runs first because page metadata may depend on its result.
159
+ * Props passed with the render win over the hook's props and are visible to
160
+ * metadata; `skipPropsHook` drops the hook. A request-time render of a Dynamic
161
+ * Page passes its `request`, which the hook receives with `query` and `locals`.
136
162
  */
137
163
  async resolvePageData(options) {
138
- const staticProps = options.routeOptions.skipStaticProps
164
+ const { routeOptions } = options;
165
+ const hookProps = routeOptions.skipPropsHook
139
166
  ? {}
140
- : (await this.getStaticPropsForPage({
141
- getStaticProps: options.pageModule.getStaticProps,
142
- params: options.routeOptions.params,
167
+ : (await this.getPropsForPage({
168
+ getProps: options.pageModule.getProps,
169
+ file: routeOptions.file,
170
+ params: routeOptions.params,
171
+ request: routeOptions.request,
172
+ query: routeOptions.query,
173
+ locals: routeOptions.locals,
143
174
  })).props;
144
- const props = { ...staticProps, ...(options.routeOptions.props ?? {}) };
175
+ const props = { ...hookProps, ...(routeOptions.props ?? {}) };
145
176
  const metadata = options.skipMetadata
146
177
  ? this.appConfig.defaultMetadata
147
178
  : await this.getMetadataPropsForPage({
@@ -1,19 +1,24 @@
1
1
  import { listFileOwnedDependencyContributions } from '../../eco/page-dependency-contributions.js';
2
2
  import { collectPageDependencyComponents } from './file-scoped-dependency-components.js';
3
+ /**
4
+ * Calls the Page's dependency resolver, with the props only when the Page is not a Dynamic Page.
5
+ *
6
+ * @remarks
7
+ * A Dynamic Page's props come from the request, while its Page Browser Graph is planned at build and cached by
8
+ * Params and Query, so its resolver reads Params and Query only.
9
+ */
10
+ function callDependencyResolver(page, context) {
11
+ if (page.cache === 'dynamic') {
12
+ return page.resolveDependencies?.({ params: context.params, query: context.query });
13
+ }
14
+ return page.resolveDependencies?.({ props: context.props ?? {}, params: context.params, query: context.query });
15
+ }
3
16
  /**
4
17
  * Resolves `eco.page().dependencies()` once for one graph contribution context.
5
18
  */
6
19
  export async function resolvePageDependenciesFromContext(context, integrationName, materializeContribution) {
7
20
  const pageComponent = context.pageModule.default;
8
- const resolveDependencies = pageComponent.resolveDependencies;
9
- if (!resolveDependencies) {
10
- return undefined;
11
- }
12
- const dependenciesResult = await resolveDependencies({
13
- props: (context.props ?? {}),
14
- params: context.params,
15
- query: context.query,
16
- });
21
+ const dependenciesResult = await callDependencyResolver(pageComponent, context);
17
22
  if (!dependenciesResult) {
18
23
  return undefined;
19
24
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The folder, relative to `srcDir`, that the Route Registry scans for routes when `pagesDir` is not configured.
3
+ *
4
+ * @remarks
5
+ * `pagesDir` is the URL space of the app: the one folder name that carries meaning, owned by the router.
6
+ */
7
+ export declare const DEFAULT_PAGES_DIR = "pages";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The folder, relative to `srcDir`, that the Route Registry scans for routes when `pagesDir` is not configured.
3
+ *
4
+ * @remarks
5
+ * `pagesDir` is the URL space of the app: the one folder name that carries meaning, owned by the router.
6
+ */
7
+ export const DEFAULT_PAGES_DIR = 'pages';
@@ -34,23 +34,20 @@ export type StaticGenerationRoute = {
34
34
  readonly templateRoute: TemplateRoute;
35
35
  readonly params: RouteParams;
36
36
  };
37
- export type StaticPathsContext = {
37
+ export type PathsContext = {
38
38
  readonly appConfig: EcoPagesAppConfig;
39
39
  readonly runtimeOrigin: string;
40
40
  };
41
41
  export type RouteRegistryPageModule = {
42
- readonly staticPaths?: (context: StaticPathsContext) => Promise<{
43
- paths: Array<{
44
- params: RouteParams;
45
- }>;
46
- }>;
47
- readonly staticProps?: unknown;
42
+ readonly paths?: (context: PathsContext) => Promise<Array<{
43
+ params: RouteParams;
44
+ }>>;
48
45
  /**
49
46
  * The Page's Cache Strategy.
50
47
  *
51
48
  * @remarks
52
49
  * `'dynamic'` Pages are omitted from Static Path Expansions (no HTML at Build-Time Rendering).
53
- * When they declare `staticPaths`, those Params are still listed for Page Browser Graph planning.
50
+ * When they declare `paths`, those Params are still listed for Page Browser Graph planning.
54
51
  */
55
52
  readonly cache?: unknown;
56
53
  };
@@ -73,12 +70,19 @@ export declare class RouteRegistry {
73
70
  readonly buildMode: boolean;
74
71
  private readonly pageModuleAdapter;
75
72
  private templateRouteList;
73
+ private routeMatchers;
76
74
  private readonly reloadListeners;
77
75
  constructor(options: RouteRegistryOptions);
78
76
  get origin(): string;
79
77
  get templateRoutes(): readonly TemplateRoute[];
78
+ /**
79
+ * True when `filePath` is the source file of a Page route.
80
+ */
81
+ isPageFile(filePath: string): boolean;
80
82
  private get pageRoutes();
81
83
  init(): Promise<void>;
84
+ /** Sets the routes in match order, parsing each pattern once instead of per request. */
85
+ private useTemplateRoutes;
82
86
  reload(): Promise<void>;
83
87
  onReload(listener: () => void): () => void;
84
88
  matchRequest(requestUrl: string, parsedPathSegments?: ParsedSegmentPath): RouteMatch | null;
@@ -101,10 +105,10 @@ export declare class RouteRegistry {
101
105
  runtimeOrigin: string;
102
106
  }): Promise<readonly StaticPathExpansion[]>;
103
107
  /**
104
- * Params of Dynamic Pages that declare `staticPaths`, for Page Browser Graph planning.
108
+ * Params of Dynamic Pages that declare `paths`, for Page Browser Graph planning.
105
109
  *
106
110
  * @remarks
107
- * The return shape is {@link PathExpansion}, the same records `staticPaths` produces. They are
111
+ * The return shape is {@link PathExpansion}, the same records `paths` produces. They are
108
112
  * not Static Path Expansions: HTML still uses Request-Time Rendering. The build uses them so
109
113
  * each Params list's graph scripts are in the production asset ledger.
110
114
  */
@@ -114,6 +118,14 @@ export declare class RouteRegistry {
114
118
  listStaticGenerationRoutes(input: {
115
119
  runtimeOrigin: string;
116
120
  }): Promise<readonly StaticGenerationRoute[]>;
121
+ /**
122
+ * Classifies `file`, relative to the pages directory, as a Page or an endpoint file, or `undefined` when it is no route.
123
+ *
124
+ * @remarks
125
+ * Private files and `.server.*` and `.script.*` modules are not routes. Any other file with a role
126
+ * segment out of place fails the build, naming the file and the expected form.
127
+ */
128
+ private classifyRouteFile;
117
129
  private scanTemplateRoutes;
118
130
  /**
119
131
  * @remarks
@@ -5,11 +5,11 @@ import { loadProductionTemplateRoutes } from '../../build/production-route-list.
5
5
  import { invariant } from '../../utils/invariant.js';
6
6
  import { isProductionRuntime } from '../../env.js';
7
7
  import { hasKnownStaticExtension } from '../../utils/static-file-extensions.js';
8
- import { ENDPOINT_FILE_EXTENSIONS, findEndpointFileExtension } from '../../utils/endpoint-file-extensions.js';
8
+ import { describeRoleForms, ENDPOINT_FILE_EXTENSIONS, findMisplacedRole, matchRoleSuffix, isPrivatePath, } from '../../utils/file-roles.js';
9
9
  import { normalizePathname } from '../../utils/path-pattern.js';
10
10
  import { parseSearchParams } from './parse-search-params.js';
11
11
  import { findIntegrationForFile, findLongestExtension } from '../../plugins/find-integration-for-file.js';
12
- import { buildSegmentPath, matchParsedSegmentPath, parseSegmentPath, segmentPathPatternKey, } from './segment-path-matcher.js';
12
+ import { buildSegmentPath, compileSegmentPattern, matchParsedSegmentPath, parseSegmentPath, segmentPathPatternKey, } from './segment-path-matcher.js';
13
13
  const ROUTE_PRIORITY = {
14
14
  exact: 0,
15
15
  dynamic: 1,
@@ -23,6 +23,7 @@ export class RouteRegistry {
23
23
  buildMode;
24
24
  pageModuleAdapter;
25
25
  templateRouteList = [];
26
+ routeMatchers = [];
26
27
  reloadListeners = new Set();
27
28
  constructor(options) {
28
29
  this.fallbackOrigin = options.origin;
@@ -38,14 +39,29 @@ export class RouteRegistry {
38
39
  get templateRoutes() {
39
40
  return this.templateRouteList;
40
41
  }
42
+ /**
43
+ * True when `filePath` is the source file of a Page route.
44
+ */
45
+ isPageFile(filePath) {
46
+ const resolved = path.resolve(filePath);
47
+ return this.templateRouteList.some((route) => route.role === 'page' && path.resolve(route.filePath) === resolved);
48
+ }
41
49
  get pageRoutes() {
42
50
  return this.templateRouteList.filter((route) => route.role === 'page');
43
51
  }
44
52
  async init() {
45
53
  const productionRoutes = isProductionRuntime() ? loadProductionTemplateRoutes(this.appConfig) : undefined;
46
- this.templateRouteList = productionRoutes ?? (await this.scanTemplateRoutes());
54
+ this.useTemplateRoutes(productionRoutes ?? (await this.scanTemplateRoutes()));
47
55
  appLogger.debug('RouteRegistry initialized', this.templateRouteList);
48
56
  }
57
+ /** Sets the routes in match order, parsing each pattern once instead of per request. */
58
+ useTemplateRoutes(routes) {
59
+ this.templateRouteList = routes;
60
+ this.routeMatchers = routes.map((route) => ({
61
+ route,
62
+ pattern: compileSegmentPattern(route.pathname, 'filesystem'),
63
+ }));
64
+ }
49
65
  async reload() {
50
66
  await this.init();
51
67
  for (const listener of this.reloadListeners) {
@@ -63,8 +79,8 @@ export class RouteRegistry {
63
79
  const requestedPathname = normalizePathname(url.pathname);
64
80
  const pathSegments = parsedPathSegments ?? parseSegmentPath(requestedPathname);
65
81
  const query = this.getSearchParams(url);
66
- for (const route of this.templateRouteList) {
67
- const params = matchParsedSegmentPath(route.pathname, pathSegments, 'filesystem');
82
+ for (const { route, pattern } of this.routeMatchers) {
83
+ const params = matchParsedSegmentPath(pattern, pathSegments);
68
84
  if (params) {
69
85
  return {
70
86
  requestedPathname,
@@ -108,12 +124,12 @@ export class RouteRegistry {
108
124
  isDynamicRouteSegment(segment) {
109
125
  return segment.startsWith('[') && segment.endsWith(']');
110
126
  }
111
- async expandStaticPaths(route, staticPaths, runtimeOrigin) {
112
- const result = await staticPaths({
127
+ async expandStaticPaths(route, listParams, runtimeOrigin) {
128
+ const result = await listParams({
113
129
  appConfig: this.appConfig,
114
130
  runtimeOrigin,
115
131
  });
116
- return result.paths.map(({ params }) => ({
132
+ return result.map(({ params }) => ({
117
133
  pathname: buildSegmentPath(route.pathname, params, 'filesystem'),
118
134
  templateRoute: route,
119
135
  params,
@@ -129,36 +145,35 @@ export class RouteRegistry {
129
145
  if (!options.include(pageModule)) {
130
146
  continue;
131
147
  }
132
- const staticPaths = pageModule.staticPaths;
133
- if (options.requireStaticHooks && this.buildMode) {
134
- invariant(staticPaths !== undefined, `[ecopages] Missing staticPaths in ${route.filePath}`);
135
- invariant(pageModule.staticProps !== undefined, `[ecopages] Missing staticProps in ${route.filePath}`);
148
+ const listParams = pageModule.paths;
149
+ if (options.requirePaths && this.buildMode) {
150
+ invariant(listParams !== undefined, `[ecopages] Missing paths in ${route.filePath}`);
136
151
  }
137
- if (!staticPaths) {
152
+ if (!listParams) {
138
153
  continue;
139
154
  }
140
- expansions.push(...(await this.expandStaticPaths(route, staticPaths, input.runtimeOrigin)));
155
+ expansions.push(...(await this.expandStaticPaths(route, listParams, input.runtimeOrigin)));
141
156
  }
142
157
  return expansions;
143
158
  }
144
159
  async listStaticPathExpansions(input) {
145
160
  return this.listPathExpansions(input, {
146
161
  include: (pageModule) => pageModule.cache !== 'dynamic',
147
- requireStaticHooks: true,
162
+ requirePaths: true,
148
163
  });
149
164
  }
150
165
  /**
151
- * Params of Dynamic Pages that declare `staticPaths`, for Page Browser Graph planning.
166
+ * Params of Dynamic Pages that declare `paths`, for Page Browser Graph planning.
152
167
  *
153
168
  * @remarks
154
- * The return shape is {@link PathExpansion}, the same records `staticPaths` produces. They are
169
+ * The return shape is {@link PathExpansion}, the same records `paths` produces. They are
155
170
  * not Static Path Expansions: HTML still uses Request-Time Rendering. The build uses them so
156
171
  * each Params list's graph scripts are in the production asset ledger.
157
172
  */
158
173
  async listDynamicPagePathExpansions(input) {
159
174
  return this.listPathExpansions(input, {
160
- include: (pageModule) => pageModule.cache === 'dynamic' && pageModule.staticPaths !== undefined,
161
- requireStaticHooks: false,
175
+ include: (pageModule) => pageModule.cache === 'dynamic' && pageModule.paths !== undefined,
176
+ requirePaths: false,
162
177
  });
163
178
  }
164
179
  async listStaticGenerationRoutes(input) {
@@ -180,6 +195,22 @@ export class RouteRegistry {
180
195
  })),
181
196
  ];
182
197
  }
198
+ /**
199
+ * Classifies `file`, relative to the pages directory, as a Page or an endpoint file, or `undefined` when it is no route.
200
+ *
201
+ * @remarks
202
+ * Private files and `.server.*` and `.script.*` modules are not routes. Any other file with a role
203
+ * segment out of place fails the build, naming the file and the expected form.
204
+ */
205
+ classifyRouteFile(file) {
206
+ const match = matchRoleSuffix(file);
207
+ if (isPrivatePath(file) || match?.role === 'server' || match?.role === 'script') {
208
+ return undefined;
209
+ }
210
+ const misplacedRole = findMisplacedRole(file);
211
+ invariant(misplacedRole === undefined, `${path.join(this.pagesDir, file)}: the "${misplacedRole}" role segment must come directly before a script extension, as in ${describeRoleForms()}. Rename the file, or prefix it with "_" to keep it out of routing.`);
212
+ return match ? { role: 'endpoint', endpointExtension: match.suffix } : { role: 'page' };
213
+ }
183
214
  async scanTemplateRoutes() {
184
215
  if (!fileSystem.exists(this.pagesDir)) {
185
216
  return [];
@@ -190,11 +221,11 @@ export class RouteRegistry {
190
221
  const templateRoutes = [];
191
222
  const routesByKey = new Map();
192
223
  for await (const file of scannedFiles) {
193
- if (file.includes('.ecopages-node.')) {
224
+ const classified = this.classifyRouteFile(file);
225
+ if (!classified) {
194
226
  continue;
195
227
  }
196
- const endpointExtension = findEndpointFileExtension(file);
197
- const role = endpointExtension ? 'endpoint' : 'page';
228
+ const { role, endpointExtension } = classified;
198
229
  const routePathname = this.getRoutePath(file, endpointExtension);
199
230
  const filePath = path.join(this.pagesDir, file);
200
231
  const kind = this.classifyRouteKind(file);
@@ -214,7 +245,7 @@ export class RouteRegistry {
214
245
  const owner = role === 'page' && kind !== 'exact'
215
246
  ? findIntegrationForFile(this.appConfig.integrations, filePath)
216
247
  : undefined;
217
- invariant(owner?.acceptsParams !== false, `${filePath}: ${findLongestExtension(owner?.extensions ?? [], filePath)} Pages cannot receive Params, so they cannot use dynamic route segments. Rename the file, or use an eco.page() Page from an Integration that supports staticPaths.`);
248
+ invariant(owner?.acceptsParams !== false, `${filePath}: ${findLongestExtension(owner?.extensions ?? [], filePath)} Pages cannot receive Params, so they cannot use dynamic route segments. Rename the file, or use an eco.page() Page from an Integration that supports paths.`);
218
249
  templateRoutes.push({
219
250
  pathname: routePathname,
220
251
  kind,
@@ -2,6 +2,33 @@ import type { PageParams } from '../../types/contracts.js';
2
2
  export type SegmentPathSyntax = 'filesystem' | 'api' | 'explicit' | 'websocket';
3
3
  export type SegmentPathParams = PageParams;
4
4
  export type ParsedSegmentPath = readonly string[];
5
+ type PatternSegment = {
6
+ kind: 'literal';
7
+ value: string;
8
+ } | {
9
+ kind: 'parameter';
10
+ name: string;
11
+ } | {
12
+ kind: 'catch-all';
13
+ name: string;
14
+ } | {
15
+ kind: 'wildcard';
16
+ };
17
+ /** Joined catch-all values make `explicit` and `websocket` params plain strings. */
18
+ type MatchedParams<S extends SegmentPathSyntax> = S extends 'explicit' | 'websocket' ? Record<string, string> : SegmentPathParams;
19
+ /**
20
+ * A route pattern parsed once, with the specificity score that orders it against other patterns.
21
+ *
22
+ * @remarks
23
+ * Build one with {@link compileSegmentPattern} when the route is registered, so a request only compares
24
+ * path segments. The score is the `api` ordering for every syntax but `websocket`, which has its own.
25
+ */
26
+ export type SegmentPattern<S extends SegmentPathSyntax = SegmentPathSyntax> = {
27
+ readonly syntax: S;
28
+ readonly segments: readonly PatternSegment[];
29
+ readonly score: number;
30
+ };
31
+ export declare function compileSegmentPattern<S extends SegmentPathSyntax>(pattern: string, syntax: S): SegmentPattern<S>;
5
32
  /**
6
33
  * Normalizes and decodes a request pathname once for matching multiple routes.
7
34
  *
@@ -10,9 +37,7 @@ export type ParsedSegmentPath = readonly string[];
10
37
  * original segment. Malformed escapes throw an HTTP 400 {@link HttpError}.
11
38
  */
12
39
  export declare function parseSegmentPath(pathname: string): ParsedSegmentPath;
13
- export declare function matchParsedSegmentPath(pattern: string, pathSegments: ParsedSegmentPath, syntax: 'filesystem' | 'api'): SegmentPathParams | null;
14
- export declare function matchParsedSegmentPath(pattern: string, pathSegments: ParsedSegmentPath, syntax: 'explicit' | 'websocket'): Record<string, string> | null;
15
- export declare function matchParsedSegmentPath(pattern: string, pathSegments: ParsedSegmentPath, syntax: SegmentPathSyntax): SegmentPathParams | null;
40
+ export declare function matchParsedSegmentPath<S extends SegmentPathSyntax>(pattern: SegmentPattern<S>, pathSegments: ParsedSegmentPath): MatchedParams<S> | null;
16
41
  /**
17
42
  * Matches one route syntax against a pathname and returns its captured parameters.
18
43
  *
@@ -43,5 +68,4 @@ export declare function buildSegmentPath(pattern: string, params: SegmentPathPar
43
68
  * catch-all shares one with a wildcard, since both take every remaining segment.
44
69
  */
45
70
  export declare function segmentPathPatternKey(pattern: string, syntax: SegmentPathSyntax): string;
46
- export declare function scoreSegmentPathPattern(pattern: string, syntax: 'api'): number;
47
- export declare function scoreSegmentPathPattern(pattern: string, syntax: 'websocket'): number;
71
+ export {};