@ecopages/react 0.2.0-beta.30 → 0.2.0-beta.32

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 (57) hide show
  1. package/README.md +5 -1
  2. package/package.json +4 -4
  3. package/src/app/client-only.js +13 -17
  4. package/src/app/dynamic.js +7 -10
  5. package/src/app/dynamic.test.browser.js +27 -29
  6. package/src/bundling/bootstrap-package-paths.js +5 -6
  7. package/src/bundling/bundle.js +115 -114
  8. package/src/bundling/discover-layout-runtime-modules.js +166 -155
  9. package/src/bundling/runtime-alias-map.d.ts +4 -1
  10. package/src/bundling/runtime-alias-map.js +107 -95
  11. package/src/bundling/runtime-bundle.js +250 -274
  12. package/src/bundling/runtime-interop-plugin.js +31 -35
  13. package/src/bundling/runtime-mode.js +10 -5
  14. package/src/bundling/runtime-modules.js +46 -35
  15. package/src/client-graph/ast-transform.js +415 -305
  16. package/src/client-graph/boundary-cache.js +146 -104
  17. package/src/client-graph/boundary-plugin.js +122 -104
  18. package/src/client-graph/component-config-traversal.js +70 -49
  19. package/src/client-graph/declared-modules.js +63 -41
  20. package/src/client-graph/reachability-analyzer.js +506 -313
  21. package/src/client-graph/specifier-classification.js +209 -141
  22. package/src/contracts/router-adapter.js +6 -0
  23. package/src/dev-transform/react-dev-transform-contributor.d.ts +17 -0
  24. package/src/dev-transform/react-dev-transform-contributor.js +22 -0
  25. package/src/hmr/hmr-scripts.js +22 -9
  26. package/src/hmr/hmr-strategy.d.ts +12 -181
  27. package/src/hmr/hmr-strategy.js +321 -650
  28. package/src/hmr/page-metadata-cache.js +43 -40
  29. package/src/hmr/react-hmr-dev-transform-plugins.d.ts +23 -0
  30. package/src/hmr/react-hmr-dev-transform-plugins.js +20 -0
  31. package/src/hydration/assert-no-bare-ecopages-imports.js +6 -6
  32. package/src/hydration/bootstrap-imports.js +30 -20
  33. package/src/hydration/hydration-asset.js +216 -213
  34. package/src/hydration/hydration-scripts.d.ts +4 -0
  35. package/src/hydration/hydration-scripts.js +199 -66
  36. package/src/hydration/hydration-scripts.test.browser.js +163 -168
  37. package/src/hydration/page-data-manifest.js +89 -45
  38. package/src/hydration/page-data-reader.js +45 -32
  39. package/src/hydration/page-payload.js +101 -99
  40. package/src/hydration/serialize-page-data-script.js +27 -28
  41. package/src/mdx/mdx-config-dependency.js +108 -112
  42. package/src/mdx/mdx-loader-plugin.js +7 -10
  43. package/src/page/page-module.js +72 -66
  44. package/src/plugin/react.constants.js +1 -4
  45. package/src/plugin/react.plugin.d.ts +1 -0
  46. package/src/plugin/react.plugin.js +227 -216
  47. package/src/plugin/react.types.js +1 -0
  48. package/src/render/component-ownership.js +42 -18
  49. package/src/render/component-ssr.js +168 -190
  50. package/src/render/eco-embed.js +8 -10
  51. package/src/render/errors.js +21 -16
  52. package/src/render/html-boundary.js +55 -51
  53. package/src/render/layout-compose.js +122 -94
  54. package/src/render/react-renderer.js +433 -468
  55. package/src/render/react-runtime.js +25 -20
  56. package/src/render/unified-layout-composition.js +74 -85
  57. package/src/runtime/use-sync-external-store-with-selector.js +52 -54
@@ -1,37 +1,34 @@
1
- import { afterEach, describe, expect, it } from "vitest";
2
- import { createHydrationScript } from "./hydration-scripts.js";
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { createHydrationScript } from './hydration-scripts.js';
3
3
  const routerAdapter = {
4
- name: "eco-router",
5
- bundle: {
6
- importPath: "/assets/router.js",
7
- outputName: "router",
8
- externals: []
9
- },
10
- components: {
11
- router: "EcoRouter",
12
- pageContent: "PageContent"
13
- },
14
- getRouterProps: (page, props) => `{ page: ${page}, pageProps: ${props} }`
4
+ name: 'eco-router',
5
+ bundle: {
6
+ importPath: '/assets/router.js',
7
+ outputName: 'router',
8
+ externals: [],
9
+ },
10
+ components: {
11
+ router: 'EcoRouter',
12
+ pageContent: 'PageContent',
13
+ },
14
+ getRouterProps: (page, props) => `{ page: ${page}, pageProps: ${props} }`,
15
15
  };
16
16
  function createModuleUrl(source) {
17
- return `data:text/javascript;base64,${btoa(source)}`;
17
+ return `data:text/javascript;base64,${btoa(source)}`;
18
18
  }
19
19
  async function importModule(moduleUrl, scriptId) {
20
- let marker;
21
- if (scriptId) {
22
- marker = document.createElement("script");
23
- marker.setAttribute("data-eco-script-id", scriptId);
24
- document.head.appendChild(marker);
25
- }
26
- await import(
27
- /* @vite-ignore */
28
- moduleUrl
29
- );
30
- marker?.remove();
20
+ let marker;
21
+ if (scriptId) {
22
+ marker = document.createElement('script');
23
+ marker.setAttribute('data-eco-script-id', scriptId);
24
+ document.head.appendChild(marker);
25
+ }
26
+ await import(/* @vite-ignore */ moduleUrl);
27
+ marker?.remove();
31
28
  }
32
29
  function createRuntimeModules() {
33
- const reactImportPath = createModuleUrl("export const createElement = (...args) => ({ args });");
34
- const reactDomClientImportPath = createModuleUrl(`
30
+ const reactImportPath = createModuleUrl('export const createElement = (...args) => ({ args });');
31
+ const reactDomClientImportPath = createModuleUrl(`
35
32
  export const hydrateRoot = (container, tree, options) => {
36
33
  const runtime = window.__ECO_REACT_HYDRATION_TEST__;
37
34
  runtime.hydrateCalls.push({
@@ -48,8 +45,8 @@ export const hydrateRoot = (container, tree, options) => {
48
45
  };
49
46
  };
50
47
  `);
51
- const importPath = createModuleUrl("export default function Page() { return null; }");
52
- const routerImportPath = createModuleUrl(`
48
+ const importPath = createModuleUrl('export default function Page() { return null; }');
49
+ const routerImportPath = createModuleUrl(`
53
50
  export function EcoRouter(props) {
54
51
  return props;
55
52
  }
@@ -58,147 +55,145 @@ export function PageContent() {
58
55
  return null;
59
56
  }
60
57
  `);
61
- return {
62
- importPath,
63
- reactImportPath,
64
- reactDomClientImportPath,
65
- routerImportPath,
66
- layoutComposeImportPath: createModuleUrl("export function composeLayoutPageTree() { return null; }"),
67
- pageLayoutNormalizationImportPath: createModuleUrl(
68
- "export function ensurePageConfigLayouts(config) { return config; }"
69
- )
70
- };
71
- }
72
- describe("createHydrationScript browser execution", () => {
73
- afterEach(() => {
74
- document.body.innerHTML = "";
75
- const testWindow = window;
76
- delete testWindow.__ECO_PAGES__;
77
- delete testWindow.__ECO_REACT_HYDRATION_TEST__;
78
- });
79
- it("registers router ownership and cleanup when the browser hydration bootstrap runs", async () => {
80
- const runtimeModules = createRuntimeModules();
81
- const testWindow = window;
82
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
83
- hydrateCalls: [],
84
- renderCalls: [],
85
- claimedOwners: [],
86
- releasedOwners: [],
87
- registrations: [],
88
- unmountCount: 0
89
- };
90
- testWindow.__ECO_PAGES__ = {
91
- navigation: {
92
- getOwnerState: () => ({
93
- owner: "html",
94
- canHandleSpaNavigation: false
95
- }),
96
- register: (registration) => {
97
- testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
98
- },
99
- claimOwnership: (owner) => {
100
- testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
101
- },
102
- releaseOwnership: (owner) => {
103
- testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
104
- }
105
- }
58
+ return {
59
+ importPath,
60
+ reactImportPath,
61
+ reactDomClientImportPath,
62
+ routerImportPath,
63
+ layoutComposeImportPath: createModuleUrl('export function composeLayoutPageTree() { return null; }'),
64
+ pageLayoutNormalizationImportPath: createModuleUrl('export function ensurePageConfigLayouts(config) { return config; }'),
106
65
  };
107
- document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
108
- title: "Hello React",
109
- locals: { theme: "dark" }
110
- })}<\/script>`;
111
- const script = createHydrationScript({
112
- ...runtimeModules,
113
- scriptId: "ecopages-react-page",
114
- hmrEnabled: true,
115
- isMdx: false,
116
- router: routerAdapter,
117
- pageDataReaderImportPath: new URL("./page-data-reader.js", import.meta.url).href
66
+ }
67
+ describe('createHydrationScript browser execution', () => {
68
+ afterEach(() => {
69
+ document.body.innerHTML = '';
70
+ const testWindow = window;
71
+ delete testWindow.__ECO_PAGES__;
72
+ delete testWindow.__ECO_REACT_HYDRATION_TEST__;
118
73
  });
119
- const moduleUrl = createModuleUrl(script);
120
- await importModule(moduleUrl, "ecopages-react-page");
121
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1);
122
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.containerTag).toBe("BODY");
123
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.hasRecoverableErrorHandler).toBe(true);
124
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toEqual(["react-router"]);
125
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(1);
126
- expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe("function");
127
- expect(testWindow.__ECO_PAGES__?.page).toEqual({
128
- module: moduleUrl,
129
- props: {
130
- title: "Hello React",
131
- locals: { theme: "dark" }
132
- }
74
+ it('registers router ownership and cleanup when the browser hydration bootstrap runs', async () => {
75
+ const runtimeModules = createRuntimeModules();
76
+ const testWindow = window;
77
+ testWindow.__ECO_REACT_HYDRATION_TEST__ = {
78
+ hydrateCalls: [],
79
+ renderCalls: [],
80
+ claimedOwners: [],
81
+ releasedOwners: [],
82
+ registrations: [],
83
+ unmountCount: 0,
84
+ };
85
+ testWindow.__ECO_PAGES__ = {
86
+ navigation: {
87
+ getOwnerState: () => ({
88
+ owner: 'html',
89
+ canHandleSpaNavigation: false,
90
+ }),
91
+ register: (registration) => {
92
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
93
+ },
94
+ claimOwnership: (owner) => {
95
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
96
+ },
97
+ releaseOwnership: (owner) => {
98
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
99
+ },
100
+ },
101
+ };
102
+ document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
103
+ title: 'Hello React',
104
+ locals: { theme: 'dark' },
105
+ })}</script>`;
106
+ const script = createHydrationScript({
107
+ ...runtimeModules,
108
+ scriptId: 'ecopages-react-page',
109
+ hmrEnabled: true,
110
+ isMdx: false,
111
+ router: routerAdapter,
112
+ pageDataReaderImportPath: new URL('./page-data-reader.js', import.meta.url).href,
113
+ });
114
+ const moduleUrl = createModuleUrl(script);
115
+ await importModule(moduleUrl, 'ecopages-react-page');
116
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(1);
117
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.containerTag).toBe('BODY');
118
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls[0]?.hasRecoverableErrorHandler).toBe(true);
119
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toEqual(['react-router']);
120
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(1);
121
+ expect(typeof testWindow.__ECO_PAGES__?.react?.cleanupPageRoot).toBe('function');
122
+ expect(testWindow.__ECO_PAGES__?.page).toEqual({
123
+ module: moduleUrl,
124
+ props: {
125
+ title: 'Hello React',
126
+ locals: { theme: 'dark' },
127
+ },
128
+ });
129
+ await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
130
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
131
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners).toEqual(['react-router']);
132
+ expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
133
+ expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
133
134
  });
134
- await testWindow.__ECO_PAGES__?.react?.cleanupPageRoot?.();
135
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.unmountCount).toBe(1);
136
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners).toEqual(["react-router"]);
137
- expect(testWindow.__ECO_PAGES__?.page).toBeUndefined();
138
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBeNull();
139
- });
140
- it("reuses an existing router-owned page root during rerun bootstrap execution", async () => {
141
- const runtimeModules = createRuntimeModules();
142
- const testWindow = window;
143
- testWindow.__ECO_REACT_HYDRATION_TEST__ = {
144
- hydrateCalls: [],
145
- renderCalls: [],
146
- claimedOwners: [],
147
- releasedOwners: [],
148
- registrations: [],
149
- unmountCount: 0
150
- };
151
- const existingRoot = {
152
- render: (tree) => {
153
- testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree);
154
- },
155
- unmount: () => {
156
- testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
157
- }
158
- };
159
- testWindow.__ECO_PAGES__ = {
160
- navigation: {
161
- getOwnerState: () => ({
162
- owner: "react-router",
163
- canHandleSpaNavigation: true
164
- }),
165
- register: (registration) => {
166
- testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
167
- },
168
- claimOwnership: (owner) => {
169
- testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
170
- },
171
- releaseOwnership: (owner) => {
172
- testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
173
- }
174
- },
175
- react: {
176
- pageRoot: existingRoot
177
- }
178
- };
179
- document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
180
- title: "Rerun"
181
- })}<\/script>`;
182
- const script = createHydrationScript({
183
- ...runtimeModules,
184
- scriptId: "ecopages-react-page-rerun",
185
- hmrEnabled: true,
186
- isMdx: false,
187
- router: routerAdapter,
188
- pageDataReaderImportPath: new URL("./page-data-reader.js", import.meta.url).href
189
- });
190
- const moduleUrl = createModuleUrl(script);
191
- await importModule(moduleUrl, "ecopages-react-page-rerun");
192
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
193
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
194
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toHaveLength(0);
195
- expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(0);
196
- expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
197
- expect(testWindow.__ECO_PAGES__?.page).toEqual({
198
- module: moduleUrl,
199
- props: {
200
- title: "Rerun"
201
- }
135
+ it('reuses an existing router-owned page root during rerun bootstrap execution', async () => {
136
+ const runtimeModules = createRuntimeModules();
137
+ const testWindow = window;
138
+ testWindow.__ECO_REACT_HYDRATION_TEST__ = {
139
+ hydrateCalls: [],
140
+ renderCalls: [],
141
+ claimedOwners: [],
142
+ releasedOwners: [],
143
+ registrations: [],
144
+ unmountCount: 0,
145
+ };
146
+ const existingRoot = {
147
+ render: (tree) => {
148
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls.push(tree);
149
+ },
150
+ unmount: () => {
151
+ testWindow.__ECO_REACT_HYDRATION_TEST__.unmountCount += 1;
152
+ },
153
+ };
154
+ testWindow.__ECO_PAGES__ = {
155
+ navigation: {
156
+ getOwnerState: () => ({
157
+ owner: 'react-router',
158
+ canHandleSpaNavigation: true,
159
+ }),
160
+ register: (registration) => {
161
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations.push(registration);
162
+ },
163
+ claimOwnership: (owner) => {
164
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners.push(owner);
165
+ },
166
+ releaseOwnership: (owner) => {
167
+ testWindow.__ECO_REACT_HYDRATION_TEST__?.releasedOwners.push(owner);
168
+ },
169
+ },
170
+ react: {
171
+ pageRoot: existingRoot,
172
+ },
173
+ };
174
+ document.body.innerHTML = `<script id="__ECO_PAGE_DATA__" type="application/json">${JSON.stringify({
175
+ title: 'Rerun',
176
+ })}</script>`;
177
+ const script = createHydrationScript({
178
+ ...runtimeModules,
179
+ scriptId: 'ecopages-react-page-rerun',
180
+ hmrEnabled: true,
181
+ isMdx: false,
182
+ router: routerAdapter,
183
+ pageDataReaderImportPath: new URL('./page-data-reader.js', import.meta.url).href,
184
+ });
185
+ const moduleUrl = createModuleUrl(script);
186
+ await importModule(moduleUrl, 'ecopages-react-page-rerun');
187
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.hydrateCalls).toHaveLength(0);
188
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.renderCalls).toHaveLength(0);
189
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.claimedOwners).toHaveLength(0);
190
+ expect(testWindow.__ECO_REACT_HYDRATION_TEST__?.registrations).toHaveLength(0);
191
+ expect(testWindow.__ECO_PAGES__?.react?.pageRoot).toBe(existingRoot);
192
+ expect(testWindow.__ECO_PAGES__?.page).toEqual({
193
+ module: moduleUrl,
194
+ props: {
195
+ title: 'Rerun',
196
+ },
197
+ });
202
198
  });
203
- });
204
199
  });
@@ -1,53 +1,97 @@
1
- const ECO_PAGE_DATA_SCHEMA_VERSION = 1;
2
- function isEcoPageDataManifestV1(value) {
3
- if (typeof value !== "object" || value === null) {
4
- return false;
5
- }
6
- const candidate = value;
7
- return candidate.schemaVersion === ECO_PAGE_DATA_SCHEMA_VERSION && candidate.navigationOwner === "react-router" && typeof candidate.moduleUrl === "string" && typeof candidate.props === "object" && candidate.props !== null && !Array.isArray(candidate.props);
1
+ /**
2
+ * Versioned React page-data document payload.
3
+ *
4
+ * @remarks
5
+ * The `__ECO_PAGE_DATA__` script emits this envelope so client navigation can
6
+ * read module identity without parsing generated hydration JavaScript. Older
7
+ * documents may still contain a flat props object; consumers must detect both.
8
+ *
9
+ * Compatibility matrix:
10
+ * - new client / new document: prefer `schemaVersion:1` envelope (`moduleUrl` + `props`)
11
+ * - new client / old document: accept legacy flat props; module discovery uses
12
+ * `window.__ECO_PAGES__.page.module` or `script[data-eco-page-bootstrap="react-router"]`
13
+ * - old client / new document: old clients that only read flat props should be
14
+ * upgraded; envelope consumers must unwrap `props` before hydration
15
+ * - malformed / unknown schema (numeric `schemaVersion` present but envelope invalid):
16
+ * empty props and no module URL from the manifest
17
+ * - HMR: `moduleUrlOverride` still bypasses document discovery
18
+ * - legacy flat props may include a string `schemaVersion` field without being treated as an envelope
19
+ */
20
+ export const ECO_PAGE_DATA_SCHEMA_VERSION = 1;
21
+ /**
22
+ * Returns whether a parsed JSON value is a versioned page-data envelope.
23
+ */
24
+ export function isEcoPageDataManifestV1(value) {
25
+ if (typeof value !== 'object' || value === null) {
26
+ return false;
27
+ }
28
+ const candidate = value;
29
+ return (candidate.schemaVersion === ECO_PAGE_DATA_SCHEMA_VERSION &&
30
+ candidate.navigationOwner === 'react-router' &&
31
+ typeof candidate.moduleUrl === 'string' &&
32
+ typeof candidate.props === 'object' &&
33
+ candidate.props !== null &&
34
+ !Array.isArray(candidate.props));
8
35
  }
36
+ /**
37
+ * Returns whether a payload claims a numeric schema version without being a valid v1 envelope.
38
+ *
39
+ * @remarks
40
+ * Only numeric `schemaVersion` values are treated as envelope attempts. Legacy flat props may
41
+ * legitimately include a string `schemaVersion` field (e.g. a version string) and must not be
42
+ * wiped. Near-miss numeric envelopes must not fall through to the flat-props path.
43
+ */
9
44
  function isMalformedPageDataEnvelope(payload) {
10
- return "schemaVersion" in payload && typeof payload.schemaVersion === "number";
45
+ return 'schemaVersion' in payload && typeof payload.schemaVersion === 'number';
11
46
  }
12
- function resolveEcoPageDataProps(payload) {
13
- if (isEcoPageDataManifestV1(payload)) {
14
- return payload.props;
15
- }
16
- if (typeof payload === "object" && payload !== null && !Array.isArray(payload)) {
17
- if (isMalformedPageDataEnvelope(payload)) {
18
- return {};
47
+ /**
48
+ * Extracts browser page props from either a v1 envelope or a legacy flat payload.
49
+ */
50
+ export function resolveEcoPageDataProps(payload) {
51
+ if (isEcoPageDataManifestV1(payload)) {
52
+ return payload.props;
53
+ }
54
+ if (typeof payload === 'object' && payload !== null && !Array.isArray(payload)) {
55
+ if (isMalformedPageDataEnvelope(payload)) {
56
+ return {};
57
+ }
58
+ return payload;
19
59
  }
20
- return payload;
21
- }
22
- return {};
60
+ return {};
23
61
  }
24
- function resolveEcoPageDataModuleUrl(payload) {
25
- return isEcoPageDataManifestV1(payload) ? payload.moduleUrl : null;
62
+ /**
63
+ * Extracts the page module URL from a v1 envelope when present.
64
+ */
65
+ export function resolveEcoPageDataModuleUrl(payload) {
66
+ return isEcoPageDataManifestV1(payload) ? payload.moduleUrl : null;
26
67
  }
27
- function createEcoPageDataManifestV1(input) {
28
- return {
29
- schemaVersion: ECO_PAGE_DATA_SCHEMA_VERSION,
30
- navigationOwner: "react-router",
31
- moduleUrl: input.moduleUrl,
32
- props: input.props
33
- };
68
+ /**
69
+ * Builds the canonical v1 page-data envelope for React documents.
70
+ */
71
+ export function createEcoPageDataManifestV1(input) {
72
+ return {
73
+ schemaVersion: ECO_PAGE_DATA_SCHEMA_VERSION,
74
+ navigationOwner: 'react-router',
75
+ moduleUrl: input.moduleUrl,
76
+ props: input.props,
77
+ };
34
78
  }
35
- function resolvePageDataDocumentPayload(data, options) {
36
- if (isEcoPageDataManifestV1(data)) {
37
- return data;
38
- }
39
- const props = { ...data };
40
- const moduleUrl = options?.moduleUrl;
41
- if (!moduleUrl) {
42
- return props;
43
- }
44
- return createEcoPageDataManifestV1({ moduleUrl, props });
79
+ /**
80
+ * Normalizes flat page props or an existing envelope into the document payload shape.
81
+ *
82
+ * @remarks
83
+ * Shared by server serializers and `EcoPropsScript` so envelope rules stay in one place.
84
+ * A valid v1 envelope is returned as-is; `options.moduleUrl` is ignored in that case.
85
+ * Flat props wrap into a v1 envelope only when `options.moduleUrl` is provided.
86
+ */
87
+ export function resolvePageDataDocumentPayload(data, options) {
88
+ if (isEcoPageDataManifestV1(data)) {
89
+ return data;
90
+ }
91
+ const props = { ...data };
92
+ const moduleUrl = options?.moduleUrl;
93
+ if (!moduleUrl) {
94
+ return props;
95
+ }
96
+ return createEcoPageDataManifestV1({ moduleUrl, props });
45
97
  }
46
- export {
47
- ECO_PAGE_DATA_SCHEMA_VERSION,
48
- createEcoPageDataManifestV1,
49
- isEcoPageDataManifestV1,
50
- resolveEcoPageDataModuleUrl,
51
- resolveEcoPageDataProps,
52
- resolvePageDataDocumentPayload
53
- };
@@ -1,29 +1,45 @@
1
- import {
2
- ECO_PAGE_DATA_SCHEMA_VERSION,
3
- resolveEcoPageDataModuleUrl,
4
- resolveEcoPageDataProps
5
- } from "./page-data-manifest.js";
6
- function readPageDataDocument() {
7
- const element = document.getElementById("__ECO_PAGE_DATA__");
8
- if (!element?.textContent) {
9
- return { props: {} };
10
- }
11
- try {
12
- const parsed = JSON.parse(element.textContent);
13
- const moduleUrl = resolveEcoPageDataModuleUrl(parsed) ?? void 0;
14
- return {
15
- ...moduleUrl && { moduleUrl },
16
- props: resolveEcoPageDataProps(parsed)
17
- };
18
- } catch {
19
- return { props: {} };
20
- }
1
+ import { ECO_PAGE_DATA_SCHEMA_VERSION, resolveEcoPageDataModuleUrl, resolveEcoPageDataProps, } from './page-data-manifest.js';
2
+ /**
3
+ * Reads `__ECO_PAGE_DATA__`, supporting both v1 envelopes and legacy flat props.
4
+ *
5
+ * @remarks
6
+ * Always returns unwrapped `props`. `moduleUrl` is set only when the document
7
+ * carries a valid v1 envelope.
8
+ */
9
+ export function readPageDataDocument() {
10
+ const element = document.getElementById('__ECO_PAGE_DATA__');
11
+ if (!element?.textContent) {
12
+ return { props: {} };
13
+ }
14
+ try {
15
+ const parsed = JSON.parse(element.textContent);
16
+ const moduleUrl = resolveEcoPageDataModuleUrl(parsed) ?? undefined;
17
+ return {
18
+ ...(moduleUrl && { moduleUrl }),
19
+ props: resolveEcoPageDataProps(parsed),
20
+ };
21
+ }
22
+ catch {
23
+ return { props: {} };
24
+ }
21
25
  }
22
- function getPageDataFromDocument() {
23
- return readPageDataDocument().props;
26
+ /**
27
+ * Returns page props from `__ECO_PAGE_DATA__` for hydration and HMR handlers.
28
+ */
29
+ export function getPageDataFromDocument() {
30
+ return readPageDataDocument().props;
24
31
  }
25
- function getDevPageDataReaderBootstrapSource() {
26
- return `const readPageDataDocument = () => {
32
+ /**
33
+ * Inlined browser bootstrap for generated hydration scripts.
34
+ *
35
+ * @remarks
36
+ * Hydration and HMR entry modules are evaluated as native browser ESM. Bare
37
+ * package imports such as `@ecopages/react/page-data-reader` are not resolvable
38
+ * there, so the reader algorithm is embedded. Keep this string aligned with
39
+ * {@link readPageDataDocument} / {@link getPageDataFromDocument}.
40
+ */
41
+ export function getDevPageDataReaderBootstrapSource() {
42
+ return `const readPageDataDocument = () => {
27
43
  const el = document.getElementById("__ECO_PAGE_DATA__");
28
44
  if (!el?.textContent) {
29
45
  return { props: {} };
@@ -53,12 +69,9 @@ function getDevPageDataReaderBootstrapSource() {
53
69
  };
54
70
  const getPageData = () => readPageDataDocument().props;`;
55
71
  }
56
- function getProdPageDataReaderBootstrapSource() {
57
- return `const rd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(!e?.textContent)return{props:{}};try{const p=JSON.parse(e.textContent);if(p&&p.schemaVersion===${ECO_PAGE_DATA_SCHEMA_VERSION}&&p.navigationOwner==="react-router"&&typeof p.moduleUrl==="string"&&p.props&&typeof p.props==="object"&&!Array.isArray(p.props))return{moduleUrl:p.moduleUrl,props:p.props};if(p&&typeof p==="object"&&typeof p.schemaVersion==="number")return{props:{}};return{props:p&&typeof p==="object"&&!Array.isArray(p)?p:{}}}catch{return{props:{}}}};const gd=()=>rd().props;`;
72
+ /**
73
+ * Minified equivalent of {@link getDevPageDataReaderBootstrapSource}.
74
+ */
75
+ export function getProdPageDataReaderBootstrapSource() {
76
+ return `const rd=()=>{const e=document.getElementById("__ECO_PAGE_DATA__");if(!e?.textContent)return{props:{}};try{const p=JSON.parse(e.textContent);if(p&&p.schemaVersion===${ECO_PAGE_DATA_SCHEMA_VERSION}&&p.navigationOwner==="react-router"&&typeof p.moduleUrl==="string"&&p.props&&typeof p.props==="object"&&!Array.isArray(p.props))return{moduleUrl:p.moduleUrl,props:p.props};if(p&&typeof p==="object"&&typeof p.schemaVersion==="number")return{props:{}};return{props:p&&typeof p==="object"&&!Array.isArray(p)?p:{}}}catch{return{props:{}}}};const gd=()=>rd().props;`;
58
77
  }
59
- export {
60
- getDevPageDataReaderBootstrapSource,
61
- getPageDataFromDocument,
62
- getProdPageDataReaderBootstrapSource,
63
- readPageDataDocument
64
- };