@kudzujs/core 0.8.37 → 0.8.38

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  This document is the source of truth for Kudzu's product direction, architecture invariants, and future development order. Read it before extending React-shaped syntax or browser capabilities.
4
4
 
5
- The executable post-`0.8.37` compiler and large-application sequence is maintained in [`docs/next-architecture/large-application-ai-native-roadmap.md`](./docs/next-architecture/large-application-ai-native-roadmap.md). Follow its PR dependencies for implementation work; this document remains authoritative when selecting or accepting a migration capability.
5
+ The executable post-`0.8.38` compiler and large-application sequence is maintained in [`docs/next-architecture/large-application-ai-native-roadmap.md`](./docs/next-architecture/large-application-ai-native-roadmap.md). Follow its PR dependencies for implementation work; this document remains authoritative when selecting or accepting a migration capability.
6
6
 
7
7
  [`GOAL_A.md`](./GOAL_A.md) and [`GOAL_B.md`](./GOAL_B.md) are completed capability-validation records. Their commerce and realtime dashboard fixtures prove general lifecycle, navigation, async-workflow, and Worker capabilities; they are not separate product verticals or future priority lists.
8
8
 
package/PERFORMANCE.md CHANGED
@@ -2,6 +2,31 @@
2
2
 
3
3
  Reproducibility classes: `npm run benchmark`, `npm run benchmark:keyed`, `npm run benchmark:native`, and `npm run benchmark:module-cache` are maintained in this repository; `npm run benchmark:commerce` is a maintained paired runner over the public external storefront; older excluded-workspace sections are historical provenance only and are not current framework rankings.
4
4
 
5
+ ## P0.11 Structural Route Artifact Graph
6
+
7
+ Measured UTC 2026-08-11 on the Intel Core i5-9500 Linux x64 host with 6 physical cores, Node 24.14.0, and npm 11.9.0. The baseline was clean tag `v0.8.37` at `8b4e8850c40f2856216e43f23ad02ada8434eb37`. The focused implementation files had SHA-256 `1a93b7fff5d80f271c588f89486a47dc262427195a6a768fe392be949eb99b5e`, produced by:
8
+
9
+ ```bash
10
+ sha256sum framework/build.mjs framework/compiler/route-build-record.mjs framework/compiler/route-capability-planner.mjs framework/core.mjs framework/core.d.ts test/compiler-passes.test.mjs | sha256sum
11
+ ```
12
+
13
+ The repository's 152-page build used one warm-up and seven alternating clean fresh-process samples. Every sample produced the same 173-file deploy graph, 3,835,970 raw bytes, 1,979,875 aggregate gzip bytes, and SHA-256 `c1f95f25d43589b61d1abe7ecf256e5b5e9dddd5647fbcf6368c08cc5ae3ee20`. Baseline and candidate `kudzu-plan.json` files are byte-identical.
14
+
15
+ | Target | Clean build median | Range | Peak RSS median | Deploy bytes |
16
+ |---|---:|---:|---:|---:|
17
+ | `v0.8.37` | 1,820.186 ms | 1,769.592-1,910.670 ms | 351.6 MiB | 3,835,970 B |
18
+ | P0.11 candidate | 1,804.568 ms | 1,756.849-1,843.941 ms | 351.4 MiB | 3,835,970 B |
19
+
20
+ The candidate's unpaired median is 0.86% lower. Round-paired candidate-minus-baseline differences had a -20.933 ms median, with the candidate faster in five of seven pairs and the baseline faster in two. Timing ranges overlap, so no material improvement is claimed; peak-RSS medians differ by 0.3 MiB.
21
+
22
+ ```text
23
+ v0.8.37: [1786.548,1834.792,1910.670,1853.493,1820.186,1769.592,1778.201]
24
+ candidate: [1756.849,1804.568,1843.941,1832.560,1811.390,1798.756,1782.132]
25
+ paired candidate-baseline: [-29.698,-30.225,-66.729,-20.933,-8.796,29.164,3.930]
26
+ ```
27
+
28
+ RouteBuildRecord now owns each rendered route's RouteIR, capabilities, entry paths, styles, and exact handler/effect edges. Handler, Worker, package-client, and chunk closure starts from those structural edges instead of serialized HTML/plan searches or formatted effect keys. This changes build-scratch orchestration only; browser runtime source, RouteIR v1, CapabilityIR v1, emitted files, and deploy bytes remain unchanged.
29
+
5
30
  ## P0.10 Structural ModuleIR References
6
31
 
7
32
  Measured UTC 2026-08-11 on an Apple M4 macOS arm64 host with 10 logical CPUs, 16 GiB RAM, Node 24.14.0, and npm 11.9.0. The baseline was clean tag `v0.8.36` at `268cd9023c9f47a912601f298963a9ffe9c00da2`. The compiler and focused-check patch had SHA-256 `f684c79027b290bc8c7d549667ef0d7f21a9d0057b5d6291fcce18b91947eff2`, produced by:
package/README.md CHANGED
@@ -14,7 +14,7 @@ Kudzu compiles ordinary React-shaped TypeScript and TSX into complete static HTM
14
14
 
15
15
  > Experimental `0.8.x`: the compiler API and supported TSX surface may change.
16
16
 
17
- **Latest release: 0.8.37 - Structural ModuleIR references.** Compiler ownership and dependency edges now use validated source-local slots and stable symbols instead of formatted names. Read the [release notes](./RELEASES.md#0837---structural-moduleir-references), open the [release page](https://github.com/kudzujs/kudzu/releases/tag/v0.8.37), or follow the [architecture packet](./docs/next-architecture/README.md).
17
+ **Latest release: 0.8.38 - Structural route artifacts.** Handler, effect, Worker, CSS, package-client, and chunk retention now follows validated per-route artifact edges instead of serialized output searches. Read the [release notes](./RELEASES.md#0838---structural-route-artifacts), open the [release page](https://github.com/kudzujs/kudzu/releases/tag/v0.8.38), or follow the [architecture packet](./docs/next-architecture/README.md).
18
18
 
19
19
  - [Documentation](https://kudzujs.cloud/docs)
20
20
  - [Installation guide](https://kudzujs.cloud/docs#install)
package/RELEASES.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # Kudzu Releases
2
2
 
3
+ ## 0.8.38 - Structural route artifacts
4
+
5
+ Kudzu 0.8.38 completes P0.11 by replacing serialized route-output searches and parallel route facts with one validated RouteBuildRecord artifact graph.
6
+
7
+ ### Changed in 0.8.38
8
+
9
+ - Each emitted route records its RouteIR, capability facts, route-entry paths, styles, and exact handler/effect references.
10
+ - Final event, effect, binding, conditional, and keyed-list descriptors retain handler references only when they are rendered.
11
+ - Handler modules resolve by exact module URL, and Worker references resolve by structural module/handler pairs instead of formatted keys.
12
+ - CSS output, package-client compilation, and bundle entry/chunk closure derive from retained route edges.
13
+ - CapabilityIR now folds RouteBuildRecord values directly; serialized HTML/plan `includes()` searches and parallel route capability/entry arrays are removed.
14
+
15
+ ### Performance
16
+
17
+ - Seven alternating clean 152-page builds measured `v0.8.37` and candidate medians of 1,820.186 ms and 1,804.568 ms. The -20.933 ms paired median and overlapping ranges establish no material speedup or regression.
18
+ - Peak RSS medians were 351.6 MiB and 351.4 MiB.
19
+ - Both targets emit the same 173 files, 3,835,970 raw bytes, 1,979,875 aggregate gzip bytes, deploy digest, and byte-identical `kudzu-plan.json`.
20
+
21
+ ### Validation
22
+
23
+ - `npm run check`, `npm test`, and `npm run test:package` pass with all 200 tests and 153 generated pages.
24
+ - Focused checks reject unsupported versions, malformed and duplicate references, missing handler modules, inconsistent route entries, and invalid JSON round trips.
25
+ - Existing static, command, binding, keyed, effect, Worker, package-import, navigation, and migration fixtures retain their browser behavior and zero-unused-runtime checks.
26
+ - P0.12 deep RouteIR and CapabilityIR validation is next.
27
+
28
+ ### Upgrade
29
+
30
+ ```bash
31
+ npm install @kudzujs/core@^0.8.38
32
+ ```
33
+
3
34
  ## 0.8.37 - Structural ModuleIR references
4
35
 
5
36
  Kudzu 0.8.37 completes P0.10 by replacing mixed state names, export strings, formatted owner keys, and partial slots with one validated structural reference graph.
@@ -11,7 +11,7 @@ The top-level [`GOAL_A.md`](../../GOAL_A.md) and [`GOAL_B.md`](../../GOAL_B.md)
11
11
  | C: state/resource model | Research only | Reduced fixtures expose a limitation |
12
12
  | D: routing compatibility | Current behavior preserved | Revisit only with migration evidence and invariant review |
13
13
 
14
- The active post-`0.8.37` implementation sequence is [`large-application-ai-native-roadmap.md`](./large-application-ai-native-roadmap.md). P0.10 ModuleIR reference unification is complete; P0.11 explicit route artifact graph is next. The plan orders compiler semantic generalization, large-application foundations, compatibility boundaries, AI tooling, and production validation without changing the invariants below.
14
+ The active post-`0.8.38` implementation sequence is [`large-application-ai-native-roadmap.md`](./large-application-ai-native-roadmap.md). P0.11 explicit route artifact graph is complete; P0.12 deep RouteIR and CapabilityIR validation is next. The plan orders compiler semantic generalization, large-application foundations, compatibility boundaries, AI tooling, and production validation without changing the invariants below.
15
15
 
16
16
  ## Required Invariants
17
17
 
@@ -1,6 +1,6 @@
1
1
  # Current Compiler Architecture
2
2
 
3
- This maps the current `0.8.37` architecture, built on the completed `0.8.23` Goal A compiler foundation. File and function names are the stable references; line numbers are intentionally omitted because later work may still move code.
3
+ This maps the current `0.8.38` architecture, built on the completed `0.8.23` Goal A compiler foundation. File and function names are the stable references; line numbers are intentionally omitted because later work may still move code.
4
4
 
5
5
  ## Responsibility Map
6
6
 
@@ -9,7 +9,7 @@ This maps the current `0.8.37` architecture, built on the completed `0.8.23` Goa
9
9
  | CLI entry | [`bin/kudzu.mjs`](../../bin/kudzu.mjs) | Dispatches build and development commands. |
10
10
  | Project session | [`framework/compiler/project-session.mjs`](../../framework/compiler/project-session.mjs), `createProjectSession()` | Owns one absolute root, standard project paths, source records, bound graph operations, and Worker compiler for a build. Omitted roots resolve from call-time CWD. |
11
11
  | Parsed module cache and symbols | [`framework/compiler/project-session.mjs`](../../framework/compiler/project-session.mjs) | Parses each unchanged source module once per ProjectSession and records source-local declaration/import/re-export sites. Stable ModuleSymbol records resolve direct, aliased, barrel, and `export *` exports with cycle and ambiguity checks; repeated resolutions are cached against their source dependencies, and normalization consumers locate the resolved SiteId in a fresh clone with independent parent links. |
12
- | Build orchestration | [`framework/build.mjs`](../../framework/build.mjs), `build()` | Coordinates config, discovery, source compilation, RouteIR rendering, CapabilityIR projection, generator invocation, artifact emission, and `afterBuild`. |
12
+ | Build orchestration | [`framework/build.mjs`](../../framework/build.mjs), `build()` | Coordinates config, discovery, source compilation, RouteBuildRecord collection, CapabilityIR projection, generator invocation, artifact emission, and `afterBuild`. |
13
13
  | Reachability/import resolution | [`framework/compiler/source-compiler.mjs`](../../framework/compiler/source-compiler.mjs), `reachableSourceFiles()`; [`framework/compiler/source-graph.mjs`](../../framework/compiler/source-graph.mjs), `ordinaryRuntimeDependencies()`, `resolveSourceImport()` | Starts from page entries, follows relative runtime imports/re-exports and validated Worker references, excludes unreachable migration source, and fails unresolved ordinary edges or dynamic imports at the importer source location before code generation. |
14
14
  | Ordered normalization | [`framework/compiler/normalization-pipeline.mjs`](../../framework/compiler/normalization-pipeline.mjs), `applyNormalizationPasses()`; [`framework/compiler/source-compiler.mjs`](../../framework/compiler/source-compiler.mjs), `normalizeCompilerSource()` | Applies migration/resource passes in order and repairs TypeScript parent pointers after every structural change. Imported source uses the same pipeline. |
15
15
  | Focused normalization passes | [`framework/compiler/`](../../framework/compiler/) | React, Router, browser signals, animation-frame refs, custom-hook timers, Zustand, and render control each validate and lower a narrow source shape. |
@@ -19,6 +19,7 @@ This maps the current `0.8.37` architecture, built on the completed `0.8.23` Goa
19
19
  | Main semantic analysis | [`framework/compiler/source-compiler.mjs`](../../framework/compiler/source-compiler.mjs), `createKudzuTransformer()` | Produces transformed source plus explicit component, handler, binding, derived, keyed, and effect ownership results. |
20
20
  | Component ownership analysis | [`framework/compiler/analysis/component-analysis.mjs`](../../framework/compiler/analysis/component-analysis.mjs) | Produces ComponentAnalysis v2 with ordered JSON-safe owner and specialization slots for state, setters, props, refs, IDs, direct SignalIR links, structural OwnerRefs, source-local SiteIds, and source provenance; AST identity remains private to its source-local session. |
21
21
  | Per-source descriptor registration | [`framework/compiler/descriptor-session.mjs`](../../framework/compiler/descriptor-session.mjs), `createSemanticArtifact()`, `createDescriptorSession()` | Keeps AST descriptors private during analysis, then finalizes ModuleIR v2 with deterministic SymbolRef, SignalIR, HandlerIR, BindingIR, DerivedIR, EffectIR, KeyedBlockIR, and ImportIR slots. One fail-closed boundary validates every source-local and component ownership edge before build-module generation. |
22
+ | Route artifact graph | [`framework/compiler/route-build-record.mjs`](../../framework/compiler/route-build-record.mjs), `createRouteBuildRecord()`, `planRouteArtifacts()` | Validates each rendered route's RouteIR, capabilities, entry paths, styles, and exact handler/effect references. Handler modules, Workers, package-client modules, and bundle entry/chunk closure derive from structural edges without serialized output searches or formatted composite keys. |
22
23
  | Command IR and codegen | [`framework/compiler/optimize/command-specialization.mjs`](../../framework/compiler/optimize/command-specialization.mjs), [`framework/compiler/ir/module-ir.mjs`](../../framework/compiler/ir/module-ir.mjs), [`framework/compiler/codegen/command-codegen.mjs`](../../framework/compiler/codegen/command-codegen.mjs) | Direct commands use the existing fast path; proven immutable state aliases and one-call local helpers specialize to the same JSON-safe command ModuleIR. Recursion, escape, mutation, and dynamic helper dispatch fail explicitly, while unrelated handlers retain native ESM. Codegen emits the existing `__kBehavior` AST and command ABI. |
23
24
  | Source compilation | [`framework/compiler/source-compiler.mjs`](../../framework/compiler/source-compiler.mjs), `compileSource()` | Runs TypeScript with the Kudzu transformer, rejects surviving React/Router references, and returns a JSON-safe project-relative build module, component analysis, ModuleIR, optional handler module, and imported assets without filesystem writes. |
24
25
  | Handler/evaluator lowering | [`framework/compiler/handler-lowering.mjs`](../../framework/compiler/handler-lowering.mjs) | Completes source-local callback/binding/list AST rewriting and diagnostics before the JSON-safe IR boundary. |
@@ -26,11 +27,11 @@ This maps the current `0.8.37` architecture, built on the completed `0.8.23` Goa
26
27
  | Effect analysis | [`framework/compiler/effect-analysis.mjs`](../../framework/compiler/effect-analysis.mjs) | Classifies ordered signal, derived, and keyed-item dependencies and validates cleanup-owned browser resources before EffectIR registration. |
27
28
  | Worker graph | [`framework/compiler/worker-compiler.mjs`](../../framework/compiler/worker-compiler.mjs) | Returns functional Worker rewrite results and JSON-safe EffectIR edges, validates relative graphs, emits content-hashed ESM, and resolves placeholders only for rendered effects. |
28
29
  | Shared path conversion | [`framework/compiler/path-helpers.mjs`](../../framework/compiler/path-helpers.mjs) | Converts project-relative module, browser, asset, and base paths for build and development serving. |
29
- | Build-time JSX execution | [`framework/core.mjs`](../../framework/core.mjs), `renderPage()` | Executes compiled pages/layouts, allocates deterministic route/layout ownership IDs, emits complete HTML, and returns RouteIR v1 plus capability facts. |
30
- | Route capability projection | [`framework/compiler/route-capability-planner.mjs`](../../framework/compiler/route-capability-planner.mjs), `planRouteCapabilities()` | Validates RouteIR v1 and purely folds rendered plans and route facts into CapabilityIR v1. |
30
+ | Build-time JSX execution | [`framework/core.mjs`](../../framework/core.mjs), `renderPage()` | Executes compiled pages/layouts, allocates deterministic route/layout ownership IDs, emits complete HTML, and returns RouteIR v1 plus capability facts and exact retained handler references. |
31
+ | Route capability projection | [`framework/compiler/route-capability-planner.mjs`](../../framework/compiler/route-capability-planner.mjs), `planRouteCapabilities()` | Validates RouteBuildRecord and RouteIR v1, then purely folds their plans and capability facts into CapabilityIR v1. |
31
32
  | Effect entry generation | [`framework/compiler/effect-codegen.mjs`](../../framework/compiler/effect-codegen.mjs) | Generates ordinary, dependency, owned, and navigable effect entries from rendered descriptors. |
32
33
  | Runtime generation | [`framework/compiler/runtime-codegen.mjs`](../../framework/compiler/runtime-codegen.mjs), [`framework/compiler/list-runtime-codegen.mjs`](../../framework/compiler/list-runtime-codegen.mjs), [`framework/compiler/param-codegen.mjs`](../../framework/compiler/param-codegen.mjs) | Consumes versioned contracts, specializes authored capability sources with fail-closed anchors, and returns source/define results without filesystem ownership. |
33
- | Artifact emission | `framework/build.mjs` | Selects required files from CapabilityIR, writes route HTML in bounded batches, writes and bundles the complete generation in a project-local staging sibling, copies public subtrees without replacing generated paths, runs `afterBuild`, then promotes with rollback so failed builds preserve the prior `dist`. Byte-identical native, parameter, and effect route entries reuse one exact-source transform result within the current build only. |
34
+ | Artifact emission | `framework/build.mjs` | Selects route artifacts from RouteBuildRecord edges and shared runtimes from CapabilityIR, writes route HTML in bounded batches, writes and bundles the complete generation in a project-local staging sibling, copies public subtrees without replacing generated paths, runs `afterBuild`, then promotes with rollback so failed builds preserve the prior `dist`. Byte-identical native, parameter, and effect route entries reuse one exact-source transform result within the current build only. |
34
35
  | Browser capabilities | [`framework/*.js`](../../framework/) | Small optional modules for commands, bindings, lists, effects, native handlers, serialization, parameters, and navigation; native contexts invalidate writes and refs at DOM ownership release, with no component runtime. |
35
36
  | Opt-in navigation | [`framework/navigation-runtime.js`](../../framework/navigation-runtime.js) plus `framework/build.mjs` navigation configuration/emission | Fetches and validates complete same-origin documents, replaces only the marked route range, manages route/layout disposal, history, focus, finite prefetch retention, and native fallback. |
36
37
  | Development serving | [`framework/dev-server.mjs`](../../framework/dev-server.mjs) and [`framework/dev-state.js`](../../framework/dev-state.js) | Rebuild/watch/SSE and response-only short-lived state restoration; failed rebuilds show the existing error overlay while preserving the previous on-disk output. |
@@ -50,10 +51,11 @@ src/pages entries + config
50
51
  -> build orchestration writes .kudzu executable and handler modules
51
52
  -> import page modules and execute renderPage()
52
53
  -> complete HTML
53
- -> RouteIR v1
54
- -> referenced handler URLs and route facts
54
+ -> RouteIR v1 and exact handler references
55
+ -> validated RouteBuildRecord per emitted route
56
+ -> capability facts, route entries, styles, handler/effect artifact edges
55
57
  -> remove unrendered handlers/effects/Workers
56
- -> planRouteCapabilities(RouteIR records, route facts)
58
+ -> planRouteCapabilities(RouteBuildRecord[])
57
59
  -> CapabilityIR v1
58
60
  -> specialize and emit only selected runtime/capability ESM
59
61
  -> reuse exact generated route-entry transforms within this build
@@ -69,7 +71,7 @@ The browser consumes static HTML first. State seeds and descriptors in that HTML
69
71
 
70
72
  - `createKudzuTransformer()` remains one large source-local analysis unit combining validation, specialization, descriptor registration, and transformed-source emission.
71
73
  - Transient component rewrite indexes remain source-local AST indexes; finalized handler, binding, derived, keyed, effect, signal, import, and component ownership edges use explicit JSON-safe slots or stable symbols.
72
- - `build()` still owns explicit artifact selection and filesystem writes after generator results are produced.
74
+ - `build()` still owns filesystem writes after structural route artifact selection and generator results are produced.
73
75
  - Runtime generators intentionally specialize readable authored sources through exact anchors; every required anchor fails closed, but a future generator format may remove this transitional dependency.
74
76
  - Source reachability and source compilation remain in one session-bound compiler factory because both consume the same normalization and import graph contracts. ModuleSymbol resolution is stable across canonical and cloned trees; unsupported export syntax remains intentionally narrow.
75
77
  - Imported declarations resolve by ModuleSymbol and source-local SiteId. Specialized and compiler-synthesized trees still use conservative name/scope fallback where the source-local binding index does not own the complete AST.
@@ -139,6 +139,7 @@ This is an incremental evolution of the current repository:
139
139
  - [x] P0.8 Stable ModuleSymbol and SiteId is complete in `0.8.35`. ProjectSession records source-local declaration, import, and re-export sites and resolves stable ModuleSymbol records through default/named exports, aliases, barrel chains, `export *`, ambiguity, and cycles. Cross-module compiler consumers locate resolved declarations by SiteId in their private normalized clones, while component calls, hooks, keyed blocks, effects, and ownership records expose deterministic source-local SiteIds. Repeated sessions and compilations preserve IDs, and symbol-only barrel traversal avoids cloning intermediate modules without changing browser artifacts or source syntax.
140
140
  - [x] P0.9 Semantic State Operations is complete in `0.8.36`. Direct setters, one immutable state-value alias, one synchronous zero-argument arrow helper, and one synchronous one-parameter function helper lower to identical existing command HandlerIR. Binding identity proves state/setter/helper/parameter ownership; recursion, escape, mutation, and dynamic helper dispatch fail at authored source locations. Existing direct command specialization remains first, unrelated safe handlers retain native ESM, and no command ABI, runtime, JavaScript VM, or general expression IR is added.
141
141
  - [x] P0.10 ModuleIR Reference Unification is complete in `0.8.37`. ModuleIR and ComponentAnalysis v2 assign deterministic slots to symbols, signals, handlers, bindings, derived values, effects, keyed blocks, imports, owners, specializations, states, refs, and IDs. State, capture, import, effect, collection, parent/child, specialization, and row edges use structural slots or ModuleSymbol records while readable names remain codegen/debug metadata. A fail-closed pre-codegen validator rejects malformed slots, unsupported versions, duplicate exports, broken reciprocity, and ownership cycles; focused JSON round-trip checks and all 198 tests pass without changing browser runtime behavior.
142
+ - [x] P0.11 RouteBuildRecord and Artifact Graph is complete in `0.8.38`. Each rendered route records RouteIR, capability facts, route-entry paths, styles, and exact handler/effect references. Build orchestration derives Handler ESM, Worker, package-client, and chunk closure from those edges; serialized HTML/plan `includes()` searches, formatted effect keys, and parallel route-fact/entry arrays are removed. Focused malformed-reference and JSON round-trip checks plus the standard suite preserve the exact 173-file deploy digest and bytes.
142
143
 
143
144
  ### P0: Semantic Correctness And Compiler Foundation
144
145
 
@@ -361,6 +362,8 @@ function increment(value) { setCount(value + 1) }; increment(count)
361
362
 
362
363
  **Done condition:** handler, effect, Worker, CSS, package, and chunk reachability derives from explicit route edges; serialized `includes()` searches and parallel route-fact maps are removed.
363
364
 
365
+ **Completed in `0.8.38`:** `renderPage()` retains exact handler references only when final event, effect, binding, conditional, or keyed-list descriptors are emitted. RouteBuildRecord validates those references with RouteIR, capability facts, route-entry paths, and styles before `build.mjs` projects runtime entries and artifact closure. Handler modules resolve by exact URL, Worker references resolve by structural module/handler pairs, and package-client/chunk roots derive from retained modules. The clean 152-page baseline and candidate builds produce byte-identical `kudzu-plan.json`, 173 deploy files, raw/gzip bytes, and deploy digest with no material build-time regression.
366
+
364
367
  ### PR 12: Deep RouteIR And CapabilityIR Validation
365
368
 
366
369
  **Objective:** fail before codegen for invalid concrete route references and capability projections.
@@ -474,4 +477,4 @@ The first comparison is Kudzu versus React + Vite using the same agent, model, t
474
477
 
475
478
  ## Immediate Decision
476
479
 
477
- PR 1 through PR 10 are complete. The next PR is **PR 11: RouteBuildRecord And Artifact Graph**. Do not skip directly to a store, resource, router, virtualization, or ecosystem package feature.
480
+ PR 1 through PR 11 are complete. The next PR is **PR 12: Deep RouteIR And CapabilityIR Validation**. Do not skip directly to a store, resource, router, virtualization, or ecosystem package feature.
@@ -1,6 +1,6 @@
1
1
  # Planned Version Sequence
2
2
 
3
- This is an execution sequence, not release history. `0.8.16` through `0.8.37` are completed scopes represented by package/release records.
3
+ This is an execution sequence, not release history. `0.8.16` through `0.8.38` are completed scopes represented by package/release records.
4
4
 
5
5
  Keep each patch behavior-preserving and independently reviewable. If a boundary proves inseparable, revise this plan before combining releases; do not silently broaden a patch.
6
6
 
@@ -28,6 +28,7 @@ Keep each patch behavior-preserving and independently reviewable. If a boundary
28
28
  | `0.8.35` | Resolve cross-module declarations through stable ModuleSymbol and source-local SiteId records. | Default/named exports, aliases, barrel chains, `export *`, cycles, ambiguity, repeated compilation, source invalidation, private clones, and measured build behavior remain deterministic. |
29
29
  | `0.8.36` | Lower equivalent direct, aliased, and local-helper state updates through existing command HandlerIR. | The four required forms emit identical commands and no native handler module; recursion, escape, mutation, and dynamic dispatch fail at authored source locations. |
30
30
  | `0.8.37` | Unify ModuleIR and ComponentAnalysis references through deterministic source-local slots and stable symbols. | Every handler, binding, derived, effect, keyed, specialization, state, ref, capture, and import edge validates before build-module generation. |
31
+ | `0.8.38` | Replace serialized route artifact discovery with validated RouteBuildRecord edges. | Handler, effect, Worker, CSS, package-client, and chunk retention is structural while deploy files, bytes, plans, and browser behavior remain unchanged. |
31
32
 
32
33
  ## Sequence Rules
33
34
 
@@ -68,7 +68,7 @@ Reduced Zustand migration stores lower to one ordinary layout-lifetime state slo
68
68
  - `dev-state.js`: dev-only, short-lived logical-state snapshot validation and restoration.
69
69
  - `*.d.ts`: public TypeScript and JSX declarations.
70
70
 
71
- Compiler ownership follows explicit stages. `build.mjs` coordinates project discovery, source compilation, RouteIR rendering, CapabilityIR planning, generator calls, and artifact emission. `compiler/normalization-pipeline.mjs` owns pass order and parent repair. The main transformer analyzes normalized source while `compiler/descriptor-session.mjs` owns one per-source semantic artifact containing HandlerIR, BindingIR, DerivedIR, KeyedBlockIR, EffectIR, and client imports. `core.mjs` emits complete HTML and RouteIR v1: route-local state `slot` is an internal array reference, `id` remains the browser/DOM identity, and `name` remains readable development metadata. `compiler/route-capability-planner.mjs` validates those plans and projects CapabilityIR v1. Focused codegen modules consume IR/descriptors and return route-specific source without source analysis or filesystem ownership. The completed architecture record lives in `docs/next-architecture`; it adds no runtime or accepted syntax by itself.
71
+ Compiler ownership follows explicit stages. `build.mjs` coordinates project discovery, source compilation, RouteIR rendering, RouteBuildRecord collection, CapabilityIR planning, generator calls, and artifact emission. `compiler/normalization-pipeline.mjs` owns pass order and parent repair. The main transformer analyzes normalized source while `compiler/descriptor-session.mjs` owns one per-source semantic artifact containing HandlerIR, BindingIR, DerivedIR, KeyedBlockIR, EffectIR, and client imports. `core.mjs` emits complete HTML, RouteIR v1, and exact handler references: route-local state `slot` is an internal array reference, `id` remains the browser/DOM identity, and `name` remains readable development metadata. `compiler/route-build-record.mjs` validates structural artifact edges, and `compiler/route-capability-planner.mjs` projects CapabilityIR v1 from those records. Focused codegen modules consume IR/descriptors and return route-specific source without source analysis or filesystem ownership. The completed architecture record lives in `docs/next-architecture`; it adds no runtime or accepted syntax by itself.
72
72
 
73
73
  New syntax support belongs in an existing pass or a focused new pass only when a reduced migration fixture proves it. Passes must preserve source-located diagnostics, avoid module-global analysis state, and expose metadata through return values rather than AST-identity side channels. Build orchestration stays in `build.mjs`; feature-specific graph validation or code generation moves under `compiler/` when it has a stable input/output boundary.
74
74
 
@@ -7,6 +7,7 @@ import { createEffectCodegen } from "./compiler/effect-codegen.mjs"
7
7
  import { generateListRuntime } from "./compiler/list-runtime-codegen.mjs"
8
8
  import { assetPath, browserPath, relativeModulePath, withBase } from "./compiler/path-helpers.mjs"
9
9
  import { createProjectSession } from "./compiler/project-session.mjs"
10
+ import { createRouteBuildRecord, planRouteArtifacts } from "./compiler/route-build-record.mjs"
10
11
  import { createSourceCompiler } from "./compiler/source-compiler.mjs"
11
12
  import { createParamCodegen } from "./compiler/param-codegen.mjs"
12
13
  import { planRouteCapabilities, usesRouteDependencyRuntime } from "./compiler/route-capability-planner.mjs"
@@ -113,18 +114,12 @@ async function buildInto(project, outputDirectory, { minify }) {
113
114
  return effect.workers.map(worker => ({ ...worker, module: assetPath(base, `assets/${result.handlerModule.path}`), handler: handler.exportName }))
114
115
  }))
115
116
 
116
- const plans = []
117
- const routeCapabilities = new Map()
118
- const pageEntries = []
119
- const effectEntries = []
120
- const nativeEntries = []
121
- const paramEntries = []
117
+ const routeRecords = []
122
118
  const routeEntryTransforms = new Map()
123
119
  const rewrites = []
124
120
  const emittedRoutes = new Set()
125
121
  const emittedApplicationRoutes = new Set()
126
122
  const emittedNavigationRecords = []
127
- const renderedHandlerUrls = new Set()
128
123
  const styleUrls = [...new Set([
129
124
  ...cssFiles.map(file => assetPath(base, `assets/${relative(sourceDirectory, file).replaceAll(sep, "/")}`)),
130
125
  ...configuredStyles.urls
@@ -190,30 +185,37 @@ async function buildInto(project, outputDirectory, { minify }) {
190
185
  runtimeParams: runtimeSchema?.params,
191
186
  ...(navigable ? { navigationAsset: navigationGroup.assetPath, applicationId: navigationGroup.applicationId, layoutId: navigationGroup.layoutId, routeId: applicationRoute } : {})
192
187
  }, props, module.layout)
193
- const renderedOutput = `${JSON.stringify(result.plan)}\n${result.html}`
194
- for (const url of result.handlerModules) if (renderedOutput.includes(JSON.stringify(url))) renderedHandlerUrls.add(url)
195
188
  if (navigationGroup) {
196
189
  navigationGroup.hasEffects ||= result.hasEffects
197
190
  navigationGroup.hasParams ||= result.hasParams
198
191
  }
199
192
  const usesDependencyRuntime = usesRouteDependencyRuntime({ plan: result.plan, navigable, hasBindings: result.hasBindings, hasLists: result.hasLists })
200
- pageEntries.push({ route, html: result.html, usesDependencyRuntime })
201
- plans.push({ route: routePath, ...result.plan })
202
- routeCapabilities.set(routePath, {
203
- navigable,
204
- usesDependencyRuntime,
205
- hasBehaviors: result.hasBehaviors,
206
- hasBindings: result.hasBindings,
207
- hasLists: result.hasLists,
208
- hasListStyles: result.hasListStyles,
209
- hasStateSeed: result.hasStateSeed
210
- })
211
- if (result.hasParams) paramEntries.push({ path: paramPath, schema: runtimeSchema, params: result.plan.params, searchParams: result.plan.searchParams, searchParamsWritable: result.plan.searchParamsWritable, usesDependencyRuntime, navigable })
212
- if (result.hasEffects) effectEntries.push({ path: effectPath, effects: runtimeEffects(result.plan.effects, navigable), paramPath: result.hasParams ? paramPath : undefined, usesDependencyRuntime, navigable })
213
- if (result.plan.events.some(event => event.native)) nativeEntries.push({
214
- path: nativePath,
215
- modules: [...new Set(result.plan.events.filter(event => event.native).map(event => event.native.module))]
216
- })
193
+ const plan = { route: routePath, ...result.plan }
194
+ routeRecords.push(createRouteBuildRecord({
195
+ route: routePath,
196
+ output: route,
197
+ html: result.html,
198
+ plan,
199
+ handlerReferences: result.handlerReferences,
200
+ styles: styleUrls,
201
+ capabilities: {
202
+ navigable,
203
+ usesDependencyRuntime,
204
+ hasBehaviors: result.hasBehaviors,
205
+ hasBindings: result.hasBindings,
206
+ hasLists: result.hasLists,
207
+ hasListStyles: result.hasListStyles,
208
+ hasStateSeed: result.hasStateSeed,
209
+ hasParams: result.hasParams,
210
+ hasEffects: result.hasEffects
211
+ },
212
+ entries: {
213
+ ...(result.hasParams ? { param: paramPath } : {}),
214
+ ...(result.hasEffects ? { effect: effectPath } : {}),
215
+ ...(result.plan.events.some(event => event.native) ? { native: nativePath } : {})
216
+ },
217
+ runtimeSchema
218
+ }))
217
219
  }
218
220
  }
219
221
 
@@ -227,9 +229,8 @@ async function buildInto(project, outputDirectory, { minify }) {
227
229
 
228
230
  const assetsDirectory = join(outputDirectory, "assets")
229
231
  await mkdir(assetsDirectory, { recursive: true })
230
- const emittedHandlerModules = handlerModules.filter(module => renderedHandlerUrls.has(assetPath(base, `assets/${module.path}`)))
231
- const renderedEffects = new Set(plans.flatMap(plan => plan.effects.map(effect => `${effect.module}:${effect.handler}`)))
232
- const renderedWorkerReferences = workerReferences.filter(reference => renderedEffects.has(`${reference.module}:${reference.handler}`))
232
+ const { handlerModules: emittedHandlerModules, workerReferences: renderedWorkerReferences, styles: renderedStyles } = planRouteArtifacts(routeRecords, handlerModules, workerReferences, module => assetPath(base, `assets/${module.path}`))
233
+ const renderedStyleUrls = new Set(renderedStyles)
233
234
  if (renderedWorkerReferences.length && await exists(join(publicDirectory, "assets", "workers"))) throw new Error("public/assets/workers collides with Kudzu's generated Worker asset namespace")
234
235
  const workerAssets = await project.workerCompiler.emit(renderedWorkerReferences, sourceFileSet, assetsDirectory, base, minify)
235
236
  for (const module of emittedHandlerModules) {
@@ -240,7 +241,8 @@ async function buildInto(project, outputDirectory, { minify }) {
240
241
  }
241
242
  if (module.code.includes("/__kudzu_worker_")) throw new Error(`Worker URL placeholder survived in ${module.path}`)
242
243
  }
243
- const capabilityIR = planRouteCapabilities(plans, { routes: routeCapabilities, navigationRouteCount: navigationRoutes.length })
244
+ const plans = routeRecords.map(record => record.plan)
245
+ const capabilityIR = planRouteCapabilities(routeRecords, { navigationRouteCount: navigationRoutes.length })
244
246
  const {
245
247
  routes: { behaviors: behaviorCount, regularBehaviors: regularBehaviorCount, dependencyStateSeeds: dependencyStateSeedCount },
246
248
  events: { command: commandEvents, hasNativeHandlers },
@@ -251,11 +253,11 @@ async function buildInto(project, outputDirectory, { minify }) {
251
253
  runtime: { shared: hasSharedRuntime, dependency: hasDependencyRuntime }
252
254
  } = capabilityIR
253
255
  const runtimeName = usesDependencyRuntime => usesDependencyRuntime ? "kudzu-deps.js" : "kudzu.js"
254
- for (let offset = 0; offset < pageEntries.length; offset += 64) {
255
- await Promise.all(pageEntries.slice(offset, offset + 64).map(async entry => {
256
- const routeDirectory = join(outputDirectory, entry.route)
256
+ for (let offset = 0; offset < routeRecords.length; offset += 64) {
257
+ await Promise.all(routeRecords.slice(offset, offset + 64).map(async record => {
258
+ const routeDirectory = join(outputDirectory, record.output)
257
259
  await mkdir(routeDirectory, { recursive: true })
258
- const html = preloadModules(entry.html.replace(runtimePlaceholder, escapeAttribute(assetPath(base, `assets/${runtimeName(entry.usesDependencyRuntime)}`))))
260
+ const html = preloadModules(record.html.replace(runtimePlaceholder, escapeAttribute(assetPath(base, `assets/${runtimeName(record.capabilities.usesDependencyRuntime)}`))))
259
261
  await writeFile(join(routeDirectory, "index.html"), html)
260
262
  }))
261
263
  }
@@ -291,7 +293,10 @@ async function buildInto(project, outputDirectory, { minify }) {
291
293
  if (hasNativeHandlers) {
292
294
  const generated = generateNativeRuntime(await readFile(new URL("./native-runtime.js", import.meta.url), "utf8"), capabilityIR)
293
295
  await writeJavaScript(join(assetsDirectory, "kudzu-native.js"), generated.source, minify, generated.define)
294
- for (const entry of nativeEntries) await printNativeEntry(entry, assetsDirectory, base, minify, routeEntryTransforms)
296
+ for (const record of routeRecords) if (record.entries.native) await printNativeEntry({
297
+ path: record.entries.native,
298
+ modules: [...new Set(record.plan.events.filter(event => event.native).map(event => event.native.module))]
299
+ }, assetsDirectory, base, minify, routeEntryTransforms)
295
300
  }
296
301
  if (navigationGroups.length) {
297
302
  const navigationSource = await readFile(new URL("./navigation-runtime.js", import.meta.url), "utf8")
@@ -304,15 +309,15 @@ async function buildInto(project, outputDirectory, { minify }) {
304
309
  await mkdir(resolve(output, ".."), { recursive: true })
305
310
  await writeJavaScript(output, handlerModule.code, minify)
306
311
  }
307
- for (const entry of paramEntries) {
308
- const output = join(assetsDirectory, entry.path)
312
+ for (const record of routeRecords) if (record.entries.param) {
313
+ const output = join(assetsDirectory, record.entries.param)
309
314
  await mkdir(dirname(output), { recursive: true })
310
- await writeRouteEntry(output, printParamEntry(entry.schema, entry.params, entry.searchParams, entry.searchParamsWritable, output, assetsDirectory, base, runtimeName(entry.usesDependencyRuntime), entry.navigable), minify, routeEntryTransforms)
315
+ await writeRouteEntry(output, printParamEntry(record.runtimeSchema, record.plan.params, record.plan.searchParams, record.plan.searchParamsWritable, output, assetsDirectory, base, runtimeName(record.capabilities.usesDependencyRuntime), record.capabilities.navigable), minify, routeEntryTransforms)
311
316
  }
312
- for (const entry of effectEntries) {
313
- const output = join(assetsDirectory, entry.path)
317
+ for (const record of routeRecords) if (record.entries.effect) {
318
+ const output = join(assetsDirectory, record.entries.effect)
314
319
  await mkdir(dirname(output), { recursive: true })
315
- await writeRouteEntry(output, printEffectEntry(entry.effects, output, emittedHandlerModules, assetsDirectory, base, entry.paramPath, runtimeName(entry.usesDependencyRuntime), entry.navigable), minify, routeEntryTransforms)
320
+ await writeRouteEntry(output, printEffectEntry(runtimeEffects(record.plan.effects, record.capabilities.navigable), output, emittedHandlerModules, assetsDirectory, base, record.entries.param, runtimeName(record.capabilities.usesDependencyRuntime), record.capabilities.navigable), minify, routeEntryTransforms)
316
321
  }
317
322
  const clientModules = await collectClientModules(emittedHandlerModules.flatMap(module => module.clientImports).map(file => resolve(root, file)), sourceFileSet)
318
323
  for (const file of clientModules) {
@@ -342,7 +347,7 @@ async function buildInto(project, outputDirectory, { minify }) {
342
347
  }
343
348
  const sortedRewrites = rewrites.sort((left, right) => runtimeSpecificity(right) - runtimeSpecificity(left) || left.pattern.localeCompare(right.pattern))
344
349
  await writeFile(join(workDirectory, "kudzu-plan.json"), JSON.stringify({ routes: plans, rewrites: sortedRewrites }, null, 2))
345
- for (const file of cssFiles) {
350
+ for (const file of cssFiles.filter(file => renderedStyleUrls.has(assetPath(base, `assets/${relative(sourceDirectory, file).replaceAll(sep, "/")}`)))) {
346
351
  const output = join(assetsDirectory, relative(sourceDirectory, file))
347
352
  await mkdir(dirname(output), { recursive: true })
348
353
  await writeFile(output, cssOutputs.get(file))
@@ -353,7 +358,7 @@ async function buildInto(project, outputDirectory, { minify }) {
353
358
  await mkdir(dirname(output), { recursive: true })
354
359
  await writeFile(output, await readFile(file))
355
360
  }
356
- for (const style of configuredStyles.sources) {
361
+ for (const style of configuredStyles.sources.filter(style => renderedStyleUrls.has(withBase(base, style.output)))) {
357
362
  let css = await readFile(style.source, "utf8")
358
363
  if (style.transform) {
359
364
  const result = await style.transform(css, { source: style.source, output: style.output })
@@ -0,0 +1,81 @@
1
+ export function createRouteBuildRecord(input) {
2
+ const record = {
3
+ version: input.version ?? 1,
4
+ route: input.route,
5
+ output: input.output,
6
+ html: input.html,
7
+ plan: input.plan,
8
+ capabilities: input.capabilities,
9
+ artifacts: {
10
+ handlers: input.handlerReferences ?? [],
11
+ effects: (input.plan?.effects ?? []).map(({ module, handler }) => ({ module, handler })),
12
+ styles: [...new Set(input.styles ?? [])]
13
+ },
14
+ entries: input.entries ?? {},
15
+ ...(input.runtimeSchema ? { runtimeSchema: input.runtimeSchema } : {})
16
+ }
17
+ return assertRouteBuildRecord(record)
18
+ }
19
+
20
+ export function assertRouteBuildRecord(record) {
21
+ if (record?.version !== 1) throw new Error(`Unsupported RouteBuildRecord version: ${JSON.stringify(record?.version)}`)
22
+ if (typeof record.route !== "string" || typeof record.output !== "string" || typeof record.html !== "string" || !isRecord(record.plan)) throw new Error("Invalid RouteBuildRecord v1 structure")
23
+ if (record.plan.route !== record.route) throw new Error(`RouteBuildRecord route ${JSON.stringify(record.route)} does not match RouteIR route ${JSON.stringify(record.plan.route)}`)
24
+ const capabilityNames = ["navigable", "usesDependencyRuntime", "hasBehaviors", "hasBindings", "hasLists", "hasListStyles", "hasStateSeed", "hasParams", "hasEffects"]
25
+ if (!isRecord(record.capabilities) || !capabilityNames.every(name => typeof record.capabilities[name] === "boolean")) throw new Error("Invalid RouteBuildRecord v1 capabilities")
26
+ if (!isRecord(record.artifacts) || !Array.isArray(record.artifacts.handlers) || !Array.isArray(record.artifacts.effects) || !Array.isArray(record.artifacts.styles) || !isRecord(record.entries)) throw new Error("Invalid RouteBuildRecord v1 artifacts")
27
+ const handlers = new Set()
28
+ for (const reference of record.artifacts.handlers) {
29
+ assertHandlerReference(reference)
30
+ const key = referenceKey(reference)
31
+ if (handlers.has(key)) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} has duplicate handler reference ${key}`)
32
+ handlers.add(key)
33
+ }
34
+ for (const effect of record.artifacts.effects) {
35
+ assertHandlerReference(effect)
36
+ if (!handlers.has(referenceKey(effect))) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} effect references an unretained handler ${referenceKey(effect)}`)
37
+ }
38
+ for (const event of record.plan.events ?? []) if (event.native && !handlers.has(referenceKey(event.native))) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} event references an unretained handler ${referenceKey(event.native)}`)
39
+ for (const descriptor of [...(record.plan.bindings ?? []), ...(record.plan.conditions ?? []), ...(record.plan.lists ?? []).map(list => list.source).filter(Boolean)]) {
40
+ if (descriptor.module && !handlers.has(referenceKey(descriptor))) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} descriptor references an unretained handler ${referenceKey(descriptor)}`)
41
+ }
42
+ if (record.artifacts.styles.some(style => typeof style !== "string")) throw new Error("RouteBuildRecord styles must be strings")
43
+ for (const [kind, path] of Object.entries(record.entries)) if (!["effect", "native", "param"].includes(kind) || typeof path !== "string") throw new Error(`Invalid RouteBuildRecord entry ${JSON.stringify(kind)}`)
44
+ if (record.runtimeSchema !== undefined && !isRecord(record.runtimeSchema)) throw new Error("Invalid RouteBuildRecord runtime schema")
45
+ const hasNative = (record.plan.events ?? []).some(event => event.native)
46
+ if (Boolean(record.entries.effect) !== record.capabilities.hasEffects || record.capabilities.hasEffects !== Boolean(record.plan.effects?.length)) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} has inconsistent effect artifacts`)
47
+ if (Boolean(record.entries.native) !== hasNative) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} has inconsistent native artifacts`)
48
+ if (Boolean(record.entries.param) !== record.capabilities.hasParams) throw new Error(`RouteBuildRecord ${JSON.stringify(record.route)} has inconsistent parameter artifacts`)
49
+ return record
50
+ }
51
+
52
+ export function planRouteArtifacts(records, handlerModules, workerReferences, moduleUrl) {
53
+ for (const record of records) assertRouteBuildRecord(record)
54
+ const modules = new Map()
55
+ for (const module of handlerModules) {
56
+ const url = moduleUrl(module)
57
+ if (modules.has(url)) throw new Error(`Duplicate compiled handler module: ${url}`)
58
+ modules.set(url, module)
59
+ }
60
+ const retainedUrls = new Set(records.flatMap(record => record.artifacts.handlers.map(reference => reference.module)))
61
+ for (const url of retainedUrls) if (!modules.has(url)) throw new Error(`Handler module was not compiled: ${url}`)
62
+ const effects = new Map()
63
+ for (const reference of records.flatMap(record => record.artifacts.effects)) {
64
+ const handlers = effects.get(reference.module) ?? new Set()
65
+ handlers.add(reference.handler)
66
+ effects.set(reference.module, handlers)
67
+ }
68
+ return {
69
+ handlerModules: handlerModules.filter(module => retainedUrls.has(moduleUrl(module))),
70
+ workerReferences: workerReferences.filter(reference => effects.get(reference.module)?.has(reference.handler)),
71
+ styles: [...new Set(records.flatMap(record => record.artifacts.styles))]
72
+ }
73
+ }
74
+
75
+ const isRecord = value => value !== null && typeof value === "object" && !Array.isArray(value)
76
+
77
+ function assertHandlerReference(reference) {
78
+ if (!isRecord(reference) || typeof reference.module !== "string" || !reference.module || typeof reference.handler !== "string" || !reference.handler) throw new Error("RouteBuildRecord handler references require module and handler strings")
79
+ }
80
+
81
+ const referenceKey = reference => `${JSON.stringify(reference.module)}#${JSON.stringify(reference.handler)}`
@@ -4,7 +4,9 @@ export function usesRouteDependencyRuntime({ plan, navigable, hasBindings, hasLi
4
4
  return !navigable && hasDependencies && !plan.effects.some(effect => effect.owner) && !hasBindings && !hasLists && !plan.events.some(event => event.native)
5
5
  }
6
6
 
7
- export function planRouteCapabilities(plans, { routes = new Map(), navigationRouteCount = 0 } = {}) {
7
+ export function planRouteCapabilities(records, { navigationRouteCount = 0 } = {}) {
8
+ for (const record of records) assertRouteBuildRecord(record)
9
+ const plans = records.map(record => record.plan)
8
10
  for (const plan of plans) assertRouteIR(plan)
9
11
  const commandEvents = new Set()
10
12
  const nativeEvents = new Set()
@@ -39,7 +41,7 @@ export function planRouteCapabilities(plans, { routes = new Map(), navigationRou
39
41
 
40
42
  for (let index = 0; index < plans.length; index++) {
41
43
  const plan = plans[index]
42
- const route = routes.get(plan.route)
44
+ const route = records[index].capabilities
43
45
  for (const event of plan.events) {
44
46
  if (event.commands) commandEvents.add(event.event)
45
47
  if (event.native) nativeEvents.add(event.event)
@@ -77,7 +79,7 @@ export function planRouteCapabilities(plans, { routes = new Map(), navigationRou
77
79
  }
78
80
  }
79
81
 
80
- const routeEntries = [...routes.values()]
82
+ const routeEntries = records.map(record => record.capabilities)
81
83
  const routeCounts = {
82
84
  behaviors: routeEntries.filter(route => route.hasBehaviors).length,
83
85
  regularBehaviors: routeEntries.filter(route => route.hasBehaviors && !route.usesDependencyRuntime).length,
@@ -151,3 +153,4 @@ function hasNestedCaptureState(value, insideCapture = false) {
151
153
  if (value.type === "object") return value.value.some(([, entry]) => hasNestedCaptureState(entry, true))
152
154
  return (Array.isArray(value) ? value : Object.values(value)).some(entry => hasNestedCaptureState(entry, false))
153
155
  }
156
+ import { assertRouteBuildRecord } from "./route-build-record.mjs"
@@ -185,6 +185,6 @@ export function renderPage<Props = Record<string, never>>(
185
185
  hasLists: boolean
186
186
  hasListStyles: boolean
187
187
  hasStateSeed: boolean
188
- handlerModules: string[]
188
+ handlerReferences: Array<{ module: string; handler: string }>
189
189
  plan: RouteIR
190
190
  }>
@@ -207,8 +207,10 @@ export function useEffect(callback, dependencies, module, handler, states, scope
207
207
  owner = nextRenderId("e")
208
208
  owners.push(owner)
209
209
  }
210
- if (!renderContext.listDepth || list) renderContext.effects.push({ module, handler, states, scope, source, renderScope: renderContext.renderScope, ...(dependencyIds.length ? { dependencies: dependencyIds } : {}), ...(dependencyExpressions.length ? { dependencyExpressions, dependencyStates: dependencyStateIds } : {}), ...(itemDependencies.length ? { itemDependencies, listState: renderContext.listRoot.state } : {}), ...(cleanup ? { cleanup: true } : {}), ...(owner ? { owner } : {}), ...(list ? { list: true } : {}) })
211
- renderContext.handlerModules.add(module)
210
+ if (!renderContext.listDepth || list) {
211
+ renderContext.effects.push({ module, handler, states, scope, source, renderScope: renderContext.renderScope, ...(dependencyIds.length ? { dependencies: dependencyIds } : {}), ...(dependencyExpressions.length ? { dependencyExpressions, dependencyStates: dependencyStateIds } : {}), ...(itemDependencies.length ? { itemDependencies, listState: renderContext.listRoot.state } : {}), ...(cleanup ? { cleanup: true } : {}), ...(owner ? { owner } : {}), ...(list ? { list: true } : {}) })
212
+ retainHandlerReference(module, handler)
213
+ }
212
214
  renderContext.hasBehaviors = true
213
215
  renderContext.hasEffects = true
214
216
  }
@@ -254,7 +256,6 @@ export function behavior(commands) {
254
256
  }
255
257
 
256
258
  export function nativeBehavior(module, handler, states, scope) {
257
- renderContext?.handlerModules.add(module)
258
259
  return {
259
260
  [nativeBehaviorMarker]: true,
260
261
  module,
@@ -325,7 +326,6 @@ export function listField(read, field) {
325
326
  }
326
327
 
327
328
  export function listExpression(read, module, handler, states = []) {
328
- renderContext?.handlerModules.add(module)
329
329
  const stateMap = Object.fromEntries(states.map(([name, state]) => {
330
330
  if (!state?.[signalMarker] || !validEffectDependency(state.value)) throw new Error(`Derived keyed list item expression state ${JSON.stringify(name)} must be primitive Kudzu state`)
331
331
  return [name, state.id]
@@ -346,7 +346,6 @@ export function listIndex() {
346
346
  }
347
347
 
348
348
  export function listConditional(kind, read, truthy, falsy, module, handler) {
349
- renderContext?.handlerModules.add(module)
350
349
  return { [listConditionalMarker]: true, kind, value: renderContext?.listTemplate ? undefined : read(), truthy, falsy, module, handler }
351
350
  }
352
351
 
@@ -380,7 +379,6 @@ function assertListValue(value, seen) {
380
379
  }
381
380
 
382
381
  function reactiveDescriptor(module, handler, states, scope) {
383
- renderContext?.handlerModules.add(module)
384
382
  const scopeStates = {}
385
383
  const serializedScope = {}
386
384
  const scopeBindings = {}
@@ -402,6 +400,16 @@ function reactiveDescriptor(module, handler, states, scope) {
402
400
  }
403
401
  }
404
402
 
403
+ function retainHandlerReference(module, handler) {
404
+ const reference = { module, handler }
405
+ renderContext?.handlerReferences.set(JSON.stringify([module, handler]), reference)
406
+ }
407
+
408
+ function retainDescriptorHandlers(descriptor) {
409
+ if (descriptor?.module && descriptor.handler) retainHandlerReference(descriptor.module, descriptor.handler)
410
+ for (const nested of Object.values(descriptor?.scopeBindings ?? {})) retainDescriptorHandlers(nested)
411
+ }
412
+
405
413
  export function bindingValue(value) {
406
414
  return value?.[signalMarker] || value?.[bindingMarker] ? value.value : value
407
415
  }
@@ -449,7 +457,7 @@ function serializeCapture(name, value, seen) {
449
457
  }
450
458
 
451
459
  export async function renderPage(component, metadata = {}, props = {}, layout) {
452
- renderContext = { scoped: Boolean(layout), renderScope: layout ? "layout" : "route", counters: { layout: { s: 0, r: 0, c: 0, l: 0, e: 0, p: 0, i: 0 }, route: { s: 0, r: 0, c: 0, l: 0, e: 0, p: 0, i: 0 } }, nextState: 0, nextRef: 0, nextCondition: 0, nextList: 0, nextEffect: 0, nextParam: 0, nextId: 0, conditionDepth: 0, listDepth: 0, listRoot: undefined, listRowRoot: undefined, listTemplate: false, listInitialMarkers: false, listConditionalBranch: false, listFields: undefined, listEffectOwners: [], listRowStates: [], listRowRefs: [], listRowConditions: [], listRowLists: [], effectOwners: [], contexts: [], stores: new Map(), states: {}, textStates: new Set(), conditionStates: new Set(), conditionOwnedStates: new Set(), events: [], effects: [], bindings: [], textBindings: [], conditions: [], lists: [], handlerModules: new Set(), runtimeParamNames: metadata.runtimeParams, paramEntries: [], params: undefined, searchParams: new Map(), searchParamEntries: [], searchParamsWritable: false, hasBehaviors: false, hasNativeBehaviors: false, hasEffects: false, hasParams: false, hasBindings: false, hasLists: false, hasListStyles: false }
460
+ renderContext = { scoped: Boolean(layout), renderScope: layout ? "layout" : "route", counters: { layout: { s: 0, r: 0, c: 0, l: 0, e: 0, p: 0, i: 0 }, route: { s: 0, r: 0, c: 0, l: 0, e: 0, p: 0, i: 0 } }, nextState: 0, nextRef: 0, nextCondition: 0, nextList: 0, nextEffect: 0, nextParam: 0, nextId: 0, conditionDepth: 0, listDepth: 0, listRoot: undefined, listRowRoot: undefined, listTemplate: false, listInitialMarkers: false, listConditionalBranch: false, listFields: undefined, listEffectOwners: [], listRowStates: [], listRowRefs: [], listRowConditions: [], listRowLists: [], effectOwners: [], contexts: [], stores: new Map(), states: {}, textStates: new Set(), conditionStates: new Set(), conditionOwnedStates: new Set(), events: [], effects: [], bindings: [], textBindings: [], conditions: [], lists: [], handlerReferences: new Map(), runtimeParamNames: metadata.runtimeParams, paramEntries: [], params: undefined, searchParams: new Map(), searchParamEntries: [], searchParamsWritable: false, hasBehaviors: false, hasNativeBehaviors: false, hasEffects: false, hasParams: false, hasBindings: false, hasLists: false, hasListStyles: false }
453
461
 
454
462
  try {
455
463
  const page = { [routeScopeMarker]: true, component, props }
@@ -525,7 +533,7 @@ export async function renderPage(component, metadata = {}, props = {}, layout) {
525
533
  hasLists: renderContext.hasLists,
526
534
  hasListStyles: renderContext.hasListStyles,
527
535
  hasStateSeed: initialState.length > 0,
528
- handlerModules: [...renderContext.handlerModules],
536
+ handlerReferences: [...renderContext.handlerReferences.values()],
529
537
  plan: {
530
538
  version: 1,
531
539
  states: Object.entries(renderContext.states).map(([id, state], slot) => ({ slot, id, ...state })),
@@ -648,6 +656,7 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
648
656
  const metadata = { id, kind: node.kind, initial: node.value, ...descriptor, ...(namespace === "svg" ? { svg: true } : {}), ...(owned ? { owned } : {}), ...(mount ? { mount: true } : {}) }
649
657
  for (const stateId of stateIds) renderContext.conditionStates.add(stateId)
650
658
  renderContext.conditions.push(metadata)
659
+ retainDescriptorHandlers(metadata)
651
660
  renderContext.hasBehaviors = true
652
661
  renderContext.hasBindings = true
653
662
  const encoded = escapeJsonAttribute(metadata)
@@ -667,7 +676,9 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
667
676
  }
668
677
  if (node?.[listExpressionMarker]) {
669
678
  const descriptor = { module: node.module, handler: node.handler, ...(Object.keys(node.states).length ? { states: node.states } : {}) }
670
- const marker = renderContext.listTemplate || renderContext.listInitialMarkers || renderContext.listConditionalBranch ? ` data-k-list-expression='${escapeJsonAttribute(descriptor)}'` : ""
679
+ const retained = renderContext.listTemplate || renderContext.listInitialMarkers || renderContext.listConditionalBranch
680
+ if (retained) retainDescriptorHandlers(descriptor)
681
+ const marker = retained ? ` data-k-list-expression='${escapeJsonAttribute(descriptor)}'` : ""
671
682
  return `<template${marker}></template>${escapeHtml(node.value ?? "")}<template data-k-list-expression-end></template>`
672
683
  }
673
684
  if (node?.[bindingMarker]) {
@@ -675,6 +686,7 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
675
686
  const reactive = reactiveStateIds(descriptor).size > 0
676
687
  if (!reactive) return renderNode(node.value, namespace, selectValue)
677
688
  renderContext.bindings.push({ target: "text", ...descriptor })
689
+ retainDescriptorHandlers(descriptor)
678
690
  if (renderContext.conditionDepth || renderContext.listDepth) for (const stateId of reactiveStateIds(descriptor)) renderContext.conditionStates.add(stateId)
679
691
  renderContext.hasBehaviors = true
680
692
  renderContext.hasBindings = true
@@ -685,6 +697,7 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
685
697
  if (node?.[listConditionalMarker]) {
686
698
  if (namespace === "svg") throw new Error("Keyed row conditions are not supported inside svg")
687
699
  const descriptor = { kind: node.kind, module: node.module, handler: node.handler }
700
+ retainDescriptorHandlers(descriptor)
688
701
  const owner = renderContext.listRoot ?? renderContext.listRowRoot
689
702
  if (owner) owner.conditions = true
690
703
  const previousBranch = renderContext.listConditionalBranch
@@ -800,6 +813,7 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
800
813
  const native = template
801
814
  attributes += ` data-k-native-${event}='${escapeJsonAttribute(native)}'`
802
815
  renderContext.events.push({ event, native })
816
+ retainDescriptorHandlers(native)
803
817
  if (renderContext.listDepth && Object.values(template.scope).some(entry => entry?.type === "list-item" || entry?.type === "list-index")) listEvents.push([event, template])
804
818
  renderContext.hasNativeBehaviors = true
805
819
  } else {
@@ -817,9 +831,10 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
817
831
  if (name === "style") renderContext.hasListStyles = true
818
832
  continue
819
833
  }
820
- if (value?.[listExpressionMarker]) {
834
+ if (value?.[listExpressionMarker]) {
821
835
  attributes += renderAttribute(name, value.value)
822
- listExpressionAttributes.push([name, value.module, value.handler, ...(Object.keys(value.states).length ? [value.states] : [])])
836
+ listExpressionAttributes.push([name, value.module, value.handler, ...(Object.keys(value.states).length ? [value.states] : [])])
837
+ if (renderContext.listTemplate || renderContext.listInitialMarkers || renderContext.listConditionalBranch) retainHandlerReference(value.module, value.handler)
823
838
  if (name === "style") renderContext.hasListStyles = true
824
839
  continue
825
840
  }
@@ -837,6 +852,7 @@ async function renderNode(node, namespace, selectValue = noSelectValue) {
837
852
  if (propertyTarget) attributes += ` data-k-bind-${name}='${escapeJsonAttribute(descriptor)}'`
838
853
  else attributeBindings.push({ target: name, ...descriptor })
839
854
  renderContext.bindings.push({ target: name, ...descriptor })
855
+ retainDescriptorHandlers(descriptor)
840
856
  if (renderContext.conditionDepth || renderContext.listDepth) for (const stateId of reactiveStateIds(descriptor)) renderContext.conditionStates.add(stateId)
841
857
  renderContext.hasBehaviors = true
842
858
  renderContext.hasBindings = true
@@ -944,6 +960,7 @@ async function renderList(node, namespace, selectValue) {
944
960
  }
945
961
  if (!node.ownerField || ownerTemplate && !rowList.planned) {
946
962
  renderContext.lists.push(descriptor)
963
+ retainDescriptorHandlers(descriptor.source)
947
964
  if (rowList) rowList.planned = true
948
965
  }
949
966
  renderContext.hasBehaviors = true
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kudzujs/core",
3
- "version": "0.8.37",
3
+ "version": "0.8.38",
4
4
  "description": "HTML-first TSX framework with synchronous state semantics and no virtual DOM",
5
5
  "type": "module",
6
6
  "license": "MIT",