@brust/core 2.0.0-alpha.1 → 2.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/README.md +66 -6
  2. package/native/index.d.ts +87 -5
  3. package/native/index.js +61 -54
  4. package/package.json +22 -9
  5. package/src/actions/client.ts +22 -5
  6. package/src/actions/load.ts +2 -1
  7. package/src/actions/prefix.ts +27 -3
  8. package/src/actions-bridge.ts +76 -19
  9. package/src/browser.ts +3 -1
  10. package/src/build/actions-only.ts +86 -0
  11. package/src/build/build-eval.ts +319 -0
  12. package/src/build/build-icons.ts +69 -0
  13. package/src/build/bundle.ts +278 -43
  14. package/src/build/cf-assets.ts +83 -0
  15. package/src/build/cf-core.ts +90 -0
  16. package/src/build/cf-entry.ts +76 -0
  17. package/src/build/cf-wrangler.ts +169 -0
  18. package/src/build/cloudflare.ts +317 -0
  19. package/src/build/compile.ts +72 -4
  20. package/src/build/config.ts +274 -15
  21. package/src/build/css.ts +275 -0
  22. package/src/build/features.ts +110 -0
  23. package/src/build/index.ts +223 -20
  24. package/src/build/manifest.ts +59 -8
  25. package/src/build/pkg-src.ts +383 -0
  26. package/src/build/scan.ts +61 -20
  27. package/src/build/server-only.ts +39 -0
  28. package/src/build/ssg-render.ts +65 -0
  29. package/src/build/ssg.ts +146 -0
  30. package/src/build/static-worker.ts +91 -0
  31. package/src/build/static.ts +258 -0
  32. package/src/build/tailwind.ts +117 -0
  33. package/src/build/tsconfig-paths.ts +67 -0
  34. package/src/build-time.ts +10 -0
  35. package/src/cache-adapter/bridge.ts +91 -0
  36. package/src/cache-adapter/conformance.ts +226 -0
  37. package/src/cache-adapter/index.ts +10 -0
  38. package/src/cache-adapter/load.ts +144 -0
  39. package/src/cache-adapter/memory.ts +229 -0
  40. package/src/cache-adapter/runtime.ts +124 -0
  41. package/src/cache-adapter/types.ts +96 -0
  42. package/src/cache-adapter/workers.ts +118 -0
  43. package/src/cache.ts +4 -1
  44. package/src/cf.ts +19 -0
  45. package/src/cli.ts +50 -2
  46. package/src/config.ts +127 -25
  47. package/src/css-modules.d.ts +8 -0
  48. package/src/dev/bun.ts +365 -0
  49. package/src/dev/client.ts +92 -0
  50. package/src/dev/devtools-data.ts +23 -0
  51. package/src/dev/devtools.ts +356 -0
  52. package/src/dev/diag.ts +30 -0
  53. package/src/dev/proxy.ts +236 -0
  54. package/src/dev/tui.ts +144 -0
  55. package/src/dev/watch.ts +81 -0
  56. package/src/dev.ts +93 -0
  57. package/src/handlers.ts +282 -0
  58. package/src/index.ts +3 -1
  59. package/src/native.ts +49 -2
  60. package/src/routes.ts +20 -1
  61. package/src/run.ts +48 -11
  62. package/src/server-handlers.ts +32 -0
  63. package/src/worker.ts +129 -245
@@ -0,0 +1,90 @@
1
+ // Locates `@brust/core-cf` (the wasm core + glue, built by lane M4-CF-3) and reads its `brust` metadata (M4-CF R3, R4).
2
+ // Order: `--wasm-from-source` > env BRUST_CORE_CF_DIR > the app's node_modules > next to @brust/core.
3
+ import { existsSync, readFileSync } from 'node:fs'
4
+ import { dirname, join } from 'node:path'
5
+ import { BuildError } from './errors'
6
+
7
+ export interface CoreCfMeta {
8
+ abi: number
9
+ /** worker-build entry, relative to `worker/` */
10
+ main: string
11
+ glue: string
12
+ /** dir under `worker/` that holds `brust-app.js` (next to the glue's `raw_module`) */
13
+ appModuleDir: string
14
+ compatibilityDate: string
15
+ }
16
+
17
+ export interface CoreCf {
18
+ dir: string
19
+ workerDir: string
20
+ meta: CoreCfMeta
21
+ version: string
22
+ warnings: string[]
23
+ }
24
+
25
+ export interface ResolveOpts {
26
+ appRoot: string
27
+ fromSource: boolean
28
+ env: Record<string, string | undefined>
29
+ /** `@brust/core`'s package dir (default: this package) */
30
+ corePkgDir?: string
31
+ run?: (cmd: string[], cwd: string) => number
32
+ which?: (bin: string) => string | null
33
+ }
34
+
35
+ const HINT = (v: string) => `install it with \`bun add -d @brust/core-cf@${v}\` or pass --wasm-from-source`
36
+
37
+ function readJson(file: string): Record<string, unknown> | null {
38
+ try {
39
+ return JSON.parse(readFileSync(file, 'utf8'))
40
+ } catch {
41
+ return null
42
+ }
43
+ }
44
+
45
+ function fromDir(dir: string, coreVersion: string): CoreCf {
46
+ const pkg = readJson(join(dir, 'package.json'))
47
+ const m = pkg?.brust as Partial<CoreCfMeta> | undefined
48
+ if (!pkg || !m) throw new BuildError('cf-wasm', `${dir}/package.json has no "brust" metadata (not a @brust/core-cf package?)`)
49
+ if (m.abi !== 1) throw new BuildError('cf-wasm', `@brust/core-cf has abi ${String(m.abi)}; this brust supports abi 1 — upgrade brust or core-cf`)
50
+ const meta: CoreCfMeta = {
51
+ abi: 1,
52
+ main: m.main ?? 'index.js',
53
+ glue: m.glue ?? m.main ?? 'index.js',
54
+ appModuleDir: m.appModuleDir ?? '.',
55
+ compatibilityDate: m.compatibilityDate ?? '2026-10-01',
56
+ }
57
+ const workerDir = join(dir, 'worker')
58
+ if (!existsSync(join(workerDir, meta.main)))
59
+ throw new BuildError('cf-wasm', `@brust/core-cf has no worker/${meta.main} (${dir}); ${HINT(coreVersion)}`)
60
+ const version = String(pkg.version ?? '')
61
+ const warnings: string[] = []
62
+ if (version !== coreVersion) warnings.push(`[brust] @brust/core-cf ${version} differs from @brust/core ${coreVersion}`)
63
+ return { dir, workerDir, meta, version, warnings }
64
+ }
65
+
66
+ export function resolveCoreCf(o: ResolveOpts): CoreCf {
67
+ const corePkgDir = o.corePkgDir ?? join(import.meta.dir, '..', '..')
68
+ const coreVersion = String(readJson(join(corePkgDir, 'package.json'))?.version ?? '0.0.0')
69
+ if (o.fromSource) {
70
+ const repo = join(corePkgDir, '..', '..')
71
+ if (!existsSync(join(repo, 'crates', 'brust-wasm'))) throw new BuildError('cf-wasm', 'cf-wasm needs crates/brust-wasm (lane M4-CF-3): --wasm-from-source requires a brust checkout')
72
+ const which = o.which ?? ((b: string) => Bun.which(b))
73
+ for (const bin of ['cargo']) if (!which(bin)) throw new BuildError('cf-wasm', `--wasm-from-source needs \`${bin}\` on PATH`)
74
+ const run = o.run ?? ((cmd, cwd) => Bun.spawnSync(cmd, { cwd, stdio: ['inherit', 'inherit', 'inherit'] }).exitCode)
75
+ // The build script writes npm/core-cf/worker/ (lane 3 owns it; never bare `worker-build`).
76
+ const code = run(['bun', join('crates', 'brust-wasm', 'scripts', 'build.ts')], repo)
77
+ if (code !== 0) throw new BuildError('cf-wasm', `crates/brust-wasm/scripts/build.ts failed (exit ${code})`)
78
+ return fromDir(join(repo, 'npm', 'core-cf'), coreVersion)
79
+ }
80
+ const envDir = o.env.BRUST_CORE_CF_DIR
81
+ if (envDir) return fromDir(envDir, coreVersion)
82
+ for (const from of [o.appRoot, corePkgDir]) {
83
+ try {
84
+ return fromDir(dirname(Bun.resolveSync('@brust/core-cf/package.json', from)), coreVersion)
85
+ } catch (e) {
86
+ if (e instanceof BuildError) throw e
87
+ }
88
+ }
89
+ throw new BuildError('cf-wasm', `@brust/core-cf is not installed; ${HINT(coreVersion)}`)
90
+ }
@@ -0,0 +1,76 @@
1
+ // The generated Cloudflare entry (M4-CF spec §4, R9, R13): ~25 lines that wire the user's routes, jobs and
2
+ // actions into the six exports the wasm glue imports from `./brust-app.js`. Pure: text in, text out.
3
+ export interface CfConfigJson {
4
+ abi: 1
5
+ generator: string
6
+ l1Capacity: number
7
+ jobCacheCapacity: number
8
+ stats: boolean
9
+ edgeCache: 'off'
10
+ cors?: unknown
11
+ actions?: { prefix: string; maxBodyBytes: number; maxResponseBytes: number; crossSite: 'reject' | 'allow' }
12
+ /** The cache adapter (optional under abi 1, cache adapters R13). */
13
+ cache?: { adapter: string; getTimeoutMs: number; maxBodyBytes: number; namespace: string; buildId: string; epochIntervalMs: number }
14
+ }
15
+
16
+ /** The cache adapter wiring of the entry: absent → the entry is byte-identical to the no-cache one (D3). */
17
+ export interface CfEntryCache {
18
+ /** The adapter module (an absolute path, or a built-in package spec). */
19
+ module: string
20
+ options: Record<string, unknown>
21
+ /** A composed built-in broadcast's package spec. */
22
+ broadcast?: string
23
+ broadcastOptions?: Record<string, unknown>
24
+ }
25
+
26
+ export interface CfEntryInput {
27
+ /** absolute paths; each goes through JSON.stringify */
28
+ entry: string
29
+ jobsEntry: string
30
+ actionsEntry: string | null
31
+ /** L16: no pages: the routes module and the jobs module are not imported; the handlers serve an empty route table. */
32
+ actionsOnly?: boolean
33
+ prefix: string
34
+ manifestPath: string
35
+ templatesPath: string
36
+ config: CfConfigJson
37
+ cache?: CfEntryCache | null
38
+ /** A Durable Object is configured: the entry re-exports `BrustCacheDO` (R1; `worker/main.js` re-exports it from this one module). */
39
+ doClass?: boolean
40
+ }
41
+
42
+ export function cfEntrySource(i: CfEntryInput): string {
43
+ const q = JSON.stringify
44
+ const actions = i.actionsEntry !== null
45
+ const c = i.cache ?? null
46
+ const pages = i.actionsOnly !== true
47
+ return `${[
48
+ '// generated by `brust build --target cloudflare` — do not edit (M4-CF spec §4)',
49
+ ...(pages ? [`import * as R from ${q(i.entry)}`, `import J, * as JM from ${q(i.jobsEntry)}`] : []),
50
+ ...(actions ? [`import A from ${q(i.actionsEntry)}`] : []),
51
+ `import M from ${q(i.manifestPath)}`,
52
+ `import T from ${q(i.templatesPath)}`,
53
+ `import { fetchInScope, flattenRoutes, jsonCall, makeHandlers, noActions } from "@brust/core/server-handlers"`,
54
+ ...(actions ? ['import { mountActions } from "@brust/core/server-handlers/actions"'] : []),
55
+ pages
56
+ ? 'const h = makeHandlers({ leaves: flattenRoutes(R.routes ?? R.default).leaves, jobs: J, manifest: M, stores: JM.stores ?? {} })'
57
+ : 'const h = makeHandlers({ leaves: [], jobs: {}, manifest: M, stores: {} })',
58
+ ...(actions ? [`const app = mountActions(A, ${q(i.prefix)}).compile() // startup-phase compile (R9)`] : []),
59
+ 'export const loader = jsonCall(h.loader)',
60
+ 'export const jobs = jsonCall(h.jobs)',
61
+ actions ? 'export const action = (req) => fetchInScope(app, req)' : 'export const action = noActions',
62
+ 'export const MANIFEST = JSON.stringify(M)',
63
+ 'export const TEMPLATES = T',
64
+ ...(c
65
+ ? [
66
+ `import CACHE from ${q(c.module)}`,
67
+ ...(c.broadcast ? [`import CACHE_BROADCAST from ${q(c.broadcast)}`] : []),
68
+ 'import { waitUntil } from "cloudflare:workers"',
69
+ 'import { install as installRuntime } from "@brust/core/server-handlers"',
70
+ `export const install = (rt) => installRuntime(rt, { adapter: CACHE, options: ${JSON.stringify(c.options)}, ${c.broadcast ? `broadcast: CACHE_BROADCAST, broadcastOptions: ${JSON.stringify(c.broadcastOptions ?? {})}, ` : ''}config: ${JSON.stringify(i.config.cache)}, waitUntil })`,
71
+ ]
72
+ : ['export { install } from "@brust/core/server-handlers"']),
73
+ ...(i.doClass ? ['export { BrustCacheDO } from "@brust/cache-cloudflare/do"'] : []),
74
+ `export const CONFIG = ${q(JSON.stringify(i.config))}`,
75
+ ].join('\n')}\n`
76
+ }
@@ -0,0 +1,169 @@
1
+ // `wrangler.jsonc` for `dist/cf/` (M4-CF R5, R6, R7): the user's app-root config merged with the keys brust owns.
2
+ // Pure apart from `readUserWrangler`. Never adds an `account_id`; copies one only if the user wrote it.
3
+ import { existsSync } from 'node:fs'
4
+ import { isAbsolute, join, relative } from 'node:path'
5
+ import { BuildError } from './errors'
6
+
7
+ type Json = Record<string, unknown>
8
+ export interface UserWrangler {
9
+ file: string | null
10
+ config: Json
11
+ }
12
+
13
+ export interface MergeOpts {
14
+ appRoot: string
15
+ cfDir: string
16
+ /** `[cloudflare] name` */
17
+ name?: string
18
+ pkgName?: string
19
+ compatibilityDate: string
20
+ /** worker-build entry, relative to `worker/` (core-cf `brust.main`) */
21
+ main: string
22
+ version: string
23
+ /** L16: an actions-only Worker has no Static Assets (and no ASSETS binding). */
24
+ noAssets?: boolean
25
+ }
26
+
27
+ const OWNED = ['main', 'assets', 'compatibility_date', 'no_bundle', 'find_additional_modules', 'base_dir', 'rules', 'build', 'site']
28
+ const CONFIG_FILES = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']
29
+
30
+ export async function readUserWrangler(appRoot: string): Promise<UserWrangler> {
31
+ const found = CONFIG_FILES.filter((f) => existsSync(join(appRoot, f)))
32
+ if (found.length > 1) throw new BuildError('cf-config', `more than one wrangler config in ${appRoot}: ${found.join(', ')} — keep one`)
33
+ const f = found[0]
34
+ if (!f) return { file: null, config: {} }
35
+ const text = await Bun.file(join(appRoot, f)).text()
36
+ try {
37
+ const parsed = f.endsWith('.toml') ? Bun.TOML.parse(text) : Bun.JSONC.parse(text)
38
+ return { file: f, config: (parsed ?? {}) as Json }
39
+ } catch (e) {
40
+ throw new BuildError('cf-config', `failed to parse ${join(appRoot, f)}: ${(e as Error).message}`)
41
+ }
42
+ }
43
+
44
+ const isObj = (v: unknown): v is Json => v !== null && typeof v === 'object' && !Array.isArray(v)
45
+
46
+ /** package.json `name` -> a Worker name: scope dropped, lowercased, non-[a-z0-9-] -> `-`, <= 63. */
47
+ export function workerNameOf(pkgName: string): string {
48
+ return pkgName.replace(/^@[^/]*\//, '').toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 63)
49
+ }
50
+
51
+ function rebase(o: MergeOpts, p: string): string {
52
+ return isAbsolute(p) ? p : relative(o.cfDir, join(o.appRoot, p))
53
+ }
54
+
55
+ function assertNoAssetsBinding(v: unknown, path: string): void {
56
+ if (Array.isArray(v)) return v.forEach((x, i) => assertNoAssetsBinding(x, `${path}[${i}]`))
57
+ if (!isObj(v)) return
58
+ for (const [k, x] of Object.entries(v)) {
59
+ if (k === 'assets' && path === '') continue
60
+ if ((k === 'binding' || (k === 'name' && /durable_objects/.test(path))) && x === 'ASSETS') throw new BuildError('cf-config', `wrangler config: a binding named ASSETS (${path || 'root'}) clashes with brust's static-assets binding`)
61
+ if (k === 'vars' && isObj(x) && 'ASSETS' in x) throw new BuildError('cf-config', 'wrangler config: vars.ASSETS clashes with brust\'s static-assets binding')
62
+ assertNoAssetsBinding(x, `${path}.${k}`)
63
+ }
64
+ }
65
+
66
+ function rebasePaths(o: MergeOpts, block: Json): void {
67
+ if (Array.isArray(block.d1_databases))
68
+ for (const d of block.d1_databases)
69
+ if (isObj(d)) d.migrations_dir = rebase(o, typeof d.migrations_dir === 'string' ? d.migrations_dir : 'migrations')
70
+ if (typeof block.tsconfig === 'string') block.tsconfig = rebase(o, block.tsconfig)
71
+ if (isObj(block.alias))
72
+ for (const [k, v] of Object.entries(block.alias)) if (typeof v === 'string' && v.startsWith('.')) block.alias[k] = rebase(o, v)
73
+ }
74
+
75
+ function checkFlags(block: Json, where: string): void {
76
+ if (Array.isArray(block.compatibility_flags) && block.compatibility_flags.some((f) => typeof f === 'string' && /^no_nodejs_compat/.test(f)))
77
+ throw new BuildError('cf-config', `wrangler config${where}: compatibility_flags "no_nodejs_compat*" is not allowed (AsyncLocalStorage needs nodejs_compat)`)
78
+ }
79
+
80
+ export function mergeWrangler(user: UserWrangler, o: MergeOpts): { config: Json; warnings: string[] } {
81
+ const warnings: string[] = []
82
+ const src = structuredClone(user.config)
83
+ assertNoAssetsBinding(src, '')
84
+ checkFlags(src, '')
85
+ const owned = (k: string, where: string) => warnings.push(`[brust] wrangler: ${where}${k} is owned by brust build --target cloudflare; ignored`)
86
+ const rest: Json = {}
87
+ for (const [k, v] of Object.entries(src)) {
88
+ if (OWNED.includes(k)) owned(k, '')
89
+ else rest[k] = v
90
+ }
91
+ const userName = typeof rest.name === 'string' ? rest.name : undefined
92
+ if (o.name !== undefined && userName !== undefined && userName !== o.name)
93
+ warnings.push(`[brust] wrangler: name "${userName}" conflicts with [cloudflare] name "${o.name}"; brust.toml wins`)
94
+ const name = o.name ?? userName ?? (o.pkgName ? workerNameOf(o.pkgName) : undefined)
95
+ rebasePaths(o, rest)
96
+ if (isObj(rest.env))
97
+ for (const [en, eb] of Object.entries(rest.env)) {
98
+ if (!isObj(eb)) continue
99
+ checkFlags(eb, ` env.${en}`)
100
+ for (const k of OWNED)
101
+ if (k in eb) {
102
+ owned(k, `env.${en}.`)
103
+ delete eb[k]
104
+ }
105
+ rebasePaths(o, eb)
106
+ }
107
+ const config: Json = {
108
+ ...(name !== undefined ? { name } : {}),
109
+ main: `worker/${o.main}`,
110
+ compatibility_date: o.compatibilityDate,
111
+ ...(o.noAssets ? {} : { assets: { directory: 'assets', binding: 'ASSETS', run_worker_first: false, html_handling: 'none', not_found_handling: 'none' } }),
112
+ ...Object.fromEntries(Object.entries(rest).filter(([k]) => k !== 'name')),
113
+ }
114
+ return { config, warnings }
115
+ }
116
+
117
+ export interface CacheNeed {
118
+ kv?: string
119
+ do?: string
120
+ }
121
+
122
+ const KV_SNIPPET = (b: string) => `"kv_namespaces": [{ "binding": "${b}", "id": "<wrangler kv namespace create brust-cache>" }]`
123
+ const DO_SNIPPET = (b: string) =>
124
+ `"durable_objects": { "bindings": [{ "name": "${b}", "class_name": "BrustCacheDO" }] },\n "migrations": [{ "tag": "brust-cache-v1", "new_sqlite_classes": ["BrustCacheDO"] }]`
125
+
126
+ /** Does `block` declare BrustCacheDO as a SQLite class (migrations or `exports`)? `'kv'` = declared only as a KV-backed `new_classes`. */
127
+ function declaresDoClass(block: Json): boolean | 'kv' {
128
+ if (Array.isArray(block.migrations)) {
129
+ let kvBacked = false
130
+ for (const m of block.migrations) {
131
+ if (!isObj(m)) continue
132
+ if (Array.isArray(m.new_sqlite_classes) && m.new_sqlite_classes.includes('BrustCacheDO')) return true
133
+ if (Array.isArray(m.new_classes) && m.new_classes.includes('BrustCacheDO')) kvBacked = true
134
+ }
135
+ if (kvBacked) return 'kv'
136
+ }
137
+ const e = isObj(block.exports) ? block.exports.BrustCacheDO : undefined
138
+ return isObj(e) && e.type === 'durable-object' && e.storage === 'sqlite'
139
+ }
140
+
141
+ /**
142
+ * R10: the user's wrangler config (top level and every `env.<name>`) must declare the bindings the configured Cloudflare cache needs. Nothing is
143
+ * added for them. A class declaration (`migrations` / `exports`) is also accepted from the top level for an env block. Pure; `config` is not mutated.
144
+ */
145
+ export function verifyCacheBindings(config: Json, need: CacheNeed): { ok: true } | { ok: false; message: string } {
146
+ const problems: string[] = []
147
+ const blocks: [string, Json][] = [['the top level', config]]
148
+ if (isObj(config.env)) for (const [n, b] of Object.entries(config.env)) if (isObj(b)) blocks.push([`env.${n}`, b])
149
+ for (const [where, b] of blocks) {
150
+ if (need.kv !== undefined) {
151
+ const ok = Array.isArray(b.kv_namespaces) && b.kv_namespaces.some((k) => isObj(k) && k.binding === need.kv)
152
+ if (!ok) problems.push(`wrangler config ${where}: no kv_namespaces binding "${need.kv}". Add:\n ${KV_SNIPPET(need.kv)}`)
153
+ }
154
+ if (need.do !== undefined) {
155
+ const bound = isObj(b.durable_objects) && Array.isArray(b.durable_objects.bindings) && b.durable_objects.bindings.some((d) => isObj(d) && d.name === need.do && d.class_name === 'BrustCacheDO' && d.script_name === undefined)
156
+ if (!bound) problems.push(`wrangler config ${where}: no durable_objects binding { "name": "${need.do}", "class_name": "BrustCacheDO" } (without script_name). Add:\n ${DO_SNIPPET(need.do)}`)
157
+ else {
158
+ const decl = declaresDoClass(b) || (where === 'the top level' ? false : declaresDoClass(config))
159
+ if (decl === 'kv') problems.push(`wrangler config ${where}: BrustCacheDO is declared with new_classes (KV-backed, no SQL API); use new_sqlite_classes:\n "migrations": [{ "tag": "brust-cache-v1", "new_sqlite_classes": ["BrustCacheDO"] }]`)
160
+ else if (decl !== true) problems.push(`wrangler config ${where}: BrustCacheDO is not declared. Add:\n "migrations": [{ "tag": "brust-cache-v1", "new_sqlite_classes": ["BrustCacheDO"] }]`)
161
+ }
162
+ }
163
+ }
164
+ return problems.length === 0 ? { ok: true } : { ok: false, message: problems.join('\n') }
165
+ }
166
+
167
+ export function renderWrangler(config: Json): string {
168
+ return `// generated by \`brust build --target cloudflare\` — edit the app-root wrangler config instead\n${JSON.stringify(config, null, 2)}\n`
169
+ }
@@ -0,0 +1,317 @@
1
+ // `brust build --target cloudflare` (M4-CF spec §4): after the normal build, writes `<out>/cf/`:
2
+ // worker/ the @brust/core-cf glue + wasm (verbatim) + <appModuleDir>/brust-app.js (ONE Bun bundle, R2)
3
+ // assets/ Static Assets tree + _headers (R7) wrangler.jsonc (user config merged with brust's keys, R5)
4
+ // .stage/ the generated entry + the smoke harness (kept for inspection)
5
+ import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
6
+ import { builtinModules } from 'node:module'
7
+ import { dirname, join, relative } from 'node:path'
8
+ import type { BunPlugin } from 'bun'
9
+ import { BrustConfigError, type CorsConfig, loadCors } from '../config'
10
+ import { layoutAssets } from './cf-assets'
11
+ import { serverOnlyEmptyPlugin } from './server-only'
12
+ import { type CfConfigJson, cfEntrySource } from './cf-entry'
13
+ import { type CoreCf, resolveCoreCf } from './cf-core'
14
+ import { type CacheNeed, mergeWrangler, readUserWrangler, renderWrangler, type UserWrangler, verifyCacheBindings } from './cf-wrangler'
15
+ import { type CloudflareBuildConfig, CF_MIN_COMPAT_DATE } from './config'
16
+ import { MANIFEST_VERSION } from './manifest'
17
+ import { exposePlugin, PRODUCTION, type SourceOf, sourceDirPlugin } from './bundle'
18
+ import type { Compiled } from './compile'
19
+ import { cssPlugin } from './css'
20
+ import { BuildError } from './errors'
21
+ import type { CacheRecord } from './manifest'
22
+ import { BUILTINS as CACHE_BUILTINS } from '../cache-adapter/load'
23
+
24
+ export interface CfFlags {
25
+ fromSource: boolean
26
+ env: Record<string, string | undefined>
27
+ }
28
+
29
+ export interface CfPrepared {
30
+ cfg: CloudflareBuildConfig
31
+ core: CoreCf
32
+ user: UserWrangler
33
+ coreVersion: string
34
+ pkgName: string | undefined
35
+ /** brust.toml `[cors]`, validated before any write */
36
+ cors: CorsConfig | undefined
37
+ warnings: string[]
38
+ }
39
+
40
+ const DEFAULT_CFG: CloudflareBuildConfig = { name: undefined, compatibilityDate: undefined, l1Capacity: 256, jobCacheCapacity: 512, stats: false, edgeCache: 'off', alias: {} }
41
+
42
+ /** Everything that can fail on the app's own input or install, before a byte is written (index.ts rule). */
43
+ export async function prepareCloudflare(appRoot: string, cfg: CloudflareBuildConfig | null, flags: CfFlags): Promise<CfPrepared> {
44
+ const core = resolveCoreCf({ appRoot, fromSource: flags.fromSource, env: flags.env })
45
+ const user = await readUserWrangler(appRoot)
46
+ const warnings = [...core.warnings]
47
+ try {
48
+ const toml = Bun.file(join(appRoot, 'brust.toml'))
49
+ if (await toml.exists()) {
50
+ const root = Bun.TOML.parse(await toml.text()) as Record<string, unknown>
51
+ for (const k of ['server', 'workers']) if (k in root) warnings.push(`[brust] brust.toml [${k}] is ignored on this target`)
52
+ }
53
+ } catch {
54
+ // loadBuildConfig already reported a malformed brust.toml
55
+ }
56
+ let pkgName: string | undefined
57
+ try {
58
+ pkgName = (JSON.parse(readFileSync(join(appRoot, 'package.json'), 'utf8')) as { name?: string }).name
59
+ } catch {
60
+ pkgName = undefined
61
+ }
62
+ const coreVersion = String((JSON.parse(readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')) as { version?: string }).version ?? '0.0.0')
63
+ let cors: CorsConfig | undefined
64
+ try {
65
+ cors = await loadCors(appRoot)
66
+ } catch (e) {
67
+ if (e instanceof BrustConfigError) throw new BuildError('config', e.message)
68
+ throw e
69
+ }
70
+ return { cfg: cfg ?? DEFAULT_CFG, core, user, coreVersion, pkgName, cors, warnings }
71
+ }
72
+
73
+ export interface CfBuildCtx {
74
+ appRoot: string
75
+ entry: string
76
+ /** the FINAL dist dir (`out` is a tmp sibling that is renamed to it): wrangler paths are relative to `<dist>/cf` */
77
+ dist: string
78
+ compiled: Map<string, Compiled>
79
+ manifest: { components: Record<string, { template: string }>; actions?: { prefix: string; maxBodyBytes: number; maxResponseBytes?: number; crossSite?: 'reject' | 'allow' } | null; cache?: CacheRecord }
80
+ sourceOf: SourceOf
81
+ actionsEntry: string | null
82
+ /** L16 R16.3: an actions-only Worker: no pages (no routes entry, no jobs, no templates), no Static Assets. */
83
+ actionsOnly?: boolean
84
+ /** A custom cache adapter's source module (absolute). */
85
+ cacheModule?: string | null
86
+ /** `[cache] get_timeout_ms` as written (absent → the Workers default, 100). */
87
+ cacheGetTimeoutMs?: number
88
+ /** L19: CSS Module class maps (the worker reads the same map as the browser). */
89
+ cssMaps?: Map<string, Record<string, string>>
90
+ log: (s: string) => void
91
+ }
92
+
93
+ const CORE_SRC = join(import.meta.dir, '..')
94
+ const BUILTINS = new Set(builtinModules.filter((m) => !m.startsWith('_')))
95
+
96
+ /** Violations of the Workers host surface: `bun`/`bun:*` anywhere in the graph (R2 f). */
97
+ function cfGuard(appRoot: string, violations: string[]): BunPlugin {
98
+ return {
99
+ name: 'brust-cf-guard',
100
+ setup(b) {
101
+ b.onResolve({ filter: /^bun(:.*)?$/ }, (a) => {
102
+ violations.push(`${relative(appRoot, a.importer) || a.importer} imports ${a.path}`)
103
+ return { path: a.path, external: true }
104
+ })
105
+ b.onResolve({ filter: /^[a-z_]+(\/[a-z_/]+)?$/ }, (a) => (BUILTINS.has(a.path) ? { path: `node:${a.path}`, external: true } : undefined))
106
+ },
107
+ }
108
+ }
109
+
110
+ /** `[cloudflare] alias` (spec R12): a module whose resolved path is a key is replaced by its value. */
111
+ function cfAlias(alias: Record<string, string>, sourceOf: SourceOf): BunPlugin {
112
+ return {
113
+ name: 'brust-cf-alias',
114
+ setup(b) {
115
+ if (Object.keys(alias).length === 0) return
116
+ b.onResolve({ filter: /.*/ }, (a) => {
117
+ if (a.importer === '' || a.importer.includes('/node_modules/')) return undefined
118
+ let abs: string
119
+ try {
120
+ abs = Bun.resolveSync(a.path, dirname(sourceOf.get(a.importer) ?? a.importer))
121
+ } catch {
122
+ return undefined
123
+ }
124
+ const to = alias[abs]
125
+ return to === undefined ? undefined : { path: to }
126
+ })
127
+ },
128
+ }
129
+ }
130
+
131
+ /** The CF bundle's stand-in for the napi addon (`native.ts` `require('../native/index.js')`, R8): every call
132
+ * fails loudly, since a Worker has no addon. */
133
+ function cfNativeStub(handlersPath: string): BunPlugin {
134
+ const names = ['startServer', 'registerWorker', 'untilReady', 'beginDrain', 'cacheInvalidate', 'cacheStats', 'localAddr', 'planJobs', 'planJobsBuf', 'takeFetchBody', 'putFetchReply', 'cacheReplay', 'cacheL2Count', 'cacheClear']
135
+ return {
136
+ name: 'brust-cf-native',
137
+ setup(b) {
138
+ b.onResolve({ filter: /^\.\.\/native\/index\.js$/ }, (a) => (/[\\/]src[\\/]native\.ts$/.test(a.importer) ? { path: 'brust-cf-native', namespace: 'brust-cf' } : undefined))
139
+ b.onLoad({ filter: /.*/, namespace: 'brust-cf' }, () => ({
140
+ loader: 'js',
141
+ // cacheInvalidate -> the `rt.invalidate` the glue installed at start (ruling 19753649); the rest has no Worker meaning.
142
+ contents: `import { installedRuntime } from ${JSON.stringify(handlersPath)}\nconst no = (n) => () => { throw new Error(n + ' is not available on Cloudflare Workers') }\nmodule.exports = {${names.map((n) => (n === 'cacheInvalidate' ? 'cacheInvalidate: (a) => installedRuntime().invalidate(a)' : `${n}: no(${JSON.stringify(n)})`)).join(', ')}}\n`,
143
+ }))
144
+ },
145
+ }
146
+ }
147
+
148
+ /** The @brust/core `workerStorePlugin` twin for a bundle that inlines `@brust/core` (not external). */
149
+ function cfStorePlugin(appRoot: string): BunPlugin {
150
+ return {
151
+ name: 'brust-cf-store',
152
+ setup(b) {
153
+ // The core's own re-export files (`src/store/{index,react}.ts`) must keep their real target, else they loop.
154
+ b.onResolve({ filter: /^@brust\/runtime-dom\/store(\/react)?$/ }, (a) =>
155
+ a.importer.startsWith(CORE_SRC) ? undefined : { path: Bun.resolveSync(a.path.replace('@brust/runtime-dom', '@brust/core'), appRoot) },
156
+ )
157
+ },
158
+ }
159
+ }
160
+
161
+ /** The entry's cache wiring (R8 on Workers): the custom source module or the built-in spec; an `env:`
162
+ * option cannot be resolved inside a Worker (no process env at bundle time) and is refused. */
163
+ function cfEntryCache(c: CacheRecord, customModule: string | null) {
164
+ const noEnv = (o: Record<string, unknown> | undefined) => {
165
+ for (const [k, v] of Object.entries(o ?? {}))
166
+ if (typeof v === 'string' && v.startsWith('env:')) throw new BuildError('cache', `cache option ${k}: "env:" values are not available on Cloudflare Workers (use a binding)`)
167
+ }
168
+ noEnv(c.options)
169
+ noEnv(c.broadcastOptions)
170
+ const module = c.adapter === 'custom' ? customModule : CACHE_BUILTINS[c.adapter]
171
+ if (!module) throw new BuildError('cache', `cache adapter "${c.adapter}" has no module to bundle`)
172
+ return { module, options: c.options, ...(c.broadcast ? { broadcast: CACHE_BUILTINS[c.broadcast]!, broadcastOptions: c.broadcastOptions ?? {} } : {}) }
173
+ }
174
+
175
+ /** R2/R10: which Cloudflare bindings the configured cache needs (`[cache.cloudflare]` keys land in the adapter's options), or null. */
176
+ export function cacheNeeds(c: Pick<CacheRecord, 'adapter' | 'broadcast' | 'options' | 'broadcastOptions'> | undefined): CacheNeed | null {
177
+ if (!c) return null
178
+ const opt = (o: Record<string, unknown> | undefined, k: string) => (typeof o?.[k] === 'string' ? (o[k] as string) : undefined)
179
+ const all = [c.options, c.broadcastOptions]
180
+ const names = [c.adapter, c.broadcast]
181
+ const kv = names.includes('cloudflare-kv') ? (all.map((o) => opt(o, 'kv_binding')).find((b) => b) ?? 'BRUST_CACHE') : undefined
182
+ const explicitDo = all.map((o) => opt(o, 'do_binding')).find((b) => b)
183
+ const dobind = names.includes('cloudflare-do') || explicitDo !== undefined ? (explicitDo ?? 'BRUST_CACHE_DO') : undefined
184
+ return kv === undefined && dobind === undefined ? null : { ...(kv !== undefined ? { kv } : {}), ...(dobind !== undefined ? { do: dobind } : {}) }
185
+ }
186
+
187
+ function smokeFiles(app: string, cache = false): { preload: string; smoke: string } {
188
+ const preload = `// generated: stubs the Workers-only modules so brust-app.js can be imported under Bun
189
+ import { plugin } from 'bun'
190
+ plugin({
191
+ name: 'brust-cf-smoke',
192
+ setup(b) {
193
+ b.module('cloudflare:workers', () => ({ exports: { env: {}, waitUntil() {}, DurableObject: class {} }, loader: 'object' }))
194
+ },
195
+ })
196
+ `
197
+ const smoke = `// generated: build-time smoke check of the CF bundle (child process; mock leaks are process-wide)
198
+ const m = await import(${JSON.stringify(app)})
199
+ const bad = []
200
+ for (const k of ['loader', 'jobs', 'action', 'install']) if (typeof m[k] !== 'function') bad.push(k + ' is not a function')
201
+ if (typeof m.MANIFEST !== 'string' || JSON.parse(m.MANIFEST).version !== ${MANIFEST_VERSION}) bad.push('MANIFEST.version !== ${MANIFEST_VERSION}')
202
+ if (typeof m.CONFIG !== 'string' || JSON.parse(m.CONFIG).abi !== 1) bad.push('CONFIG.abi !== 1')
203
+ if (typeof m.TEMPLATES !== 'object' || m.TEMPLATES === null) bad.push('TEMPLATES is not an object')
204
+ const r = await m.loader('{}')
205
+ if (typeof r !== 'string' || !r.includes('error')) bad.push('loader({}) did not resolve an error string: ' + String(r))${cache ? `
206
+ try {
207
+ const out = m.install({ invalidate: () => ({ l1Removed: 0, jobRemoved: 0 }), l2Count: () => true })
208
+ if (!out || !out.cache || typeof out.cache.origin !== 'string') bad.push('install() returned no cache bridge')
209
+ } catch (e) { bad.push('cache adapter: ' + (e && e.message ? e.message : String(e))) }` : ''}
210
+ if (bad.length) { console.error(bad.join('\\n')); process.exit(1) }
211
+ `
212
+ return { preload, smoke }
213
+ }
214
+
215
+ export async function buildCloudflare(out: string, ctx: CfBuildCtx, p: CfPrepared): Promise<string[]> {
216
+ const cfDir = join(out, 'cf')
217
+ const stage = join(cfDir, '.stage')
218
+ const warnings = [...p.warnings]
219
+ // R10: a Cloudflare cache built-in needs the user's own bindings; verify (never add) before anything is bundled.
220
+ const need = cacheNeeds(ctx.manifest.cache)
221
+ if (need) {
222
+ const v = verifyCacheBindings(p.user.config, need)
223
+ if (!v.ok) throw new BuildError('cf-config', v.message)
224
+ }
225
+ const doClass = need?.do !== undefined
226
+ if (doClass && existsSync(join(p.core.workerDir, 'main.js'))) throw new BuildError('cf-config', `@brust/core-cf ships its own worker/main.js; brust cannot add the BrustCacheDO re-export (R1)`)
227
+ mkdirSync(stage, { recursive: true })
228
+ cpSync(p.core.workerDir, join(cfDir, 'worker'), { recursive: true })
229
+
230
+ const templates: Record<string, string> = {}
231
+ for (const [id, c] of Object.entries(ctx.manifest.components)) {
232
+ const comp = ctx.compiled.get(id)
233
+ if (comp) templates[c.template] = comp.jinja
234
+ }
235
+ const templatesPath = join(stage, 'templates.json')
236
+ writeFileSync(templatesPath, JSON.stringify(templates))
237
+
238
+ const cors = p.cors
239
+ const a = ctx.manifest.actions
240
+ const cache = ctx.manifest.cache ? { ...ctx.manifest.cache, getTimeoutMs: ctx.cacheGetTimeoutMs ?? 100 } : null
241
+ const entryCache = cache ? cfEntryCache(cache, ctx.cacheModule ?? null) : null
242
+ const config: CfConfigJson = {
243
+ abi: 1,
244
+ generator: `brust/${p.coreVersion}`,
245
+ l1Capacity: p.cfg.l1Capacity,
246
+ jobCacheCapacity: p.cfg.jobCacheCapacity,
247
+ stats: p.cfg.stats,
248
+ edgeCache: p.cfg.edgeCache,
249
+ ...(cors ? { cors } : {}),
250
+ ...(a ? { actions: { prefix: a.prefix, maxBodyBytes: a.maxBodyBytes, maxResponseBytes: a.maxResponseBytes ?? 8_388_608, crossSite: a.crossSite ?? 'reject' } } : {}),
251
+ ...(cache ? { cache: { adapter: cache.adapter, getTimeoutMs: cache.getTimeoutMs, maxBodyBytes: cache.maxBodyBytes, namespace: cache.namespace, buildId: cache.buildId, epochIntervalMs: cache.epochIntervalMs } } : {}),
252
+ }
253
+ const entryPath = join(stage, 'brust-app.entry.js')
254
+ const jobsEntry = join(out, '.stage', 'jobs.ts')
255
+ writeFileSync(
256
+ entryPath,
257
+ cfEntrySource({ entry: ctx.entry, jobsEntry, actionsOnly: ctx.actionsOnly === true, actionsEntry: a ? ctx.actionsEntry : null, prefix: a?.prefix ?? '', manifestPath: join(out, 'manifest.json'), templatesPath, config, cache: entryCache, doClass }),
258
+ )
259
+ // Bare imports of the generated files resolve from the app root (an --out-dir outside the app has no node_modules above it).
260
+ // (registered by absolute AND real path: the bundler reports the real one, e.g. /private/var on macOS)
261
+ for (const f of ctx.actionsOnly ? [entryPath] : [entryPath, jobsEntry]) {
262
+ ctx.sourceOf.set(f, ctx.entry)
263
+ ctx.sourceOf.set(realpathSync(f), ctx.entry)
264
+ }
265
+
266
+ const glue = p.core.meta.glue
267
+ const appDir = join(cfDir, 'worker', p.core.meta.appModuleDir)
268
+ const glueRel = relative(appDir, join(cfDir, 'worker', glue)).split('\\').join('/')
269
+ const glueSpec = glueRel.startsWith('.') ? glueRel : `./${glueRel}`
270
+ const violations: string[] = []
271
+ const res = await Bun.build({
272
+ entrypoints: [entryPath],
273
+ target: 'browser',
274
+ format: 'esm',
275
+ conditions: ['workerd', 'worker', 'browser'],
276
+ define: PRODUCTION,
277
+ minify: false,
278
+ external: ['node:*', 'cloudflare:*', glueSpec],
279
+ plugins: [serverOnlyEmptyPlugin(), cssPlugin(ctx.cssMaps ?? new Map()), cfGuard(ctx.appRoot, violations), cfAlias(p.cfg.alias, ctx.sourceOf), cfNativeStub(Bun.resolveSync('@brust/core/server-handlers', ctx.appRoot)), cfStorePlugin(ctx.appRoot), sourceDirPlugin(ctx.sourceOf, ctx.appRoot, ['node:*', 'cloudflare:*']), exposePlugin(ctx.compiled)],
280
+ })
281
+ if (violations.length > 0) throw new BuildError('cf-unsupported', `${[...new Set(violations)].join('\n')}\nthese modules do not exist on Cloudflare Workers; swap them with [cloudflare] alias`)
282
+ if (!res.success) throw new BuildError('bundle', `cloudflare: ${res.logs.map(String).join('\n')}`)
283
+ const js = res.outputs.filter((o) => o.kind === 'entry-point')
284
+ if (js.length !== 1) throw new BuildError('bundle', `cloudflare: expected one entry-point output, got ${js.length}`)
285
+ for (const o of res.outputs) if (o.kind !== 'entry-point') warnings.push(`[brust] cloudflare bundle: dropped non-JS output ${o.path}`)
286
+ const appFile = join(appDir, 'brust-app.js')
287
+ mkdirSync(appDir, { recursive: true })
288
+ writeFileSync(appFile, await js[0]!.text())
289
+
290
+ // An actions-only Worker has no pages and so no Static Assets (no `assets` binding in its wrangler.jsonc either).
291
+ if (!ctx.actionsOnly) warnings.push(...layoutAssets(out, cfDir, p.coreVersion).warnings)
292
+ const compatibilityDate = p.cfg.compatibilityDate ?? p.core.meta.compatibilityDate
293
+ if (compatibilityDate < CF_MIN_COMPAT_DATE) throw new BuildError('config', `compatibility_date ${compatibilityDate} is older than ${CF_MIN_COMPAT_DATE}`)
294
+ if (doClass) {
295
+ // R1: the Durable Object class must be exported by the deployed main module; the glue already imports ./brust-app.js, so it is one module copy.
296
+ const appRel = relative(join(cfDir, 'worker'), appFile).split('\\').join('/')
297
+ writeFileSync(
298
+ join(cfDir, 'worker', 'main.js'),
299
+ `// generated by brust build --target cloudflare (do not edit)\nexport * from "./${p.core.meta.main}"\nexport { default } from "./${p.core.meta.main}"\nexport { BrustCacheDO } from "./${appRel}"\n`,
300
+ )
301
+ }
302
+ const merged = mergeWrangler(p.user, { appRoot: ctx.appRoot, cfDir: join(ctx.dist, 'cf'), name: p.cfg.name, pkgName: p.pkgName, compatibilityDate, main: doClass ? 'main.js' : p.core.meta.main, version: p.coreVersion, ...(ctx.actionsOnly ? { noAssets: true } : {}) })
303
+ warnings.push(...merged.warnings)
304
+ writeFileSync(join(cfDir, 'wrangler.jsonc'), renderWrangler(merged.config))
305
+
306
+ const { preload, smoke } = smokeFiles(appFile, cache !== null)
307
+ writeFileSync(join(stage, 'smoke-preload.ts'), preload)
308
+ writeFileSync(join(stage, 'smoke.ts'), smoke)
309
+ const r = Bun.spawnSync([process.execPath, '--preload', join(stage, 'smoke-preload.ts'), join(stage, 'smoke.ts')], {
310
+ cwd: ctx.appRoot,
311
+ env: { ...process.env, NODE_ENV: 'production' },
312
+ stdout: 'pipe',
313
+ stderr: 'pipe',
314
+ })
315
+ if (r.exitCode !== 0) throw new BuildError('cf-smoke', `${r.stderr.toString().trim() || r.stdout.toString().trim()}\n(open bindings lazily: module top level runs at build time with env = {})`)
316
+ return warnings
317
+ }