@ecopages/react 0.2.0-beta.31 → 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,114 +1,156 @@
1
- import { rapidhash } from "@ecopages/core/utils/hash";
2
- const DEFAULT_MAX_ENTRIES = 5e3;
1
+ /**
2
+ * Per-app persistent cache for `client-graph-boundary` plugin transforms.
3
+ *
4
+ * @remarks
5
+ * The plugin's `transformModuleImports` function is the second most
6
+ * expensive operation in the React build path (after `parseSync`).
7
+ * It walks the AST to find reachable exports and prunes forbidden
8
+ * imports. On a no-op rebuild (file unchanged, no plugin signature
9
+ * change) the entire walk can be skipped if the inputs are identical.
10
+ *
11
+ * This cache is owned by the {@link ReactPlugin} for the app's lifetime.
12
+ * It persists across HMR rebuilds but is invalidated per-file when the
13
+ * watcher detects a source change. The `requestedExports` registry
14
+ * remains per-build (it's mutated during cross-file propagation and
15
+ * must not accumulate stale state across builds).
16
+ *
17
+ * The cache is content-hashed (via `rapidhash`) so a `touch`/`utimes`
18
+ * does not invalidate a still-valid entry.
19
+ *
20
+ * **`rulesAdded` semantics:** the map holds the **after-state** of
21
+ * every registry key this transform touched — both newly added keys
22
+ * and keys that were grown (Set union) or promoted to `'*'`. On
23
+ * replay the cache applies each entry via the same merge rules the
24
+ * live transform uses (`mergeRequestedExportRules`), so a key that
25
+ * was already in the live registry when the transform ran and grew
26
+ * during the transform is correctly grown on replay against a fresh
27
+ * registry as well.
28
+ */
29
+ import { rapidhash } from '@ecopages/core/utils/hash';
30
+ const DEFAULT_MAX_ENTRIES = 5_000;
31
+ /**
32
+ * Clone a single rule value: `'*'` is a singleton, Sets get a shallow copy.
33
+ */
3
34
  function cloneRules(rules) {
4
- return rules instanceof Set ? new Set(rules) : rules;
35
+ return rules instanceof Set ? new Set(rules) : rules;
5
36
  }
6
- class ClientGraphBoundaryCache {
7
- entries = /* @__PURE__ */ new Map();
8
- maxEntries;
9
- hits = 0;
10
- misses = 0;
11
- constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
12
- if (maxEntries <= 0) {
13
- throw new Error(`ClientGraphBoundaryCache: maxEntries must be > 0, got ${maxEntries}`);
37
+ /**
38
+ * LRU-bounded cache for client-graph-boundary transform results.
39
+ *
40
+ * One instance is owned by the React plugin for the app's lifetime and
41
+ * shared across all builds. The cache key is `(filePath, source, allowList)`
42
+ * so a file whose source or whose global allow list changes gets a fresh
43
+ * entry, while everything else hits.
44
+ */
45
+ export class ClientGraphBoundaryCache {
46
+ entries = new Map();
47
+ maxEntries;
48
+ hits = 0;
49
+ misses = 0;
50
+ constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
51
+ if (maxEntries <= 0) {
52
+ throw new Error(`ClientGraphBoundaryCache: maxEntries must be > 0, got ${maxEntries}`);
53
+ }
54
+ this.maxEntries = maxEntries;
14
55
  }
15
- this.maxEntries = maxEntries;
16
- }
17
- /**
18
- * Look up a cached transform for `filePath`.
19
- *
20
- * Returns `undefined` if the source or allow list has changed since
21
- * the entry was stored. The caller is responsible for re-running the
22
- * transform in that case and calling `set` to update the entry.
23
- */
24
- get(filePath, source, globallyAllowedSpecifiers) {
25
- const sourceHash = rapidhash(source);
26
- const allowListHash = hashAllowList(globallyAllowedSpecifiers);
27
- const existing = this.entries.get(filePath);
28
- if (existing && existing.sourceHash === sourceHash && existing.allowListHash === allowListHash) {
29
- this.hits += 1;
30
- this.entries.delete(filePath);
31
- this.entries.set(filePath, existing);
32
- return existing;
56
+ /**
57
+ * Look up a cached transform for `filePath`.
58
+ *
59
+ * Returns `undefined` if the source or allow list has changed since
60
+ * the entry was stored. The caller is responsible for re-running the
61
+ * transform in that case and calling `set` to update the entry.
62
+ */
63
+ get(filePath, source, globallyAllowedSpecifiers) {
64
+ const sourceHash = rapidhash(source);
65
+ const allowListHash = hashAllowList(globallyAllowedSpecifiers);
66
+ const existing = this.entries.get(filePath);
67
+ if (existing && existing.sourceHash === sourceHash && existing.allowListHash === allowListHash) {
68
+ this.hits += 1;
69
+ // Refresh LRU position.
70
+ this.entries.delete(filePath);
71
+ this.entries.set(filePath, existing);
72
+ return existing;
73
+ }
74
+ this.misses += 1;
75
+ return undefined;
33
76
  }
34
- this.misses += 1;
35
- return void 0;
36
- }
37
- /**
38
- * Store a transform result.
39
- *
40
- * Evicts the least recently used entry if the cache exceeds its
41
- * capacity. Defensively copies any `Set`-typed rules in `rulesAdded`
42
- * so later mutations to the caller's sets cannot corrupt the cache.
43
- */
44
- set(filePath, source, globallyAllowedSpecifiers, entry) {
45
- const sourceHash = rapidhash(source);
46
- const allowListHash = hashAllowList(globallyAllowedSpecifiers);
47
- const rulesAddedCopy = /* @__PURE__ */ new Map();
48
- for (const [key, rules] of entry.rulesAdded) {
49
- rulesAddedCopy.set(key, cloneRules(rules));
77
+ /**
78
+ * Store a transform result.
79
+ *
80
+ * Evicts the least recently used entry if the cache exceeds its
81
+ * capacity. Defensively copies any `Set`-typed rules in `rulesAdded`
82
+ * so later mutations to the caller's sets cannot corrupt the cache.
83
+ */
84
+ set(filePath, source, globallyAllowedSpecifiers, entry) {
85
+ const sourceHash = rapidhash(source);
86
+ const allowListHash = hashAllowList(globallyAllowedSpecifiers);
87
+ const rulesAddedCopy = new Map();
88
+ for (const [key, rules] of entry.rulesAdded) {
89
+ rulesAddedCopy.set(key, cloneRules(rules));
90
+ }
91
+ const full = {
92
+ sourceHash,
93
+ allowListHash,
94
+ transformed: entry.transformed,
95
+ modified: entry.modified,
96
+ rulesAdded: rulesAddedCopy,
97
+ };
98
+ this.entries.set(filePath, full);
99
+ if (this.entries.size > this.maxEntries) {
100
+ const oldestKey = this.entries.keys().next().value;
101
+ if (oldestKey !== undefined) {
102
+ this.entries.delete(oldestKey);
103
+ }
104
+ }
50
105
  }
51
- const full = {
52
- sourceHash,
53
- allowListHash,
54
- transformed: entry.transformed,
55
- modified: entry.modified,
56
- rulesAdded: rulesAddedCopy
57
- };
58
- this.entries.set(filePath, full);
59
- if (this.entries.size > this.maxEntries) {
60
- const oldestKey = this.entries.keys().next().value;
61
- if (oldestKey !== void 0) {
62
- this.entries.delete(oldestKey);
63
- }
106
+ /**
107
+ * Invalidate a single file's entry. Call this from the file watcher
108
+ * when `filePath`'s content has changed.
109
+ */
110
+ invalidate(filePath) {
111
+ this.entries.delete(filePath);
64
112
  }
65
- }
66
- /**
67
- * Invalidate a single file's entry. Call this from the file watcher
68
- * when `filePath`'s content has changed.
69
- */
70
- invalidate(filePath) {
71
- this.entries.delete(filePath);
72
- }
73
- /**
74
- * Invalidate every file whose key matches a prefix. Useful for
75
- * "anything under `src/pages/` changed" signals.
76
- */
77
- invalidateMatching(predicate) {
78
- let removed = 0;
79
- for (const key of this.entries.keys()) {
80
- if (predicate(key)) {
81
- this.entries.delete(key);
82
- removed += 1;
83
- }
113
+ /**
114
+ * Invalidate every file whose key matches a prefix. Useful for
115
+ * "anything under `src/pages/` changed" signals.
116
+ */
117
+ invalidateMatching(predicate) {
118
+ let removed = 0;
119
+ for (const key of this.entries.keys()) {
120
+ if (predicate(key)) {
121
+ this.entries.delete(key);
122
+ removed += 1;
123
+ }
124
+ }
125
+ return removed;
126
+ }
127
+ /** Clear all entries. */
128
+ clear() {
129
+ this.entries.clear();
130
+ this.hits = 0;
131
+ this.misses = 0;
132
+ }
133
+ /** Current cache size. */
134
+ get size() {
135
+ return this.entries.size;
136
+ }
137
+ /** Hit/miss counters for observability. */
138
+ stats() {
139
+ const total = this.hits + this.misses;
140
+ return {
141
+ hits: this.hits,
142
+ misses: this.misses,
143
+ size: this.entries.size,
144
+ hitRate: total === 0 ? 0 : this.hits / total,
145
+ };
84
146
  }
85
- return removed;
86
- }
87
- /** Clear all entries. */
88
- clear() {
89
- this.entries.clear();
90
- this.hits = 0;
91
- this.misses = 0;
92
- }
93
- /** Current cache size. */
94
- get size() {
95
- return this.entries.size;
96
- }
97
- /** Hit/miss counters for observability. */
98
- stats() {
99
- const total = this.hits + this.misses;
100
- return {
101
- hits: this.hits,
102
- misses: this.misses,
103
- size: this.entries.size,
104
- hitRate: total === 0 ? 0 : this.hits / total
105
- };
106
- }
107
147
  }
148
+ /**
149
+ * Hash a list of globally-allowed specifiers. The order of iteration
150
+ * must be stable for the hash to be deterministic; we sort before
151
+ * hashing.
152
+ */
108
153
  function hashAllowList(specifiers) {
109
- const sorted = Array.from(specifiers).sort();
110
- return rapidhash(sorted.join("\n"));
154
+ const sorted = Array.from(specifiers).sort();
155
+ return rapidhash(sorted.join('\n'));
111
156
  }
112
- export {
113
- ClientGraphBoundaryCache
114
- };
@@ -1,107 +1,125 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { dirname, extname, resolve } from "node:path";
3
- import { ClientGraphBoundaryCache } from "./boundary-cache.js";
4
- import {
5
- parseDeclaredModules,
6
- toModuleBaseSpecifier,
7
- mergeRequestedExportRules,
8
- snapshotRegistry,
9
- diffRequestedExportRules
10
- } from "./specifier-classification.js";
11
- import { transformModuleImports } from "./ast-transform.js";
1
+ /**
2
+ * @module ClientGraphBoundaryPlugin
3
+ *
4
+ * Build plugin securing the Ecopages isomorphic compilation pipeline.
5
+ */
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { dirname, extname, resolve } from 'node:path';
8
+ import { ClientGraphBoundaryCache } from './boundary-cache.js';
9
+ import { parseDeclaredModules, toModuleBaseSpecifier, mergeRequestedExportRules, snapshotRegistry, diffRequestedExportRules, } from './specifier-classification.js';
10
+ import { transformModuleImports } from './ast-transform.js';
12
11
  const SOURCE_FILE_FILTER = /\.(tsx?|jsx?)$/;
13
- function createClientGraphBoundaryPlugin(options) {
14
- return {
15
- name: "ecopages-client-graph-boundary",
16
- setup(build) {
17
- const absWorkingDir = options?.absWorkingDir ?? process.cwd();
18
- const cache = options?.cache;
19
- const globallyDeclaredSources = parseDeclaredModules(options?.declaredModules);
20
- const requestedExports = /* @__PURE__ */ new Map();
21
- for (const alwaysAllow of options?.alwaysAllowSpecifiers ?? []) {
22
- globallyDeclaredSources.set(toModuleBaseSpecifier(alwaysAllow), "*");
23
- }
24
- const allowListForCache = Array.from(globallyDeclaredSources.keys()).sort();
25
- build.onLoad({ filter: SOURCE_FILE_FILTER }, (args) => {
26
- let source;
27
- try {
28
- source = readFileSync(args.path, "utf-8");
29
- } catch {
30
- return void 0;
31
- }
32
- if (cache) {
33
- const cached = cache.get(args.path, source, allowListForCache);
34
- if (cached) {
35
- for (const [moduleKey, rules] of cached.rulesAdded) {
36
- mergeRequestedExportRules(requestedExports, moduleKey, rules);
12
+ /**
13
+ * Instantiates the client graph boundary build plugin.
14
+ *
15
+ * @param options - Configuration options for the graph boundary.
16
+ * @returns The resulting `EcoBuildPlugin`.
17
+ */
18
+ export function createClientGraphBoundaryPlugin(options) {
19
+ return {
20
+ name: 'ecopages-client-graph-boundary',
21
+ setup(build) {
22
+ const absWorkingDir = options?.absWorkingDir ?? process.cwd();
23
+ const cache = options?.cache;
24
+ const globallyDeclaredSources = parseDeclaredModules(options?.declaredModules);
25
+ const requestedExports = new Map();
26
+ for (const alwaysAllow of options?.alwaysAllowSpecifiers ?? []) {
27
+ globallyDeclaredSources.set(toModuleBaseSpecifier(alwaysAllow), '*');
37
28
  }
38
- if (!cached.modified) return void 0;
39
- const ext2 = extname(args.path).slice(1);
40
- return { contents: cached.transformed, loader: ext2, resolveDir: dirname(args.path) };
41
- }
42
- }
43
- let transformed = source;
44
- let modified = false;
45
- if (source.includes("readFileSync")) {
46
- const readFileTransformed = transformed.replace(
47
- /\bfs\.readFileSync\s*\(\s*path\.resolve\s*\(\s*(['"`])([^'"`\n]+)\1\s*\)\s*,\s*['"`]utf-?8['"`]\s*\)/g,
48
- (_match, _q, relPath) => {
49
- modified = true;
50
- try {
51
- const sourceDir = dirname(args.path);
52
- const srcDirIndex = args.path.lastIndexOf("/src/");
53
- const inferredProjectRoot = srcDirIndex >= 0 ? args.path.slice(0, srcDirIndex) : void 0;
54
- const candidates = [
55
- resolve(absWorkingDir, relPath),
56
- resolve(process.cwd(), relPath),
57
- resolve(sourceDir, relPath),
58
- ...inferredProjectRoot ? [resolve(inferredProjectRoot, relPath)] : []
59
- ];
60
- const absolutePath = candidates.find((candidate) => existsSync(candidate));
61
- if (!absolutePath) return '""';
62
- const content = readFileSync(absolutePath, "utf-8");
63
- return JSON.stringify(content);
64
- } catch {
65
- return '""';
66
- }
67
- }
68
- );
69
- transformed = readFileTransformed;
70
- }
71
- const registryBefore = snapshotRegistry(requestedExports);
72
- const { transformed: oxcTransformed, modified: importsModified } = transformModuleImports(
73
- transformed,
74
- args.path,
75
- globallyDeclaredSources,
76
- requestedExports,
77
- options?.projectRoot
78
- );
79
- if (importsModified) {
80
- modified = true;
81
- transformed = oxcTransformed;
82
- }
83
- if (cache) {
84
- const rulesAdded = /* @__PURE__ */ new Map();
85
- for (const [key, afterRules] of requestedExports) {
86
- const beforeRules = registryBefore.get(key);
87
- const diff = diffRequestedExportRules(beforeRules, afterRules);
88
- if (!diff) continue;
89
- rulesAdded.set(key, diff);
90
- }
91
- const entry = {
92
- transformed,
93
- modified,
94
- rulesAdded
95
- };
96
- cache.set(args.path, source, allowListForCache, entry);
97
- }
98
- if (!modified) return void 0;
99
- const ext = extname(args.path).slice(1);
100
- return { contents: transformed, loader: ext, resolveDir: dirname(args.path) };
101
- });
102
- }
103
- };
29
+ /**
30
+ * Stable list of globally-allowed specifiers, used as part of
31
+ * the cache key. Sorted on construction so iteration order is
32
+ * deterministic for hashing.
33
+ */
34
+ const allowListForCache = Array.from(globallyDeclaredSources.keys()).sort();
35
+ build.onLoad({ filter: SOURCE_FILE_FILTER }, (args) => {
36
+ let source;
37
+ try {
38
+ source = readFileSync(args.path, 'utf-8');
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ /**
44
+ * Fast path: if the cache has a transform result for this
45
+ * exact (filePath, source, allowList) tuple, replay the
46
+ * captured `rulesAdded` into the live registry and return
47
+ * the cached transformed source. Skips the entire
48
+ * `parseSync` + AST walk on a no-op rebuild.
49
+ */
50
+ if (cache) {
51
+ const cached = cache.get(args.path, source, allowListForCache);
52
+ if (cached) {
53
+ for (const [moduleKey, rules] of cached.rulesAdded) {
54
+ mergeRequestedExportRules(requestedExports, moduleKey, rules);
55
+ }
56
+ if (!cached.modified)
57
+ return undefined;
58
+ const ext = extname(args.path).slice(1);
59
+ return { contents: cached.transformed, loader: ext, resolveDir: dirname(args.path) };
60
+ }
61
+ }
62
+ let transformed = source;
63
+ let modified = false;
64
+ if (source.includes('readFileSync')) {
65
+ const readFileTransformed = transformed.replace(/\bfs\.readFileSync\s*\(\s*path\.resolve\s*\(\s*(['"`])([^'"`\n]+)\1\s*\)\s*,\s*['"`]utf-?8['"`]\s*\)/g, (_match, _q, relPath) => {
66
+ modified = true;
67
+ try {
68
+ const sourceDir = dirname(args.path);
69
+ const srcDirIndex = args.path.lastIndexOf('/src/');
70
+ const inferredProjectRoot = srcDirIndex >= 0 ? args.path.slice(0, srcDirIndex) : undefined;
71
+ const candidates = [
72
+ resolve(absWorkingDir, relPath),
73
+ resolve(process.cwd(), relPath),
74
+ resolve(sourceDir, relPath),
75
+ ...(inferredProjectRoot ? [resolve(inferredProjectRoot, relPath)] : []),
76
+ ];
77
+ const absolutePath = candidates.find((candidate) => existsSync(candidate));
78
+ if (!absolutePath)
79
+ return '""';
80
+ const content = readFileSync(absolutePath, 'utf-8');
81
+ return JSON.stringify(content);
82
+ }
83
+ catch {
84
+ return '""';
85
+ }
86
+ });
87
+ transformed = readFileTransformed;
88
+ }
89
+ // Snapshot the live registry so we can diff per-key after
90
+ // the transform. We must capture the **after-state** of
91
+ // every key the transform touched — including keys that
92
+ // already existed and grew via Set union or were promoted
93
+ // to `'*'`. A snapshot keyed only on newly-added entries
94
+ // would under-populate the registry on cache hit.
95
+ const registryBefore = snapshotRegistry(requestedExports);
96
+ const { transformed: oxcTransformed, modified: importsModified } = transformModuleImports(transformed, args.path, globallyDeclaredSources, requestedExports, options?.projectRoot);
97
+ if (importsModified) {
98
+ modified = true;
99
+ transformed = oxcTransformed;
100
+ }
101
+ // Build the rulesAdded diff for cache storage.
102
+ if (cache) {
103
+ const rulesAdded = new Map();
104
+ for (const [key, afterRules] of requestedExports) {
105
+ const beforeRules = registryBefore.get(key);
106
+ const diff = diffRequestedExportRules(beforeRules, afterRules);
107
+ if (!diff)
108
+ continue;
109
+ rulesAdded.set(key, diff);
110
+ }
111
+ const entry = {
112
+ transformed,
113
+ modified,
114
+ rulesAdded,
115
+ };
116
+ cache.set(args.path, source, allowListForCache, entry);
117
+ }
118
+ if (!modified)
119
+ return undefined;
120
+ const ext = extname(args.path).slice(1);
121
+ return { contents: transformed, loader: ext, resolveDir: dirname(args.path) };
122
+ });
123
+ },
124
+ };
104
125
  }
105
- export {
106
- createClientGraphBoundaryPlugin
107
- };
@@ -1,56 +1,77 @@
1
- function walkConfigTree(config, visitor, visited = /* @__PURE__ */ new Set()) {
2
- if (!config || visited.has(config)) {
3
- return;
4
- }
5
- visited.add(config);
6
- visitor(config);
7
- for (const layout of config.layouts ?? []) {
8
- if (layout?.config) {
9
- walkConfigTree(layout.config, visitor, visited);
1
+ /**
2
+ * Walks a component config tree once, including nested layout configs and
3
+ * dependency component configs.
4
+ *
5
+ * The shared React integration code performs several different analyses over the
6
+ * same config graph. Centralizing the traversal keeps cycle handling and graph
7
+ * shape assumptions in one place instead of repeating them in the renderer and
8
+ * services.
9
+ */
10
+ export function walkConfigTree(config, visitor, visited = new Set()) {
11
+ if (!config || visited.has(config)) {
12
+ return;
13
+ }
14
+ visited.add(config);
15
+ visitor(config);
16
+ for (const layout of config.layouts ?? []) {
17
+ if (layout?.config) {
18
+ walkConfigTree(layout.config, visitor, visited);
19
+ }
20
+ }
21
+ for (const component of config.dependencies?.components ?? []) {
22
+ walkConfigTree(component.config, visitor, visited);
10
23
  }
11
- }
12
- for (const component of config.dependencies?.components ?? []) {
13
- walkConfigTree(component.config, visitor, visited);
14
- }
15
24
  }
16
- function walkConfigForest(configs, visitor) {
17
- const visited = /* @__PURE__ */ new Set();
18
- for (const config of configs) {
19
- walkConfigTree(config, visitor, visited);
20
- }
25
+ /**
26
+ * Walks a forest of root component configs using one shared visited set.
27
+ *
28
+ * This is useful when a page contributes multiple config roots, such as a page
29
+ * config plus a resolved layout config, and duplicate nested nodes should still
30
+ * be processed only once.
31
+ */
32
+ export function walkConfigForest(configs, visitor) {
33
+ const visited = new Set();
34
+ for (const config of configs) {
35
+ walkConfigTree(config, visitor, visited);
36
+ }
21
37
  }
22
- function collectFromConfigTree(config, collector) {
23
- const values = [];
24
- walkConfigTree(config, (node) => {
25
- values.push(...collector(node));
26
- });
27
- return values;
38
+ /**
39
+ * Collects values from a config tree while preserving the shared traversal and
40
+ * cycle protection behavior used across the React integration.
41
+ */
42
+ export function collectFromConfigTree(config, collector) {
43
+ const values = [];
44
+ walkConfigTree(config, (node) => {
45
+ values.push(...collector(node));
46
+ });
47
+ return values;
28
48
  }
29
- function collectFromConfigForest(configs, collector) {
30
- const values = [];
31
- walkConfigForest(configs, (node) => {
32
- values.push(...collector(node));
33
- });
34
- return values;
49
+ /**
50
+ * Collects values from multiple config roots with one shared visited set.
51
+ */
52
+ export function collectFromConfigForest(configs, collector) {
53
+ const values = [];
54
+ walkConfigForest(configs, (node) => {
55
+ values.push(...collector(node));
56
+ });
57
+ return values;
35
58
  }
36
- function someInConfigTree(config, predicate) {
37
- let matched = false;
38
- walkConfigTree(config, (node) => {
39
- if (matched) {
40
- return;
41
- }
42
- matched = predicate(node);
43
- });
44
- return matched;
59
+ /**
60
+ * Returns true when any node in the config tree matches the predicate.
61
+ */
62
+ export function someInConfigTree(config, predicate) {
63
+ let matched = false;
64
+ walkConfigTree(config, (node) => {
65
+ if (matched) {
66
+ return;
67
+ }
68
+ matched = predicate(node);
69
+ });
70
+ return matched;
45
71
  }
46
- function getComponentConfigs(components) {
47
- return components.map((component) => component.config);
72
+ /**
73
+ * Reads config roots from partial components while tolerating undefined config.
74
+ */
75
+ export function getComponentConfigs(components) {
76
+ return components.map((component) => component.config);
48
77
  }
49
- export {
50
- collectFromConfigForest,
51
- collectFromConfigTree,
52
- getComponentConfigs,
53
- someInConfigTree,
54
- walkConfigForest,
55
- walkConfigTree
56
- };