@ecopages/core 0.9.0 → 0.10.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 (53) hide show
  1. package/package.json +3 -3
  2. package/src/adapters/node/create-app.d.ts +4 -4
  3. package/src/adapters/shared/http/api-request-pipeline.js +8 -6
  4. package/src/adapters/shared/http/define-api-handler.d.ts +8 -8
  5. package/src/adapters/shared/http/file-route-middleware-pipeline.d.ts +10 -11
  6. package/src/adapters/shared/http/file-route-middleware-pipeline.js +5 -6
  7. package/src/adapters/shared/http/fs-server-response-matcher.js +12 -4
  8. package/src/adapters/shared/http/run-middleware-chain.d.ts +29 -2
  9. package/src/adapters/shared/http/run-middleware-chain.js +108 -10
  10. package/src/adapters/shared/runtime/render-context.js +2 -21
  11. package/src/build/runtime/build-request-policy.js +4 -1
  12. package/src/build.d.ts +1 -0
  13. package/src/build.js +1 -0
  14. package/src/declarations.d.ts +2 -0
  15. package/src/eco/eco.browser.js +6 -26
  16. package/src/eco/eco.js +5 -16
  17. package/src/eco/page-data-hooks.d.ts +27 -0
  18. package/src/eco/page-data-hooks.js +64 -0
  19. package/src/eco/page-layout-normalization.d.ts +2 -2
  20. package/src/index.d.ts +1 -0
  21. package/src/index.js +1 -0
  22. package/src/integration.d.ts +1 -1
  23. package/src/integration.js +1 -1
  24. package/src/middleware/create-middleware.d.ts +41 -0
  25. package/src/middleware/create-middleware.js +72 -0
  26. package/src/plugins/eco-component-meta-plugin.d.ts +33 -0
  27. package/src/plugins/eco-component-meta-plugin.js +170 -23
  28. package/src/route-renderer/error-pages/error-page-renderer.js +29 -1
  29. package/src/route-renderer/explicit-view-render-preparation.d.ts +18 -0
  30. package/src/route-renderer/explicit-view-render-preparation.js +53 -7
  31. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.d.ts +15 -5
  32. package/src/route-renderer/orchestration/document-shell/layout-shell-props.service.js +27 -15
  33. package/src/route-renderer/orchestration/integration-renderer.d.ts +3 -1
  34. package/src/route-renderer/orchestration/integration-renderer.js +10 -6
  35. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.builder.js +0 -3
  36. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.d.ts +4 -0
  37. package/src/route-renderer/orchestration/route-pipeline/route-render-orchestrator.js +6 -1
  38. package/src/route-renderer/page-loading/page-module-loader.d.ts +27 -7
  39. package/src/route-renderer/page-loading/page-module-loader.js +46 -15
  40. package/src/route-renderer/page-loading/resolved-page-dependencies.js +14 -9
  41. package/src/static-site-generator/static-site-generator.d.ts +0 -1
  42. package/src/static-site-generator/static-site-generator.js +6 -6
  43. package/src/types/contracts.d.ts +196 -140
  44. package/src/types/eco-api-types.d.ts +76 -46
  45. package/src/types/locals-brand.d.ts +9 -0
  46. package/src/types/locals-brand.js +9 -0
  47. package/src/types/middleware-types.d.ts +143 -0
  48. package/src/types/middleware-types.js +1 -0
  49. package/src/types/public-types.d.ts +3 -2
  50. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.d.ts +0 -4
  51. package/src/route-renderer/orchestration/route-pipeline/route-prepared-options.utils.js +0 -30
  52. package/src/utils/locals-utils.d.ts +0 -15
  53. package/src/utils/locals-utils.js +0 -34
@@ -4,6 +4,7 @@ import { ensureIntegrationRuntimeReady } from '../../build/app-build-manifest-ru
4
4
  import { hasProductionServerModule } from '../../build/server/server-modules-manifest.js';
5
5
  import { findIntegrationForFile } from '../../plugins/find-integration-for-file.js';
6
6
  import { prepareExplicitStaticRender } from '../explicit-view-render-preparation.js';
7
+ import { isDynamicPage } from '../../eco/page-data-hooks.js';
7
8
  import { ERROR_PAGE_STATUS_BY_KIND, kindForStatus } from '../../errors/http-error-page-contract.js';
8
9
  import { buildDefaultErrorHtml, getDefaultServerErrorDetails, getPublicErrorMessage, } from './default-error-pages.js';
9
10
  const ERROR_PAGE_RENDER_ERRORS = {
@@ -17,6 +18,29 @@ function resolveRenderTarget(input) {
17
18
  kind: input.kind ?? kindForStatus(status),
18
19
  };
19
20
  }
21
+ /**
22
+ * Fails for an error page that needs the request pipeline it does not get.
23
+ *
24
+ * @remarks
25
+ * An error page renders outside the failed request's pipeline, with no request and no middleware, so a Dynamic
26
+ * Page's `props` hook, which is a request handler, cannot run and a `middleware` list would never guard it. Without
27
+ * this check the hook fails deep in render preparation with a message that names no file.
28
+ * @throws When the page is a Dynamic Page that declares `props`, or declares `middleware`.
29
+ */
30
+ function assertErrorPageRendersWithoutRequest(status, source, page) {
31
+ if (isDynamicPage(page) && hasDeclared(page, 'props')) {
32
+ throw new Error(`[ecopages] The ${status} error page ${source} has cache: 'dynamic' and props, but an error page renders without a request, so its props hook cannot run. Remove props and render from the error page props (status, message), or drop cache: 'dynamic'.`);
33
+ }
34
+ if (hasDeclared(page, 'middleware')) {
35
+ throw new Error(`[ecopages] The ${status} error page ${source} declares middleware, but an error page renders without a request, so no middleware would run. Remove the middleware from the error page.`);
36
+ }
37
+ }
38
+ function hasDeclared(page, option) {
39
+ if (typeof page !== 'function' || !(option in page))
40
+ return false;
41
+ const value = Reflect.get(page, option);
42
+ return Array.isArray(value) ? value.length > 0 : value !== undefined;
43
+ }
20
44
  /**
21
45
  * Owns error-page source precedence and rendering for runtime and static paths.
22
46
  *
@@ -86,7 +110,10 @@ export class ErrorPageRenderer {
86
110
  integrationName: integration.name,
87
111
  });
88
112
  }
89
- const result = await this.routeRendererFactory.getPageRenderer(templatePath).execute({
113
+ const renderer = this.routeRendererFactory.getPageRenderer(templatePath);
114
+ const pageModule = await renderer.loadPageModule(templatePath);
115
+ assertErrorPageRendersWithoutRequest(props.status, templatePath, pageModule.default);
116
+ const result = await renderer.execute({
90
117
  file: templatePath,
91
118
  props,
92
119
  locals: {},
@@ -98,6 +125,7 @@ export class ErrorPageRenderer {
98
125
  throw new Error(`No route renderer available for __error__/${status}`);
99
126
  }
100
127
  const view = (await loader()).default;
128
+ assertErrorPageRendersWithoutRequest(status, loader.filePath ?? `__error__/${status}`, view);
101
129
  const { renderer, props: hookProps, view: renderableView, } = await prepareExplicitStaticRender({
102
130
  routePath: `__error__/${status}`,
103
131
  view,
@@ -6,6 +6,21 @@ type ExplicitStaticRenderPreparationResult = {
6
6
  props: Record<string, unknown>;
7
7
  view: EcoFunctionComponent<Record<string, unknown>, any>;
8
8
  };
9
+ /**
10
+ * Fails for a view that a render without a request cannot serve: one that declares `middleware`, or a Dynamic Page
11
+ * that declares `props`.
12
+ *
13
+ * @remarks
14
+ * `app.static()`, error pages and static generation render a view with no request, so no middleware runs, its
15
+ * layout factories receive no locals, and a Dynamic Page's `props` hook, which is a request handler, cannot run.
16
+ * Ignoring the list would serve the view unguarded while its types promise the locals the guard provides, and a
17
+ * skipped Dynamic Page would build and then fail on every request. Static generation calls this before it skips a
18
+ * Dynamic Page, so both fail the build. `view` is `EcoPageComponent<any>` for the reason given on
19
+ * `readViewPropsWithoutRequest`: a View loader erases the props type.
20
+ * @throws When the view declares a non-empty `middleware` list, or has `cache: 'dynamic'` and `props`, naming the
21
+ * route and the view's file.
22
+ */
23
+ export declare function assertViewRendersWithoutRequest(routePath: string, view: EcoPageComponent<any>): void;
9
24
  /**
10
25
  * Resolves the renderer for one explicit view without reading its `props` hook.
11
26
  *
@@ -33,6 +48,9 @@ export declare function resolveExplicitViewRenderer(input: {
33
48
  /**
34
49
  * Resolves the renderer and props needed to render one explicit static
35
50
  * view at runtime or during static generation.
51
+ *
52
+ * @remarks
53
+ * No request exists here, so the view's `props` hook receives the build context.
36
54
  */
37
55
  export declare function prepareExplicitStaticRender(input: {
38
56
  routePath: string;
@@ -1,6 +1,30 @@
1
1
  import { getComponentOwner } from '../eco/component-identity.js';
2
+ import { assertNoRouteProps, isDynamicPage } from '../eco/page-data-hooks.js';
2
3
  import { ensureIntegrationRuntimeReady } from '../build/app-build-manifest-runtime.js';
3
4
  import { assertViewDeclaredIn } from './page-declaration.js';
5
+ /**
6
+ * Fails for a view that a render without a request cannot serve: one that declares `middleware`, or a Dynamic Page
7
+ * that declares `props`.
8
+ *
9
+ * @remarks
10
+ * `app.static()`, error pages and static generation render a view with no request, so no middleware runs, its
11
+ * layout factories receive no locals, and a Dynamic Page's `props` hook, which is a request handler, cannot run.
12
+ * Ignoring the list would serve the view unguarded while its types promise the locals the guard provides, and a
13
+ * skipped Dynamic Page would build and then fail on every request. Static generation calls this before it skips a
14
+ * Dynamic Page, so both fail the build. `view` is `EcoPageComponent<any>` for the reason given on
15
+ * `readViewPropsWithoutRequest`: a View loader erases the props type.
16
+ * @throws When the view declares a non-empty `middleware` list, or has `cache: 'dynamic'` and `props`, naming the
17
+ * route and the view's file.
18
+ */
19
+ export function assertViewRendersWithoutRequest(routePath, view) {
20
+ const name = view.config?.identity?.file ?? 'its view';
21
+ if (view.middleware?.length) {
22
+ throw new Error(`[ecopages] ${routePath} renders ${name} without a request, so it cannot declare middleware: no middleware would run and the view would be served unguarded. Serve it from the pages directory, or render it from a route handler with ctx.render and give the handler the middleware.`);
23
+ }
24
+ if (isDynamicPage(view) && view.props) {
25
+ throw new Error(`[ecopages] ${routePath} renders ${name} without a request, so a view with cache: 'dynamic' cannot declare props. Serve it from the pages directory, or render it from a route handler with the props it needs.`);
26
+ }
27
+ }
4
28
  /**
5
29
  * Resolves the renderer for one explicit view without reading its `props` hook.
6
30
  *
@@ -11,6 +35,7 @@ import { assertViewDeclaredIn } from './page-declaration.js';
11
35
  export function resolveExplicitViewRenderer(input) {
12
36
  if (input.declaredIn)
13
37
  assertViewDeclaredIn(input.declaredIn.file, input.view, input.declaredIn.rootDir);
38
+ assertViewRendersWithoutRequest(input.routePath, input.view);
14
39
  const integrationName = getComponentOwner(input.view);
15
40
  if (!integrationName) {
16
41
  throw new Error(input.errors.missingIntegration(input.routePath));
@@ -24,9 +49,36 @@ export function resolveExplicitViewRenderer(input) {
24
49
  view: input.view,
25
50
  };
26
51
  }
52
+ /**
53
+ * Runs the `props` hook of a view rendered without a request, with the build context.
54
+ *
55
+ * @remarks
56
+ * A Dynamic Page view still renders per request through `app.static()`, with no `props`: {@link
57
+ * assertViewRendersWithoutRequest} has already rejected one that declares them.
58
+ *
59
+ * `view` is `EcoPageComponent<any>` because a View loader erases the props type: that member of the union is not
60
+ * assignable to `EcoPageComponent<unknown>` or `EcoPageComponent<Record<string, unknown>>`, so a narrower type
61
+ * would reject every loaded view. The hook's result is returned as the props the renderer passes back to it.
62
+ */
63
+ async function readViewPropsWithoutRequest(input) {
64
+ const { view } = input;
65
+ if (isDynamicPage(view) || !view.props) {
66
+ return {};
67
+ }
68
+ const props = await view.props({
69
+ params: input.params,
70
+ appConfig: input.appConfig,
71
+ runtimeOrigin: input.runtimeOrigin,
72
+ });
73
+ assertNoRouteProps(props, view.config?.identity?.file ?? input.routePath);
74
+ return props;
75
+ }
27
76
  /**
28
77
  * Resolves the renderer and props needed to render one explicit static
29
78
  * view at runtime or during static generation.
79
+ *
80
+ * @remarks
81
+ * No request exists here, so the view's `props` hook receives the build context.
30
82
  */
31
83
  export async function prepareExplicitStaticRender(input) {
32
84
  const integrationName = getComponentOwner(input.view);
@@ -40,13 +92,7 @@ export async function prepareExplicitStaticRender(input) {
40
92
  ...input,
41
93
  declaredIn: input.viewFile ? { file: input.viewFile, rootDir: input.appConfig.rootDir } : undefined,
42
94
  });
43
- const props = input.view.props
44
- ? await input.view.props({
45
- params: input.params,
46
- appConfig: input.appConfig,
47
- runtimeOrigin: input.runtimeOrigin,
48
- })
49
- : {};
95
+ const props = await readViewPropsWithoutRequest(input);
50
96
  return {
51
97
  renderer,
52
98
  props,
@@ -8,11 +8,12 @@ export type DocumentShellLayoutResolutionInput = LayoutShellPropsContext & {
8
8
  layoutEntries?: EcoPageLayoutEntry[];
9
9
  };
10
10
  /**
11
- * Resolves the default shell props passed to a layout tier during route render.
12
- */
13
- export declare function resolveLayoutShellProps(context: LayoutShellPropsContext): Record<string, unknown>;
14
- /**
15
- * Resolves props for one layout entry, merging shell props with an optional factory.
11
+ * Resolves the props one layout tier renders with: what its `props` factory returns, or nothing.
12
+ *
13
+ * @remarks
14
+ * A layout receives request data only through its factory, so the server and the browser render the tier from
15
+ * the same props. The factory sees `locals`; the layout itself does not. A Static Page renders without a request,
16
+ * so its factories receive empty `locals`; their type has no `locals` to read.
16
17
  */
17
18
  export declare function resolveLayoutEntryProps(entry: EcoPageLayoutEntry, context: LayoutShellPropsContext): Record<string, unknown>;
18
19
  /**
@@ -22,6 +23,15 @@ export declare function resolveLayoutEntryProps(entry: EcoPageLayoutEntry, conte
22
23
  * silently fall back to the innermost layout and discard route-specific props.
23
24
  */
24
25
  export declare function resolveDocumentShellLayouts(input: DocumentShellLayoutResolutionInput): DocumentShellLayoutInput[];
26
+ /**
27
+ * Resolves the layouts of one render, once per `render` object, the render options both callers hold.
28
+ *
29
+ * @remarks
30
+ * The document shell renders each tier from these props and an integration writes the same props into its page
31
+ * payload. Resolving them for each would run every layout factory twice per request, and a factory that is not
32
+ * deterministic, such as one reading the clock, would give the HTML and the payload different values.
33
+ */
34
+ export declare function resolveRenderLayouts(render: object, input: DocumentShellLayoutResolutionInput): DocumentShellLayoutInput[];
25
35
  /**
26
36
  * Reads the normalized layout stack from a page component config.
27
37
  */
@@ -1,26 +1,21 @@
1
1
  /**
2
- * Resolves the default shell props passed to a layout tier during route render.
3
- */
4
- export function resolveLayoutShellProps(context) {
5
- return context.locals ? { locals: context.locals } : {};
6
- }
7
- /**
8
- * Resolves props for one layout entry, merging shell props with an optional factory.
2
+ * Resolves the props one layout tier renders with: what its `props` factory returns, or nothing.
3
+ *
4
+ * @remarks
5
+ * A layout receives request data only through its factory, so the server and the browser render the tier from
6
+ * the same props. The factory sees `locals`; the layout itself does not. A Static Page renders without a request,
7
+ * so its factories receive empty `locals`; their type has no `locals` to read.
9
8
  */
10
9
  export function resolveLayoutEntryProps(entry, context) {
11
- const shellProps = resolveLayoutShellProps(context);
12
10
  if (!entry.props) {
13
- return shellProps;
11
+ return {};
14
12
  }
15
13
  const layoutPropsContext = {
16
14
  params: context.params,
17
15
  query: context.query,
18
- locals: context.locals,
19
- };
20
- return {
21
- ...shellProps,
22
- ...entry.props(layoutPropsContext),
16
+ locals: context.locals ?? {},
23
17
  };
18
+ return entry.props(layoutPropsContext);
24
19
  }
25
20
  /**
26
21
  * Resolves declarative layout entries into the document-shell inputs used during route render.
@@ -35,7 +30,24 @@ export function resolveDocumentShellLayouts(input) {
35
30
  props: resolveLayoutEntryProps(entry, input),
36
31
  }));
37
32
  }
38
- return input.layout ? [{ component: input.layout, props: resolveLayoutShellProps(input) }] : [];
33
+ return input.layout ? [{ component: input.layout, props: {} }] : [];
34
+ }
35
+ const layoutsByRender = new WeakMap();
36
+ /**
37
+ * Resolves the layouts of one render, once per `render` object, the render options both callers hold.
38
+ *
39
+ * @remarks
40
+ * The document shell renders each tier from these props and an integration writes the same props into its page
41
+ * payload. Resolving them for each would run every layout factory twice per request, and a factory that is not
42
+ * deterministic, such as one reading the clock, would give the HTML and the payload different values.
43
+ */
44
+ export function resolveRenderLayouts(render, input) {
45
+ let layouts = layoutsByRender.get(render);
46
+ if (!layouts) {
47
+ layouts = resolveDocumentShellLayouts(input);
48
+ layoutsByRender.set(render, layouts);
49
+ }
50
+ return layouts;
39
51
  }
40
52
  /**
41
53
  * Reads the normalized layout stack from a page component config.
@@ -214,7 +214,9 @@ export declare abstract class IntegrationRenderer<C = EcoPagesElement> {
214
214
  * @remarks
215
215
  * The scripts the route's render would bundle, from the shell, the page Dependencies, the Page Browser Graph
216
216
  * dependencies and the components and scripts its contribution names, go to `bundledScripts`, prepared as asset
217
- * processing prepares them.
217
+ * processing prepares them. A Dynamic Page is planned without its `props` hook, which is its request handler: the
218
+ * build has no request to give it. A plan without the `props` hook also skips `metadata`, which would read props
219
+ * that were never resolved. Planning does not read metadata, and static export never renders from such a plan.
218
220
  */
219
221
  private planRouteInstance;
220
222
  private runInRenderSession;
@@ -16,6 +16,7 @@ import { HttpError } from '../../errors/http-error.js';
16
16
  import { DependencyResolverService } from '../page-loading/dependency-resolver.js';
17
17
  import { PageModuleLoaderService } from '../page-loading/page-module-loader.js';
18
18
  import { getComponentIdentity } from '../../eco/component-identity.js';
19
+ import { isDynamicPage } from '../../eco/page-data-hooks.js';
19
20
  import { isPathInside } from '../../utils/path-containment.js';
20
21
  import { createLiteralPageDeclarationError, isPageDeclaredIn, isUnattributedPage } from '../page-declaration.js';
21
22
  import { OwnershipValidationService } from './ownership-graph/ownership-validation.service.js';
@@ -36,7 +37,7 @@ import { ensureIntegrationRuntimeReady } from '../../build/app-build-manifest-ru
36
37
  import { assignSsrPreloadScripts, CustomElementScriptPreloader, } from './custom-element-scripts/custom-element-script-preloader.js';
37
38
  import { createQueuedRuntime, executeComponentRender, getQueuedRuntimeContext, resolveQueuedHtml, resolveStringQueuedHtml, } from './foreign-child/foreign-subtree-execution.service.js';
38
39
  import { renderPageDocumentShell, } from './document-shell/document-shell-render.service.js';
39
- import { resolveInnermostPageLayout, resolvePageLayoutComponents, resolveDocumentShellLayouts, } from './document-shell/layout-shell-props.service.js';
40
+ import { resolveInnermostPageLayout, resolvePageLayoutComponents, resolveRenderLayouts, } from './document-shell/layout-shell-props.service.js';
40
41
  import { stampIslandHost } from '../../islands/island-host.js';
41
42
  import { requireAppRuntime } from '../../utils/app-runtime.js';
42
43
  import { prepareAssetDependencies } from '../../assets/asset-processing-service/asset-processing.service.js';
@@ -149,17 +150,21 @@ export class IntegrationRenderer {
149
150
  * @remarks
150
151
  * The scripts the route's render would bundle, from the shell, the page Dependencies, the Page Browser Graph
151
152
  * dependencies and the components and scripts its contribution names, go to `bundledScripts`, prepared as asset
152
- * processing prepares them.
153
+ * processing prepares them. A Dynamic Page is planned without its `props` hook, which is its request handler: the
154
+ * build has no request to give it. A plan without the `props` hook also skips `metadata`, which would read props
155
+ * that were never resolved. Planning does not read metadata, and static export never renders from such a plan.
153
156
  */
154
157
  async planRouteInstance(routeInstance) {
158
+ const pageModule = await this.loadPageModule(routeInstance.routeFile);
159
+ const skipPropsHook = routeInstance.skipPropsHook || isDynamicPage(pageModule.default);
155
160
  const routeOptions = {
156
161
  file: routeInstance.routeFile,
157
162
  params: routeInstance.params,
158
163
  query: routeInstance.query,
159
- skipPropsHook: routeInstance.skipPropsHook,
164
+ skipPropsHook,
160
165
  };
161
166
  const resolvedInputs = await this.resolveRouteRenderInputs(routeOptions, {
162
- skipMetadata: routeInstance.isRouteTemplate,
167
+ skipMetadata: routeInstance.isRouteTemplate || skipPropsHook,
163
168
  });
164
169
  const graphContext = await this.routeRenderOrchestrator.prepareRouteGraphContext({
165
170
  routeOptions,
@@ -839,10 +844,9 @@ export class IntegrationRenderer {
839
844
  ...options.props,
840
845
  params: options.params ?? {},
841
846
  query: options.query ?? {},
842
- locals: options.pageLocals,
843
847
  },
844
848
  },
845
- layouts: resolveDocumentShellLayouts({
849
+ layouts: resolveRenderLayouts(options, {
846
850
  layout: options.Layout,
847
851
  layoutEntries: options.layoutEntries,
848
852
  params: options.params,
@@ -1,6 +1,5 @@
1
1
  import { createPagePackage } from '../../../assets/asset-processing-service/index.js';
2
2
  import { dedupeProcessedAssets } from '../../../assets/processed-asset-dedupe.js';
3
- import { createPageLocalsProxy } from './route-prepared-options.utils.js';
4
3
  /**
5
4
  * Assembles the final integration render options after route prep dependencies resolve.
6
5
  */
@@ -16,7 +15,6 @@ export function buildPreparedRenderOptions(input) {
16
15
  query: routeOptions.query || {},
17
16
  };
18
17
  const cacheStrategy = Page.cache;
19
- const pageLocals = routeOptions.locals ?? createPageLocalsProxy(routeOptions.file);
20
18
  const locals = routeOptions.locals;
21
19
  const preparedOptions = {
22
20
  ...routeOptions,
@@ -34,7 +32,6 @@ export function buildPreparedRenderOptions(input) {
34
32
  query: routeOptions.query || {},
35
33
  pageProps,
36
34
  locals,
37
- pageLocals,
38
35
  cacheStrategy,
39
36
  };
40
37
  return {
@@ -87,6 +87,10 @@ export declare class RouteRenderOrchestrator {
87
87
  /**
88
88
  * Shares route graph preparation with the production grouped prebuild.
89
89
  *
90
+ * @remarks
91
+ * The graph context of a Dynamic Page carries no props: they come from the request, while its Page Browser Graph
92
+ * is planned at build and cached by Params and Query alone.
93
+ *
90
94
  * @internal
91
95
  */
92
96
  prepareRouteGraphContext<C>(input: {
@@ -13,6 +13,7 @@ import { buildGlobalInjectorAssets } from '../page-browser-graph/global-injector
13
13
  import { mergePageBrowserGraphContributions } from '../page-browser-graph/page-browser-graph-contribution.merge.js';
14
14
  import { PageBrowserGraphService } from '../page-browser-graph/page-browser-graph.service.js';
15
15
  import { createPageDependencyInstanceKey } from '../page-browser-graph/route-instance-key.js';
16
+ import { isDynamicPage } from '../../../eco/page-data-hooks.js';
16
17
  import { buildPreparedRenderOptions } from './route-prepared-options.builder.js';
17
18
  import { measureRouteRenderPhase } from '../../../diagnostics/request-pipeline-metrics.js';
18
19
  /**
@@ -48,6 +49,10 @@ export class RouteRenderOrchestrator {
48
49
  /**
49
50
  * Shares route graph preparation with the production grouped prebuild.
50
51
  *
52
+ * @remarks
53
+ * The graph context of a Dynamic Page carries no props: they come from the request, while its Page Browser Graph
54
+ * is planned at build and cached by Params and Query alone.
55
+ *
51
56
  * @internal
52
57
  */
53
58
  async prepareRouteGraphContext(input) {
@@ -60,7 +65,7 @@ export class RouteRenderOrchestrator {
60
65
  const graphContext = {
61
66
  file: routeOptions.file,
62
67
  pageModule: resolvedInputs.pageModule,
63
- props,
68
+ props: isDynamicPage(resolvedInputs.pageModule.default) ? undefined : props,
64
69
  params: routeOptions.params,
65
70
  query: routeOptions.query,
66
71
  dependencyInstanceKey,
@@ -1,5 +1,18 @@
1
- import type { EcoPageFile, GetMetadata, GetMetadataContext, GetProps, 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
  *
@@ -32,14 +45,19 @@ export declare class PageModuleLoaderService {
32
45
  * @remarks
33
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
- getPropsForPage(options: {
37
- getProps?: GetProps<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
- getProps?: GetProps<Record<string, unknown>>;
94
+ getProps?: PagePropsHook;
77
95
  getMetadata?: GetMetadata;
78
96
  integrationSpecificProps: Record<string, unknown>;
79
97
  }>;
@@ -83,11 +101,12 @@ export declare class PageModuleLoaderService {
83
101
  * @remarks
84
102
  * The `props` hook runs first because page metadata may depend on its result.
85
103
  * Props passed with the render win over the hook's props and are visible to
86
- * metadata; `skipPropsHook` drops the hook.
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`.
87
106
  */
88
107
  resolvePageData(options: {
89
108
  pageModule: {
90
- getProps?: GetProps<Record<string, unknown>>;
109
+ getProps?: PagePropsHook;
91
110
  getMetadata?: GetMetadata;
92
111
  };
93
112
  routeOptions: RouteRendererOptions;
@@ -97,3 +116,4 @@ export declare class PageModuleLoaderService {
97
116
  metadata: PageMetadataProps;
98
117
  }>;
99
118
  }
119
+ export {};
@@ -2,8 +2,14 @@ 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
4
  import { DATA_HOOKS_MIGRATION_URL } from '../../eco/migration-docs.js';
5
+ import { assertNoRouteProps } from '../../eco/page-data-hooks.js';
5
6
  import { HttpError } from '../../errors/http-error.js';
6
- 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
+ }
7
13
  /**
8
14
  * Loads route page modules and normalizes their data hooks for rendering.
9
15
  *
@@ -49,19 +55,18 @@ export class PageModuleLoaderService {
49
55
  * @remarks
50
56
  * Pages without a `props` hook still return a normalized empty props
51
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`.
52
60
  */
53
61
  async getPropsForPage(options) {
54
- const { getProps, params } = options;
62
+ const { getProps } = options;
55
63
  if (!getProps) {
56
64
  return { props: {}, metadata: undefined };
57
65
  }
66
+ const callHook = this.bindPropsHook(getProps, options);
67
+ let props;
58
68
  try {
59
- const props = await getProps({
60
- params: params ?? {},
61
- appConfig: this.appConfig,
62
- runtimeOrigin: requireAppRuntime(this.appConfig).origin,
63
- });
64
- return { props };
69
+ props = await callHook();
65
70
  }
66
71
  catch (err) {
67
72
  if (HttpError.isHttpError(err) || err instanceof Response) {
@@ -70,6 +75,26 @@ export class PageModuleLoaderService {
70
75
  const message = err instanceof Error ? err.message : String(err);
71
76
  throw new Error(`Error fetching props: ${message}`, { cause: err });
72
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);
73
98
  }
74
99
  /**
75
100
  * Builds the final page metadata object for one render request.
@@ -93,7 +118,7 @@ export class PageModuleLoaderService {
93
118
  return metadata;
94
119
  }
95
120
  /**
96
- * 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.
97
122
  *
98
123
  * @remarks
99
124
  * Integrations that cannot call `eco.page(...)`, such as MDX, move their metadata export onto the
@@ -103,7 +128,7 @@ export class PageModuleLoaderService {
103
128
  const found = LEGACY_PAGE_EXPORT_NAMES.filter((name) => module[name] !== undefined);
104
129
  if (found.length === 0)
105
130
  return;
106
- throw new Error(`[ecopages] ${file} exports ${found.join(', ')}. Pages declare data through the paths, props and metadata options of eco.page({ ... }); module-level exports are no longer read. Migration steps: ${DATA_HOOKS_MIGRATION_URL}`);
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}`);
107
132
  }
108
133
  /**
109
134
  * Loads a page module and resolves the data hooks of its Page component.
@@ -121,7 +146,7 @@ export class PageModuleLoaderService {
121
146
  return {
122
147
  module,
123
148
  Page,
124
- getProps: pageComponent.props,
149
+ getProps: readPropsHook(pageComponent),
125
150
  getMetadata: pageComponent.metadata,
126
151
  integrationSpecificProps,
127
152
  };
@@ -132,16 +157,22 @@ export class PageModuleLoaderService {
132
157
  * @remarks
133
158
  * The `props` hook runs first because page metadata may depend on its result.
134
159
  * Props passed with the render win over the hook's props and are visible to
135
- * metadata; `skipPropsHook` drops the hook.
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 hookProps = options.routeOptions.skipPropsHook
164
+ const { routeOptions } = options;
165
+ const hookProps = routeOptions.skipPropsHook
139
166
  ? {}
140
167
  : (await this.getPropsForPage({
141
168
  getProps: options.pageModule.getProps,
142
- params: options.routeOptions.params,
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 = { ...hookProps, ...(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
  }
@@ -52,7 +52,6 @@ export declare class StaticSiteGenerator {
52
52
  });
53
53
  private getExportDir;
54
54
  private shouldSkipStaticPageFile;
55
- private shouldSkipStaticView;
56
55
  /**
57
56
  * Writes the robots.txt file declared by the app config.
58
57
  */