@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,514 @@
1
+ // Package sources (shadcn S3 step 1, F153c, R34.61/R34.62): the compiler analyses a package component from the
2
+ // AUTHORED source its source map carries (`sourcesContent`), never from the published JS (G1, G2). This module runs
3
+ // no package code: sources are read, transpiled for the integrity check, and written, never imported; the compiler
4
+ // only parses them, and the build never evaluates a slot of a component compiled from them (L2). (The route scan
5
+ // imports the app graph, and with it the packages' published JS, as it always has: that is not new here.)
6
+ //
7
+ // For every bare import the app reaches (and, transitively, every bare import of a package source written here),
8
+ // the package's ESM entry is resolved, its `.map` read, and the `.ts`/`.tsx` sources written under
9
+ // `<app>/.brust/pkg-src/p-<hash>/` (the hash of the package's path: bun's store installs one copy per dependant; no
10
+ // text the package controls is ever part of a path). The compiler gets the resolution map (`PackageSources`), so it reads only what this build wrote:
11
+ // the directory is removed first, and a stale one is never consulted.
12
+ //
13
+ // Fail closed: a package with no ESM entry, no map, no source for its entry, a source outside the package, a
14
+ // relative import the map does not carry, a dynamic `import()` or `eval`, or a source whose literals and names are
15
+ // not all in the published JS (R34.62: the React build runs the dist, not the map; a containment check of literals and
16
+ // names, i.e. fidelity, not a security boundary: the author controls both files) is REFUSED, with the reason;
17
+ // the compiler then renders its components as React islands of the package export, exactly as before.
18
+ import { createHash } from 'node:crypto'
19
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs'
20
+ import { dirname, join, posix, relative, resolve, sep } from 'node:path'
21
+ import { BuildError } from './errors'
22
+ import { RELATIVE_SPEC } from './esm-resolve'
23
+ import { RECOGNISED, verifyRecognised } from './recognised'
24
+
25
+ /** What the compiler reads (`AnalyzeOptions.packages`): per importing scope (`""` = the app, else the root-relative
26
+ * directory of a written package), each bare specifier → the root-relative path of its written entry source, or the
27
+ * reason it was refused. */
28
+ export interface PackageSources {
29
+ scopes: Record<string, Record<string, string>>
30
+ refused: Record<string, Record<string, string>>
31
+ /** R34.140: packages the compiler recognises by version + hash instead of reading (`recognised.ts`), name → version. A
32
+ * name is here only when EVERY copy of it the build met verified. */
33
+ recognised: Record<string, string>
34
+ /** Each written directory (root-relative) → the package's real directory: a bare import in an artifact compiled from
35
+ * a package source resolves from the package, as it does in a real install (not read by the compiler). */
36
+ dirs: Record<string, string>
37
+ }
38
+
39
+ /** The last build's written directories (absolute) → the package's real directory, for the bundler. */
40
+ const writtenDirs = new Map<string, string>()
41
+
42
+ /** The real directory of the package whose written source `file` (absolute) is, if it is one. */
43
+ export function packageDirOf(file: string): string | undefined {
44
+ for (const [dir, real] of writtenDirs) if (file.startsWith(dir + sep) || file.startsWith(`${dir}/`)) return real
45
+ return undefined
46
+ }
47
+
48
+ /** Where the sources go, relative to the app root. */
49
+ export const PKG_SRC_DIR = '.brust/pkg-src'
50
+
51
+ const lstatSyncOrNull = (p: string) => {
52
+ try {
53
+ return lstatSync(p)
54
+ } catch {
55
+ return null
56
+ }
57
+ }
58
+
59
+ /** Never followed: the React runtime itself, brust, and platform modules. */
60
+ const NEVER = (spec: string) =>
61
+ /^(react|react-dom|scheduler)(\/|$)/.test(spec) ||
62
+ /^(@brust\/|brust(\/|$)|brustjs(\/|$))/.test(spec) ||
63
+ /^(node|bun):/.test(spec) ||
64
+ // L23 inlines lucide icons from the package export; the icons pass owns them.
65
+ /^lucide-react(\/|$)/.test(spec)
66
+
67
+ const LIMITS = { packages: 256, bytesPerPackage: 4 * 1024 * 1024, totalBytes: 64 * 1024 * 1024 }
68
+
69
+ type Outcome = { ok: true; dir: string; entry: string; imports: string[] } | { ok: false; reason: string }
70
+
71
+ /** `@scope/name/sub` → [`@scope/name`, `sub`]. */
72
+ export function splitSpecifier(spec: string): [string, string] {
73
+ const parts = spec.split('/')
74
+ const n = spec.startsWith('@') ? 2 : 1
75
+ return [parts.slice(0, n).join('/'), parts.slice(n).join('/')]
76
+ }
77
+
78
+ /** The first `node_modules/<name>` from `from` upwards, as a real path. */
79
+ function findPackage(name: string, from: string): string | null {
80
+ for (let dir = from; ; ) {
81
+ const p = join(dir, 'node_modules', name)
82
+ if (existsSync(join(p, 'package.json'))) return realpathSync(p)
83
+ const up = dirname(dir)
84
+ if (up === dir) return null
85
+ dir = up
86
+ }
87
+ }
88
+
89
+ /** The package's ESM entry for `import` (exports `.` → `import`/`module`/`default`, then `module`). */
90
+ function esmEntry(pj: Record<string, unknown>): string | null {
91
+ const pick = (x: unknown): string | null => {
92
+ if (typeof x === 'string') return x
93
+ if (!x || typeof x !== 'object') return null
94
+ const o = x as Record<string, unknown>
95
+ for (const k of ['import', 'module', 'default']) if (k in o) return pick(o[k])
96
+ return null
97
+ }
98
+ const exp = pj.exports
99
+ const dot = typeof exp === 'string' ? exp : exp && typeof exp === 'object' ? (exp as Record<string, unknown>)['.'] : undefined
100
+ const viaExports = dot === undefined ? null : pick(dot)
101
+ if (viaExports) return viaExports
102
+ return typeof pj.module === 'string' ? pj.module : null
103
+ }
104
+
105
+ /** The source map of `file`: its `sourceMappingURL` (a relative file), else `<file>.map`. */
106
+ function mapOf(file: string): string | null {
107
+ const text = readFileSync(file, 'utf8')
108
+ const m = /\/\/# sourceMappingURL=([^\s'"]+)\s*$/.exec(text)
109
+ if (m && !m[1]!.startsWith('data:') && !/^[a-z]+:/i.test(m[1]!)) {
110
+ const p = join(dirname(file), m[1]!)
111
+ if (existsSync(p)) return p
112
+ }
113
+ return existsSync(`${file}.map`) ? `${file}.map` : null
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------------------------------------------
117
+ // Integrity (R34.62): every string/number literal and every name of the transpiled sources occurs in the published
118
+ // file the map belongs to. Both sides go through the same transpiler first, so quoting and type syntax agree.
119
+
120
+ /** Names the JSX transform and esbuild add or rename (`undefined` prints as `void 0`); not evidence either way. */
121
+ const JSX_NAMES = new Set(['createElement', '__name', '__defProp', 'React', 'undefined'])
122
+ const JSX_RUNTIME = /^(?:jsx|jsxs|jsxDEV|Fragment)(?:_[\w$]+)?$/
123
+ /** Keywords are syntax, not names: esbuild prints `const` as `var` and drops `type`/`interface` with the types. */
124
+ const KEYWORDS = new Set(
125
+ 'await break case catch class const continue debugger default delete do else enum export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield async of get set as from type declare readonly abstract namespace module satisfies keyof infer is unique asserts override accessor'.split(' '),
126
+ )
127
+
128
+ export interface Skeleton {
129
+ strings: Set<string>
130
+ names: Set<string>
131
+ }
132
+
133
+ /** Literals and names of transpiled JS (a small lexer: strings, templates, comments, numbers, identifiers; a regex
134
+ * literal may be read as names, which only makes a mismatch more likely: fail closed). */
135
+ export function skeleton(js: string): Skeleton {
136
+ const strings = new Set<string>()
137
+ const names = new Set<string>()
138
+ let i = 0
139
+ const n = js.length
140
+ const templateDepth: number[] = []
141
+ let braces = 0
142
+ const readTemplateChunk = () => {
143
+ // at the char after '`' or after the '}' that closes `${`
144
+ let s = ''
145
+ while (i < n) {
146
+ const c = js[i]!
147
+ if (c === '\\') {
148
+ s += js.slice(i, i + 2)
149
+ i += 2
150
+ } else if (c === '`') {
151
+ i++
152
+ strings.add(s)
153
+ return
154
+ } else if (c === '$' && js[i + 1] === '{') {
155
+ i += 2
156
+ strings.add(s)
157
+ templateDepth.push(braces)
158
+ braces++
159
+ return
160
+ } else {
161
+ s += c
162
+ i++
163
+ }
164
+ }
165
+ }
166
+ while (i < n) {
167
+ const c = js[i]!
168
+ if (c === '/' && js[i + 1] === '/') {
169
+ while (i < n && js[i] !== '\n') i++
170
+ } else if (c === '/' && js[i + 1] === '*') {
171
+ const end = js.indexOf('*/', i + 2)
172
+ i = end < 0 ? n : end + 2
173
+ } else if (c === '"' || c === "'") {
174
+ let s = ''
175
+ i++
176
+ while (i < n && js[i] !== c) {
177
+ if (js[i] === '\\') {
178
+ s += js.slice(i, i + 2)
179
+ i += 2
180
+ } else s += js[i++]
181
+ }
182
+ i++
183
+ strings.add(s)
184
+ } else if (c === '`') {
185
+ i++
186
+ readTemplateChunk()
187
+ } else if (c === '{') {
188
+ braces++
189
+ i++
190
+ } else if (c === '}') {
191
+ braces--
192
+ i++
193
+ if (templateDepth.length && templateDepth[templateDepth.length - 1] === braces) {
194
+ templateDepth.pop()
195
+ readTemplateChunk()
196
+ }
197
+ } else if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(js[i + 1] ?? ''))) {
198
+ const m = /^(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?))n?/.exec(js.slice(i))
199
+ const tok = m ? m[0] : c
200
+ const num = Number(tok.replace(/_/g, '').replace(/n$/, ''))
201
+ strings.add(Number.isNaN(num) ? tok : `#${num}`)
202
+ i += tok.length
203
+ } else if (/[A-Za-z_$]/.test(c)) {
204
+ const m = /^[A-Za-z_$][\w$]*/.exec(js.slice(i))!
205
+ names.add(m[0])
206
+ i += m[0].length
207
+ } else i++
208
+ }
209
+ return { strings, names }
210
+ }
211
+
212
+ const transpile = (code: string, loader: 'tsx' | 'ts' | 'js') =>
213
+ new Bun.Transpiler({ loader, target: 'browser', minifyWhitespace: false, deadCodeElimination: false, trimUnusedImports: false }).transformSync(code)
214
+
215
+ /** What of `sources` is not in `published`; empty = the sources are what the published file was built from. */
216
+ export function integrityGaps(sources: { path: string; text: string }[], published: string): string[] {
217
+ const pubJs = transpile(published, 'js')
218
+ const pub = skeleton(pubJs)
219
+ const pubPairs = exportPairs(pubJs)
220
+ const gaps: string[] = []
221
+ for (const s of sources) {
222
+ const loader = s.path.endsWith('.tsx') ? 'tsx' : 'ts'
223
+ const sk = skeleton(withoutUnstableAliases(transpile(s.text, loader), pub.names, pubPairs))
224
+ // Import specifiers are module names, which bundling replaces; they are checked as imports instead.
225
+ for (const im of new Bun.Transpiler({ loader }).scanImports(s.text)) sk.strings.delete(im.path)
226
+ for (const v of sk.strings) if (!pub.strings.has(v)) gaps.push(`${s.path}: literal ${JSON.stringify(v.startsWith('#') ? v.slice(1) : v).slice(0, 60)}`)
227
+ const aliases = importAliases(transpile(s.text, loader), pub.names)
228
+ for (const v of sk.names) if (!JSX_NAMES.has(v) && !JSX_RUNTIME.test(v) && !KEYWORDS.has(v) && !pub.names.has(v) && !aliases.has(v)) gaps.push(`${s.path}: name \`${v}\``)
229
+ }
230
+ return gaps
231
+ }
232
+
233
+ /** R34.142 (W1b): `import { X as Y } from './sibling'` names the same binding as `X` under a local name. A bundler resolves
234
+ * the binding to the sibling's declaration, so `Y` is not in the published file; `X` is. `Y` is dropped from the name check
235
+ * ONLY for a RELATIVE import DECLARATION at the start of a line (a sibling of the same package, bundled in) whose imported name `X` the published file has.
236
+ * An alias of anything else stays a name difference. */
237
+ function importAliases(js: string, pubNames: Set<string>): Set<string> {
238
+ const out = new Set<string>()
239
+ for (const m of js.matchAll(/^import\s*\{([^}]*)\}\s*from\s*["'](\.[^"']*)["']/gm)) {
240
+ for (const item of m[1]!.split(',')) {
241
+ const parts = item.trim().split(/\s+as\s+/)
242
+ if (parts.length === 2 && /^[A-Za-z_$][\w$]*$/.test(parts[1]!) && pubNames.has(parts[0]!)) out.add(parts[1]!)
243
+ }
244
+ }
245
+ return out
246
+ }
247
+
248
+
249
+ /** The `local as exported` pairs of the `export { … }` clauses of transpiled JS (`x` alone is `x as x`). */
250
+ function exportPairs(js: string): Set<string> {
251
+ const out = new Set<string>()
252
+ for (const m of js.matchAll(/\bexport\s*\{([^}]*)\}/g)) {
253
+ for (const item of m[1]!.split(',')) {
254
+ const parts = item.trim().split(/\s+as\s+/)
255
+ if (parts[0] && /^[A-Za-z_$][\w$]*$/.test(parts[0])) out.add(`${parts[0]} as ${parts[1] ?? parts[0]}`)
256
+ }
257
+ }
258
+ return out
259
+ }
260
+
261
+ /** P2 (wave A step 0): a source export clause `export { Local as Alias }` whose alias the published file spells
262
+ * `unstable_Alias` (the Radix convention) names the same binding under another export name; an export name carries no
263
+ * behaviour. The alias is dropped from the source text before the name check ONLY when the published file exports the
264
+ * IDENTICAL local binding as EXACTLY `unstable_` + the alias. Any other alias that the published file does not have stays
265
+ * a name difference (a refusal). */
266
+ function withoutUnstableAliases(js: string, pubNames: Set<string>, pubPairs: Set<string>): string {
267
+ return js.replace(/\bexport\s*\{([^}]*)\}/g, (all, body: string) => {
268
+ const items = body.split(',').map((item) => {
269
+ const parts = item.trim().split(/\s+as\s+/)
270
+ const [local, alias] = [parts[0] ?? '', parts[1]]
271
+ if (alias === undefined || pubNames.has(alias)) return item.trim()
272
+ return pubPairs.has(`${local} as unstable_${alias}`) ? local : item.trim()
273
+ })
274
+ return `export { ${items.join(', ')} }`
275
+ })
276
+ }
277
+
278
+ /** P1 (wave A step 0): a published file bundled from SEVERAL sources, none of which is the entry (the `index.ts` is not in
279
+ * the ESM map). Provable only when the published file's one `export { a, b }` clause lists plain names (no alias, no
280
+ * `export *`, no default) and EACH of them is declared by `export function|const|let|class` in exactly one source and
281
+ * EVERY source declares at least one of them: the entry is then a barrel the build writes from those names (identifiers
282
+ * only), never one of the sources chosen by eye. Every source still goes through the integrity check. */
283
+ function barrelOf(files: { path: string; text: string }[], published: string): { path: string; text: string } | undefined {
284
+ let js: string
285
+ try {
286
+ js = transpile(published, 'js')
287
+ } catch {
288
+ return undefined
289
+ }
290
+ if (/\bexport\s+(?:(?:default|function|const|let|var|class)\b|\*)/.test(js)) return undefined
291
+ const clauses = [...js.matchAll(/\bexport\s*\{([^}]*)\}/g)]
292
+ if (clauses.length !== 1) return undefined
293
+ const names: string[] = []
294
+ for (const item of clauses[0]![1]!.split(',')) {
295
+ const n = item.trim()
296
+ if (n === '') continue
297
+ if (!/^[A-Za-z_$][\w$]*$/.test(n)) return undefined // an alias (`a as b`) or anything else
298
+ names.push(n)
299
+ }
300
+ if (names.length === 0 || new Set(names).size !== names.length) return undefined
301
+ const owner = new Map<string, string>()
302
+ const used = new Set<string>()
303
+ for (const name of names) {
304
+ const owners = files.filter((f) => new RegExp(`^export\\s+(?:async\\s+)?(?:function\\*?|const|let|class)\\s+${name.replace(/\$/g, '\\$')}\\b`, 'm').test(f.text))
305
+ if (owners.length !== 1) return undefined
306
+ owner.set(name, owners[0]!.path)
307
+ used.add(owners[0]!.path)
308
+ }
309
+ if (files.some((f) => !used.has(f.path))) return undefined
310
+ // The barrel's specifiers are source-map paths (package-controlled text): only plain path characters, no `..` segment,
311
+ // never absolute; and each is printed as a JSON string, so nothing in it can end the string or the statement.
312
+ const plainPath = (p: string) => /^[A-Za-z0-9_@./-]+$/.test(p) && !p.startsWith('/') && !p.split('/').some((seg) => seg === '..' || seg === '')
313
+ if (files.some((f) => !plainPath(f.path))) return undefined
314
+ const dir = posix.dirname(files[0]!.path)
315
+ const path = posix.join(dir, 'index.ts')
316
+ if (files.some((f) => f.path === path)) return undefined
317
+ const lines = [...used].map((src) => {
318
+ const rel = posix.relative(dir, src).replace(/\.tsx?$/, '')
319
+ return `export { ${names.filter((n) => owner.get(n) === src).join(', ')} } from ${JSON.stringify(rel.startsWith('.') ? rel : `./${rel}`)}`
320
+ })
321
+ return { path, text: `${lines.join('\n')}\n` }
322
+ }
323
+
324
+ // ---------------------------------------------------------------------------------------------------------------
325
+
326
+ /** Reads one package (real directory `dir`), checks it, and writes its sources under `outRoot`. */
327
+ function writePackage(appRoot: string, dir: string, budget: { bytes: number }): Outcome {
328
+ const pj = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>
329
+ const entryRel = esmEntry(pj)
330
+ if (!entryRel) return { ok: false, reason: 'no ESM entry (exports `import` or `module`)' }
331
+ const entry = join(dir, entryRel)
332
+ if (!existsSync(entry) || !statSync(entry).isFile()) return { ok: false, reason: `the ESM entry ${entryRel} is missing` }
333
+ const mapFile = mapOf(entry)
334
+ if (!mapFile) return { ok: false, reason: 'no source map for the ESM entry' }
335
+ let map: { sources?: unknown; sourcesContent?: unknown }
336
+ try {
337
+ map = JSON.parse(readFileSync(mapFile, 'utf8'))
338
+ } catch {
339
+ return { ok: false, reason: 'the source map is not JSON' }
340
+ }
341
+ const sources = Array.isArray(map.sources) ? (map.sources as unknown[]) : []
342
+ const contents = Array.isArray(map.sourcesContent) ? (map.sourcesContent as unknown[]) : []
343
+ // Each source as a path inside the package; anything outside it, or not TS/TSX, is not ours to read.
344
+ const files: { path: string; text: string }[] = []
345
+ for (const [k, s] of sources.entries()) {
346
+ const text = contents[k]
347
+ if (typeof s !== 'string' || typeof text !== 'string') continue
348
+ const abs = posix.normalize(posix.join(relative(dir, dirname(mapFile)).split(sep).join('/'), s))
349
+ if (abs.startsWith('..') || posix.isAbsolute(abs) || posix.isAbsolute(s) || /^[a-z]+:/i.test(s)) return { ok: false, reason: `the source ${s} lies outside the package` }
350
+ // Map paths are package-controlled text and become file names, the entry path and import specifiers the compiler
351
+ // prints: only plain path characters, no `//`, no `..` segment left after normalizing (Mellow, wave A step 0).
352
+ if (!/^[A-Za-z0-9_@./-]+$/.test(s) || s.includes('//') || !/^[A-Za-z0-9_@][A-Za-z0-9_@./-]*$/.test(abs) || abs.split('/').includes('..'))
353
+ return { ok: false, reason: `the source path ${JSON.stringify(s).slice(0, 80)} has characters other than letters, digits and _ @ . / -` }
354
+ if (!/\.tsx?$/.test(abs)) continue
355
+ files.push({ path: abs, text })
356
+ }
357
+ if (files.length === 0) return { ok: false, reason: 'the source map carries no TypeScript sources (`sourcesContent`)' }
358
+ const bytes = files.reduce((a, f) => a + f.text.length, 0)
359
+ if (bytes > LIMITS.bytesPerPackage) return { ok: false, reason: `the sources are ${bytes} bytes (limit ${LIMITS.bytesPerPackage})` }
360
+ if (budget.bytes + bytes > LIMITS.totalBytes) return { ok: false, reason: 'the package-source budget of this build is spent' }
361
+ // Imports: relative ones must be in the map (the compiler would otherwise fail on them), bare ones are followed.
362
+ const have = new Set(files.map((f) => f.path))
363
+ const bare = new Set<string>()
364
+ const imported = new Set<string>()
365
+ for (const f of files) {
366
+ if (/\beval\s*\(|\bnew\s+Function\b/.test(f.text)) return { ok: false, reason: `${f.path} calls eval or new Function` }
367
+ let imports: { path: string; kind: string }[]
368
+ try {
369
+ imports = new Bun.Transpiler({ loader: f.path.endsWith('.tsx') ? 'tsx' : 'ts' }).scanImports(f.text)
370
+ } catch (e) {
371
+ return { ok: false, reason: `${f.path} does not parse: ${String(e instanceof Error ? e.message : e).split('\n')[0]}` }
372
+ }
373
+ for (const im of imports) {
374
+ // The JSX transform's own runtime import (the transpiler adds it), and React itself.
375
+ if (NEVER(im.path)) continue
376
+ if (im.kind === 'dynamic-import' || im.kind === 'require-call' || im.kind === 'require-resolve') return { ok: false, reason: `${f.path} has a ${im.kind} (${im.path})` }
377
+ if (RELATIVE_SPEC.test(im.path)) {
378
+ const base = posix.normalize(posix.join(posix.dirname(f.path), im.path))
379
+ // `.` and `..` name a directory (F244): only its index answers, never a sibling file of the same name.
380
+ const dirOnly = im.path === '.' || im.path === '..'
381
+ const hit = [...(dirOnly ? [] : [base, `${base}.tsx`, `${base}.ts`]), posix.join(base, 'index.tsx'), posix.join(base, 'index.ts')].find((c) => have.has(c))
382
+ if (hit) imported.add(hit)
383
+ else return { ok: false, reason: `${f.path} imports ${im.path}, which the source map does not carry` }
384
+ } else if (im.path.startsWith('/') || /^[a-z]+:/i.test(im.path)) return { ok: false, reason: `${f.path} imports ${im.path}` }
385
+ else bare.add(im.path)
386
+ }
387
+ }
388
+ // The entry source: the one `package.json#source` names, else the only source no other source imports.
389
+ const declared = typeof pj.source === 'string' ? posix.normalize(pj.source.replace(/^\.\//, '')) : null
390
+ const roots = files.filter((f) => !imported.has(f.path))
391
+ const entrySrc = files.find((f) => f.path === declared) ?? (roots.length === 1 ? roots[0] : undefined)
392
+ const barrel = entrySrc ? undefined : barrelOf(files, readFileSync(entry, 'utf8'))
393
+ if (!entrySrc && !barrel) return { ok: false, reason: `the source map has ${files.length} sources and none is the entry (no \`source\` field, ${roots.length} unimported)` }
394
+ // R34.62: the published file must be what these sources were built into.
395
+ let gaps: string[]
396
+ try {
397
+ gaps = integrityGaps(files, readFileSync(entry, 'utf8'))
398
+ } catch (e) {
399
+ return { ok: false, reason: `the integrity check could not read the sources or ${entryRel}: ${String(e instanceof Error ? e.message : e).split('\n')[0]}` }
400
+ }
401
+ if (gaps.length > 0) return { ok: false, reason: `the sources do not match the published ${entryRel} (${gaps.length} differences, first: ${gaps[0]})` }
402
+ // Keyed on where the package sits relative to the app (stable across machines), not its absolute path.
403
+ // Review F1 (security): no package-controlled text in the path. The directory is named by a hash of where the package
404
+ // sits relative to the app (stable across machines), and every target must resolve inside the directory this build
405
+ // owns before anything is created; a `name`/`version` of `../..` cannot move a write.
406
+ const hash = createHash('sha256').update(relative(appRoot, dir).split(sep).join('/')).digest('hex').slice(0, 16)
407
+ const outRel = posix.join(PKG_SRC_DIR, `p-${hash}`)
408
+ const own = resolve(appRoot, PKG_SRC_DIR) + sep
409
+ const written = barrel ? [...files, barrel] : files
410
+ const targets = written.map((f) => ({ f, target: resolve(appRoot, outRel, f.path) }))
411
+ const escaped = targets.find((t) => !t.target.startsWith(own))
412
+ if (escaped) return { ok: false, reason: `the source ${escaped.f.path} would be written outside ${PKG_SRC_DIR}` }
413
+ for (const { f, target } of targets) {
414
+ mkdirSync(dirname(target), { recursive: true })
415
+ // The directories just made are this build's: a real path elsewhere means a link was planted in between.
416
+ if (!`${realpathSync(dirname(target))}${sep}`.startsWith(realpathSync(resolve(appRoot, PKG_SRC_DIR)) + sep))
417
+ return { ok: false, reason: `the source ${f.path} would be written outside ${PKG_SRC_DIR}` }
418
+ writeFileSync(target, f.text)
419
+ }
420
+ budget.bytes += bytes
421
+ return { ok: true, dir: outRel, entry: posix.join(outRel, (entrySrc ?? barrel)!.path), imports: [...bare].sort() }
422
+ }
423
+
424
+ /** The verified version of the pinned package at `dir` (`RECOGNISED`), `null` when its version or entry bytes differ. */
425
+ function recognisedVersion(name: string, dir: string): string | null {
426
+ try {
427
+ const pj = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as Record<string, unknown>
428
+ const entryRel = esmEntry(pj)
429
+ if (!entryRel) return null
430
+ const entry = join(dir, entryRel)
431
+ if (!statSync(entry).isFile()) return null
432
+ return verifyRecognised(name, pj.version, readFileSync(entry))
433
+ } catch {
434
+ return null
435
+ }
436
+ }
437
+
438
+ /**
439
+ * Writes the sources of every package `specs` reaches from the app (and of every package those sources import),
440
+ * and returns the resolution map for the compiler. The directory is rebuilt from nothing on every call.
441
+ */
442
+ export function preparePackageSources(appRoot: string, specs: Iterable<string>): PackageSources {
443
+ const root = realpathSync(appRoot)
444
+ // BEFORE anything is removed (Mellow N1, F163): neither `.brust` nor `.brust/pkg-src` may be a link out of the app, or
445
+ // the recursive remove below would delete whatever the link points at.
446
+ for (const p of [dirname(PKG_SRC_DIR), PKG_SRC_DIR].map((d) => join(root, d))) {
447
+ if (!lstatSyncOrNull(p)) continue
448
+ let real = '' // a dangling link resolves to nothing: refused as well
449
+ try {
450
+ real = realpathSync(p)
451
+ } catch {}
452
+ if (!`${real}${sep}`.startsWith(root + sep)) throw new BuildError('package-source', `${relative(root, p)} resolves outside the app root (a link?); remove it and build again`)
453
+ }
454
+ rmSync(join(root, PKG_SRC_DIR), { recursive: true, force: true })
455
+ mkdirSync(join(root, PKG_SRC_DIR), { recursive: true })
456
+ if (!realpathSync(join(root, PKG_SRC_DIR)).startsWith(root + sep)) throw new BuildError('package-source', `${PKG_SRC_DIR} resolves outside the app root (a link?); remove it and build again`)
457
+ const out: PackageSources = { scopes: {}, refused: {}, dirs: {}, recognised: {} }
458
+ const recognisedBad = new Set<string>()
459
+ writtenDirs.clear()
460
+ const byDir = new Map<string, Outcome>()
461
+ const budget = { bytes: 0 }
462
+ // (scope, the real directory bare imports resolve from, specifier)
463
+ const queue: [string, string, string][] = [...new Set(specs)].sort().map((s) => ['', root, s])
464
+ const seen = new Set<string>()
465
+ while (queue.length > 0) {
466
+ const [scope, from, spec] = queue.shift()!
467
+ const key = `${scope}\0${spec}`
468
+ if (seen.has(key) || NEVER(spec)) continue
469
+ seen.add(key)
470
+ const refuse = (reason: string) => {
471
+ ;(out.refused[scope] ??= {})[spec] = reason
472
+ }
473
+ const [name, sub] = splitSpecifier(spec)
474
+ if (sub) {
475
+ refuse('a package subpath import is not followed')
476
+ continue
477
+ }
478
+ const dir = findPackage(name, from)
479
+ if (!dir) {
480
+ refuse('not installed')
481
+ continue
482
+ }
483
+ let o = byDir.get(dir)
484
+ if (!o && Object.hasOwn(RECOGNISED, name)) {
485
+ // R34.140: not read: pinned by version and hash. The refusal stays (its imports stay islands where nothing recognises them).
486
+ const v = recognisedVersion(name, dir)
487
+ if (v) out.recognised[name] ??= v
488
+ else recognisedBad.add(name)
489
+ o = { ok: false, reason: v ? `recognised by the compiler (${name}@${v}), not read` : `${name} is not the pinned release the compiler recognises` }
490
+ byDir.set(dir, o)
491
+ }
492
+ if (!o) {
493
+ try {
494
+ o = byDir.size >= LIMITS.packages ? { ok: false, reason: `more than ${LIMITS.packages} packages` } : writePackage(root, dir, budget)
495
+ } catch (e) {
496
+ // An unreadable package.json or map is a refusal: a package never fails the build here.
497
+ o = { ok: false, reason: `unreadable: ${String(e instanceof Error ? e.message : e).split('\n')[0]}` }
498
+ }
499
+ byDir.set(dir, o)
500
+ // A refusal is reported where it matters: the compiler names it on the island it leaves (`external-component`).
501
+ if (o.ok) {
502
+ out.dirs[o.dir] = dir
503
+ writtenDirs.set(join(root, o.dir), dir)
504
+ for (const im of o.imports) queue.push([o.dir, dir, im])
505
+ }
506
+ }
507
+ if (o.ok) (out.scopes[scope] ??= {})[spec] = o.entry
508
+ else refuse(o.reason)
509
+ }
510
+ for (const n of recognisedBad) delete out.recognised[n]
511
+ mkdirSync(join(root, PKG_SRC_DIR), { recursive: true })
512
+ writeFileSync(join(root, PKG_SRC_DIR, 'index.json'), `${JSON.stringify(out, null, 2)}\n`)
513
+ return out
514
+ }
@@ -0,0 +1,19 @@
1
+ // Packages the compiler RECOGNISES by what they are rather than reading their source (R34.140). A recognised package is
2
+ // pinned: the installed package.json `version` AND the SHA-256 of its published ESM entry must be one of the pairs below.
3
+ // Any other version, or the same version with another byte in the entry, is not recognised (its import stays the React
4
+ // island it is without it). The compiler is told only the package name and the verified version (`index.json#recognised`).
5
+ import { createHash } from 'node:crypto'
6
+
7
+ /** package name → published version → SHA-256 (hex) of the file `module` / `exports['.'].import` names. */
8
+ export const RECOGNISED: Record<string, Record<string, string>> = {
9
+ // `createCollection` (the 3-tuple form roving focus, accordion, menus and slider use) of the 1.2.0 release
10
+ '@radix-ui/react-collection': { '1.2.0': '52a6719c7c1a7a5202ab5ae58bb552f0d7853965a0833cf0e71749ac580e349f' },
11
+ }
12
+
13
+ /** The verified version of `name` when `version` and the bytes of its ESM `entry` are a pinned pair; else `null`. */
14
+ export function verifyRecognised(name: string, version: unknown, entryBytes: Uint8Array): string | null {
15
+ const pins = RECOGNISED[name]
16
+ if (!pins || typeof version !== 'string' || !Object.hasOwn(pins, version)) return null
17
+ const sha = createHash('sha256').update(entryBytes).digest('hex')
18
+ return sha === pins[version] ? version : null
19
+ }
package/src/build/scan.ts CHANGED
@@ -1,15 +1,21 @@
1
- // Route scan (plan T5): import the route entry, then map every route Component to the `.tsx`
2
- // file it is the default export of. The compiler only ever sees files, never functions.
3
- import { readFileSync } from 'node:fs'
4
- import { dirname } from 'node:path'
1
+ // Route scan (plan T5, gaps L7): import the route entry, then walk its static import graph (inside the app root,
2
+ // outside node_modules) and map every Component to the `.tsx` file it is the default export of. The compiler only ever sees files, never functions.
3
+ import { readFileSync, realpathSync } from 'node:fs'
4
+ import { dirname, resolve, sep } from 'node:path'
5
5
  import { BrustRouteError, type Route } from '../routes'
6
6
  import { BuildError } from './errors'
7
+ import { installServerOnlyRuntime } from './server-only'
7
8
 
8
- const DEFAULT_IMPORT = /^\s*import\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{[^}]*\})?\s+from\s+['"]([^'"]+)['"]/gm
9
-
10
- export async function scanRoutes(entryFile: string): Promise<{ routes: Route[]; componentFile: Map<Function, string> }> {
9
+ /** `componentIssue` explains a Component the walk saw but could not map (named-only, outside the root, in node_modules). */
10
+ export async function scanRoutes(
11
+ entryFile: string,
12
+ appRoot?: string,
13
+ /** `[build] source_roots` (F256): app-root-relative directories outside the app; their modules are part of the graph (F276). */
14
+ sourceRoots: string[] = [],
15
+ ): Promise<{ routes: Route[]; componentFile: Map<Function, string>; componentIssue: Map<Function, string>; appModules: string[]; appGraph: Map<string, string[]> }> {
11
16
  // biome-ignore lint/suspicious/noExplicitAny: an arbitrary user module
12
17
  let mod: any
18
+ installServerOnlyRuntime() // `server-only` resolves to an empty module: a loader may import server-only code
13
19
  try {
14
20
  mod = await import(entryFile)
15
21
  } catch (e) {
@@ -21,22 +27,67 @@ export async function scanRoutes(entryFile: string): Promise<{ routes: Route[];
21
27
  if (!Array.isArray(routes))
22
28
  throw new BuildError('route-entry', `${entryFile} exports neither \`routes\` nor a default route array`)
23
29
 
24
- const src = readFileSync(entryFile, 'utf8')
25
- const real = new Set(new Bun.Transpiler({ loader: 'tsx' }).scanImports(src).map((i) => i.path))
26
30
  const componentFile = new Map<Function, string>()
27
- for (const m of src.matchAll(DEFAULT_IMPORT)) {
28
- const spec = m[2]!
29
- if (!real.has(spec)) continue // inside a comment or string: not an import
30
- let file: string
31
+ const componentIssue = new Map<Function, string>()
32
+ const root = realpathSync(resolve(appRoot ?? dirname(entryFile)))
33
+ const transpiler = new Bun.Transpiler({ loader: 'tsx' })
34
+ // F276: the app root and every `source_roots` directory: a module in `../shared` is as much part of the app as one in
35
+ // the root, so a load-time write it makes is seen by the F230 scan. Roots are real paths, as `f` is.
36
+ const scopes = [root, ...sourceRoots.map((r) => realpathSync(resolve(root, r)))]
37
+ const inRoot = (f: string) => scopes.some((s) => f.startsWith(s + sep)) && !f.split(sep).includes('node_modules')
38
+ const visited = new Set<string>()
39
+ // F230: each in-root module's in-root static imports (absolute paths), for the island chunks' load-time writers.
40
+ const appGraph = new Map<string, string[]>()
41
+ // Post-order: a file's imports are mapped before the file itself, and the first file to claim a function
42
+ // keeps it, so the module that defines a Component beats a barrel that re-exports it.
43
+ const visit = async (file: string): Promise<void> => {
44
+ if (visited.has(file)) return
45
+ visited.add(file)
46
+ let src: string
31
47
  try {
32
- file = Bun.resolveSync(spec, dirname(entryFile))
48
+ src = readFileSync(file, 'utf8')
33
49
  } catch {
34
- continue // a bare specifier the route file never uses as a Component; checked below
50
+ return
51
+ }
52
+ const loader = file.endsWith('.tsx') ? transpiler : file.endsWith('.ts') ? new Bun.Transpiler({ loader: 'ts' }) : null
53
+ if (!loader) return
54
+ const deps: string[] = []
55
+ // Only static imports are followed: a dynamic import() is not part of the route table's static graph.
56
+ for (const imp of loader.scanImports(src)) {
57
+ if (imp.kind !== 'import-statement') continue
58
+ let dep: string
59
+ try {
60
+ dep = Bun.resolveSync(imp.path, dirname(file))
61
+ } catch {
62
+ continue // a bare specifier that does not resolve; a route using it fails in compileApp
63
+ }
64
+ if (!dep.endsWith('.tsx') && !dep.endsWith('.ts')) continue
65
+ if (inRoot(dep)) deps.push(dep)
66
+ else if (dep.endsWith('.tsx')) await note(dep, dep.split(sep).includes('node_modules') ? 'in node_modules' : `outside the app root ${root}`)
67
+ }
68
+ appGraph.set(file, deps)
69
+ for (const dep of deps) await visit(dep)
70
+ if (!file.endsWith('.tsx')) return
71
+ const m = await import(file)
72
+ for (const [name, v] of Object.entries(m)) {
73
+ if (typeof v !== 'function') continue
74
+ if (name === 'default') {
75
+ if (!componentFile.has(v)) componentFile.set(v, file)
76
+ } else if (!componentIssue.has(v)) {
77
+ componentIssue.set(v, `${v.name || name} is only a named export of ${file} (export ${name}): export it as default`)
78
+ }
35
79
  }
36
- if (!file.endsWith('.tsx')) continue // not a component source; a route using it fails in compileApp
37
- const def = (await import(file)).default
38
- // Bun's module cache: the same function object the routes tree holds.
39
- if (typeof def === 'function') componentFile.set(def, file)
40
80
  }
41
- return { routes, componentFile }
81
+ const note = async (file: string, why: string) => {
82
+ try {
83
+ const def = (await import(file)).default
84
+ if (typeof def === 'function' && !componentIssue.has(def)) componentIssue.set(def, `${def.name || '(anonymous)'} lives in ${file}, which is ${why}`)
85
+ } catch {}
86
+ }
87
+ await visit(entryFile)
88
+ // A function reachable as a default somewhere is fine; only an unmapped one keeps its explanation.
89
+ for (const f of componentFile.keys()) componentIssue.delete(f)
90
+ // F230: every app module of the static graph (`.ts`/`.tsx` inside the root, outside node_modules), for the scan of
91
+ // load-time writes into another module's exports (`scanLoadWrites`).
92
+ return { routes, componentFile, componentIssue, appModules: [...visited].filter(inRoot), appGraph }
42
93
  }