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

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.
@@ -16,10 +16,11 @@ import { BuildError } from './errors'
16
16
 
17
17
  const REACT_EXTERNALS = ['react', 'react/*', 'react-dom', 'react-dom/*']
18
18
  /** Production React (and the production JSX transform: `react/jsx-runtime`, never `jsxDEV`). */
19
- const PRODUCTION = { 'process.env.NODE_ENV': JSON.stringify('production') }
19
+ export const PRODUCTION = { 'process.env.NODE_ENV': JSON.stringify('production') }
20
20
 
21
21
  const matchesExternal = (spec: string, external: string[]) =>
22
- external.some((p) => (p.endsWith('/*') ? spec.startsWith(p.slice(0, -1)) : spec === p))
22
+ // A trailing `*` is a prefix (`elysia/*`, `node:*`, `cloudflare:*`): the generated CF entry imports `cloudflare:workers`.
23
+ external.some((p) => (p.endsWith('*') ? spec.startsWith(p.slice(0, -1)) : spec === p))
23
24
 
24
25
  /** Staged artifact (by its absolute and its real path) → the component SOURCE file it was
25
26
  * generated from. */
@@ -341,6 +342,15 @@ export async function buildActions(dist: string, entry: string): Promise<string>
341
342
  return 'actions.js'
342
343
  }
343
344
 
345
+ /** `dist/cache-adapter.js` (cache adapters R8): a custom adapter module for the worker (`target: 'bun'`), with
346
+ * the actions externals so it shares the app's dependencies. */
347
+ export async function buildCacheAdapter(dist: string, entry: string): Promise<string> {
348
+ const res = await Bun.build({ entrypoints: [entry], target: 'bun', format: 'esm', external: ACTIONS_EXTERNALS })
349
+ if (!res.success) throw new BuildError('bundle', `cache adapter: ${res.logs.map(String).join('\n')}`)
350
+ write(join(dist, 'cache-adapter.js'), await res.outputs[0]!.text())
351
+ return 'cache-adapter.js'
352
+ }
353
+
344
354
  /** `dist/jobs.js` (`target: 'bun'`, React and `@brust/core` external): default export
345
355
  * `{ [componentId]: { precompute?, ssr? } }`; `ssr` only for react-tier, non-client_only components. */
346
356
  export async function buildJobs(dist: string, compiled: Map<string, Compiled>, sourceOf: SourceOf, appRoot: string, stores: string[] = []): Promise<void> {
@@ -0,0 +1,81 @@
1
+ // Static assets for Workers Static Assets (M4-CF R7): only files the native host would serve (`safe_rel` in
2
+ // `crates/brust-core/src/static_rules.rs`), laid out under the URL they are requested at, plus `_headers`.
3
+ import { cpSync, existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join } from 'node:path'
5
+
6
+ const SEG = /^[A-Za-z0-9_.-]+$/
7
+ const IMMUTABLE = 'public, max-age=31536000, immutable'
8
+ const PUBLIC_DEFAULT = 'public, max-age=3600'
9
+ const MAX_RULES = 100
10
+
11
+ /** `static_rules.rs` `is_hashed`: the stem ends in `-<hex6+>` (lowercase) with at least one digit. */
12
+ export function isHashed(file: string): boolean {
13
+ const base = file.slice(file.lastIndexOf('/') + 1)
14
+ const dot = base.lastIndexOf('.')
15
+ const stem = dot > 0 ? base.slice(0, dot) : base
16
+ const i = stem.lastIndexOf('-')
17
+ if (i < 0) return false
18
+ const h = stem.slice(i + 1)
19
+ return h.length >= 6 && /^[0-9a-f]+$/.test(h) && /\d/.test(h)
20
+ }
21
+
22
+ const segOk = (s: string) => s !== '' && !s.startsWith('.') && SEG.test(s)
23
+
24
+ /** `client/<file>.js|.css`: `is_safe_island_filename` / `is_safe_css_filename`. */
25
+ const clientOk = (f: string) => segOk(f) && !f.includes('..') && (f.endsWith('.js') || f.endsWith('.css'))
26
+
27
+ function walk(dir: string, rel = ''): string[] {
28
+ const out: string[] = []
29
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
30
+ const r = rel ? `${rel}/${e.name}` : e.name
31
+ if (e.isDirectory()) out.push(...walk(join(dir, e.name), r))
32
+ else if (e.isFile() || statSync(join(dir, e.name)).isFile()) out.push(r)
33
+ }
34
+ return out.sort()
35
+ }
36
+
37
+ /** Copies the admissible files of `<out>/client` and `<out>/public` into `<cfDir>/assets/...`; returns the
38
+ * asset-relative paths (`_brust/client/x.js`, `public/img/a.png`) and writes `assets/_headers`. */
39
+ export function layoutAssets(out: string, cfDir: string, version: string): { files: string[]; warnings: string[] } {
40
+ const assets = join(cfDir, 'assets')
41
+ mkdirSync(assets, { recursive: true })
42
+ const files: string[] = []
43
+ const warnings: string[] = []
44
+ const copy = (from: string, to: string) => {
45
+ mkdirSync(dirname(join(assets, to)), { recursive: true })
46
+ cpSync(from, join(assets, to))
47
+ files.push(to)
48
+ }
49
+ const client = join(out, 'client')
50
+ if (existsSync(client))
51
+ for (const f of walk(client)) {
52
+ if (!f.includes('/') && clientOk(f)) copy(join(client, f), `_brust/client/${f}`)
53
+ else warnings.push(`[brust] assets: client/${f} is not served natively; skipped`)
54
+ }
55
+ const pub = join(out, 'public')
56
+ if (existsSync(pub))
57
+ for (const f of walk(pub)) {
58
+ if (f.split('/').every(segOk)) copy(join(pub, f), `public/${f}`)
59
+ else warnings.push(`[brust] assets: public/${f} has a name the native host would not serve; skipped`)
60
+ }
61
+ const h = headersFile(files, version)
62
+ warnings.push(...h.warnings)
63
+ writeFileSync(join(assets, '_headers'), h.text)
64
+ return { files, warnings }
65
+ }
66
+
67
+ export function headersFile(files: string[], version: string): { text: string; warnings: string[] } {
68
+ const warnings: string[] = []
69
+ const rules: string[] = [
70
+ `/*\n X-Content-Type-Options: nosniff\n X-Powered-By: brust/${version}`,
71
+ `/_brust/client/*\n Cache-Control: ${IMMUTABLE}`,
72
+ ]
73
+ const pub = files.filter((f) => f.startsWith('public/'))
74
+ if (rules.length + pub.length <= MAX_RULES)
75
+ for (const f of pub) rules.push(`/${f}\n Cache-Control: ${isHashed(f) ? IMMUTABLE : PUBLIC_DEFAULT}`)
76
+ else if (pub.length > 0) {
77
+ rules.push(`/public/*\n Cache-Control: ${PUBLIC_DEFAULT}`)
78
+ warnings.push(`[brust] assets: ${pub.length} public files exceed the 100-rule _headers limit; one /public/* max-age=3600 rule (no per-file immutable)`)
79
+ }
80
+ return { text: `${rules.join('\n\n')}\n`, warnings }
81
+ }
@@ -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,72 @@
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
+ prefix: string
32
+ manifestPath: string
33
+ templatesPath: string
34
+ config: CfConfigJson
35
+ cache?: CfEntryCache | null
36
+ /** A Durable Object is configured: the entry re-exports `BrustCacheDO` (R1; `worker/main.js` re-exports it from this one module). */
37
+ doClass?: boolean
38
+ }
39
+
40
+ export function cfEntrySource(i: CfEntryInput): string {
41
+ const q = JSON.stringify
42
+ const actions = i.actionsEntry !== null
43
+ const c = i.cache ?? null
44
+ return `${[
45
+ '// generated by `brust build --target cloudflare` — do not edit (M4-CF spec §4)',
46
+ `import * as R from ${q(i.entry)}`,
47
+ `import J, * as JM from ${q(i.jobsEntry)}`,
48
+ ...(actions ? [`import A from ${q(i.actionsEntry)}`] : []),
49
+ `import M from ${q(i.manifestPath)}`,
50
+ `import T from ${q(i.templatesPath)}`,
51
+ `import { fetchInScope, flattenRoutes, jsonCall, makeHandlers, noActions } from "@brust/core/server-handlers"`,
52
+ ...(actions ? ['import { mountActions } from "@brust/core/server-handlers/actions"'] : []),
53
+ 'const h = makeHandlers({ leaves: flattenRoutes(R.routes ?? R.default).leaves, jobs: J, manifest: M, stores: JM.stores ?? {} })',
54
+ ...(actions ? [`const app = mountActions(A, ${q(i.prefix)}).compile() // startup-phase compile (R9)`] : []),
55
+ 'export const loader = jsonCall(h.loader)',
56
+ 'export const jobs = jsonCall(h.jobs)',
57
+ actions ? 'export const action = (req) => fetchInScope(app, req)' : 'export const action = noActions',
58
+ 'export const MANIFEST = JSON.stringify(M)',
59
+ 'export const TEMPLATES = T',
60
+ ...(c
61
+ ? [
62
+ `import CACHE from ${q(c.module)}`,
63
+ ...(c.broadcast ? [`import CACHE_BROADCAST from ${q(c.broadcast)}`] : []),
64
+ 'import { waitUntil } from "cloudflare:workers"',
65
+ 'import { install as installRuntime } from "@brust/core/server-handlers"',
66
+ `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 })`,
67
+ ]
68
+ : ['export { install } from "@brust/core/server-handlers"']),
69
+ ...(i.doClass ? ['export { BrustCacheDO } from "@brust/cache-cloudflare/do"'] : []),
70
+ `export const CONFIG = ${q(JSON.stringify(i.config))}`,
71
+ ].join('\n')}\n`
72
+ }
@@ -0,0 +1,167 @@
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
+ }
24
+
25
+ const OWNED = ['main', 'assets', 'compatibility_date', 'no_bundle', 'find_additional_modules', 'base_dir', 'rules', 'build', 'site']
26
+ const CONFIG_FILES = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml']
27
+
28
+ export async function readUserWrangler(appRoot: string): Promise<UserWrangler> {
29
+ const found = CONFIG_FILES.filter((f) => existsSync(join(appRoot, f)))
30
+ if (found.length > 1) throw new BuildError('cf-config', `more than one wrangler config in ${appRoot}: ${found.join(', ')} — keep one`)
31
+ const f = found[0]
32
+ if (!f) return { file: null, config: {} }
33
+ const text = await Bun.file(join(appRoot, f)).text()
34
+ try {
35
+ const parsed = f.endsWith('.toml') ? Bun.TOML.parse(text) : Bun.JSONC.parse(text)
36
+ return { file: f, config: (parsed ?? {}) as Json }
37
+ } catch (e) {
38
+ throw new BuildError('cf-config', `failed to parse ${join(appRoot, f)}: ${(e as Error).message}`)
39
+ }
40
+ }
41
+
42
+ const isObj = (v: unknown): v is Json => v !== null && typeof v === 'object' && !Array.isArray(v)
43
+
44
+ /** package.json `name` -> a Worker name: scope dropped, lowercased, non-[a-z0-9-] -> `-`, <= 63. */
45
+ export function workerNameOf(pkgName: string): string {
46
+ return pkgName.replace(/^@[^/]*\//, '').toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 63)
47
+ }
48
+
49
+ function rebase(o: MergeOpts, p: string): string {
50
+ return isAbsolute(p) ? p : relative(o.cfDir, join(o.appRoot, p))
51
+ }
52
+
53
+ function assertNoAssetsBinding(v: unknown, path: string): void {
54
+ if (Array.isArray(v)) return v.forEach((x, i) => assertNoAssetsBinding(x, `${path}[${i}]`))
55
+ if (!isObj(v)) return
56
+ for (const [k, x] of Object.entries(v)) {
57
+ if (k === 'assets' && path === '') continue
58
+ 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`)
59
+ if (k === 'vars' && isObj(x) && 'ASSETS' in x) throw new BuildError('cf-config', 'wrangler config: vars.ASSETS clashes with brust\'s static-assets binding')
60
+ assertNoAssetsBinding(x, `${path}.${k}`)
61
+ }
62
+ }
63
+
64
+ function rebasePaths(o: MergeOpts, block: Json): void {
65
+ if (Array.isArray(block.d1_databases))
66
+ for (const d of block.d1_databases)
67
+ if (isObj(d)) d.migrations_dir = rebase(o, typeof d.migrations_dir === 'string' ? d.migrations_dir : 'migrations')
68
+ if (typeof block.tsconfig === 'string') block.tsconfig = rebase(o, block.tsconfig)
69
+ if (isObj(block.alias))
70
+ for (const [k, v] of Object.entries(block.alias)) if (typeof v === 'string' && v.startsWith('.')) block.alias[k] = rebase(o, v)
71
+ }
72
+
73
+ function checkFlags(block: Json, where: string): void {
74
+ if (Array.isArray(block.compatibility_flags) && block.compatibility_flags.some((f) => typeof f === 'string' && /^no_nodejs_compat/.test(f)))
75
+ throw new BuildError('cf-config', `wrangler config${where}: compatibility_flags "no_nodejs_compat*" is not allowed (AsyncLocalStorage needs nodejs_compat)`)
76
+ }
77
+
78
+ export function mergeWrangler(user: UserWrangler, o: MergeOpts): { config: Json; warnings: string[] } {
79
+ const warnings: string[] = []
80
+ const src = structuredClone(user.config)
81
+ assertNoAssetsBinding(src, '')
82
+ checkFlags(src, '')
83
+ const owned = (k: string, where: string) => warnings.push(`[brust] wrangler: ${where}${k} is owned by brust build --target cloudflare; ignored`)
84
+ const rest: Json = {}
85
+ for (const [k, v] of Object.entries(src)) {
86
+ if (OWNED.includes(k)) owned(k, '')
87
+ else rest[k] = v
88
+ }
89
+ const userName = typeof rest.name === 'string' ? rest.name : undefined
90
+ if (o.name !== undefined && userName !== undefined && userName !== o.name)
91
+ warnings.push(`[brust] wrangler: name "${userName}" conflicts with [cloudflare] name "${o.name}"; brust.toml wins`)
92
+ const name = o.name ?? userName ?? (o.pkgName ? workerNameOf(o.pkgName) : undefined)
93
+ rebasePaths(o, rest)
94
+ if (isObj(rest.env))
95
+ for (const [en, eb] of Object.entries(rest.env)) {
96
+ if (!isObj(eb)) continue
97
+ checkFlags(eb, ` env.${en}`)
98
+ for (const k of OWNED)
99
+ if (k in eb) {
100
+ owned(k, `env.${en}.`)
101
+ delete eb[k]
102
+ }
103
+ rebasePaths(o, eb)
104
+ }
105
+ const config: Json = {
106
+ ...(name !== undefined ? { name } : {}),
107
+ main: `worker/${o.main}`,
108
+ compatibility_date: o.compatibilityDate,
109
+ assets: { directory: 'assets', binding: 'ASSETS', run_worker_first: false, html_handling: 'none', not_found_handling: 'none' },
110
+ ...Object.fromEntries(Object.entries(rest).filter(([k]) => k !== 'name')),
111
+ }
112
+ return { config, warnings }
113
+ }
114
+
115
+ export interface CacheNeed {
116
+ kv?: string
117
+ do?: string
118
+ }
119
+
120
+ const KV_SNIPPET = (b: string) => `"kv_namespaces": [{ "binding": "${b}", "id": "<wrangler kv namespace create brust-cache>" }]`
121
+ const DO_SNIPPET = (b: string) =>
122
+ `"durable_objects": { "bindings": [{ "name": "${b}", "class_name": "BrustCacheDO" }] },\n "migrations": [{ "tag": "brust-cache-v1", "new_sqlite_classes": ["BrustCacheDO"] }]`
123
+
124
+ /** Does `block` declare BrustCacheDO as a SQLite class (migrations or `exports`)? `'kv'` = declared only as a KV-backed `new_classes`. */
125
+ function declaresDoClass(block: Json): boolean | 'kv' {
126
+ if (Array.isArray(block.migrations)) {
127
+ let kvBacked = false
128
+ for (const m of block.migrations) {
129
+ if (!isObj(m)) continue
130
+ if (Array.isArray(m.new_sqlite_classes) && m.new_sqlite_classes.includes('BrustCacheDO')) return true
131
+ if (Array.isArray(m.new_classes) && m.new_classes.includes('BrustCacheDO')) kvBacked = true
132
+ }
133
+ if (kvBacked) return 'kv'
134
+ }
135
+ const e = isObj(block.exports) ? block.exports.BrustCacheDO : undefined
136
+ return isObj(e) && e.type === 'durable-object' && e.storage === 'sqlite'
137
+ }
138
+
139
+ /**
140
+ * R10: the user's wrangler config (top level and every `env.<name>`) must declare the bindings the configured Cloudflare cache needs. Nothing is
141
+ * added for them. A class declaration (`migrations` / `exports`) is also accepted from the top level for an env block. Pure; `config` is not mutated.
142
+ */
143
+ export function verifyCacheBindings(config: Json, need: CacheNeed): { ok: true } | { ok: false; message: string } {
144
+ const problems: string[] = []
145
+ const blocks: [string, Json][] = [['the top level', config]]
146
+ if (isObj(config.env)) for (const [n, b] of Object.entries(config.env)) if (isObj(b)) blocks.push([`env.${n}`, b])
147
+ for (const [where, b] of blocks) {
148
+ if (need.kv !== undefined) {
149
+ const ok = Array.isArray(b.kv_namespaces) && b.kv_namespaces.some((k) => isObj(k) && k.binding === need.kv)
150
+ if (!ok) problems.push(`wrangler config ${where}: no kv_namespaces binding "${need.kv}". Add:\n ${KV_SNIPPET(need.kv)}`)
151
+ }
152
+ if (need.do !== undefined) {
153
+ 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)
154
+ 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)}`)
155
+ else {
156
+ const decl = declaresDoClass(b) || (where === 'the top level' ? false : declaresDoClass(config))
157
+ 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"] }]`)
158
+ else if (decl !== true) problems.push(`wrangler config ${where}: BrustCacheDO is not declared. Add:\n "migrations": [{ "tag": "brust-cache-v1", "new_sqlite_classes": ["BrustCacheDO"] }]`)
159
+ }
160
+ }
161
+ }
162
+ return problems.length === 0 ? { ok: true } : { ok: false, message: problems.join('\n') }
163
+ }
164
+
165
+ export function renderWrangler(config: Json): string {
166
+ return `// generated by \`brust build --target cloudflare\` — edit the app-root wrangler config instead\n${JSON.stringify(config, null, 2)}\n`
167
+ }