prunelle 0.0.0-stage → 0.5.2

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 (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,57 @@
1
+ // The previous build's client files that a new build dropped, linked into its stage for one more deploy,
2
+ // so a page loaded before the deploy still finds the deferred island chunks it links (#3663).
3
+
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { linkOrCopyFile } from './bundle'
7
+ import { isInside } from './is-inside'
8
+
9
+ /** Written at the root of each output: which client files the build made itself, and which it carried from the one before. */
10
+ export const ASSET_RECORD = '.prunelle-assets.json'
11
+
12
+ interface AssetRecord {
13
+ /** The client folder, from the output root: `client`, or the asset prefix's folder in a static export. */
14
+ dir: string
15
+ assets: string[]
16
+ carried: string[]
17
+ }
18
+
19
+ function readRecord(path: string): AssetRecord | undefined {
20
+ if (!existsSync(path))
21
+ return undefined
22
+ try {
23
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<AssetRecord>
24
+ return typeof parsed.dir === 'string' && Array.isArray(parsed.assets) ? parsed as AssetRecord : undefined
25
+ }
26
+ catch {
27
+ // A record prunelle cannot read carries nothing: the deploy still works, an old page reloads for its chunk as before.
28
+ return undefined
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Hard-links into `stageRoot/dir` each client file the build in `previousRoot` made and the stage lacks, with its `.br` and `.gz`, and writes this build's record.
34
+ * What the previous build carried itself is left behind, so a file outlives one deploy, never two.
35
+ */
36
+ export function carryPreviousAssets(previousRoot: string, stageRoot: string, dir: string, assets: readonly string[]): string[] {
37
+ const previous = readRecord(join(previousRoot, ASSET_RECORD))
38
+ const carried: string[] = []
39
+ if (previous !== undefined) {
40
+ const fromDir = join(previousRoot, previous.dir)
41
+ const toDir = join(stageRoot, dir)
42
+ for (const rel of previous.assets) {
43
+ const from = join(fromDir, rel)
44
+ const to = join(toDir, rel)
45
+ if (!isInside(previousRoot, from) || !isInside(toDir, to) || !existsSync(from) || existsSync(to))
46
+ continue
47
+ for (const ext of ['', '.br', '.gz']) {
48
+ if (existsSync(`${from}${ext}`))
49
+ linkOrCopyFile(`${from}${ext}`, `${to}${ext}`)
50
+ }
51
+ carried.push(rel)
52
+ }
53
+ }
54
+ const record: AssetRecord = { dir, assets: [...assets], carried }
55
+ writeFileSync(join(stageRoot, ASSET_RECORD), JSON.stringify(record))
56
+ return carried
57
+ }
@@ -0,0 +1,107 @@
1
+ // The generated entry files of the client build (the island runtime, the region bundle, one per island) and the hydrate strategies its loader keeps.
2
+
3
+ import type { BundleEnv } from './bundle'
4
+ import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+
7
+ const LEADING_DOT_SLASH_RE = /^\.\//
8
+
9
+ /** The lazy strategies some island of the app hydrates with, so the loader keeps only theirs. A mode computed at runtime (`*`) may be any of them. */
10
+ export function hydrateStrategies(analyses: Iterable<{ defaultHydrate?: string | undefined, hydrateModes: Set<string> }>): { strategies: Record<'visible' | 'idle' | 'interaction' | 'media', boolean>, hasClientOnlyHydrate: boolean } {
11
+ const strategies = { visible: false, idle: false, interaction: false, media: false }
12
+ let hasClientOnlyHydrate = false
13
+ for (const analysis of analyses) {
14
+ for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
15
+ const any = mode === '*'
16
+ hasClientOnlyHydrate ||= any || mode === 'client'
17
+ strategies.visible ||= any || mode === 'visible'
18
+ strategies.idle ||= any || mode === 'idle'
19
+ strategies.interaction ||= any || mode === 'interaction'
20
+ strategies.media ||= any || (mode?.startsWith('media(') ?? false)
21
+ }
22
+ }
23
+ return { strategies, hasClientOnlyHydrate }
24
+ }
25
+
26
+ // Another build of the same app (`prunelle build` beside `prunelle dev`) may be reading the file, hence the rename.
27
+ function writeEntry(path: string, contents: string): void {
28
+ if (existsSync(path) && readFileSync(path, 'utf8') === contents)
29
+ return
30
+ const tmpPath = `${path}.${process.pid}.tmp`
31
+ writeFileSync(tmpPath, contents)
32
+ renameSync(tmpPath, path)
33
+ }
34
+
35
+ export interface ClientEntryFiles {
36
+ entryPoints: string[]
37
+ islandEntryToKey: Map<string, string>
38
+ runtimeEntryPath: string | undefined
39
+ /** The plugins' `regionClientEntry` modules, bundled apart so only the routes that render a `<Region>` load them. */
40
+ regionEntryPath: string | undefined
41
+ }
42
+
43
+ export function writeClientEntries(env: BundleEnv, entriesDir: string, options: { pluginClientEntries: string[], regionClientEntries: string[], hasClientOnlyHydrate: boolean, standaloneCss: string[] }): ClientEntryFiles {
44
+ const { pluginClientEntries, regionClientEntries, hasClientOnlyHydrate } = options
45
+ const out: ClientEntryFiles = { entryPoints: [], islandEntryToKey: new Map(), runtimeEntryPath: undefined, regionEntryPath: undefined }
46
+ if (env.islands.targets.size > 0 || pluginClientEntries.length > 0) {
47
+ const runtimeLines: string[] = []
48
+ if (env.islands.targets.size > 0) {
49
+ runtimeLines.push(`import { defineIslandElement } from 'prunelle/internal/island';`)
50
+ runtimeLines.push(`defineIslandElement();`)
51
+ }
52
+ for (const pe of pluginClientEntries)
53
+ runtimeLines.push(`import ${JSON.stringify(pe)};`)
54
+ out.runtimeEntryPath = join(entriesDir, 'runtime.ts')
55
+ writeEntry(out.runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
56
+ out.entryPoints.push(out.runtimeEntryPath)
57
+ }
58
+ if (regionClientEntries.length > 0) {
59
+ out.regionEntryPath = join(entriesDir, 'regions.ts')
60
+ writeEntry(out.regionEntryPath, `${regionClientEntries.map(pe => `import ${JSON.stringify(pe)};`).join('\n')}\n`)
61
+ out.entryPoints.push(out.regionEntryPath)
62
+ }
63
+
64
+ out.entryPoints.push(...options.standaloneCss)
65
+
66
+ // Each island hands the loader the DOM runtime its chunk imports anyway, so a page whose islands all wait downloads the loader alone.
67
+ const domExports = `export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'prunelle/internal/dom';\n`
68
+ for (const [key, target] of env.islands.targets) {
69
+ const entryPath = join(entriesDir, `${target.id}.ts`)
70
+ const exportStmt = target.exportName === 'default'
71
+ ? `export { default } from ${JSON.stringify(target.file)};\n`
72
+ : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
73
+ writeEntry(entryPath, exportStmt + domExports)
74
+ out.entryPoints.push(entryPath)
75
+ out.islandEntryToKey.set(entryPath, key)
76
+ }
77
+ return out
78
+ }
79
+
80
+ /** For each JS entry of the client build with static imports, every chunk it imports, transitively: the page preloads them beside the entry, so the browser fetches them at once rather than one level at a time. */
81
+ export function entryStaticImports(metafile: Bun.BuildOutput['metafile'], assetPrefix: string): Record<string, string[]> {
82
+ const deps = new Map<string, string[]>()
83
+ const entries: string[] = []
84
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
85
+ const rel = outKey.replace(LEADING_DOT_SLASH_RE, '')
86
+ if (!rel.endsWith('.js'))
87
+ continue
88
+ deps.set(rel, (info.imports ?? []).filter(imp => imp.kind === 'import-statement').map(imp => imp.path.replace(LEADING_DOT_SLASH_RE, '')))
89
+ if (info.entryPoint !== undefined)
90
+ entries.push(rel)
91
+ }
92
+ const out: Record<string, string[]> = {}
93
+ for (const entry of entries) {
94
+ const seen = new Set<string>()
95
+ const stack = [...deps.get(entry)!]
96
+ while (stack.length > 0) {
97
+ const cur = stack.pop()!
98
+ if (seen.has(cur) || cur === entry)
99
+ continue
100
+ seen.add(cur)
101
+ stack.push(...deps.get(cur) ?? [])
102
+ }
103
+ if (seen.size > 0)
104
+ out[`${assetPrefix}/${entry}`] = [...seen].sort().map(rel => `${assetPrefix}/${rel}`)
105
+ }
106
+ return out
107
+ }
@@ -0,0 +1,173 @@
1
+ // The Bun plugin of the client build: prunelle specifiers, action stubs, compiled islands, and imports of the `prunelle` barrel pointed at the module holding each name.
2
+
3
+ import type { BunPlugin } from 'bun'
4
+ import type { BuildCache, ModuleGraph } from './graph'
5
+ import type { ActionsByFile } from './islands'
6
+ import { parseSync } from 'oxc-parser'
7
+ import { compileDom } from '../compiler/index'
8
+ import { SERVER_ONLY_FILTER } from '../compiler/server-only'
9
+ import { pruneForClient } from './client-prune'
10
+ import { isInNodeModules, relPosix } from './files'
11
+ import { resolvePrunelleSpecifier } from './resolve'
12
+
13
+ export const PRUNELLE_SPECIFIER_FILTER = /^prunelle(?:\/.*)?$/
14
+ export const TS_FILTER = /\.(?:ts|tsx)$/
15
+ const TS_LANG_RE = /\.[cm]?ts$/i
16
+
17
+ export interface ClientTransforms {
18
+ active: boolean
19
+ key: string
20
+ /** The first hook that threw, named, rethrown once the build is done. */
21
+ failure: Error | undefined
22
+ apply: (code: string, id: string, target: 'server' | 'client') => string
23
+ }
24
+
25
+ export interface ClientPluginEnv {
26
+ root: string
27
+ isDev: boolean
28
+ graph: ModuleGraph
29
+ cache: BuildCache | undefined
30
+ actionsByFile: ActionsByFile
31
+ transforms: ClientTransforms
32
+ /** Collects each server-only import a browser file makes, reported once the build ends. */
33
+ leaks: Set<string>
34
+ /** Per file, the `export { … }` statement naming the islands it does not export itself. */
35
+ localExports: ReadonlyMap<string, string>
36
+ /** Per file the browser loads only for its own islands, the top-level names its client copy keeps. */
37
+ clientKeep: ReadonlyMap<string, ReadonlySet<string>>
38
+ }
39
+
40
+ /** The `export { … }` statement each file needs so the client entry can import the islands the file does not export. */
41
+ export function localIslandExports(targets: Iterable<{ file: string, exportName: string, local?: string | undefined }>): Map<string, string> {
42
+ const names = new Map<string, string[]>()
43
+ for (const t of targets) {
44
+ if (t.local === undefined)
45
+ continue
46
+ const list = names.get(t.file) ?? []
47
+ list.push(t.local === t.exportName ? t.local : `${t.local} as ${t.exportName}`)
48
+ names.set(t.file, list)
49
+ }
50
+ return new Map([...names].map(([file, list]) => [file, `\nexport { ${list.join(', ')} };\n`]))
51
+ }
52
+
53
+ /**
54
+ * Rewrites top-level `import { a, b } from 'prunelle'` statements to import each name from the module declaring it.
55
+ * Through the barrel every island reaches every module it re-exports, and Bun then places a module only some islands use (the action runtime) in the shared chunk in one build and in the island's own chunk in the next (#3598).
56
+ */
57
+ export function directPrunelleImports(code: string, graph: ModuleGraph, filename = 'module.tsx'): string {
58
+ if (!code.includes('prunelle'))
59
+ return code
60
+ const barrel = resolvePrunelleSpecifier('prunelle')!
61
+ const lang = TS_LANG_RE.test(filename) ? 'ts' : 'tsx'
62
+ const parsed = parseSync(filename, code, { lang, sourceType: 'module' })
63
+ if (parsed.errors.length > 0)
64
+ return code
65
+
66
+ const edits: { start: number, end: number, text: string }[] = []
67
+ for (const stmt of parsed.program.body) {
68
+ if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type' || stmt.source.value !== 'prunelle')
69
+ continue
70
+ if (stmt.specifiers.length === 0 || stmt.specifiers.some(s => s.type !== 'ImportSpecifier'))
71
+ continue
72
+
73
+ const byFile = new Map<string, string[]>()
74
+ const kept: string[] = []
75
+ for (const spec of stmt.specifiers) {
76
+ if (spec.type !== 'ImportSpecifier')
77
+ continue
78
+ const imported = spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value
79
+ const importedRaw = spec.imported.type === 'Identifier' ? imported : JSON.stringify(imported)
80
+ const local = spec.local.name
81
+ const rawSpec = imported === local && spec.imported.type === 'Identifier' ? local : `${importedRaw} as ${local}`
82
+ if (spec.importKind === 'type') {
83
+ kept.push(`type ${rawSpec}`)
84
+ continue
85
+ }
86
+ const target = graph.exportTarget(barrel, imported)
87
+ if (target.file === barrel) {
88
+ kept.push(rawSpec)
89
+ continue
90
+ }
91
+ const names = byFile.get(target.file) ?? []
92
+ names.push(target.exportName === local ? local : `${target.exportName} as ${local}`)
93
+ byFile.set(target.file, names)
94
+ }
95
+ if (byFile.size === 0)
96
+ continue
97
+
98
+ const lines = [...byFile].map(([file, names]) => `import { ${names.join(', ')} } from ${JSON.stringify(file)};`)
99
+ if (kept.length > 0)
100
+ lines.push(`import { ${kept.join(', ')} } from 'prunelle';`)
101
+ const stmtText = code.slice(stmt.start, stmt.end)
102
+ // Same line count, so later positions in the module stay where they were.
103
+ edits.push({ start: stmt.start, end: stmt.end, text: `${lines.join(' ')}${'\n'.repeat(stmtText.split('\n').length - 1)}` })
104
+ }
105
+
106
+ if (edits.length === 0)
107
+ return code
108
+ let out = ''
109
+ let cursor = 0
110
+ for (const edit of edits) {
111
+ out += code.slice(cursor, edit.start) + edit.text
112
+ cursor = edit.end
113
+ }
114
+ return out + code.slice(cursor)
115
+ }
116
+
117
+ export function clientPlugin(env: ClientPluginEnv): BunPlugin {
118
+ const { root, isDev, graph, cache, actionsByFile, transforms, leaks, localExports, clientKeep } = env
119
+ return {
120
+ name: 'prunelle-client',
121
+ setup(b) {
122
+ // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
123
+ b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
124
+ if (!isInNodeModules(args.importer))
125
+ leaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
126
+ return undefined
127
+ })
128
+ b.onResolve({ filter: PRUNELLE_SPECIFIER_FILTER }, (args) => {
129
+ const resolved = resolvePrunelleSpecifier(args.path)
130
+ return resolved !== undefined ? { path: resolved } : undefined
131
+ })
132
+ b.onLoad({ filter: TS_FILTER }, (args) => {
133
+ const actions = actionsByFile.get(args.path)
134
+ if (actions !== undefined) {
135
+ if (graph.analyses.get(args.path)?.isInteractive) {
136
+ leaks.add(`${relPosix(root, args.path)} exports server actions and uses browser interactivity (move actions to a separate non-interactive file)`)
137
+ return undefined
138
+ }
139
+ const lines = [`import { actionStub } from 'prunelle/internal/action';`]
140
+ for (const a of actions)
141
+ lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
142
+ return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
143
+ }
144
+
145
+ if (!args.path.endsWith('.tsx')) {
146
+ const raw = graph.source(args.path)
147
+ const own = transforms.active && !isInNodeModules(args.path) ? transforms.apply(raw, args.path, 'client') : raw
148
+ const direct = directPrunelleImports(own, graph, args.path)
149
+ return direct !== raw ? { contents: direct, loader: 'ts' } : undefined
150
+ }
151
+
152
+ const stamp = graph.stamp(args.path)
153
+ const extraExports = localExports.get(args.path) ?? ''
154
+ const keep = clientKeep.get(args.path)
155
+ const key = `${isDev ? 'd:' : ''}${transforms.key}${extraExports}${keep === undefined ? '' : `|keep=${[...keep].sort().join(',')}`}`
156
+ const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
157
+ if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === key)
158
+ return { contents: cachedDom.code, loader: 'tsx' }
159
+ const analysis = graph.analyses.get(args.path)
160
+ const source = graph.source(args.path)
161
+ const clientSource = keep === undefined || analysis === undefined ? source : pruneForClient(source, analysis.program, keep, { preserveLines: isDev })
162
+ const dom = compileDom(args.path, clientSource, {
163
+ ...(clientSource === source ? { analysis } : {}),
164
+ devSourceRoot: isDev ? root : undefined,
165
+ })
166
+ const compiled = directPrunelleImports(transforms.apply(dom.code, args.path, 'client'), graph, args.path) + extraExports
167
+ if (cache !== undefined && stamp !== undefined)
168
+ cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code: compiled })
169
+ return { contents: compiled, loader: 'tsx' }
170
+ })
171
+ },
172
+ }
173
+ }
@@ -0,0 +1,168 @@
1
+ // The browser's copy of a module it loads only for the islands declared in it: the code those islands reach, without the server code around them.
2
+
3
+ import type { Declaration, ImportDeclaration, ModuleExportName, Node, Program } from 'oxc-parser'
4
+ import type { ModuleAnalysis } from '../compiler/analyze'
5
+ import { parseTsx } from '../compiler/analyze'
6
+ import { clientReach } from '../compiler/interactivity'
7
+ import { SourceEditor } from '../compiler/patch'
8
+ import { referencesAny } from '../compiler/scope'
9
+ import { collectPatternNames } from '../compiler/shared'
10
+
11
+ /** The top-level names the browser needs to run the islands `localNames` of a module: the bindings they reach and the imports those name. */
12
+ export function clientNeeds(analysis: Pick<ModuleAnalysis, 'bindings'>, localNames: readonly string[]): Set<string> {
13
+ const keep = new Set<string>()
14
+ for (const b of clientReach(analysis.bindings, localNames)) {
15
+ keep.add(b.name)
16
+ for (const ref of b.refs.keys())
17
+ keep.add(ref)
18
+ }
19
+ return keep
20
+ }
21
+
22
+ /** The analysis of the client copy `keep` gives, for the walk of what the browser loads: its imports, dynamic imports and program. */
23
+ export function clientView(analysis: ModuleAnalysis, code: string, keep: ReadonlySet<string>): ModuleAnalysis {
24
+ const pruned = pruneForClient(code, analysis.program, keep)
25
+ if (pruned === code)
26
+ return analysis
27
+ const spans = analysis.bindings.filter(b => b.name === '' || keep.has(b.name))
28
+ return {
29
+ ...analysis,
30
+ program: parseTsx(analysis.filename, pruned),
31
+ imports: analysis.imports.flatMap((imp) => {
32
+ if (imp.specifiers.length === 0)
33
+ return [imp]
34
+ const specifiers = imp.specifiers.filter(s => keep.has(s.local))
35
+ return specifiers.length === 0 ? [] : [{ ...imp, specifiers }]
36
+ }),
37
+ reexports: [],
38
+ dynamicImports: analysis.dynamicImports.filter(d => spans.some(b => d.start >= b.start && d.start < b.end)),
39
+ }
40
+ }
41
+
42
+ function padPreservingLines(original: string, replacement: string): string {
43
+ if (replacement === '')
44
+ return original.replace(/[^\r\n]/g, ' ')
45
+ const origNewlines = original.split('\n').length - 1
46
+ const nextNewlines = replacement.split('\n').length - 1
47
+ return origNewlines > nextNewlines ? `${replacement}${'\n'.repeat(origNewlines - nextNewlines)}` : replacement
48
+ }
49
+
50
+ /** `code` with each top-level declaration, import, re-export, and pruned-binding statement outside `keep` removed. Everything else stays. */
51
+ export function pruneForClient(code: string, program: Program, keep: ReadonlySet<string>, options?: { preserveLines?: boolean | undefined }): string {
52
+ const editor = new SourceEditor(code)
53
+ const preserveLines = options?.preserveLines === true
54
+ const prunedNames = new Set<string>()
55
+ const planned: { stmt: Node, text: string | undefined }[] = []
56
+ for (const stmt of program.body) {
57
+ const text = keptText(stmt, code, keep)
58
+ planned.push({ stmt, text })
59
+ collectPrunedNames(stmt, text, keep, prunedNames)
60
+ }
61
+ for (const { stmt, text } of planned) {
62
+ let next = text
63
+ if (next === undefined && prunedNames.size > 0 && (stmt.type === 'ExpressionStatement' || stmt.type === 'IfStatement') && referencesAny(stmt, prunedNames))
64
+ next = ''
65
+ if (next !== undefined)
66
+ editor.replace(stmt.start, stmt.end, preserveLines ? padPreservingLines(code.slice(stmt.start, stmt.end), next) : next)
67
+ }
68
+ return editor.toString()
69
+ }
70
+
71
+ function collectPrunedNames(stmt: Node, text: string | undefined, keep: ReadonlySet<string>, out: Set<string>): void {
72
+ if (stmt.type === 'ImportDeclaration') {
73
+ if (text === undefined || stmt.importKind === 'type')
74
+ return
75
+ for (const s of stmt.specifiers) {
76
+ if (!keep.has(s.local.name) && !(s.type === 'ImportSpecifier' && s.importKind === 'type'))
77
+ out.add(s.local.name)
78
+ }
79
+ return
80
+ }
81
+ if (text !== '')
82
+ return
83
+ if (stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' || stmt.type === 'VariableDeclaration') {
84
+ for (const n of declaredNames(stmt) ?? [])
85
+ out.add(n)
86
+ }
87
+ else if (stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null && stmt.declaration !== undefined) {
88
+ for (const n of declaredNames(stmt.declaration) ?? [])
89
+ out.add(n)
90
+ }
91
+ else if (stmt.type === 'ExportDefaultDeclaration') {
92
+ const decl = stmt.declaration
93
+ if ((decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null)
94
+ out.add(decl.id.name)
95
+ }
96
+ }
97
+
98
+ const nameOf = (name: ModuleExportName): string => name.type === 'Identifier' ? name.name : String(name.value)
99
+
100
+ function declaredNames(decl: Declaration): string[] | undefined {
101
+ if (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration')
102
+ return decl.id === null ? undefined : [decl.id.name]
103
+ if (decl.type !== 'VariableDeclaration')
104
+ return undefined
105
+ const names = new Set<string>()
106
+ for (const d of decl.declarations)
107
+ collectPatternNames(d.id, names)
108
+ return [...names]
109
+ }
110
+
111
+ /** The text replacing a top-level statement: `''` to drop it, `undefined` to leave it as written. */
112
+ function keptText(stmt: Node, code: string, keep: ReadonlySet<string>): string | undefined {
113
+ switch (stmt.type) {
114
+ case 'ImportDeclaration':
115
+ return keptImport(stmt, code, keep)
116
+ case 'FunctionDeclaration':
117
+ case 'ClassDeclaration':
118
+ case 'VariableDeclaration': {
119
+ const names = declaredNames(stmt)
120
+ return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
121
+ }
122
+ case 'ExportNamedDeclaration': {
123
+ if (stmt.exportKind === 'type')
124
+ return undefined
125
+ if (stmt.declaration !== null && stmt.declaration !== undefined) {
126
+ const names = declaredNames(stmt.declaration)
127
+ return names === undefined || names.some(n => keep.has(n)) ? undefined : ''
128
+ }
129
+ if (stmt.source !== null)
130
+ return ''
131
+ const specs = stmt.specifiers.filter(s => keep.has(nameOf(s.local)))
132
+ if (specs.length === stmt.specifiers.length)
133
+ return undefined
134
+ return specs.length === 0 ? '' : `export { ${specs.map(s => code.slice(s.start, s.end)).join(', ')} };`
135
+ }
136
+ case 'ExportDefaultDeclaration': {
137
+ const decl = stmt.declaration
138
+ const name = decl.type === 'Identifier' ? decl.name : (decl.type === 'FunctionDeclaration' || decl.type === 'ClassDeclaration') && decl.id !== null ? decl.id.name : 'default'
139
+ return keep.has(name) ? undefined : ''
140
+ }
141
+ case 'ExportAllDeclaration':
142
+ return stmt.exportKind === 'type' ? undefined : ''
143
+ default:
144
+ return undefined
145
+ }
146
+ }
147
+
148
+ function keptImport(stmt: ImportDeclaration, code: string, keep: ReadonlySet<string>): string | undefined {
149
+ // A type import stays as written; a side-effect import keeps all of its zero specifiers.
150
+ if (stmt.importKind === 'type')
151
+ return undefined
152
+ // A type specifier is erased with the types, so it stays whatever uses it.
153
+ const specs = stmt.specifiers.filter(s => keep.has(s.local.name) || (s.type === 'ImportSpecifier' && s.importKind === 'type'))
154
+ if (specs.length === stmt.specifiers.length)
155
+ return undefined
156
+ if (specs.length === 0)
157
+ return ''
158
+ if ((stmt.attributes?.length ?? 0) > 0)
159
+ return undefined
160
+ const source = code.slice(stmt.source.start, stmt.source.end)
161
+ return specs.map((s) => {
162
+ if (s.type === 'ImportDefaultSpecifier')
163
+ return `import ${s.local.name} from ${source};`
164
+ if (s.type === 'ImportNamespaceSpecifier')
165
+ return `import * as ${s.local.name} from ${source};`
166
+ return `import { ${code.slice(s.start, s.end)} } from ${source};`
167
+ }).join(' ')
168
+ }
@@ -0,0 +1,129 @@
1
+ // Single-executable standalone compiler (`prunelle build --compile [outfile]`)
2
+ // Embeds routes, plugins, prerendered HTML, and native zero-copy assets via `with { type: "file" }`.
3
+
4
+ import type { BunPlugin } from 'bun'
5
+ import type { BuildManifest } from './index'
6
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { formatBunBuildLogs } from './files'
9
+ import { SERVER_ENTRY_FILE } from './server-entry'
10
+
11
+ export interface CompileExecutableOptions {
12
+ root: string
13
+ outDir: string
14
+ clientDir: string
15
+ manifest: BuildManifest
16
+ assetPrefix: string
17
+ site?: string | undefined
18
+ defaultPort?: number | undefined
19
+ outfile: string
20
+ resolvePrunelleSpecifier: (specifier: string) => string | undefined
21
+ bunPlugins?: BunPlugin[] | undefined
22
+ }
23
+
24
+ export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
25
+ const { root, outDir, clientDir, manifest, assetPrefix, site, defaultPort, outfile, resolvePrunelleSpecifier, bunPlugins = [] } = opts
26
+ const entryPath = join(outDir, '__compile_entry.ts')
27
+ const entryJs = join(outDir, 'server', SERVER_ENTRY_FILE)
28
+ const lifecycle = join(import.meta.dir, '../server/lifecycle.ts')
29
+ const imports: string[] = []
30
+
31
+ // Embed client assets, public files and prerendered pages natively via `with { type: "file" }` (0 base64, 0 startup decode!), each with the sidecars the build compressed it into.
32
+ let fileIdx = 0
33
+ const embed = (entries: string[], rel: string, abs: string): void => {
34
+ for (const ext of ['', '.br', '.gz']) {
35
+ if (ext === '' || existsSync(`${abs}${ext}`)) {
36
+ const v = `_f${fileIdx++}`
37
+ imports.push(`import ${v} from ${JSON.stringify(`${abs}${ext}`)} with { type: "file" };`)
38
+ entries.push(`${JSON.stringify(`${rel}${ext}`)}: ${v}`)
39
+ }
40
+ }
41
+ }
42
+ const embeddedAssets: string[] = []
43
+ for (const rel of [...manifest.assets, ...(manifest.carriedAssets ?? [])]) {
44
+ const abs = join(clientDir, rel)
45
+ if (existsSync(abs))
46
+ embed(embeddedAssets, rel, abs)
47
+ }
48
+ const embeddedPublic: string[] = []
49
+ const embeddedPublicEtags: string[] = []
50
+ for (const rel of manifest.publicFiles) {
51
+ const abs = join(outDir, 'public', rel)
52
+ if (!existsSync(abs))
53
+ continue
54
+ embed(embeddedPublic, rel, abs)
55
+ embeddedPublicEtags.push(`${JSON.stringify(rel)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
56
+ }
57
+ const embeddedPrerenderedFiles: string[] = []
58
+ const embeddedPrerenderedEtags: string[] = []
59
+ for (const r of manifest.routes) {
60
+ if (r.prerendered) {
61
+ for (const [, relHtml] of Object.entries(r.prerendered)) {
62
+ const abs = join(outDir, relHtml)
63
+ if (!existsSync(abs))
64
+ continue
65
+ embed(embeddedPrerenderedFiles, relHtml, abs)
66
+ // An embedded file has no mtime to version it by.
67
+ embeddedPrerenderedEtags.push(`${JSON.stringify(relHtml)}: ${JSON.stringify(`W/"${Bun.hash(readFileSync(abs)).toString(36)}"`)}`)
68
+ }
69
+ }
70
+ }
71
+
72
+ const siteProp = site !== undefined ? ` site: ${JSON.stringify(site)},` : ''
73
+ const healthPath = `${assetPrefix.replace(/\/$/, '')}/health`
74
+ const code = [
75
+ ...imports,
76
+ `const hostname = process.env.HOST || undefined;`,
77
+ `const formatHost = (h: string) => h.includes(':') && !h.startsWith('[') ? \`[\${h}]\` : h;`,
78
+ `if (Bun.argv.includes('--health')) { const healthPort = Number(process.env.PORT || ${JSON.stringify(defaultPort ?? 3000)}); const rawHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${formatHost(rawHost)}:\${healthPort}\${${JSON.stringify(healthPath)}}\`).catch(() => null); process.exit(r && r.ok ? 0 : 1); }`,
79
+ `const _envKey = 'NODE_ENV';`,
80
+ `process.env[_envKey] ??= 'production';`,
81
+ `const { createApp, prunelleConfig } = await import(${JSON.stringify(entryJs)});`,
82
+ `const { handleSignals } = await import(${JSON.stringify(lifecycle)});`,
83
+ `const manifest = ${JSON.stringify(manifest)};`,
84
+ `const assets = { ${embeddedAssets.join(', ')} };`,
85
+ `const publicAssets = { ${embeddedPublic.join(', ')} };`,
86
+ `const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
87
+ `const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
88
+ `const prerenderedEtags = { ${embeddedPrerenderedEtags.join(', ')} };`,
89
+ `const port = Number(process.env.PORT || prunelleConfig.port || 3000);`,
90
+ `const app = await createApp({ assetPrefix: ${JSON.stringify(assetPrefix)},${siteProp} manifest, assets, publicAssets, publicEtags, prerenderedFiles, prerenderedEtags });`,
91
+ `const server = app.serve(port, hostname);`,
92
+ `handleSignals(app, server);`,
93
+ `console.log(\`prunelle server listening on http://\${formatHost(hostname ?? 'localhost')}:\${server.port}\`);`,
94
+ ].join('\n')
95
+
96
+ writeFileSync(entryPath, code)
97
+ try {
98
+ const prunelleResolvePlugin: BunPlugin = {
99
+ name: 'prunelle-compile-resolve',
100
+ setup(b) {
101
+ b.onResolve({ filter: /^prunelle(?:\/.*)?$/ }, (args) => {
102
+ const resolved = resolvePrunelleSpecifier(args.path)
103
+ return resolved !== undefined ? { path: resolved } : undefined
104
+ })
105
+ },
106
+ }
107
+ let res: Awaited<ReturnType<typeof Bun.build>>
108
+ try {
109
+ res = await Bun.build({
110
+ entrypoints: [entryPath],
111
+ compile: { outfile },
112
+ minify: true,
113
+ plugins: [prunelleResolvePlugin, ...bunPlugins],
114
+ })
115
+ }
116
+ catch (err) {
117
+ if (err instanceof AggregateError && err.errors.length > 0)
118
+ throw new Error(`prunelle build: --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
119
+ throw err
120
+ }
121
+ if (!res.success) {
122
+ const msgs = formatBunBuildLogs(res.logs, root)
123
+ throw new Error(`prunelle build: --compile failed:\n${msgs}`)
124
+ }
125
+ }
126
+ finally {
127
+ rmSync(entryPath, { force: true })
128
+ }
129
+ }