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

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 (64) hide show
  1. package/README.md +66 -6
  2. package/native/index.d.ts +63 -4
  3. package/native/index.js +57 -54
  4. package/package.json +29 -15
  5. package/src/actions/client.ts +53 -7
  6. package/src/actions/elysia.ts +1 -1
  7. package/src/actions/load.ts +24 -1
  8. package/src/actions/prefix.ts +24 -2
  9. package/src/actions-bridge.ts +2 -2
  10. package/src/assets.d.ts +55 -0
  11. package/src/browser.ts +6 -1
  12. package/src/build/actions-only.ts +86 -0
  13. package/src/build/build-eval.ts +332 -0
  14. package/src/build/build-icons.ts +69 -0
  15. package/src/build/bundle.ts +466 -54
  16. package/src/build/cf-assets.ts +4 -2
  17. package/src/build/cf-entry.ts +7 -3
  18. package/src/build/cf-wrangler.ts +3 -1
  19. package/src/build/cloudflare.ts +21 -11
  20. package/src/build/compile.ts +263 -6
  21. package/src/build/config.ts +85 -11
  22. package/src/build/css.ts +353 -0
  23. package/src/build/esm-resolve.ts +170 -0
  24. package/src/build/features.ts +119 -0
  25. package/src/build/index.ts +210 -27
  26. package/src/build/manifest.ts +88 -7
  27. package/src/build/pkg-src.ts +514 -0
  28. package/src/build/recognised.ts +19 -0
  29. package/src/build/scan.ts +71 -20
  30. package/src/build/server-only.ts +62 -0
  31. package/src/build/ssg-render.ts +65 -0
  32. package/src/build/ssg.ts +146 -0
  33. package/src/build/static-worker.ts +91 -0
  34. package/src/build/static.ts +259 -0
  35. package/src/build/tailwind.ts +117 -0
  36. package/src/build/tsconfig-paths.ts +67 -0
  37. package/src/build-time.ts +10 -0
  38. package/src/cache-adapter/types.ts +1 -1
  39. package/src/cf.ts +4 -1
  40. package/src/cli.ts +40 -4
  41. package/src/config.ts +111 -25
  42. package/src/css-modules.d.ts +8 -0
  43. package/src/dev/bun.ts +371 -0
  44. package/src/dev/client.ts +92 -0
  45. package/src/dev/devtools-data.ts +23 -0
  46. package/src/dev/devtools.ts +358 -0
  47. package/src/dev/diag.ts +30 -0
  48. package/src/dev/proxy.ts +236 -0
  49. package/src/dev/tui.ts +144 -0
  50. package/src/dev/watch.ts +130 -0
  51. package/src/dev.ts +15 -28
  52. package/src/handlers.ts +115 -9
  53. package/src/index.ts +6 -1
  54. package/src/native.ts +18 -0
  55. package/src/navigate-browser.ts +19 -0
  56. package/src/navigate.ts +19 -0
  57. package/src/navigation.ts +91 -0
  58. package/src/routes.ts +31 -1
  59. package/src/run.ts +53 -11
  60. package/src/shadcn/init.ts +513 -0
  61. package/src/shadcn/jsonc.ts +129 -0
  62. package/src/shadcn/registry.ts +149 -0
  63. package/src/store/builtin.ts +4 -0
  64. package/src/worker.ts +98 -22
@@ -0,0 +1,62 @@
1
+ // The `server-only` marker package (Next.js convention): a module that starts with `import 'server-only'` is server code.
2
+ // The published package throws when it is resolved without the `react-server` condition, which both lets server-only code
3
+ // into a browser bundle whenever the marker is stubbed (a bundler alias, an empty `node_modules/server-only`) and breaks a
4
+ // correct app whose route scan imports it under the default condition. brust does not rely on the throw:
5
+ // - a BROWSER build that reaches the specifier is refused (`server-only-in-client`, bundle.ts `isServerOnly`);
6
+ // - every SERVER side (route scan, worker import of the app, jobs / actions / cache-adapter / build-eval / Worker
7
+ // bundles) resolves it to an empty module, the same thing the `react-server` condition resolves to.
8
+ import type { BunPlugin } from 'bun'
9
+
10
+ const MARKER = /^server-only(\/.*)?$/
11
+ const NS = 'brust-server-only-empty'
12
+
13
+ /** `server-only` itself or one of its subpaths. */
14
+ export const isServerOnlyMarker = (spec: string): boolean => MARKER.test(spec)
15
+
16
+ /** A build plugin for a SERVER bundle: the marker becomes an empty module. */
17
+ export function serverOnlyEmptyPlugin(): BunPlugin {
18
+ return {
19
+ name: 'brust-server-only-empty',
20
+ setup(b) {
21
+ b.onResolve({ filter: MARKER }, (a) => ({ path: a.path, namespace: NS }))
22
+ b.onLoad({ filter: /.*/, namespace: NS }, () => ({ contents: 'export {}', loader: 'js' }))
23
+ },
24
+ }
25
+ }
26
+
27
+ let installed = false
28
+ /** For code the process imports directly (the build's route scan, the worker's import of the app entry): a virtual
29
+ * module, so a bare `import 'server-only'` never reaches the package. Idempotent; only the marker is touched. */
30
+ export function installServerOnlyRuntime(): void {
31
+ if (installed) return
32
+ installed = true
33
+ Bun.plugin({
34
+ name: 'brust-server-only-runtime',
35
+ setup(b) {
36
+ b.module('server-only', () => ({ exports: {}, loader: 'object' }))
37
+ },
38
+ })
39
+ }
40
+
41
+ let jsxDevInstalled = false
42
+ /** F425: Bun picks the dev JSX transform (`jsxDEV` from `react/jsx-dev-runtime`) for modules the process imports directly
43
+ * when NODE_ENV is unset as Bun boots (a plain shell `brust start`), but React's production `react/jsx-dev-runtime` has no
44
+ * `jsxDEV`, and run.ts sets NODE_ENV=production for the workers afterwards. A module that builds a JSX element at import
45
+ * time (`export const el = <b/>`) then died with "jsxDEV_… is not a function". In production, `react/jsx-dev-runtime` is the
46
+ * production `jsx`/`jsxs` (resolved from the app, so it is the app's one React) with a `jsxDEV` over them; dev keeps React's own. */
47
+ export function installProductionJsxDev(appDir: string): void {
48
+ if (jsxDevInstalled || process.env.NODE_ENV !== 'production') return
49
+ jsxDevInstalled = true
50
+ Bun.plugin({
51
+ name: 'brust-jsx-dev-production',
52
+ setup(b) {
53
+ b.module('react/jsx-dev-runtime', async () => {
54
+ const rt = await import(Bun.resolveSync('react/jsx-runtime', appDir))
55
+ return {
56
+ exports: { Fragment: rt.Fragment, jsx: rt.jsx, jsxs: rt.jsxs, jsxDEV: (type: unknown, props: unknown, key: unknown, isStatic: boolean) => (isStatic ? rt.jsxs : rt.jsx)(type, props, key) },
57
+ loader: 'object',
58
+ }
59
+ })
60
+ },
61
+ })
62
+ }
@@ -0,0 +1,65 @@
1
+ // The child process `brust build --target static` renders in (gaps round L9): boots the real server
2
+ // on loopback with the normal workers (`run()`, so every byte is what `brust start` sends), fetches
3
+ // each planned path, writes the responses to `BRUST_SSG_OUT`, then drains. A child process, because
4
+ // the napi server is a per-process singleton. Input: `BRUST_SSG_PLAN` (a JSON list of paths).
5
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
6
+ import { run } from '../run'
7
+
8
+ export interface Rendered {
9
+ path: string
10
+ status: number
11
+ headers: Record<string, string>
12
+ /** base64 */
13
+ body: string
14
+ }
15
+
16
+ /** A page that did not answer within the per-page limit (review N3). */
17
+ export class PageTimeout extends Error {
18
+ constructor(
19
+ readonly path: string,
20
+ readonly ms: number,
21
+ ) {
22
+ super(`GET ${path} did not answer within ${ms} ms`)
23
+ }
24
+ }
25
+
26
+ /** The seam an in-process host can replace later: GET each path from `base`, uncompressed, no redirect
27
+ * following, each within `pageMs` (`PageTimeout`). `started` hears each path before it is requested. */
28
+ export async function renderPaths(base: string, paths: string[], pageMs = 30_000, started: (path: string) => void = () => {}): Promise<Rendered[]> {
29
+ const out: Rendered[] = []
30
+ for (const path of paths) {
31
+ started(path)
32
+ const signal = AbortSignal.timeout(pageMs)
33
+ try {
34
+ const r = await fetch(base + path, { redirect: 'manual', headers: { 'accept-encoding': 'identity' }, signal })
35
+ out.push({ path, status: r.status, headers: Object.fromEntries(r.headers), body: Buffer.from(await r.arrayBuffer()).toString('base64') })
36
+ } catch (e) {
37
+ if (signal.aborted) throw new PageTimeout(path, pageMs)
38
+ throw e
39
+ }
40
+ }
41
+ return out
42
+ }
43
+
44
+ if (import.meta.main) {
45
+ const env = process.env
46
+ const paths = JSON.parse(readFileSync(env.BRUST_SSG_PLAN!, 'utf8')) as string[]
47
+ await run({
48
+ distDir: env.BRUST_DIST_DIR,
49
+ entry: env.BRUST_APP_ENTRY,
50
+ config: { host: '127.0.0.1', port: 0 },
51
+ onReady: async (addr) => {
52
+ const pageMs = Number(env.BRUST_SSG_PAGE_TIMEOUT_MS) || 30_000
53
+ const progress = env.BRUST_SSG_PROGRESS
54
+ try {
55
+ const pages = await renderPaths(`http://${addr}`, paths, pageMs, (p) => progress && appendFileSync(progress, `${p}\n`))
56
+ writeFileSync(env.BRUST_SSG_OUT!, JSON.stringify({ addr, pages }))
57
+ return 0
58
+ } catch (e) {
59
+ if (!(e instanceof PageTimeout)) throw e
60
+ writeFileSync(env.BRUST_SSG_OUT!, JSON.stringify({ addr, timeout: { path: e.path, ms: e.ms } }))
61
+ return 1
62
+ }
63
+ },
64
+ })
65
+ }
@@ -0,0 +1,146 @@
1
+ // `brust build --target static` planner (gaps round L9, R9.2-R9.3): which paths to render and the
2
+ // file each one is written to. Pure: no server, no filesystem. `params()` results come in resolved.
3
+ import type { FlatRoute, RouteSsgConfig } from '../routes'
4
+ import { BuildError } from './errors'
5
+
6
+ /** The path the `*` route is rendered at: no route matches it, so the server answers the 404 page. */
7
+ export const NOT_FOUND_PATH = '/__brust_ssg_not_found__'
8
+
9
+ export interface PlannedPage {
10
+ /** The request path (each `{name}` value percent-encoded). */
11
+ path: string
12
+ /** Relative to the static dir: `index.html`, `docs.html`, `docs/x.html`, `404.html`. */
13
+ file: string
14
+ routeId: string
15
+ pattern: string
16
+ /** 200, or 404 for the `*` route. */
17
+ expect: 200 | 404
18
+ }
19
+
20
+ export interface StaticPlan {
21
+ pages: PlannedPage[]
22
+ /** Routes `ssg: false` left out (listed in the report). */
23
+ skipped: { routeId: string; pattern: string }[]
24
+ /** No `*` route: the build writes a default 404.html. */
25
+ defaultNotFound: boolean
26
+ }
27
+
28
+ /** A leaf's own `ssg` field (the last node of its chain). */
29
+ export function ssgOf(leaf: FlatRoute): RouteSsgConfig | undefined {
30
+ return leaf.chain[leaf.chain.length - 1]?.ssg
31
+ }
32
+
33
+ const SEGMENT = /\{(\*?)([^}]*)\}/g
34
+
35
+ /** The `{name}` / `{*name}` segment names of a pattern, in order. */
36
+ export function patternParams(pattern: string): { name: string; rest: boolean }[] {
37
+ return [...pattern.matchAll(SEGMENT)].map((m) => ({ name: m[2]!, rest: m[1] === '*' }))
38
+ }
39
+
40
+ /** The file a request path is written to: `/` → `index.html`, `/a/b` → `a/b.html` (decoded, so a
41
+ * host that decodes the URL finds it). A segment that is not valid percent-encoding (a stray `%`)
42
+ * is a `ssg-param-encoding` error naming `where` (review N1), never a URIError. */
43
+ export function fileFor(path: string, where = path): string {
44
+ if (path === '/') return 'index.html'
45
+ const decoded = path
46
+ .slice(1)
47
+ .split('/')
48
+ .map((s) => {
49
+ try {
50
+ return decodeURIComponent(s)
51
+ } catch {
52
+ throw new BuildError('ssg-param-encoding', `${where}: path segment ${JSON.stringify(s)} is not valid percent-encoding (write a literal % as %25)`)
53
+ }
54
+ })
55
+ .join('/')
56
+ return `${decoded}.html`
57
+ }
58
+
59
+ /** `encodeURIComponent`, as an `ssg-param-encoding` error naming `where` for a lone surrogate (review N1). */
60
+ function encodeSegment(v: string, where: string): string {
61
+ try {
62
+ return encodeURIComponent(v)
63
+ } catch {
64
+ throw new BuildError('ssg-param-encoding', `${where} = ${JSON.stringify(v)} is not encodable (a lone UTF-16 surrogate)`)
65
+ }
66
+ }
67
+
68
+ /** One `{name}` value: a non-empty string; `/` only in a `{*rest}` value, and never an empty, `.`
69
+ * or `..` segment (the file name would leave its directory). */
70
+ function checkValue(leaf: FlatRoute, i: number, name: string, rest: boolean, v: unknown): string {
71
+ const where = `route ${leaf.id} (${leaf.pattern}) ssg.params()[${i}].${name}`
72
+ if (typeof v !== 'string' || v === '') throw new BuildError('ssg-params', `${where} is ${v === '' ? 'empty' : 'missing'}: every {${name}} needs a non-empty string`)
73
+ if (!rest && v.includes('/')) throw new BuildError('ssg-params', `${where} = ${JSON.stringify(v)} contains '/': a {${name}} value is one path segment`)
74
+ for (const seg of v.split('/'))
75
+ if (seg === '' || seg === '.' || seg === '..') throw new BuildError('ssg-params', `${where} = ${JSON.stringify(v)} has an empty, '.' or '..' segment`)
76
+ return v
77
+ }
78
+
79
+ /** Plans every page. `params` holds each dynamic route's resolved `ssg.params()` by route id. */
80
+ export function planStatic(leaves: FlatRoute[], params: Map<string, unknown>): StaticPlan {
81
+ const pages: PlannedPage[] = []
82
+ const skipped: StaticPlan['skipped'] = []
83
+ let catchAll: FlatRoute | undefined
84
+ for (const leaf of leaves) {
85
+ const ssg = ssgOf(leaf)
86
+ if (ssg === false) {
87
+ skipped.push({ routeId: leaf.id, pattern: leaf.pattern })
88
+ continue
89
+ }
90
+ if (leaf.catchAll) {
91
+ catchAll = leaf
92
+ continue
93
+ }
94
+ const names = patternParams(leaf.pattern)
95
+ if (names.length === 0) {
96
+ pages.push({ path: leaf.pattern, file: fileFor(leaf.pattern, `route ${leaf.id} (${leaf.pattern})`), routeId: leaf.id, pattern: leaf.pattern, expect: 200 })
97
+ continue
98
+ }
99
+ if (!ssg || ssg.params === undefined)
100
+ throw new BuildError(
101
+ 'ssg-params-missing',
102
+ `route ${leaf.id} (${leaf.pattern}) is dynamic: add ssg: { params: () => [{ ${names.map((n) => `${n.name}: '…'`).join(', ')} }] } or ssg: false`,
103
+ )
104
+ const recs = params.get(leaf.id)
105
+ if (!Array.isArray(recs)) throw new BuildError('ssg-params', `route ${leaf.id} (${leaf.pattern}) ssg.params() must return an array of records`)
106
+ recs.forEach((rec, i) => {
107
+ if (typeof rec !== 'object' || rec === null || Array.isArray(rec)) throw new BuildError('ssg-params', `route ${leaf.id} (${leaf.pattern}) ssg.params()[${i}] is not a record`)
108
+ const r = rec as Record<string, unknown>
109
+ let k = 0
110
+ const path = leaf.pattern.replace(SEGMENT, () => {
111
+ const { name, rest } = names[k++]!
112
+ const v = checkValue(leaf, i, name, rest, r[name])
113
+ return v
114
+ .split('/')
115
+ .map((seg) => encodeSegment(seg, `route ${leaf.id} (${leaf.pattern}) ssg.params()[${i}].${name}`))
116
+ .join('/')
117
+ })
118
+ pages.push({ path, file: fileFor(path, `route ${leaf.id} (${leaf.pattern})`), routeId: leaf.id, pattern: leaf.pattern, expect: 200 })
119
+ })
120
+ }
121
+ const seen = new Map<string, PlannedPage>()
122
+ // Keyed case-folded (review N2): macOS and Windows file systems are case-insensitive, so `/A` and
123
+ // `/a` would overwrite each other's file.
124
+ for (const p of pages) {
125
+ const key = p.file.toLowerCase()
126
+ const prev = seen.get(key)
127
+ if (prev && prev.file === p.file) throw new BuildError('ssg-params', `${prev.path} (route ${prev.routeId}) and ${p.path} (route ${p.routeId}) both write ${p.file}`)
128
+ if (prev)
129
+ throw new BuildError(
130
+ 'ssg-path-collision',
131
+ `${prev.path} (route ${prev.routeId}, ${prev.file}) and ${p.path} (route ${p.routeId}, ${p.file}) differ only by case: on a case-insensitive file system one file overwrites the other`,
132
+ )
133
+ seen.set(key, p)
134
+ }
135
+ if (seen.has('404.html')) throw new BuildError('ssg-params', `${seen.get('404.html')!.path} would overwrite 404.html`)
136
+ if (catchAll) pages.push({ path: NOT_FOUND_PATH, file: '404.html', routeId: catchAll.id, pattern: catchAll.pattern, expect: 404 })
137
+ return { pages, skipped, defaultNotFound: catchAll === undefined }
138
+ }
139
+
140
+ /** The output paths `ssg.params()` must be resolved for: dynamic leaves with `ssg.params`. */
141
+ export function paramRoutes(leaves: FlatRoute[]): FlatRoute[] {
142
+ return leaves.filter((l) => {
143
+ const ssg = ssgOf(l)
144
+ return !l.catchAll && ssg && ssg.params !== undefined && patternParams(l.pattern).length > 0
145
+ })
146
+ }
@@ -0,0 +1,91 @@
1
+ // `brust build --target static` with `[actions]` (gaps round L12, R12.1): the static tree plus a
2
+ // Cloudflare Pages advanced-mode Worker that serves ONLY the action prefix.
3
+ // static/_worker.js/index.js a WorkerEntrypoint: the action prefix -> the Cloudflare core, everything else -> env.ASSETS
4
+ // static/_worker.js/core/ the `--target cloudflare` worker tree (glue + wasm + brust-app.js), verbatim
5
+ // static/_routes.json include: the prefix only, so pages and assets never invoke the Worker
6
+ // wrangler.jsonc the Pages project file (name, compatibility date); sits next to `static/`
7
+ import { cpSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { type CfPrepared, cacheNeeds } from './cloudflare'
10
+ import { workerNameOf } from './cf-wrangler'
11
+ import { BuildError } from './errors'
12
+ import { CF_MIN_COMPAT_DATE } from './config'
13
+ import type { CacheRecord } from './manifest'
14
+
15
+ /** `.assetsignore`: the Worker source and the routes file are deploy inputs, never public assets. */
16
+ export const ASSETS_IGNORE = '_worker.js\n_routes.json\n.assetsignore\n'
17
+
18
+ /** The deploy inputs the Worker answers with a 404 (N1). */
19
+ export const HIDDEN = ['/_worker.js', '/_worker.js/*', '/_routes.json', '/.assetsignore']
20
+
21
+ /** `_routes.json` (R12.1): the prefix itself and everything under it reach the Worker, and so do the
22
+ * deploy inputs (N1): a static host that would otherwise serve `_worker.js/*` as files (the local
23
+ * `wrangler pages dev` does) is answered by the Worker's 404 instead. Pages and assets never do. */
24
+ export function routesJson(prefix: string): string {
25
+ return `${JSON.stringify({ version: 1, include: [prefix, `${prefix}/*`, ...HIDDEN], exclude: [] }, null, 2)}\n`
26
+ }
27
+
28
+ /** `_worker.js/index.js`. Pages' pipeline wants a module object with `fetch`, not the class the core
29
+ * exports (a WorkerEntrypoint whose `fetch` reads `this.env` and `this.ctx`), so the core's method is
30
+ * called with exactly those two. A request that reaches the Worker and is not an action (a path
31
+ * `_routes.json` keeps away, or a probe) falls through to the static files, except the deploy inputs
32
+ * themselves (`_worker.js/*`, `_routes.json`, `.assetsignore`), which are a 404 whatever serves the assets (N1). */
33
+ export function workerSource(main: string, prefix: string): string {
34
+ const q = JSON.stringify
35
+ return `${[
36
+ '// generated by `brust build --target static` (actions on Pages) — do not edit',
37
+ `import Core from ${q(`./core/${main}`)}`,
38
+ `const PREFIX = ${q(prefix)}`,
39
+ 'export default {',
40
+ ' fetch(request, env, ctx) {',
41
+ ' const path = new URL(request.url).pathname',
42
+ ' if (path === PREFIX || path.startsWith(`${PREFIX}/`)) return Core.prototype.fetch.call({ env, ctx }, request)',
43
+ ' let plain = path',
44
+ ' try { plain = decodeURIComponent(path) } catch {}',
45
+ ' if (/^\\/(_worker\\.js(\\/|$)|_routes\\.json$|\\.assetsignore$)/i.test(plain)) return new Response("Not Found", { status: 404 })',
46
+ ' return env.ASSETS.fetch(request)',
47
+ ' },',
48
+ '}',
49
+ ].join('\n')}\n`
50
+ }
51
+
52
+ /** The Pages project file: bindings and secrets are the user's (`wrangler pages` / the dashboard), never baked. */
53
+ export function pagesConfig(p: CfPrepared): string {
54
+ const name = p.cfg.name ?? (p.pkgName ? workerNameOf(p.pkgName) : undefined)
55
+ const compatibilityDate = p.cfg.compatibilityDate ?? p.core.meta.compatibilityDate
56
+ if (compatibilityDate < CF_MIN_COMPAT_DATE) throw new BuildError('config', `compatibility_date ${compatibilityDate} is older than ${CF_MIN_COMPAT_DATE}`)
57
+ const c = { ...(name !== undefined ? { name } : {}), pages_build_output_dir: './static', compatibility_date: compatibilityDate }
58
+ return `// generated by \`brust build --target static\` — bindings and secrets: \`wrangler pages secret put\` / the dashboard (docs/cloudflare.md §12)\n${JSON.stringify(c, null, 2)}\n`
59
+ }
60
+
61
+ /** R12: `[cache]` does not apply to static pages, and the Worker serves actions only, so an adapter
62
+ * that needs a Cloudflare binding (KV, Durable Object) has nowhere to be used: refused before any write. */
63
+ export function assertNoCacheBindings(cache: Pick<CacheRecord, 'adapter' | 'broadcast' | 'options' | 'broadcastOptions'> | null | undefined): void {
64
+ const need = cacheNeeds(cache ?? undefined)
65
+ if (need)
66
+ throw new BuildError(
67
+ 'ssg-actions-cache',
68
+ `[cache] adapter "${cache!.adapter}" needs a Cloudflare binding (${[need.kv && `KV ${need.kv}`, need.do && `Durable Object ${need.do}`].filter(Boolean).join(', ')}), which the static + actions Worker does not carry (static pages are never cached, the Worker serves actions only); drop [cache], or use --target cloudflare`,
69
+ )
70
+ }
71
+
72
+ /** Turns `<dist>/cf/` (built by `buildCloudflare`) into the Pages Worker inside `<dist>/static/`, then
73
+ * drops `cf/`: the build is `--target static`, its only output is `static/`. */
74
+ export function writeStaticWorker(dist: string, actions: { prefix: string }, p: CfPrepared, log: (s: string) => void): void {
75
+ const staticDir = join(dist, 'static')
76
+ const worker = join(dist, 'cf', 'worker')
77
+ if (!existsSync(join(worker, p.core.meta.main))) throw new BuildError('cf-wasm', `the Cloudflare build wrote no worker/${p.core.meta.main}`)
78
+ const out = join(staticDir, '_worker.js')
79
+ rmSync(out, { recursive: true, force: true })
80
+ cpSync(worker, join(out, 'core'), { recursive: true })
81
+ writeFileSync(join(out, 'index.js'), workerSource(p.core.meta.main, actions.prefix))
82
+ writeFileSync(join(staticDir, '_routes.json'), routesJson(actions.prefix))
83
+ // Workers Static Assets uploads the whole directory as public files unless told otherwise; Pages never serves these two.
84
+ writeFileSync(join(staticDir, '.assetsignore'), ASSETS_IGNORE)
85
+ writeFileSync(join(dist, 'wrangler.jsonc'), pagesConfig(p))
86
+ const report = join(staticDir, 'ssg.json')
87
+ const json = JSON.parse(readFileSync(report, 'utf8')) as Record<string, unknown>
88
+ writeFileSync(report, `${JSON.stringify({ ...json, actions: { prefix: actions.prefix, worker: '_worker.js' } }, null, 2)}\n`)
89
+ rmSync(join(dist, 'cf'), { recursive: true, force: true })
90
+ log(`[brust] static: actions under ${actions.prefix} are served by _worker.js (_routes.json keeps pages and assets off the Worker)`)
91
+ }
@@ -0,0 +1,259 @@
1
+ // `brust build --target static` (gaps round L9, R9.1-R9.5): after the normal dist is built, render
2
+ // every planned page through the real server (a child process, `ssg-render.ts`) and write
3
+ // `<out>/static/`: one HTML file per page, `404.html`, the assets the native host serves
4
+ // (`layoutAssets`), `_headers`, `_redirects` and an `ssg.json` report. The layout is what
5
+ // Cloudflare Pages and Workers Static Assets (`not_found_handling = "404-page"`) serve as is.
6
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import type { FlatRoute } from '../routes'
9
+ import { layoutAssets } from './cf-assets'
10
+ import { BuildError } from './errors'
11
+ import type { Rendered } from './ssg-render'
12
+ import { assertNoCacheBindings } from './static-worker'
13
+ import { NOT_FOUND_PATH, type PlannedPage, type StaticPlan, paramRoutes, planStatic, ssgOf } from './ssg'
14
+
15
+ export interface StaticOptions {
16
+ /** `--strict`: a loader reading the request fails the build instead of warning. */
17
+ strict: boolean
18
+ }
19
+
20
+ /** The request reads of one cache key expression (the server's grammar, through the addon). */
21
+ export type ExprReads = (expr: string) => string[]
22
+
23
+ /** R9.3/R9.4: everything that refuses a static build, checked before a byte is written; then the
24
+ * resolved plan. `actions`: whether `[actions]` is configured. */
25
+ export async function prepareStatic(
26
+ leaves: FlatRoute[],
27
+ actions: boolean,
28
+ reads: ExprReads,
29
+ log: (s: string) => void,
30
+ cache?: Parameters<typeof assertNoCacheBindings>[0],
31
+ ): Promise<StaticPlan> {
32
+ // L12: `[actions]` makes the output hybrid (static pages + a Pages Worker for the action prefix).
33
+ if (actions) assertNoCacheBindings(cache)
34
+ let cacheInfo = false
35
+ for (const leaf of leaves) {
36
+ const cache = leaf.chain[leaf.chain.length - 1]?.cache
37
+ if (!cache || ssgOf(leaf) === false) continue
38
+ cacheInfo = true
39
+ for (const [field, expr] of [
40
+ ['prefix', cache.prefix],
41
+ ['bypass', typeof cache.bypass === 'string' ? cache.bypass : undefined],
42
+ ] as const) {
43
+ if (expr === undefined) continue
44
+ let r: string[]
45
+ try {
46
+ r = reads(expr)
47
+ } catch (e) {
48
+ throw new BuildError('ssg-varies', `route ${leaf.id} (${leaf.pattern}) cache.${field}: ${(e as Error).message}`)
49
+ }
50
+ if (r.length > 0)
51
+ throw new BuildError(
52
+ 'ssg-varies',
53
+ `route ${leaf.id} (${leaf.pattern}) cache.${field} reads ${r.join(', ')}: the page varies per request, and a static file is one page for everyone (set ssg: false on the route, or drop the read)`,
54
+ )
55
+ }
56
+ }
57
+ if (cacheInfo) log('[brust] static: cache.ttl_seconds does not apply to static files (ignored)')
58
+ const params = new Map<string, unknown>()
59
+ for (const leaf of paramRoutes(leaves)) {
60
+ const ssg = ssgOf(leaf)
61
+ if (!ssg || !ssg.params) continue
62
+ try {
63
+ params.set(leaf.id, await ssg.params())
64
+ } catch (e) {
65
+ throw new BuildError('ssg-params', `route ${leaf.id} (${leaf.pattern}) ssg.params() threw: ${(e as Error).message ?? String(e)}`)
66
+ }
67
+ }
68
+ return planStatic(leaves, params)
69
+ }
70
+
71
+ export interface StaticReport {
72
+ pages: { path: string; file: string; routeId: string }[]
73
+ redirects: { from: string; to: string; status: number }[]
74
+ skipped: { routeId: string; pattern: string }[]
75
+ notFound: { file: '404.html'; routeId: string | null }
76
+ warnings: string[]
77
+ }
78
+
79
+ type SsgRecord =
80
+ | { kind: 'read'; routeId: string; path: string; field: string; key: string }
81
+ | { kind: 'headers'; routeId: string; path: string; names: string[] }
82
+
83
+ // F468: like every page the build renders, the default 404 carries `<meta name="generator" content="brust/<version>">`.
84
+ const default404 = (version: string) =>
85
+ `<!doctype html>\n<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>404 Not Found</title><meta name="generator" content="brust/${version.replace(/[&"<>]/g, (c) => `&#${c.charCodeAt(0)};`)}"></head><body><h1>404 Not Found</h1></body></html>\n`
86
+
87
+ /** A `_redirects` source as Cloudflare Pages matches it (review N4): the decoded path, with only what
88
+ * the file format or the decoding needs escaped (whitespace and control characters, and `%`, so a
89
+ * literal `%` is not read as an escape). Non-ASCII stays as UTF-8. */
90
+ export function redirectSource(path: string): string {
91
+ let decoded: string
92
+ try {
93
+ decoded = decodeURIComponent(path)
94
+ } catch {
95
+ decoded = path
96
+ }
97
+ return decoded.replace(/[\s%\u0000-\u001f\u007f]/gu, (c) => encodeURIComponent(c))
98
+ }
99
+
100
+ const text = (r: Rendered) => Buffer.from(r.body, 'base64').toString('utf8')
101
+ const excerpt = (s: string) => (s.length > 300 ? `${s.slice(0, 300)}…` : s).replace(/\s+/g, ' ').trim()
102
+
103
+ /** Spawns the render child against the dist at `dist`; the rendered responses in plan order and
104
+ * the loader records. `cwd` is the app root (its `brust.toml` is the server's config). */
105
+ async function render(dist: string, entry: string, cwd: string, paths: string[]): Promise<{ addr: string; rendered: Rendered[]; records: SsgRecord[] }> {
106
+ const stage = join(dist, '.ssg')
107
+ mkdirSync(stage, { recursive: true })
108
+ const plan = join(stage, 'plan.json')
109
+ const out = join(stage, 'rendered.json')
110
+ const logFile = join(stage, 'records.jsonl')
111
+ const progress = join(stage, 'progress.txt')
112
+ writeFileSync(plan, JSON.stringify(paths))
113
+ writeFileSync(logFile, '')
114
+ writeFileSync(progress, '')
115
+ const proc = Bun.spawn([process.execPath, join(import.meta.dir, 'ssg-render.ts')], {
116
+ cwd,
117
+ env: {
118
+ ...process.env,
119
+ BRUST_DIST_DIR: dist,
120
+ BRUST_APP_ENTRY: entry,
121
+ BRUST_SSG: '1',
122
+ BRUST_SSG_PLAN: plan,
123
+ BRUST_SSG_OUT: out,
124
+ BRUST_SSG_LOG: logFile,
125
+ BRUST_SSG_PROGRESS: progress,
126
+ BRUST_ADDR: '127.0.0.1',
127
+ BRUST_PORT: '',
128
+ },
129
+ stdout: 'pipe',
130
+ stderr: 'pipe',
131
+ })
132
+ // Review N3: the whole render is bounded too; past it the child (our own PID) is killed.
133
+ const totalMs = Number(process.env.BRUST_SSG_TIMEOUT_MS) || 600_000
134
+ let timer: ReturnType<typeof setTimeout> | undefined
135
+ const late = new Promise<'late'>((r) => {
136
+ timer = setTimeout(() => r('late'), totalMs)
137
+ })
138
+ const texts = Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()])
139
+ const first = await Promise.race([proc.exited, late])
140
+ clearTimeout(timer)
141
+ if (first === 'late') {
142
+ proc.kill('SIGKILL')
143
+ await proc.exited
144
+ const last = readFileSync(progress, 'utf8').trim().split('\n').pop() || '(before the first page)'
145
+ throw new BuildError('ssg-timeout', `the render took longer than ${totalMs} ms (BRUST_SSG_TIMEOUT_MS); it was rendering ${last}`)
146
+ }
147
+ const code = first
148
+ const [stdout, stderr] = await texts
149
+ const result = existsSync(out) ? (JSON.parse(readFileSync(out, 'utf8')) as { addr: string; pages?: Rendered[]; timeout?: { path: string; ms: number } }) : null
150
+ if (result?.timeout)
151
+ throw new BuildError('ssg-timeout', `GET ${result.timeout.path} did not answer within ${result.timeout.ms} ms (BRUST_SSG_PAGE_TIMEOUT_MS)`)
152
+ if (code !== 0 || !result?.pages) throw new BuildError('ssg-render', `the render server failed (exit ${code}):\n${(stderr || stdout).trim()}`)
153
+ const { addr, pages: rendered } = result as { addr: string; pages: Rendered[] }
154
+ const records = readFileSync(logFile, 'utf8')
155
+ .split('\n')
156
+ .filter((l) => l !== '')
157
+ .map((l) => JSON.parse(l) as SsgRecord)
158
+ rmSync(stage, { recursive: true, force: true })
159
+ return { addr, rendered, records }
160
+ }
161
+
162
+ /** Renders `plan` against the built dist at `dist` and writes `<dist>/static/`. Returns the report. */
163
+ export async function writeStatic(
164
+ dist: string,
165
+ o: { entry: string; appRoot: string; plan: StaticPlan; version: string; strict: boolean; log: (s: string) => void; /** The dir as the user will find it (the build renders into a temp dist). */ shownDir?: string },
166
+ ): Promise<StaticReport> {
167
+ const dir = join(dist, 'static')
168
+ rmSync(dir, { recursive: true, force: true })
169
+ const assetsStage = join(dist, '.ssg-assets')
170
+ const assets = layoutAssets(dist, assetsStage, o.version)
171
+ renameSync(join(assetsStage, 'assets'), dir)
172
+ rmSync(assetsStage, { recursive: true, force: true })
173
+ const warnings = [...assets.warnings]
174
+ const warn = (w: string) => {
175
+ warnings.push(w)
176
+ o.log(w)
177
+ }
178
+ for (const w of assets.warnings) o.log(w)
179
+
180
+ // R9.4: [cache] does not apply to static files, so the render must not need its adapter (a Redis
181
+ // that is not running at build time): the render reads a manifest without `cache`, and the dist
182
+ // keeps the real one for `brust start`.
183
+ const manifestFile = join(dist, 'manifest.json')
184
+ const manifest = readFileSync(manifestFile, 'utf8')
185
+ const parsed = JSON.parse(manifest) as { cache?: unknown }
186
+ if (parsed.cache) {
187
+ o.log('[brust] static: [cache] does not apply to static files (ignored while rendering)')
188
+ writeFileSync(manifestFile, `${JSON.stringify({ ...parsed, cache: null }, null, 2)}\n`)
189
+ }
190
+ let r: Awaited<ReturnType<typeof render>>
191
+ try {
192
+ r = await render(dist, o.entry, o.appRoot, o.plan.pages.map((p) => p.path))
193
+ } finally {
194
+ writeFileSync(manifestFile, manifest)
195
+ }
196
+ const { addr, rendered, records } = r
197
+ const report: StaticReport = { pages: [], redirects: [], skipped: o.plan.skipped, notFound: { file: '404.html', routeId: null }, warnings }
198
+ const write = (file: string, body: Buffer) => {
199
+ mkdirSync(dirname(join(dir, file)), { recursive: true })
200
+ writeFileSync(join(dir, file), body)
201
+ }
202
+ rendered.forEach((r, i) => {
203
+ const page: PlannedPage = o.plan.pages[i]!
204
+ const where = `GET ${page.path} (route ${page.routeId} ${page.pattern})`
205
+ const body = Buffer.from(r.body, 'base64')
206
+ if (text(r).includes(addr) || (r.headers.location ?? '').includes(addr))
207
+ throw new BuildError('ssg-render', `${where}: the response names the render server's loopback origin; a static page must not (build absolute URLs from a configured origin)`)
208
+ if (page.expect === 404) {
209
+ if (r.status !== 404) throw new BuildError('ssg-render', `${where}: the * route answered ${r.status}, want 404: ${excerpt(text(r))}`)
210
+ write('404.html', body)
211
+ report.notFound.routeId = page.routeId
212
+ return
213
+ }
214
+ if (r.status === 200) {
215
+ write(page.file, body)
216
+ report.pages.push({ path: page.path, file: page.file, routeId: page.routeId })
217
+ return
218
+ }
219
+ if (r.status >= 300 && r.status < 400 && r.headers.location) {
220
+ report.redirects.push({ from: page.path, to: r.headers.location, status: r.status })
221
+ return
222
+ }
223
+ throw new BuildError('ssg-render', `${where}: status ${r.status}, want 200 (or a redirect()): ${excerpt(text(r))}`)
224
+ })
225
+ if (o.plan.defaultNotFound) {
226
+ write('404.html', Buffer.from(default404(o.version)))
227
+ warn("[brust] warning ssg-404 no '*' route: wrote a default 404.html (without one, Cloudflare Pages serves every unknown path as the home page)")
228
+ }
229
+ writeFileSync(join(dir, '_redirects'), report.redirects.map((r) => `${redirectSource(r.from)} ${r.to} ${r.status}\n`).join(''))
230
+
231
+ const seen = new Set<string>()
232
+ const reads: string[] = []
233
+ for (const rec of records) {
234
+ const leaf = o.plan.pages.find((p) => p.routeId === rec.routeId)
235
+ const route = `route ${rec.routeId}${leaf ? ` (${leaf.pattern})` : ''}`
236
+ if (rec.kind === 'headers') {
237
+ const key = `h ${rec.routeId} ${rec.names.join(',')}`
238
+ if (seen.has(key)) continue
239
+ seen.add(key)
240
+ warn(`[brust] warning ssg-headers ${route}: the loader's response headers (${rec.names.join(', ')}) are dropped: a static file carries none`)
241
+ continue
242
+ }
243
+ const key = `r ${rec.routeId} ${rec.field} ${rec.key}`
244
+ if (seen.has(key)) continue
245
+ seen.add(key)
246
+ const what = rec.key === '*' ? `lists req.${rec.field}` : `reads req.${rec.field}[${JSON.stringify(rec.key)}]`
247
+ reads.push(`${route} ${what} (at ${rec.path}): the static page is what a visitor with no headers, cookies or query sees`)
248
+ }
249
+ if (reads.length > 0 && o.strict) throw new BuildError('ssg-request-read', reads.join('\n'))
250
+ for (const r of reads) warn(`[brust] warning ssg-request-read ${r}`)
251
+
252
+ writeFileSync(join(dir, 'ssg.json'), `${JSON.stringify(report, null, 2)}\n`)
253
+ o.log(
254
+ `[brust] static: ${report.pages.length} page(s), ${report.redirects.length} redirect(s), 404.html${report.notFound.routeId ? '' : ' (default)'}${report.skipped.length ? `, ${report.skipped.length} route(s) ssg: false` : ''} -> ${o.shownDir ?? dir}`,
255
+ )
256
+ return report
257
+ }
258
+
259
+ export { NOT_FOUND_PATH }