@kudzujs/core 0.8.32 → 0.8.33
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.
- package/MIGRATION_ROADMAP.md +7 -1
- package/README.md +1 -1
- package/RELEASES.md +26 -0
- package/docs/next-architecture/README.md +1 -1
- package/docs/next-architecture/compiler-current-architecture.md +4 -2
- package/docs/next-architecture/large-application-ai-native-roadmap.md +8 -5
- package/docs/next-architecture/versioning.md +2 -1
- package/framework/build.mjs +43 -41
- package/framework/compiler/project-session.mjs +21 -0
- package/framework/compiler/source-compiler.mjs +26 -16
- package/framework/compiler/source-graph.mjs +39 -37
- package/framework/compiler/worker-compiler.mjs +0 -8
- package/package.json +1 -1
package/MIGRATION_ROADMAP.md
CHANGED
|
@@ -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.
|
|
5
|
+
The executable post-`0.8.33` 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
|
|
|
@@ -302,6 +302,12 @@ This queue orders the next investigations by general migration value. Start only
|
|
|
302
302
|
- Same-root builds use an exclusive PID lock, stale locks fail closed, interrupted promotion backups recover on the next admitted build after lock removal, and successful replacement removes stale output.
|
|
303
303
|
- Route HTML writes use bounded batches, keyed reverse/remove paths avoid repeated map reconstruction, and binding/condition commits share one dispatch without adding a runtime or public API.
|
|
304
304
|
|
|
305
|
+
### Completed In 0.8.33
|
|
306
|
+
|
|
307
|
+
- Build root, source paths, source graph resolution, source records, and Worker compilation now belong to one explicit ProjectSession created for each build.
|
|
308
|
+
- Programmatic build and development entry points accept an explicit root while omitted roots preserve call-time CWD and existing CLI behavior.
|
|
309
|
+
- One process compiles two independent roots with identical module names and verifies isolated config, HTML, `.kudzu`, source results, and Worker output; no browser runtime or migration syntax changes.
|
|
310
|
+
|
|
305
311
|
## Cross-Cutting Performance Gates
|
|
306
312
|
|
|
307
313
|
Every migration feature must preserve:
|
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.
|
|
17
|
+
**Latest release: 0.8.33 - Project-scoped compilation.** Every build now owns its root, source graph, source maps, compiler paths, and Worker compiler in an explicit ProjectSession, so independent projects compile safely in one Node process while the CLI keeps its current-directory behavior. Read the [release notes](./RELEASES.md#0833---project-scoped-compilation), open the [release page](https://github.com/kudzujs/kudzu/releases/tag/v0.8.33), 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,31 @@
|
|
|
1
1
|
# Kudzu Releases
|
|
2
2
|
|
|
3
|
+
## 0.8.33 - Project-scoped compilation
|
|
4
|
+
|
|
5
|
+
Kudzu 0.8.33 completes P0.6 by replacing import-time project globals with an explicit build-scoped ProjectSession. Independent roots can now compile in one Node process without sharing paths, source records, graph resolution, or Worker compiler ownership.
|
|
6
|
+
|
|
7
|
+
### Changed in 0.8.33
|
|
8
|
+
|
|
9
|
+
- Each `build()` creates a ProjectSession containing the absolute project root, `src`, `src/pages`, `.kudzu`, and `dist` paths.
|
|
10
|
+
- Source graph resolution, source indexes, reachable source sets, source compiler helpers, and Worker compilation are bound to that session instead of the directory where compiler modules were first imported.
|
|
11
|
+
- The internal programmatic build and development entry points accept an explicit `root`; omitted roots still use call-time `process.cwd()`, preserving existing `kudzu build` and `kudzu dev` behavior.
|
|
12
|
+
- Config loading, styles, static assets, route diagnostics, generated modules, output locking, staging, promotion, and development serving all resolve against the selected project.
|
|
13
|
+
- Parsed-module and export-summary caching remains deferred to P0.7; this release establishes ownership without adding speculative shared caches or changing browser output.
|
|
14
|
+
|
|
15
|
+
### Validation
|
|
16
|
+
|
|
17
|
+
- `npm run check`, `npm test`, `npm run test:package`, and all 191 tests pass.
|
|
18
|
+
- One imported `build()` function compiles two roots with identical source filenames in sequence and verifies isolated config metadata, HTML, source results, `.kudzu` modules, and content-distinct Worker bundles.
|
|
19
|
+
- The standard CLI output-safety fixture still verifies staging, collision rejection, lock behavior, recovery, and replacement through call-time CWD.
|
|
20
|
+
- The repository build emits 148 pages, and existing static zero-JavaScript, interactive capability, Worker, navigation, ownership, and migration behavior remains covered.
|
|
21
|
+
- P0.7 parsed module and export summary caching is next.
|
|
22
|
+
|
|
23
|
+
### Upgrade
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
npm install @kudzujs/core@^0.8.33
|
|
27
|
+
```
|
|
28
|
+
|
|
3
29
|
## 0.8.32 - Staged and collision-safe output
|
|
4
30
|
|
|
5
31
|
Kudzu 0.8.32 completes P0.5 by building production artifacts away from the active deploy tree, rejecting public/generated collisions, and replacing `dist` only after generation and trusted `afterBuild()` work succeed.
|
|
@@ -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.
|
|
14
|
+
The active post-`0.8.33` implementation sequence is [`large-application-ai-native-roadmap.md`](./large-application-ai-native-roadmap.md). P0.6 ProjectSession and explicit root is complete; P0.7 parsed module and export summary caching 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,12 +1,13 @@
|
|
|
1
1
|
# Current Compiler Architecture
|
|
2
2
|
|
|
3
|
-
This maps the current `0.8.
|
|
3
|
+
This maps the current `0.8.33` 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
|
|
|
7
7
|
| Responsibility | Current owner | Current contract |
|
|
8
8
|
|---|---|---|
|
|
9
9
|
| CLI entry | [`bin/kudzu.mjs`](../../bin/kudzu.mjs) | Dispatches build and development commands. |
|
|
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. |
|
|
10
11
|
| Build orchestration | [`framework/build.mjs`](../../framework/build.mjs), `build()` | Coordinates config, discovery, source compilation, RouteIR rendering, CapabilityIR projection, generator invocation, artifact emission, and `afterBuild`. |
|
|
11
12
|
| 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. |
|
|
12
13
|
| 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. |
|
|
@@ -37,6 +38,7 @@ This maps the current `0.8.32` architecture built on the completed `0.8.23` Goal
|
|
|
37
38
|
|
|
38
39
|
```text
|
|
39
40
|
src/pages entries + config
|
|
41
|
+
-> ProjectSession(root) with project paths, source records, graph, and Worker compiler
|
|
40
42
|
-> project discovery and reachable relative graph
|
|
41
43
|
-> compileSource()
|
|
42
44
|
-> ordered normalization and parent repair
|
|
@@ -68,7 +70,7 @@ The browser consumes static HTML first. State seeds and descriptors in that HTML
|
|
|
68
70
|
- Transient component rewrite indexes remain source-local AST indexes; handler, binding, derived, keyed, effect, and component ownership now have explicit JSON-safe source results.
|
|
69
71
|
- `build()` still owns explicit artifact selection and filesystem writes after generator results are produced.
|
|
70
72
|
- 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.
|
|
71
|
-
- Source reachability and source compilation
|
|
73
|
+
- Source reachability and source compilation remain in one session-bound compiler factory because both consume the same normalization and import graph contracts; parsed-module and export-summary caching is deferred to P0.7.
|
|
72
74
|
- Imported, specialized, and compiler-synthesized trees still use conservative name/scope fallback where the source-local binding index does not own the complete AST; cross-module semantics remain deferred to stable ModuleSymbol and SiteId work.
|
|
73
75
|
|
|
74
76
|
These are future simplification opportunities, not incomplete Goal A contracts. Goal A changed no source support, browser output semantics, or browser architecture.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Status
|
|
4
4
|
|
|
5
|
-
Active execution plan after `0.8.
|
|
5
|
+
Active execution plan after `0.8.33`. This document turns the current compiler audit into an ordered implementation program. It does not mark any planned capability as supported and does not authorize a React runtime, VDOM, hydration, retained browser component tree, generic rerenderer, public store/query/resource API, SPA router, or islands.
|
|
6
6
|
|
|
7
7
|
[`MIGRATION_ROADMAP.md`](../../MIGRATION_ROADMAP.md) remains authoritative for product invariants and fixture-driven feature selection. This plan is authoritative for the order and completion evidence of compiler generalization, large-application foundations, compatibility boundaries, AI tooling, and scale validation. If implementation evidence changes a boundary, update this document before broadening a patch.
|
|
8
8
|
|
|
@@ -34,7 +34,7 @@ The current limiting architecture is observable in these files:
|
|
|
34
34
|
|
|
35
35
|
| Concern | Current owner | Limitation to remove |
|
|
36
36
|
|---|---|---|
|
|
37
|
-
| Project graph | `framework/compiler/source-graph.mjs`, `
|
|
37
|
+
| Project graph | `framework/compiler/project-session.mjs`, `source-graph.mjs`, `build.mjs` | Explicit build-scoped root and source ownership; repeated parsing, narrow export resolution, and no incremental invalidation remain |
|
|
38
38
|
| Normalization | `framework/compiler/source-compiler.mjs`, focused passes | Pass order and package ownership are implicit; semantically equal source often follows different shape-specific paths |
|
|
39
39
|
| Component/state analysis | `framework/compiler/source-compiler.mjs`, `analysis/component-analysis.mjs` | AST identity, identifier text, source offsets, and caller-side AST specialization remain central |
|
|
40
40
|
| Handler/binding analysis | `framework/compiler/descriptor-session.mjs`, `handler-lowering.mjs` | Capture/import/state discovery is name-based and arbitrary handlers become code before IR finalization |
|
|
@@ -112,7 +112,7 @@ This is an incremental evolution of the current repository:
|
|
|
112
112
|
- Resource-specific ownership passes into a package-neutral ResourceIR when evidence permits.
|
|
113
113
|
- Serialized handler URL searches into explicit artifact references.
|
|
114
114
|
- Site-wide capability unions into route capability signatures.
|
|
115
|
-
- Full
|
|
115
|
+
- Full development rebuilds into project-session invalidation; rollback-safe production output and explicit session ownership are complete.
|
|
116
116
|
- String-only diagnostics into structured diagnostics suitable for machines and AI agents.
|
|
117
117
|
|
|
118
118
|
### Avoid
|
|
@@ -134,7 +134,8 @@ This is an incremental evolution of the current repository:
|
|
|
134
134
|
- [x] P0.3 Graph diagnostics is complete in `0.8.30`. Reachable ordinary modules validate relative runtime imports/re-exports and reject every dynamic `import()` at the importer source location before compilation or generated module loading. Ordinary and Worker traversal retain separate ownership, type-only and unreachable edges remain excluded, focused page/helper/re-export/dynamic fixtures pass with all 189 tests and packed-package smoke, and no export-symbol graph, ProjectSession, runtime, or public API is added.
|
|
135
135
|
- [x] P0.4 Async native handler ownership is complete in `0.8.31`. Mounted native registrations invalidate direct/captured setters, queued commits, and captured refs before listener removal. Chrome route, keyed-row, document-disposal, and synchronous event-dispatch checks, all 189 tests, and packed-package smoke pass without cancelling application promises or adding a scheduler.
|
|
136
136
|
- [x] P0.5 Staged and collision-safe output is complete in `0.8.32`. Production output completes in one project-local staging tree, public files are compared against generated route/runtime/handler/chunk/Worker/CSS paths while copying, `afterBuild` runs before rollback-safe promotion, and ordinary failures preserve the prior `dist`. Same-root overlap and stale locks fail closed; after stale-lock removal, an interrupted promotion backup recovers on the next admitted build. Focused collision/replacement/dev checks pass with equivalent `v0.8.31` commerce deploy output; `.kudzu` remains compiler scratch for P0.6.
|
|
137
|
-
- [
|
|
137
|
+
- [x] P0.6 Explicit ProjectSession is complete in `0.8.33`. Each build owns an absolute root, project paths, source records, bound graph operations, and Worker compiler. Explicit-root build/dev entry points preserve omitted-root CLI CWD behavior. One imported build function compiles two same-shaped roots with isolated config, HTML, `.kudzu`, source results, and Worker bundles; all 191 tests and package checks pass without browser or source-syntax changes.
|
|
138
|
+
- [ ] P0.7 Parsed module and export summary caching is next. Shared modules must be parsed and summarized once per project session without sharing transformed mutable AST.
|
|
138
139
|
|
|
139
140
|
### P0: Semantic Correctness And Compiler Foundation
|
|
140
141
|
|
|
@@ -296,6 +297,8 @@ Every result carries a stable source-local binding slot, debug name, declaration
|
|
|
296
297
|
|
|
297
298
|
**Done condition:** two independent roots compile in one process, current CLI behavior and artifacts remain unchanged, and source caches cannot leak between projects.
|
|
298
299
|
|
|
300
|
+
**Completed in `0.8.33`:** `createProjectSession()` resolves one explicit or call-time-CWD root and owns standard paths, source records, bound graph resolution, and a root-bound Worker compiler. Build, development, config, styles, routes, generated modules, locking, staging, and promotion consume that ownership. One process compiles two roots with identical module names and verifies distinct config, HTML, `.kudzu`, source results, and Worker bundles. Existing CLI output-safety coverage remains unchanged; no parsed-module cache, browser runtime, source syntax, or public migration API is added.
|
|
301
|
+
|
|
299
302
|
### PR 7: Parsed Module And Export Summary Cache
|
|
300
303
|
|
|
301
304
|
**Objective:** make work proportional to unique modules instead of importer edges.
|
|
@@ -460,4 +463,4 @@ The first comparison is Kudzu versus React + Vite using the same agent, model, t
|
|
|
460
463
|
|
|
461
464
|
## Immediate Decision
|
|
462
465
|
|
|
463
|
-
PR 1 through PR
|
|
466
|
+
PR 1 through PR 6 are complete. The next PR is **PR 7: Parsed Module And Export Summary Cache**. 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.
|
|
3
|
+
This is an execution sequence, not release history. `0.8.16` through `0.8.33` 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
|
|
|
@@ -23,6 +23,7 @@ Keep each patch behavior-preserving and independently reviewable. If a boundary
|
|
|
23
23
|
| `0.8.30` | Validate ordinary runtime graph edges before code generation and reject dynamic imports at the importer source. | Page/helper/re-export/dynamic fixtures report original file/range/specifier without `.kudzu` paths; Worker, type-only, unreachable, output, and runtime behavior remain unchanged. |
|
|
24
24
|
| `0.8.31` | Invalidate pending native-handler contexts when their route, keyed, conditional, or document DOM owner is released. | Late setters, queued commits, and captured refs cannot mutate replacement ownership; synchronous dispatch remains within the performance gate and runtime bytes are recorded. |
|
|
25
25
|
| `0.8.32` | Stage and validate production output before rollback-safe promotion, reject same-root overlap, and tighten keyed browser paths. | Build/hook failures preserve the prior output, stale locks fail closed, interrupted backups recover on the next admitted build after lock removal, public/generated collisions fail, and deploy output remains equivalent. |
|
|
26
|
+
| `0.8.33` | Move root, graph, source records, compiler paths, and Worker ownership into an explicit build-scoped ProjectSession. | Two independent roots compile through one imported build entry without config, source, `.kudzu`, Worker, or output leakage; CLI CWD behavior remains unchanged. |
|
|
26
27
|
|
|
27
28
|
## Sequence Rules
|
|
28
29
|
|
package/framework/build.mjs
CHANGED
|
@@ -6,24 +6,18 @@ import { build as bundle, transform } from "esbuild"
|
|
|
6
6
|
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
|
-
import {
|
|
9
|
+
import { createProjectSession } from "./compiler/project-session.mjs"
|
|
10
|
+
import { createSourceCompiler } from "./compiler/source-compiler.mjs"
|
|
10
11
|
import { createParamCodegen } from "./compiler/param-codegen.mjs"
|
|
11
12
|
import { planRouteCapabilities, usesRouteDependencyRuntime } from "./compiler/route-capability-planner.mjs"
|
|
12
13
|
import { generateBindingRuntime, generateCoreRuntime, generateEffectRuntime, generateNativeRuntime, generateNavigationRuntime, specializeRuntime } from "./compiler/runtime-codegen.mjs"
|
|
13
|
-
import { emitWorkers } from "./compiler/worker-compiler.mjs"
|
|
14
14
|
import { renderPage } from "./core.mjs"
|
|
15
15
|
import { parseDevHost, parseDevPort, startDevServer } from "./dev-server.mjs"
|
|
16
16
|
|
|
17
17
|
export { parseDevHost, parseDevPort }
|
|
18
18
|
export { specializeRuntime }
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
const sourceDirectory = join(root, "src")
|
|
22
|
-
const pagesDirectory = join(sourceDirectory, "pages")
|
|
23
|
-
const workDirectory = join(root, ".kudzu")
|
|
24
|
-
const outputDirectory = join(root, "dist")
|
|
25
|
-
|
|
26
|
-
async function loadConfig() {
|
|
20
|
+
async function loadConfig(root) {
|
|
27
21
|
for (const name of ["kudzu.config.mjs", "kudzu.config.js"]) {
|
|
28
22
|
const file = join(root, name)
|
|
29
23
|
if (!(await exists(file))) continue
|
|
@@ -34,7 +28,9 @@ async function loadConfig() {
|
|
|
34
28
|
return {}
|
|
35
29
|
}
|
|
36
30
|
|
|
37
|
-
export async function build({ quiet = false, minify = true } = {}) {
|
|
31
|
+
export async function build({ quiet = false, minify = true, root: projectRoot = process.cwd() } = {}) {
|
|
32
|
+
const project = createProjectSession(projectRoot)
|
|
33
|
+
const { root, outputDirectory } = project
|
|
38
34
|
const stagedOutput = join(root, ".kudzu-dist-staging")
|
|
39
35
|
const backupOutput = join(root, ".kudzu-dist-backup")
|
|
40
36
|
const lockPath = join(root, ".kudzu-build.lock")
|
|
@@ -42,7 +38,7 @@ export async function build({ quiet = false, minify = true } = {}) {
|
|
|
42
38
|
try {
|
|
43
39
|
await recoverOutput(outputDirectory, backupOutput)
|
|
44
40
|
await rm(stagedOutput, { recursive: true, force: true })
|
|
45
|
-
const { result, pageCount, behaviorCount } = await buildInto(stagedOutput, { minify })
|
|
41
|
+
const { result, pageCount, behaviorCount } = await buildInto(project, stagedOutput, { minify })
|
|
46
42
|
await promoteOutput(stagedOutput, outputDirectory, backupOutput)
|
|
47
43
|
if (!quiet) console.log(`Built ${pageCount} page(s), ${behaviorCount} interactive page(s) into dist/`)
|
|
48
44
|
return result
|
|
@@ -59,11 +55,13 @@ export async function build({ quiet = false, minify = true } = {}) {
|
|
|
59
55
|
}
|
|
60
56
|
}
|
|
61
57
|
|
|
62
|
-
async function buildInto(outputDirectory, { minify }) {
|
|
63
|
-
const
|
|
58
|
+
async function buildInto(project, outputDirectory, { minify }) {
|
|
59
|
+
const { root, sourceDirectory, pagesDirectory, workDirectory } = project
|
|
60
|
+
const { collectClientModules, compileClientModule, compiledPath, compileSource, layoutExportError, orderSourceStyles, reachableSourceFiles, safeStaticFiles } = createSourceCompiler(project)
|
|
61
|
+
const config = await loadConfig(root)
|
|
64
62
|
const base = normalizeBase(config.base)
|
|
65
|
-
const configuredStyles = normalizeStyles(config.styles, base)
|
|
66
|
-
const publicDirectory = normalizePublicDirectory(config.publicDir)
|
|
63
|
+
const configuredStyles = normalizeStyles(config.styles, base, project)
|
|
64
|
+
const publicDirectory = normalizePublicDirectory(config.publicDir, project)
|
|
67
65
|
const navigationGroups = normalizeNavigation(config.navigation)
|
|
68
66
|
const navigationRoutes = navigationGroups.flatMap(group => group.routes)
|
|
69
67
|
const navigationByRoute = new Map(navigationGroups.flatMap(group => group.routes.map(route => [route, group])))
|
|
@@ -86,15 +84,17 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
86
84
|
const discoveredCssFiles = projectFiles.filter(file => file.toLowerCase().endsWith(".css") && !configuredStyleSources.has(file)).sort()
|
|
87
85
|
if (!allSourceFiles.length) throw new Error("No TypeScript files found in src/")
|
|
88
86
|
const allSourceFileSet = new Set(allSourceFiles)
|
|
89
|
-
const sourceIndex =
|
|
87
|
+
const sourceIndex = project.sourceIndex
|
|
88
|
+
for (const [file, source] of await Promise.all(allSourceFiles.map(async file => [file, await readFile(file, "utf8")]))) sourceIndex.set(file, source)
|
|
90
89
|
const pageFiles = allSourceFiles.filter(file => file.startsWith(`${pagesDirectory}${sep}`) && file.endsWith(".tsx"))
|
|
91
90
|
if (!pageFiles.length) throw new Error("No pages found in src/pages/")
|
|
92
91
|
const sourceFiles = reachableSourceFiles(pageFiles, allSourceFileSet, sourceIndex)
|
|
93
|
-
const sourceFileSet =
|
|
92
|
+
const sourceFileSet = project.sourceFiles
|
|
93
|
+
for (const file of sourceFiles) sourceFileSet.add(file)
|
|
94
94
|
const staticFiles = await safeStaticFiles(projectFiles)
|
|
95
95
|
const cssFiles = orderSourceStyles(discoveredCssFiles, sourceFiles, sourceIndex, staticFiles)
|
|
96
96
|
const importedAssets = new Set()
|
|
97
|
-
const { cssModules, cssOutputs } = await prepareSourceStyles(cssFiles, staticFiles, importedAssets, base)
|
|
97
|
+
const { cssModules, cssOutputs } = await prepareSourceStyles(cssFiles, staticFiles, importedAssets, base, project)
|
|
98
98
|
|
|
99
99
|
const sourceResults = []
|
|
100
100
|
for (const file of sourceFiles) {
|
|
@@ -137,7 +137,7 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
137
137
|
if (typeof module.default !== "function") throw new Error(`${relative(root, pageFile)} must export a default component`)
|
|
138
138
|
if (Object.hasOwn(module, "layout") && typeof module.layout !== "function") throw layoutExportError(pageFile, sourceIndex.get(pageFile))
|
|
139
139
|
|
|
140
|
-
const runtimeSchema = runtimeRouteSchema(module, pageFile)
|
|
140
|
+
const runtimeSchema = runtimeRouteSchema(module, pageFile, project)
|
|
141
141
|
if (runtimeSchema) {
|
|
142
142
|
const conflicting = rewrites.find(rewrite => sameRuntimePrecedence(rewrite, runtimeSchema))
|
|
143
143
|
if (conflicting) throw new Error(`Ambiguous runtime routes: ${conflicting.route} and ${runtimeSchema.route}`)
|
|
@@ -149,9 +149,9 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
149
149
|
segments: runtimeSchema.segments
|
|
150
150
|
})
|
|
151
151
|
}
|
|
152
|
-
const entries = runtimeSchema ? [{ params: {}, props: {} }] : await staticPathEntries(module, pageFile)
|
|
152
|
+
const entries = runtimeSchema ? [{ params: {}, props: {} }] : await staticPathEntries(module, pageFile, root)
|
|
153
153
|
for (const { params, props } of entries) {
|
|
154
|
-
const route = runtimeSchema?.route ?? routeFromPage(pageFile, params)
|
|
154
|
+
const route = runtimeSchema?.route ?? routeFromPage(pageFile, params, pagesDirectory)
|
|
155
155
|
const applicationRoute = `/${route}`
|
|
156
156
|
const routePath = withBase(base, `/${route}`)
|
|
157
157
|
const metadataContext = { route: routePath, params, props }
|
|
@@ -231,7 +231,7 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
231
231
|
const renderedEffects = new Set(plans.flatMap(plan => plan.effects.map(effect => `${effect.module}:${effect.handler}`)))
|
|
232
232
|
const renderedWorkerReferences = workerReferences.filter(reference => renderedEffects.has(`${reference.module}:${reference.handler}`))
|
|
233
233
|
if (renderedWorkerReferences.length && await exists(join(publicDirectory, "assets", "workers"))) throw new Error("public/assets/workers collides with Kudzu's generated Worker asset namespace")
|
|
234
|
-
const workerAssets = await
|
|
234
|
+
const workerAssets = await project.workerCompiler.emit(renderedWorkerReferences, sourceFileSet, assetsDirectory, base, minify)
|
|
235
235
|
for (const module of emittedHandlerModules) {
|
|
236
236
|
for (const reference of workerReferences) {
|
|
237
237
|
if (reference.module !== assetPath(base, `assets/${module.path}`)) continue
|
|
@@ -366,7 +366,7 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
366
366
|
await writeFile(output, css)
|
|
367
367
|
}
|
|
368
368
|
if (await exists(publicDirectory)) {
|
|
369
|
-
await copyPublic(publicDirectory, outputDirectory)
|
|
369
|
+
await copyPublic(publicDirectory, outputDirectory, outputDirectory, root)
|
|
370
370
|
}
|
|
371
371
|
if (config.afterBuild !== undefined) {
|
|
372
372
|
if (typeof config.afterBuild !== "function") throw new Error("kudzu.config afterBuild must be a function")
|
|
@@ -376,7 +376,7 @@ async function buildInto(outputDirectory, { minify }) {
|
|
|
376
376
|
return { result: { sourceResults }, pageCount: plans.length, behaviorCount }
|
|
377
377
|
}
|
|
378
378
|
|
|
379
|
-
async function acquireBuildLock(lockPath) {
|
|
379
|
+
async function acquireBuildLock(lockPath, root = dirname(lockPath)) {
|
|
380
380
|
let lock
|
|
381
381
|
try {
|
|
382
382
|
lock = await open(lockPath, "wx")
|
|
@@ -432,7 +432,7 @@ async function promoteOutput(stagedOutput, finalOutput, backup) {
|
|
|
432
432
|
if (previous) await rm(backup, { recursive: true, force: true }).catch(error => console.warn(`Built output was promoted, but ${backup} could not be removed and will be retried on the next build: ${error.message}`))
|
|
433
433
|
}
|
|
434
434
|
|
|
435
|
-
async function copyPublic(sourceDirectory, destinationDirectory, destinationRoot
|
|
435
|
+
async function copyPublic(sourceDirectory, destinationDirectory, destinationRoot, root) {
|
|
436
436
|
for (const entry of await readdir(sourceDirectory, { withFileTypes: true })) {
|
|
437
437
|
const source = join(sourceDirectory, entry.name)
|
|
438
438
|
const destination = join(destinationDirectory, entry.name)
|
|
@@ -445,7 +445,7 @@ async function copyPublic(sourceDirectory, destinationDirectory, destinationRoot
|
|
|
445
445
|
if (!generated) {
|
|
446
446
|
await cp(source, destination, { recursive: entry.isDirectory(), force: false, errorOnExist: true })
|
|
447
447
|
} else if (entry.isDirectory() && generated.isDirectory()) {
|
|
448
|
-
await copyPublic(source, destination, destinationRoot)
|
|
448
|
+
await copyPublic(source, destination, destinationRoot, root)
|
|
449
449
|
} else {
|
|
450
450
|
throw new Error(`${relative(root, source)} collides with generated output ${relative(destinationRoot, destination).replaceAll(sep, "/")}`)
|
|
451
451
|
}
|
|
@@ -514,11 +514,13 @@ async function writeBundledJavaScript(file, source, minify, define) {
|
|
|
514
514
|
await writeFile(file, result.outputFiles[0].contents)
|
|
515
515
|
}
|
|
516
516
|
|
|
517
|
-
export async function dev({ port = parseDevPort(process.env.PORT), host = parseDevHost(process.env.HOST) } = {}) {
|
|
517
|
+
export async function dev({ port = parseDevPort(process.env.PORT), host = parseDevHost(process.env.HOST), root: projectRoot = process.cwd() } = {}) {
|
|
518
518
|
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`Invalid dev server port: ${port}`)
|
|
519
519
|
if (typeof host !== "string" || !host.trim()) throw new Error(`Invalid dev server host: ${host}`)
|
|
520
|
-
const
|
|
521
|
-
|
|
520
|
+
const project = createProjectSession(projectRoot)
|
|
521
|
+
const { root, sourceDirectory, workDirectory, outputDirectory } = project
|
|
522
|
+
const base = normalizeBase((await loadConfig(root)).base)
|
|
523
|
+
return startDevServer({ build: options => build({ ...options, root }), port, host, base, sourceDirectory, workDirectory, outputDirectory })
|
|
522
524
|
}
|
|
523
525
|
|
|
524
526
|
function inlineJson(value) {
|
|
@@ -533,11 +535,11 @@ function escapeAttribute(value) {
|
|
|
533
535
|
return escapeHtml(value).replaceAll('"', """).replaceAll("'", "'")
|
|
534
536
|
}
|
|
535
537
|
|
|
536
|
-
async function prepareSourceStyles(cssFiles, staticFiles, importedAssets, base) {
|
|
538
|
+
async function prepareSourceStyles(cssFiles, staticFiles, importedAssets, base, { root, sourceDirectory }) {
|
|
537
539
|
const cssModules = new Map()
|
|
538
540
|
const cssOutputs = new Map()
|
|
539
541
|
for (const file of cssFiles) {
|
|
540
|
-
let css = rewriteCssUrls(await readFile(file, "utf8"), file, staticFiles, importedAssets, base)
|
|
542
|
+
let css = rewriteCssUrls(await readFile(file, "utf8"), file, staticFiles, importedAssets, base, root, sourceDirectory)
|
|
541
543
|
if (file.toLowerCase().endsWith(".module.css")) {
|
|
542
544
|
if (/\bcomposes\s*:/i.test(maskCssCommentsAndStrings(css))) throw new Error(`${relative(root, file)} CSS Modules composes is not supported`)
|
|
543
545
|
const prefix = `k${createHash("sha256").update(relative(sourceDirectory, file).replaceAll(sep, "/")).digest("hex").slice(0, 8)}`
|
|
@@ -551,7 +553,7 @@ async function prepareSourceStyles(cssFiles, staticFiles, importedAssets, base)
|
|
|
551
553
|
return { cssModules, cssOutputs }
|
|
552
554
|
}
|
|
553
555
|
|
|
554
|
-
function rewriteCssUrls(css, file, staticFiles, importedAssets, base) {
|
|
556
|
+
function rewriteCssUrls(css, file, staticFiles, importedAssets, base, root, sourceDirectory) {
|
|
555
557
|
let output = ""
|
|
556
558
|
let cursor = 0
|
|
557
559
|
let index = 0
|
|
@@ -596,7 +598,7 @@ function rewriteCssUrls(css, file, staticFiles, importedAssets, base) {
|
|
|
596
598
|
continue
|
|
597
599
|
}
|
|
598
600
|
const value = css.slice(valueStart, end).trim()
|
|
599
|
-
const replacement = rewriteCssUrl(value, quote, file, staticFiles, importedAssets, base)
|
|
601
|
+
const replacement = rewriteCssUrl(value, quote, file, staticFiles, importedAssets, base, root, sourceDirectory)
|
|
600
602
|
output += css.slice(cursor, index) + (replacement ?? css.slice(index, close + 1))
|
|
601
603
|
cursor = close + 1
|
|
602
604
|
index = close + 1
|
|
@@ -604,7 +606,7 @@ function rewriteCssUrls(css, file, staticFiles, importedAssets, base) {
|
|
|
604
606
|
return output + css.slice(cursor)
|
|
605
607
|
}
|
|
606
608
|
|
|
607
|
-
function rewriteCssUrl(value, quote, file, staticFiles, importedAssets, base) {
|
|
609
|
+
function rewriteCssUrl(value, quote, file, staticFiles, importedAssets, base, root, sourceDirectory) {
|
|
608
610
|
if (!value || value.startsWith("/") || value.startsWith("#") || value.startsWith("//") || /^[a-z][a-z\d+.-]*:/i.test(value)) return undefined
|
|
609
611
|
const split = value.search(/[?#]/)
|
|
610
612
|
const pathname = split === -1 ? value : value.slice(0, split)
|
|
@@ -646,7 +648,7 @@ function maskCssCommentsAndStrings(css) {
|
|
|
646
648
|
return masked.join("")
|
|
647
649
|
}
|
|
648
650
|
|
|
649
|
-
function normalizeStyles(value, base) {
|
|
651
|
+
function normalizeStyles(value, base, { root }) {
|
|
650
652
|
if (value === undefined) return { urls: [], sources: [] }
|
|
651
653
|
if (!Array.isArray(value)) throw new Error("kudzu.config styles must be an array")
|
|
652
654
|
const urls = []
|
|
@@ -680,7 +682,7 @@ function normalizeStyles(value, base) {
|
|
|
680
682
|
return { urls, sources }
|
|
681
683
|
}
|
|
682
684
|
|
|
683
|
-
function normalizePublicDirectory(value) {
|
|
685
|
+
function normalizePublicDirectory(value, { root, outputDirectory, workDirectory }) {
|
|
684
686
|
if (value === undefined) return join(root, "public")
|
|
685
687
|
if (typeof value !== "string" || !value) throw new Error("kudzu.config publicDir must be a non-empty directory path")
|
|
686
688
|
const directory = resolve(root, value)
|
|
@@ -771,7 +773,7 @@ function normalizeBase(value) {
|
|
|
771
773
|
const printEffectEntry = createEffectCodegen({ assetPath, inlineJson, relativeModulePath })
|
|
772
774
|
const printParamEntry = createParamCodegen({ browserPath, inlineJson, relativeModulePath })
|
|
773
775
|
|
|
774
|
-
async function staticPathEntries(module, file) {
|
|
776
|
+
async function staticPathEntries(module, file, root) {
|
|
775
777
|
if (typeof module.getStaticPaths !== "function") return [{ params: {}, props: {} }]
|
|
776
778
|
const entries = await module.getStaticPaths()
|
|
777
779
|
if (!Array.isArray(entries)) throw new Error(`${relative(root, file)} getStaticPaths() must return an array`)
|
|
@@ -785,11 +787,11 @@ async function staticPathEntries(module, file) {
|
|
|
785
787
|
})
|
|
786
788
|
}
|
|
787
789
|
|
|
788
|
-
function runtimeRouteSchema(module, file) {
|
|
790
|
+
function runtimeRouteSchema(module, file, { root, pagesDirectory }) {
|
|
789
791
|
if (!Object.hasOwn(module, "runtimeParams")) return undefined
|
|
790
792
|
if (module.runtimeParams !== true) throw new Error(`${relative(root, file)} runtimeParams must be exactly true`)
|
|
791
793
|
if (typeof module.getStaticPaths === "function") throw new Error(`${relative(root, file)} runtimeParams cannot be combined with getStaticPaths()`)
|
|
792
|
-
const route = pageRoutePattern(file)
|
|
794
|
+
const route = pageRoutePattern(file, pagesDirectory)
|
|
793
795
|
if (route.includes("[...")) throw new Error(`Catch-all routes are not supported: ${route}`)
|
|
794
796
|
const names = new Set()
|
|
795
797
|
const segments = route.split("/").map(segment => {
|
|
@@ -808,7 +810,7 @@ function runtimeRouteSchema(module, file) {
|
|
|
808
810
|
return { route, segments, params: [...names] }
|
|
809
811
|
}
|
|
810
812
|
|
|
811
|
-
function pageRoutePattern(file) {
|
|
813
|
+
function pageRoutePattern(file, pagesDirectory) {
|
|
812
814
|
const page = relative(pagesDirectory, file).replace(/\\/g, "/").replace(/\.tsx$/, "")
|
|
813
815
|
return page === "index" ? "" : page.replace(/\/index$/, "")
|
|
814
816
|
}
|
|
@@ -822,7 +824,7 @@ function sameRuntimePrecedence(left, right) {
|
|
|
822
824
|
return left.segments.every((segment, index) => segment.literal === undefined || right.segments[index].literal === undefined || segment.literal === right.segments[index].literal)
|
|
823
825
|
}
|
|
824
826
|
|
|
825
|
-
function routeFromPage(file, params = {}) {
|
|
827
|
+
function routeFromPage(file, params = {}, pagesDirectory) {
|
|
826
828
|
const page = relative(pagesDirectory, file).replace(/\\/g, "/").replace(/\.tsx$/, "")
|
|
827
829
|
if (page.includes("[...")) throw new Error(`Catch-all routes are not supported: ${page}`)
|
|
828
830
|
const filled = page.replace(/\[([^\]]+)\]/g, (_, name) => {
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { join, resolve } from "node:path"
|
|
2
|
+
import { assetPath } from "./path-helpers.mjs"
|
|
3
|
+
import { createSourceGraph } from "./source-graph.mjs"
|
|
4
|
+
import { createWorkerCompiler } from "./worker-compiler.mjs"
|
|
5
|
+
|
|
6
|
+
export function createProjectSession(projectRoot = process.cwd()) {
|
|
7
|
+
const root = resolve(projectRoot)
|
|
8
|
+
const sourceDirectory = join(root, "src")
|
|
9
|
+
const graph = createSourceGraph(root)
|
|
10
|
+
return {
|
|
11
|
+
root,
|
|
12
|
+
sourceDirectory,
|
|
13
|
+
pagesDirectory: join(sourceDirectory, "pages"),
|
|
14
|
+
workDirectory: join(root, ".kudzu"),
|
|
15
|
+
outputDirectory: join(root, "dist"),
|
|
16
|
+
sourceIndex: new Map(),
|
|
17
|
+
sourceFiles: new Set(),
|
|
18
|
+
graph,
|
|
19
|
+
workerCompiler: createWorkerCompiler({ root, sourceDirectory, assetPath, ...graph })
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -18,17 +18,15 @@ import { assetPath, relativeModulePath, withBase } from "./path-helpers.mjs"
|
|
|
18
18
|
import { createReactMigrationPass, reactMemoExpression } from "./react-migration-pass.mjs"
|
|
19
19
|
import { normalizeRenderControlFlow } from "./render-control-pass.mjs"
|
|
20
20
|
import { createRouterPass } from "./router-pass.mjs"
|
|
21
|
-
import {
|
|
22
|
-
import { createWorkerCompiler } from "./worker-compiler.mjs"
|
|
21
|
+
import { createProjectSession } from "./project-session.mjs"
|
|
23
22
|
import { createZustandPass } from "./zustand-pass.mjs"
|
|
24
23
|
|
|
25
|
-
|
|
26
|
-
const sourceDirectory
|
|
27
|
-
const
|
|
28
|
-
const workDirectory = join(root, ".kudzu")
|
|
24
|
+
export function createSourceCompiler(project) {
|
|
25
|
+
const { root, sourceDirectory, pagesDirectory, workDirectory, workerCompiler } = project
|
|
26
|
+
const { ordinaryRuntimeDependencies, parseSourceFile, resolveSourceImport, runtimeModuleReference } = project.graph
|
|
29
27
|
const staticAssetExtensions = new Set([".avif", ".gif", ".ico", ".jpeg", ".jpg", ".otf", ".png", ".svg", ".ttf", ".webp", ".woff", ".woff2"])
|
|
30
28
|
|
|
31
|
-
|
|
29
|
+
function compileSource(file, sourceFiles, sourceIndex, staticFiles, cssModules, base) {
|
|
32
30
|
const importedAssets = new Set()
|
|
33
31
|
const source = sourceIndex.get(file)
|
|
34
32
|
const semantic = createSemanticArtifact(relative(root, file).replaceAll(sep, "/"))
|
|
@@ -90,7 +88,7 @@ function emittedPackageReference(source, file, packages) {
|
|
|
90
88
|
return found
|
|
91
89
|
}
|
|
92
90
|
|
|
93
|
-
|
|
91
|
+
function reachableSourceFiles(entries, sourceFiles, sourceIndex) {
|
|
94
92
|
const reachable = new Set()
|
|
95
93
|
const ordinary = new Set()
|
|
96
94
|
const workers = new Set()
|
|
@@ -2767,7 +2765,7 @@ function localComponentDeclaration(sourceFile, name) {
|
|
|
2767
2765
|
return undefined
|
|
2768
2766
|
}
|
|
2769
2767
|
|
|
2770
|
-
|
|
2768
|
+
async function collectClientModules(entries, sourceFiles) {
|
|
2771
2769
|
const modules = new Set()
|
|
2772
2770
|
const queue = [...new Set(entries)]
|
|
2773
2771
|
while (queue.length) {
|
|
@@ -2795,7 +2793,7 @@ export async function collectClientModules(entries, sourceFiles) {
|
|
|
2795
2793
|
return [...modules].sort()
|
|
2796
2794
|
}
|
|
2797
2795
|
|
|
2798
|
-
|
|
2796
|
+
async function compileClientModule(file, sourceFiles, staticFiles, cssModules, base) {
|
|
2799
2797
|
const importedAssets = new Set()
|
|
2800
2798
|
const source = await readFile(file, "utf8")
|
|
2801
2799
|
const transformer = context => sourceFile => {
|
|
@@ -2840,7 +2838,7 @@ function resolveStaticImport(importer, specifier, staticFiles) {
|
|
|
2840
2838
|
return target
|
|
2841
2839
|
}
|
|
2842
2840
|
|
|
2843
|
-
|
|
2841
|
+
async function safeStaticFiles(files) {
|
|
2844
2842
|
const sourceRoot = await realpath(sourceDirectory)
|
|
2845
2843
|
const entries = await Promise.all(files.map(async file => {
|
|
2846
2844
|
try {
|
|
@@ -2855,7 +2853,7 @@ export async function safeStaticFiles(files) {
|
|
|
2855
2853
|
return new Set(entries.filter(Boolean))
|
|
2856
2854
|
}
|
|
2857
2855
|
|
|
2858
|
-
|
|
2856
|
+
function orderSourceStyles(cssFiles, sourceFiles, sourceIndex, staticFiles) {
|
|
2859
2857
|
const ordered = []
|
|
2860
2858
|
const seenStyles = new Set()
|
|
2861
2859
|
const seenSources = new Set()
|
|
@@ -2940,7 +2938,7 @@ function rejectUnsupportedClientImports(sourceFile, file) {
|
|
|
2940
2938
|
visit(sourceFile)
|
|
2941
2939
|
}
|
|
2942
2940
|
|
|
2943
|
-
|
|
2941
|
+
function layoutExportError(file, source) {
|
|
2944
2942
|
const sourceFile = parseSourceFile(file, source)
|
|
2945
2943
|
for (const statement of sourceFile.statements) {
|
|
2946
2944
|
if (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)) {
|
|
@@ -2956,20 +2954,32 @@ export function layoutExportError(file, source) {
|
|
|
2956
2954
|
return new Error(`${relative(root, file)} layout export must be a function`)
|
|
2957
2955
|
}
|
|
2958
2956
|
|
|
2959
|
-
|
|
2957
|
+
function clientModulePath(file) {
|
|
2960
2958
|
return `modules/${relative(sourceDirectory, file).replaceAll(sep, "/").replace(/\.(?:ts|tsx)$/, ".js")}`
|
|
2961
2959
|
}
|
|
2962
2960
|
|
|
2963
|
-
|
|
2961
|
+
function compiledPath(file) {
|
|
2964
2962
|
return join(workDirectory, relative(sourceDirectory, file)).replace(/\.(?:ts|tsx)$/, ".mjs")
|
|
2965
2963
|
}
|
|
2966
2964
|
|
|
2967
2965
|
const compileEventCommand = createCommandSpecializer({ isPrimitiveLiteral: isPrimitiveDefaultLiteral })
|
|
2968
2966
|
const { analyzeZustandStores, normalizeZustandMigrationSyntax } = createZustandPass({ isSerializableStateLiteral, nativeCaptureNames, sourceDirectory })
|
|
2969
|
-
const workerCompiler = createWorkerCompiler({ root, sourceDirectory, assetPath, parseSourceFile, resolveSourceImport, runtimeModuleReference })
|
|
2970
2967
|
const handlerLowering = createHandlerLowering({ cloneAst, synthesizeTree })
|
|
2971
2968
|
const printHandlerModule = createHandlerCodegen({
|
|
2972
2969
|
resolveClientImport: (entry, handlerPath) => entry.package ? entry.target : relativeModulePath(handlerPath, clientModulePath(entry.target))
|
|
2973
2970
|
})
|
|
2974
2971
|
const { normalizeReactMigrationSyntax, validateUseIdSyntax } = createReactMigrationPass({ cloneAst, jsxTagName })
|
|
2975
2972
|
const normalizeReactRouterSyntax = createRouterPass({ withBase })
|
|
2973
|
+
|
|
2974
|
+
return { collectClientModules, compileClientModule, compiledPath, compileSource, layoutExportError, orderSourceStyles, reachableSourceFiles, safeStaticFiles }
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
const currentCompiler = () => createSourceCompiler(createProjectSession())
|
|
2978
|
+
export const collectClientModules = (...arguments_) => currentCompiler().collectClientModules(...arguments_)
|
|
2979
|
+
export const compileClientModule = (...arguments_) => currentCompiler().compileClientModule(...arguments_)
|
|
2980
|
+
export const compiledPath = (...arguments_) => currentCompiler().compiledPath(...arguments_)
|
|
2981
|
+
export const compileSource = (...arguments_) => currentCompiler().compileSource(...arguments_)
|
|
2982
|
+
export const layoutExportError = (...arguments_) => currentCompiler().layoutExportError(...arguments_)
|
|
2983
|
+
export const orderSourceStyles = (...arguments_) => currentCompiler().orderSourceStyles(...arguments_)
|
|
2984
|
+
export const reachableSourceFiles = (...arguments_) => currentCompiler().reachableSourceFiles(...arguments_)
|
|
2985
|
+
export const safeStaticFiles = (...arguments_) => currentCompiler().safeStaticFiles(...arguments_)
|
|
@@ -2,18 +2,46 @@ import { dirname, extname, join, relative, resolve } from "node:path"
|
|
|
2
2
|
import ts from "typescript"
|
|
3
3
|
import { sourceNodeError } from "./ast-helpers.mjs"
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
export function createSourceGraph(root) {
|
|
6
|
+
const resolveSourceImport = (importer, specifier, sourceFiles) => {
|
|
7
|
+
const base = resolve(dirname(importer), specifier)
|
|
8
|
+
const extension = extname(base)
|
|
9
|
+
const stem = /\.(?:js|jsx|ts|tsx)$/.test(extension) ? base.slice(0, -extension.length) : base
|
|
10
|
+
const candidates = extension === ".ts" || extension === ".tsx"
|
|
11
|
+
? [base]
|
|
12
|
+
: [`${stem}.ts`, `${stem}.tsx`, join(stem, "index.ts"), join(stem, "index.tsx")]
|
|
13
|
+
const matches = candidates.filter(candidate => sourceFiles.has(candidate))
|
|
14
|
+
if (matches.length !== 1) throw new Error(`${relative(root, importer)} Relative import ${JSON.stringify(specifier)} must resolve to one TypeScript file in src/`)
|
|
15
|
+
return matches[0]
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const ordinaryRuntimeDependencies = (file, sourceFile, sourceFiles, isStaticImport) => {
|
|
19
|
+
const dependencies = []
|
|
20
|
+
const rejectDynamicImports = node => {
|
|
21
|
+
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
22
|
+
const argument = node.arguments[0]
|
|
23
|
+
const specifier = node.arguments.length === 1 && ts.isStringLiteralLike(argument) ? JSON.stringify(argument.text) : argument?.getText(sourceFile) ?? "<missing>"
|
|
24
|
+
throw sourceNodeError(node, sourceFile, `Dynamic import ${specifier} is not supported in ordinary source modules`)
|
|
25
|
+
}
|
|
26
|
+
ts.forEachChild(node, rejectDynamicImports)
|
|
27
|
+
}
|
|
28
|
+
rejectDynamicImports(sourceFile)
|
|
29
|
+
for (const node of sourceFile.statements) {
|
|
30
|
+
if ((!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) || !runtimeModuleReference(node) || !node.moduleSpecifier || !ts.isStringLiteral(node.moduleSpecifier)) continue
|
|
31
|
+
const specifier = node.moduleSpecifier
|
|
32
|
+
if (!specifier.text.startsWith(".") || isStaticImport(specifier.text)) continue
|
|
33
|
+
try {
|
|
34
|
+
dependencies.push(resolveSourceImport(file, specifier.text, sourceFiles))
|
|
35
|
+
} catch (error) {
|
|
36
|
+
const detail = error.message.slice(error.message.indexOf("Relative import"))
|
|
37
|
+
const edge = ts.isExportDeclaration(node) ? "re-export" : "import"
|
|
38
|
+
throw sourceNodeError(specifier, sourceFile, detail.replace("Relative import", `Relative runtime ${edge}`))
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return dependencies
|
|
42
|
+
}
|
|
6
43
|
|
|
7
|
-
|
|
8
|
-
const base = resolve(dirname(importer), specifier)
|
|
9
|
-
const extension = extname(base)
|
|
10
|
-
const stem = /\.(?:js|jsx|ts|tsx)$/.test(extension) ? base.slice(0, -extension.length) : base
|
|
11
|
-
const candidates = extension === ".ts" || extension === ".tsx"
|
|
12
|
-
? [base]
|
|
13
|
-
: [`${stem}.ts`, `${stem}.tsx`, join(stem, "index.ts"), join(stem, "index.tsx")]
|
|
14
|
-
const matches = candidates.filter(candidate => sourceFiles.has(candidate))
|
|
15
|
-
if (matches.length !== 1) throw new Error(`${relative(root, importer)} Relative import ${JSON.stringify(specifier)} must resolve to one TypeScript file in src/`)
|
|
16
|
-
return matches[0]
|
|
44
|
+
return { ordinaryRuntimeDependencies, parseSourceFile, resolveSourceImport, runtimeModuleReference }
|
|
17
45
|
}
|
|
18
46
|
|
|
19
47
|
export function runtimeModuleReference(node) {
|
|
@@ -25,32 +53,6 @@ export function runtimeModuleReference(node) {
|
|
|
25
53
|
return clause.namedBindings?.elements.some(entry => !entry.isTypeOnly) ?? false
|
|
26
54
|
}
|
|
27
55
|
|
|
28
|
-
export function ordinaryRuntimeDependencies(file, sourceFile, sourceFiles, isStaticImport) {
|
|
29
|
-
const dependencies = []
|
|
30
|
-
const rejectDynamicImports = node => {
|
|
31
|
-
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
32
|
-
const argument = node.arguments[0]
|
|
33
|
-
const specifier = node.arguments.length === 1 && ts.isStringLiteralLike(argument) ? JSON.stringify(argument.text) : argument?.getText(sourceFile) ?? "<missing>"
|
|
34
|
-
throw sourceNodeError(node, sourceFile, `Dynamic import ${specifier} is not supported in ordinary source modules`)
|
|
35
|
-
}
|
|
36
|
-
ts.forEachChild(node, rejectDynamicImports)
|
|
37
|
-
}
|
|
38
|
-
rejectDynamicImports(sourceFile)
|
|
39
|
-
for (const node of sourceFile.statements) {
|
|
40
|
-
if ((!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) || !runtimeModuleReference(node) || !node.moduleSpecifier || !ts.isStringLiteral(node.moduleSpecifier)) continue
|
|
41
|
-
const specifier = node.moduleSpecifier
|
|
42
|
-
if (!specifier.text.startsWith(".") || isStaticImport(specifier.text)) continue
|
|
43
|
-
try {
|
|
44
|
-
dependencies.push(resolveSourceImport(file, specifier.text, sourceFiles))
|
|
45
|
-
} catch (error) {
|
|
46
|
-
const detail = error.message.slice(error.message.indexOf("Relative import"))
|
|
47
|
-
const edge = ts.isExportDeclaration(node) ? "re-export" : "import"
|
|
48
|
-
throw sourceNodeError(specifier, sourceFile, detail.replace("Relative import", `Relative runtime ${edge}`))
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return dependencies
|
|
52
|
-
}
|
|
53
|
-
|
|
54
56
|
export function parseSourceFile(file, source) {
|
|
55
57
|
return ts.createSourceFile(file, source, ts.ScriptTarget.ES2022, true, file.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS)
|
|
56
58
|
}
|
|
@@ -4,8 +4,6 @@ import { dirname, relative, resolve, sep } from "node:path"
|
|
|
4
4
|
import { build as bundle } from "esbuild"
|
|
5
5
|
import ts from "typescript"
|
|
6
6
|
import { containsJsx, isUnshadowedGlobal, nearestFunction, sourceNodeError } from "./ast-helpers.mjs"
|
|
7
|
-
import { assetPath } from "./path-helpers.mjs"
|
|
8
|
-
import { parseSourceFile, resolveSourceImport, runtimeModuleReference } from "./source-graph.mjs"
|
|
9
7
|
|
|
10
8
|
export function createWorkerCompiler({
|
|
11
9
|
root,
|
|
@@ -168,9 +166,3 @@ export function createWorkerCompiler({
|
|
|
168
166
|
|
|
169
167
|
return { candidate, emit, rejectConstructions, rejectOrdinaryImports, rewriteEffect }
|
|
170
168
|
}
|
|
171
|
-
|
|
172
|
-
export function emitWorkers(references, sourceFiles, assetsDirectory, base, minify) {
|
|
173
|
-
const root = process.cwd()
|
|
174
|
-
const sourceDirectory = resolve(root, "src")
|
|
175
|
-
return createWorkerCompiler({ root, sourceDirectory, assetPath, parseSourceFile, resolveSourceImport, runtimeModuleReference }).emit(references, sourceFiles, assetsDirectory, base, minify)
|
|
176
|
-
}
|