prunelle 0.0.0-stage → 0.1.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 (173) hide show
  1. package/llms.txt +148 -0
  2. package/package.json +53 -4
  3. package/src/ambient.d.ts +6 -0
  4. package/src/attrs.ts +35 -0
  5. package/src/build/bundle.ts +613 -0
  6. package/src/build/carry.ts +57 -0
  7. package/src/build/client-entries.ts +106 -0
  8. package/src/build/client-plugin.ts +169 -0
  9. package/src/build/client-prune.ts +118 -0
  10. package/src/build/compile.ts +127 -0
  11. package/src/build/files.ts +156 -0
  12. package/src/build/first-load.ts +164 -0
  13. package/src/build/graph.ts +247 -0
  14. package/src/build/index.ts +575 -0
  15. package/src/build/is-inside.ts +12 -0
  16. package/src/build/islands.ts +641 -0
  17. package/src/build/manifest.ts +264 -0
  18. package/src/build/output.ts +84 -0
  19. package/src/build/plugin-host.ts +220 -0
  20. package/src/build/precompress.ts +126 -0
  21. package/src/build/prerender.ts +150 -0
  22. package/src/build/render-rules.ts +205 -0
  23. package/src/build/report.ts +247 -0
  24. package/src/build/resolve.ts +50 -0
  25. package/src/build/routes.ts +177 -0
  26. package/src/build/server-entry.ts +38 -0
  27. package/src/build/static.ts +109 -0
  28. package/src/cli/check.ts +334 -0
  29. package/src/cli/commands.ts +265 -0
  30. package/src/cli/index.ts +70 -0
  31. package/src/cli/inspect.ts +316 -0
  32. package/src/cli/new.ts +41 -0
  33. package/src/cli/upgrade-names.ts +149 -0
  34. package/src/cli/upgrade.ts +258 -0
  35. package/src/compiler/analyze.ts +618 -0
  36. package/src/compiler/ast.ts +82 -0
  37. package/src/compiler/browser-globals.ts +127 -0
  38. package/src/compiler/compliance.ts +598 -0
  39. package/src/compiler/data-keys.ts +295 -0
  40. package/src/compiler/dom-attrs.ts +379 -0
  41. package/src/compiler/dom.ts +566 -0
  42. package/src/compiler/emit.ts +131 -0
  43. package/src/compiler/expr-context.ts +408 -0
  44. package/src/compiler/index.ts +8 -0
  45. package/src/compiler/interactivity.ts +366 -0
  46. package/src/compiler/mistakes.ts +499 -0
  47. package/src/compiler/node-env.ts +50 -0
  48. package/src/compiler/patch.ts +97 -0
  49. package/src/compiler/props.ts +460 -0
  50. package/src/compiler/scope.ts +568 -0
  51. package/src/compiler/server-only.ts +326 -0
  52. package/src/compiler/shared.ts +369 -0
  53. package/src/compiler/signal-reads.ts +242 -0
  54. package/src/compiler/slots.ts +227 -0
  55. package/src/compiler/ssr-helpers.ts +555 -0
  56. package/src/compiler/ssr-island.ts +90 -0
  57. package/src/compiler/ssr-prunelle-tags.ts +56 -0
  58. package/src/compiler/ssr.ts +394 -0
  59. package/src/context.ts +165 -0
  60. package/src/dev/child.ts +30 -0
  61. package/src/dev/index.ts +208 -0
  62. package/src/dev/modules.ts +68 -0
  63. package/src/dev/protocol.ts +21 -0
  64. package/src/dev/queue.ts +79 -0
  65. package/src/dev/reload.ts +157 -0
  66. package/src/dev/supervisor.ts +187 -0
  67. package/src/dev/watchers.ts +215 -0
  68. package/src/dom/action.ts +161 -0
  69. package/src/dom/attrs.ts +72 -0
  70. package/src/dom/claim.ts +120 -0
  71. package/src/dom/extras.ts +562 -0
  72. package/src/dom/index.ts +289 -0
  73. package/src/dom/island.ts +284 -0
  74. package/src/dom/loop.ts +450 -0
  75. package/src/dom/revive.ts +36 -0
  76. package/src/index.ts +22 -0
  77. package/src/jsx-runtime.ts +566 -0
  78. package/src/plugins/config.ts +86 -0
  79. package/src/plugins/context.ts +66 -0
  80. package/src/plugins/index.ts +14 -0
  81. package/src/plugins/load.ts +70 -0
  82. package/src/plugins/order.ts +111 -0
  83. package/src/plugins/public.ts +12 -0
  84. package/src/plugins/requires.ts +47 -0
  85. package/src/plugins/services.ts +35 -0
  86. package/src/plugins/types.ts +234 -0
  87. package/src/reactivity/graph.ts +249 -0
  88. package/src/reactivity/index.ts +533 -0
  89. package/src/reactivity/selector.ts +51 -0
  90. package/src/reactivity/store.ts +208 -0
  91. package/src/server/action-registry.ts +78 -0
  92. package/src/server/action.ts +475 -0
  93. package/src/server/app-entry.ts +23 -0
  94. package/src/server/assets.ts +136 -0
  95. package/src/server/compress.ts +560 -0
  96. package/src/server/consent.ts +253 -0
  97. package/src/server/cookies.ts +139 -0
  98. package/src/server/document.ts +271 -0
  99. package/src/server/env.ts +33 -0
  100. package/src/server/errors.ts +153 -0
  101. package/src/server/http.ts +441 -0
  102. package/src/server/index.ts +616 -0
  103. package/src/server/lifecycle.ts +75 -0
  104. package/src/server/loader.ts +118 -0
  105. package/src/server/page.ts +107 -0
  106. package/src/server/plugin-host.ts +251 -0
  107. package/src/server/prerendered.ts +71 -0
  108. package/src/server/public.ts +19 -0
  109. package/src/server/rate-limit.ts +133 -0
  110. package/src/server/region.ts +96 -0
  111. package/src/server/request-body.ts +27 -0
  112. package/src/server/request-path.ts +73 -0
  113. package/src/server/request-scope.ts +22 -0
  114. package/src/server/route-table.ts +79 -0
  115. package/src/server/router.ts +184 -0
  116. package/src/server/routing.ts +339 -0
  117. package/src/server/security.ts +323 -0
  118. package/src/server/serve-handlers.ts +69 -0
  119. package/src/server/served-file.ts +128 -0
  120. package/src/server/standard-schema.ts +87 -0
  121. package/src/server/start.ts +99 -0
  122. package/src/server/static-dir.ts +167 -0
  123. package/src/server/stream.ts +192 -0
  124. package/src/ssr/context.ts +301 -0
  125. package/src/ssr/index.ts +477 -0
  126. package/src/ssr/navigation.ts +96 -0
  127. package/src/ssr/region.ts +171 -0
  128. package/src/style.ts +33 -0
  129. package/src/test/browser.ts +186 -0
  130. package/src/test/index.ts +177 -0
  131. package/src/unrenderable.ts +35 -0
  132. package/templates/_shared/AGENTS.md +10 -0
  133. package/templates/_shared/CLAUDE.md +1 -0
  134. package/templates/_shared/gitignore +3 -0
  135. package/templates/_shared/public/robots.txt +2 -0
  136. package/templates/_shared/src/routes/legal.tsx +8 -0
  137. package/templates/_shared/tsconfig.json +20 -0
  138. package/templates/app/.env.example +4 -0
  139. package/templates/app/package.json +21 -0
  140. package/templates/app/prunelle.config.ts +11 -0
  141. package/templates/app/src/auth.ts +14 -0
  142. package/templates/app/src/routes/_layout.tsx +32 -0
  143. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  144. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  145. package/templates/app/src/routes/index.tsx +15 -0
  146. package/templates/app/src/routes/login.tsx +34 -0
  147. package/templates/app/src/styles/app.css +7 -0
  148. package/templates/app/tests/app.test.ts +32 -0
  149. package/templates/blog/content/posts/welcome.md +9 -0
  150. package/templates/blog/package.json +22 -0
  151. package/templates/blog/prunelle.config.ts +23 -0
  152. package/templates/blog/src/posts.ts +26 -0
  153. package/templates/blog/src/routes/_layout.tsx +20 -0
  154. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  155. package/templates/blog/src/routes/index.tsx +29 -0
  156. package/templates/blog/src/styles/app.css +10 -0
  157. package/templates/fullstack/package.json +19 -0
  158. package/templates/fullstack/prunelle.config.ts +6 -0
  159. package/templates/fullstack/src/actions/greet.ts +19 -0
  160. package/templates/fullstack/src/components/Counter.tsx +10 -0
  161. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  162. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  163. package/templates/fullstack/src/routes/api/health.ts +5 -0
  164. package/templates/fullstack/src/routes/index.tsx +13 -0
  165. package/templates/fullstack/src/styles/app.css +29 -0
  166. package/templates/fullstack/tests/app.test.ts +37 -0
  167. package/templates/minimal/package.json +19 -0
  168. package/templates/minimal/prunelle.config.ts +6 -0
  169. package/templates/minimal/src/components/Counter.tsx +10 -0
  170. package/templates/minimal/src/routes/_layout.tsx +14 -0
  171. package/templates/minimal/src/routes/index.tsx +11 -0
  172. package/templates/minimal/src/styles/app.css +22 -0
  173. package/README.md +0 -3
@@ -0,0 +1,264 @@
1
+ // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
+
3
+ import type { ModuleGraph } from './graph'
4
+ import type { IslandPlan } from './islands'
5
+ import { join } from 'node:path'
6
+ import { isInside } from './is-inside'
7
+ import { islandKey } from './islands'
8
+ import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
9
+
10
+ const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
+
12
+ export interface ActionManifestEntry {
13
+ url: string
14
+ file: string
15
+ exportName: string
16
+ /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
17
+ middlewares: string[]
18
+ }
19
+
20
+ export interface RouteManifestEntry {
21
+ path: string
22
+ file: string
23
+ layouts: string[]
24
+ middlewares: string[]
25
+ hasLoad?: boolean | undefined
26
+ isIsland?: boolean | undefined
27
+ islandChunk?: string | undefined
28
+ islandHydrate?: string | undefined
29
+ /** Top-level keys of `load()` data statically read by a page island (`undefined` when `data` escapes). */
30
+ islandDataKeys?: string[] | undefined
31
+ islandChunks: string[]
32
+ eagerIslandChunks?: string[] | undefined
33
+ /** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
34
+ styles?: string[] | undefined
35
+ /** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
36
+ headTags?: string[] | undefined
37
+ usesRenderContext?: boolean | undefined
38
+ /** The route, a layout or a component it renders imports `<Region>`. */
39
+ usesRegion?: boolean | undefined
40
+ prerender?: boolean | undefined
41
+ prerendered?: Record<string, string> | undefined
42
+ /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
43
+ prerenderedStyleHashes?: Record<string, string[]> | undefined
44
+ }
45
+
46
+ export interface BuildManifest {
47
+ runtimeScript: string | undefined
48
+ /** The plugins' `regionClientEntry`, loaded by the routes with `usesRegion`. */
49
+ regionScript?: string | undefined
50
+ /** The prop revivers, preloaded by a page whose island props hold a Date, Map, Set or another tagged value. */
51
+ reviveScript?: string | undefined
52
+ /** Entry URL (runtime, island, region bundle) to the chunks it imports statically, transitively: a page preloads them with the entry. */
53
+ chunkImports?: Record<string, string[]> | undefined
54
+ /** A plugin's `clientEntry` is in the runtime, so every page loads it, islands or not. */
55
+ runtimeOnEveryPage?: boolean | undefined
56
+ styles: string[]
57
+ /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
58
+ globalStyles?: string[] | undefined
59
+ headTags?: string[] | undefined
60
+ routes: RouteManifestEntry[]
61
+
62
+ /** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
63
+ rootLayoutFile?: string | undefined
64
+ errorFile?: string | undefined
65
+ notFoundFile?: string | undefined
66
+ actions: ActionManifestEntry[]
67
+ islands: Record<string, string>
68
+ assets: string[]
69
+ /** The previous build's client files this one dropped, kept one more deploy for pages loaded before it (#3663); never linked from a page. */
70
+ carriedAssets?: string[] | undefined
71
+ publicFiles: string[]
72
+ /** Serializable build-time metadata persisted by plugins via `ctx.setData()`, read via `api.getBuildData()`. */
73
+ pluginData?: Record<string, Record<string, unknown>> | undefined
74
+ }
75
+
76
+ interface FileReach {
77
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
78
+ chunks: Set<string>
79
+ eager: Set<string>
80
+ styles: Set<string>
81
+ usesRenderContext: boolean
82
+ usesRegion: boolean
83
+ }
84
+
85
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
86
+ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
87
+ const { analyses } = graph
88
+
89
+ function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
90
+ if (seen.has(file))
91
+ return
92
+ seen.add(file)
93
+ const analysis = analyses.get(file)
94
+ if (analysis === undefined)
95
+ return
96
+ if (analysis.isInteractive) {
97
+ const chunk = islandChunks.get(`${file}#default`)
98
+ if (chunk !== undefined) {
99
+ reach.chunks.add(chunk)
100
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
101
+ reach.eager.add(chunk)
102
+ }
103
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
104
+ if (analysis.staticJsxTags.size === 0)
105
+ return
106
+ }
107
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
108
+ const chunk = islandChunks.get(islandKey(target))
109
+ if (chunk === undefined)
110
+ continue
111
+ reach.chunks.add(chunk)
112
+ const isDeferred = analysis.deferredIslandTags.has(localName)
113
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
114
+ if (!isDeferred)
115
+ reach.eager.add(chunk)
116
+ }
117
+ for (const dep of graph.localDeps(file))
118
+ walkIslands(dep, seen, reach)
119
+ }
120
+
121
+ function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
122
+ if (seen.has(file))
123
+ return
124
+ seen.add(file)
125
+ const analysis = analyses.get(file)
126
+ if (analysis === undefined)
127
+ return
128
+ if (analysis.isInteractive) {
129
+ const islCss = islandCssUrl.get(`${file}#default`)
130
+ if (islCss !== undefined)
131
+ out.add(islCss)
132
+ }
133
+ for (const target of islands.pageBindings.get(file)?.values() ?? []) {
134
+ const islCss = islandCssUrl.get(islandKey(target))
135
+ if (islCss !== undefined)
136
+ out.add(islCss)
137
+ walkStyles(target.file, seen, out)
138
+ }
139
+ for (const imp of analysis.imports) {
140
+ const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
141
+ if (cssUrl !== undefined)
142
+ out.add(cssUrl)
143
+ }
144
+ for (const dep of graph.localDeps(file))
145
+ walkStyles(dep, seen, out)
146
+ }
147
+
148
+ function walkRenderContext(file: string, seen: Set<string>): boolean {
149
+ if (seen.has(file))
150
+ return false
151
+ seen.add(file)
152
+ const analysis = analyses.get(file)
153
+ if (analysis === undefined)
154
+ return false
155
+ return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
156
+ }
157
+
158
+ // A namespace import of prunelle may render `NS.Region`, so it counts.
159
+ function walkRegion(file: string, seen: Set<string>): boolean {
160
+ if (seen.has(file))
161
+ return false
162
+ seen.add(file)
163
+ const analysis = analyses.get(file)
164
+ if (analysis === undefined)
165
+ return false
166
+ return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
167
+ || graph.localDeps(file).some(dep => walkRegion(dep, seen))
168
+ }
169
+
170
+ // Layouts are shared by many routes, so each file is walked once.
171
+ const memo = new Map<string, FileReach>()
172
+ return (file: string): FileReach => {
173
+ let reach = memo.get(file)
174
+ if (reach === undefined) {
175
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
176
+ walkIslands(file, new Set(), reach)
177
+ walkStyles(file, new Set(), reach.styles)
178
+ reach.usesRenderContext = walkRenderContext(file, new Set())
179
+ reach.usesRegion = walkRegion(file, new Set())
180
+ memo.set(file, reach)
181
+ }
182
+ return reach
183
+ }
184
+ }
185
+
186
+ export interface RouteEntries {
187
+ routes: RouteManifestEntry[]
188
+ /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
+ globalStyles: string[]
190
+ /** The plugins' CSS alone. */
191
+ globalPluginStyles: string[]
192
+ }
193
+
194
+ export function buildRouteEntries(options: {
195
+ graph: ModuleGraph
196
+ islands: IslandPlan
197
+ islandChunks: Map<string, string>
198
+ srcCssToUrl: Map<string, string>
199
+ islandCssUrl: Map<string, string>
200
+ routesDir: string
201
+ pageFiles: string[]
202
+ pluginCssFiles: string[]
203
+ isStatic: boolean
204
+ /** Maps a source file to its compiled module, relative to the out dir. */
205
+ toOutRel: (srcFile: string) => string
206
+ }): RouteEntries {
207
+ const { graph, islands, islandChunks, routesDir, toOutRel } = options
208
+ const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
209
+
210
+ const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
211
+ const rootLayout = join(routesDir, '_layout.tsx')
212
+ const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
213
+
214
+ const routes = options.pageFiles.map((file): RouteManifestEntry => {
215
+ const analysis = graph.analyses.get(file)
216
+ const page = analysis?.exports.get('default')
217
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
218
+ const chunks = new Set<string>()
219
+ const eagerChunks = new Set<string>()
220
+ const styles = new Set<string>(globalPluginStyles)
221
+ let usesRenderContext = false
222
+ let usesRegion = false
223
+ for (const src of [...layoutSrcs, file]) {
224
+ const reach = reachOf(src)
225
+ for (const chunk of reach.chunks)
226
+ chunks.add(chunk)
227
+ for (const chunk of reach.eager)
228
+ eagerChunks.add(chunk)
229
+ for (const style of reach.styles)
230
+ styles.add(style)
231
+ usesRenderContext ||= reach.usesRenderContext
232
+ usesRegion ||= reach.usesRegion
233
+ }
234
+ return {
235
+ path: fileToRoutePath(routesDir, file),
236
+ file: toOutRel(file),
237
+ layouts: layoutSrcs.map(toOutRel),
238
+ middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
239
+ hasLoad: analysis?.hasLoadExport,
240
+ isIsland: page?.interactive,
241
+ islandChunk: islandChunks.get(`${file}#default`),
242
+ islandHydrate: analysis?.defaultHydrate,
243
+ islandDataKeys: page?.interactive === true && analysis?.hasLoadExport === true ? analysis.defaultDataKeys : undefined,
244
+ islandChunks: [...chunks],
245
+ eagerIslandChunks: [...eagerChunks],
246
+ styles: [...styles],
247
+ usesRenderContext,
248
+ usesRegion,
249
+ prerender: analysis?.hasPrerender || options.isStatic,
250
+ }
251
+ })
252
+ return { routes, globalStyles, globalPluginStyles }
253
+ }
254
+
255
+ export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
256
+ const entries: ActionManifestEntry[] = []
257
+ for (const [srcFile, list] of actionsByFile) {
258
+ const inRoutes = isInside(routesDir, srcFile, { orSame: true })
259
+ const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, MIDDLEWARE_NAMES).map(toOutRel) : []
260
+ for (const a of list)
261
+ entries.push({ url: a.url, file: toOutRel(srcFile), exportName: a.exportName, middlewares })
262
+ }
263
+ return entries
264
+ }
@@ -0,0 +1,84 @@
1
+ // The output folder's life: a build writes into a stage beside it, and swaps the stage in only once every step passed.
2
+
3
+ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { basename, dirname, join } from 'node:path'
5
+ import { relPosix } from './files'
6
+
7
+ /** The file prunelle writes into each folder it builds, so a later build knows the folder is its own to replace. */
8
+ export const OUTPUT_MARKER = '.prunelle-output'
9
+
10
+ const LEADING_SLASH_RE = /^\/+/
11
+
12
+ /** Throws unless `outDir` is missing, empty, or a folder prunelle built: replacing it must never delete someone's files. */
13
+ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: string): void {
14
+ if (!existsSync(outDir))
15
+ return
16
+ const names = new Set(readdirSync(outDir))
17
+ if (names.size === 0 || names.has(OUTPUT_MARKER))
18
+ return
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder.
20
+ const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
22
+ return
23
+ throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
+ }
25
+
26
+ /** The stage folder a build writes into, beside `finalOutDir` so a rename swaps it in. */
27
+ export function stageDirFor(finalOutDir: string, suffix: string): string {
28
+ return join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${suffix}`)
29
+ }
30
+
31
+ /** A suffix naming the running process first, so a later build can tell a dead build's leftovers from a live one's. */
32
+ export function processSuffix(): string {
33
+ return `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
34
+ }
35
+
36
+ function isAlive(pid: number): boolean {
37
+ try {
38
+ process.kill(pid, 0)
39
+ return true
40
+ }
41
+ catch (err) {
42
+ return err instanceof Error && 'code' in err && err.code === 'EPERM'
43
+ }
44
+ }
45
+
46
+ /** Removes the folders under `parent` whose name is `prefix` then a process suffix, when that process has died. */
47
+ export function removeDeadProcessDirs(parent: string, prefix: string): void {
48
+ if (!existsSync(parent))
49
+ return
50
+ for (const name of readdirSync(parent)) {
51
+ if (!name.startsWith(prefix))
52
+ continue
53
+ const pid = Number.parseInt(name.slice(prefix.length), 10)
54
+ if (Number.isInteger(pid) && pid !== process.pid && !isAlive(pid))
55
+ rmSync(join(parent, name), { recursive: true, force: true })
56
+ }
57
+ }
58
+
59
+ /** Removes the stage and backup folders a killed build left beside `finalOutDir`. */
60
+ export function removeStaleStages(finalOutDir: string): void {
61
+ const parent = dirname(finalOutDir)
62
+ removeDeadProcessDirs(parent, `.${basename(finalOutDir)}.stage-`)
63
+ removeDeadProcessDirs(parent, `.${basename(finalOutDir)}.prev-`)
64
+ }
65
+
66
+ /** Marks `stageDir` as prunelle's output and renames it to `finalOutDir`, putting the previous folder back if the rename fails. */
67
+ export function swapStage(stageDir: string, finalOutDir: string, suffix: string): void {
68
+ writeFileSync(join(stageDir, OUTPUT_MARKER), 'Built by prunelle. The next prunelle build replaces this folder.\n')
69
+ if (!existsSync(finalOutDir)) {
70
+ mkdirSync(dirname(finalOutDir), { recursive: true })
71
+ renameSync(stageDir, finalOutDir)
72
+ return
73
+ }
74
+ const backupDir = join(dirname(finalOutDir), `.${basename(finalOutDir)}.prev-${suffix}`)
75
+ renameSync(finalOutDir, backupDir)
76
+ try {
77
+ renameSync(stageDir, finalOutDir)
78
+ }
79
+ catch (err) {
80
+ renameSync(backupDir, finalOutDir)
81
+ throw err
82
+ }
83
+ rmSync(backupDir, { recursive: true, force: true })
84
+ }
@@ -0,0 +1,220 @@
1
+ // What plugins see of a build: the `build(ctx)` and `afterPrerender(ctx)` hooks, and the shared lists (assets, styles, head tags, public files) those hooks add to.
2
+
3
+ import type { AppRuntimeContext } from '../plugins/context'
4
+ import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
+ import type { RouteManifestEntry } from './manifest'
6
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import { precompressFiles } from './precompress'
9
+
10
+ const LEADING_SLASHES_RE = /^\/+/
11
+ const BACKSLASH_RE = /\\/g
12
+
13
+ function cleanRel(relPath: string): string {
14
+ return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
15
+ }
16
+
17
+ export interface PublicFiles {
18
+ /** Public files known so far, as relative paths in registration order. */
19
+ files: string[]
20
+ /** Records a public file and returns its normalized relative path. */
21
+ register: (relPath: string) => string
22
+ }
23
+
24
+ /** A plugin hook's throw, renamed `prunelle build: plugin "<name>" <hook> failed: <message>` with the original as `cause`. */
25
+ export function pluginHookError(plugin: Pick<PrunellePlugin, 'name'>, hook: string, error: unknown): Error {
26
+ const message = error instanceof Error ? error.message : String(error)
27
+ return new Error(`prunelle build: plugin "${plugin.name}" ${hook} failed: ${message}`, { cause: error })
28
+ }
29
+
30
+ /** Runs one plugin hook, so a throw names the plugin and the hook. */
31
+ export async function runPluginHook<T>(plugin: Pick<PrunellePlugin, 'name'>, hook: string, run: () => T | Promise<T>): Promise<T> {
32
+ try {
33
+ return await run()
34
+ }
35
+ catch (error) {
36
+ throw pluginHookError(plugin, hook, error)
37
+ }
38
+ }
39
+
40
+ export function createPublicFiles(): PublicFiles {
41
+ const files: string[] = []
42
+ const seen = new Set<string>()
43
+ return {
44
+ files,
45
+ register(relPath) {
46
+ const clean = cleanRel(relPath)
47
+ if (clean !== '' && !seen.has(clean)) {
48
+ seen.add(clean)
49
+ files.push(clean)
50
+ }
51
+ return clean
52
+ },
53
+ }
54
+ }
55
+
56
+ export interface PluginHostOptions {
57
+ plugins: PrunellePlugin[]
58
+ appCtx: AppRuntimeContext
59
+ root: string
60
+ outDir: string
61
+ clientDir: string
62
+ outPublicDir: string
63
+ assetPrefix: string
64
+ site?: string | undefined
65
+ minify: boolean
66
+ isStatic: boolean
67
+ isDev: boolean
68
+ routes: RouteManifestEntry[]
69
+ publicFiles: PublicFiles
70
+ /** Client files already emitted, relative to the client dir. */
71
+ assets: string[]
72
+ styleUrls: string[]
73
+ globalStyles: string[]
74
+ }
75
+
76
+ export function createPluginHost(options: PluginHostOptions) {
77
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
78
+ const assetSet = new Set(assets)
79
+ const styleSet = new Set(styleUrls)
80
+ const globalStyleSet = new Set(globalStyles)
81
+ const headTags: string[] = []
82
+ const pluginData: Record<string, Record<string, unknown>> = {}
83
+ const precompressed = new Set<string>()
84
+
85
+ function emitAsset(relPath: string, content: string | Uint8Array): string {
86
+ const clean = cleanRel(relPath)
87
+ const dst = join(clientDir, clean)
88
+ mkdirSync(dirname(dst), { recursive: true })
89
+ writeFileSync(dst, content)
90
+ if (!assetSet.has(clean)) {
91
+ assetSet.add(clean)
92
+ assets.push(clean)
93
+ }
94
+ return `${assetPrefix}/${clean}`
95
+ }
96
+
97
+ function emitPublic(relPath: string, content: string | Uint8Array): string {
98
+ const clean = options.publicFiles.register(relPath)
99
+ const dst = join(outPublicDir, clean)
100
+ mkdirSync(dirname(dst), { recursive: true })
101
+ writeFileSync(dst, content)
102
+ return `/${clean}`
103
+ }
104
+
105
+ function addStyleUrl(href: string): void {
106
+ if (!styleSet.has(href)) {
107
+ styleSet.add(href)
108
+ styleUrls.push(href)
109
+ }
110
+ }
111
+
112
+ // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
+ const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
+ pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
115
+ }
116
+
117
+ const shared = {
118
+ root: options.root,
119
+ outDir,
120
+ assetPrefix,
121
+ ...(options.site !== undefined ? { site: options.site } : {}),
122
+ minify: options.minify,
123
+ isStatic: options.isStatic,
124
+ dev: options.isDev,
125
+ routes,
126
+ emitAsset,
127
+ emitPublic,
128
+ provide: appCtx.provide,
129
+ inject: appCtx.inject,
130
+ }
131
+
132
+ const buildCtx = {
133
+ ...shared,
134
+ addStyle(href: string) {
135
+ addStyleUrl(href)
136
+ if (!globalStyleSet.has(href)) {
137
+ globalStyleSet.add(href)
138
+ globalStyles.push(href)
139
+ }
140
+ for (const r of routes) {
141
+ if (r.styles !== undefined && !r.styles.includes(href))
142
+ r.styles.push(href)
143
+ }
144
+ },
145
+ addRouteStyle(routePath: string, href: string) {
146
+ addStyleUrl(href)
147
+ const route = routes.find(r => r.path === routePath)
148
+ if (route !== undefined) {
149
+ route.styles ??= [...globalStyles]
150
+ if (!route.styles.includes(href))
151
+ route.styles.push(href)
152
+ }
153
+ },
154
+ addHead(html: string) {
155
+ if (html !== '')
156
+ headTags.push(html)
157
+ },
158
+ addRouteHead(routePath: string, html: string) {
159
+ const route = html === '' ? undefined : routes.find(r => r.path === routePath)
160
+ if (route !== undefined)
161
+ (route.headTags ??= []).push(html)
162
+ },
163
+ }
164
+
165
+ return {
166
+ headTags,
167
+ pluginData,
168
+ /** Runs every plugin's `build(ctx)`, so plugins can emit hashed assets, public files, styles, <head> tags, or services. */
169
+ async runBuild(): Promise<void> {
170
+ for (const plugin of plugins) {
171
+ if (plugin.build !== undefined) {
172
+ const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin) }
173
+ await runPluginHook(plugin, 'build', () => plugin.build!(ctx))
174
+ }
175
+ }
176
+ },
177
+
178
+ /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
+ async runAfterPrerender(): Promise<boolean> {
180
+ let ran = false
181
+ for (const plugin of plugins) {
182
+ if (plugin.afterPrerender !== undefined) {
183
+ ran = true
184
+ const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
185
+ await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
+ }
187
+ }
188
+ return ran
189
+ },
190
+
191
+ /**
192
+ * Writes `.br`/`.gz` sidecars for the client assets, public files and prerendered pages not compressed yet, so the server never compresses them itself.
193
+ * Production server builds only: `--static` compresses its own output. A public file the app ships with its own sidecar keeps it.
194
+ */
195
+ async precompressOutput(): Promise<void> {
196
+ if (options.isDev || options.isStatic)
197
+ return
198
+ const pending: string[] = []
199
+ const once = (abs: string): void => {
200
+ if (!precompressed.has(abs)) {
201
+ precompressed.add(abs)
202
+ pending.push(abs)
203
+ }
204
+ }
205
+ for (const rel of assets)
206
+ once(join(clientDir, rel))
207
+ const listed = new Set(options.publicFiles.files)
208
+ for (const rel of listed) {
209
+ const abs = join(outPublicDir, rel)
210
+ if (!listed.has(`${rel}.br`) && !listed.has(`${rel}.gz`) && existsSync(abs))
211
+ once(abs)
212
+ }
213
+ for (const route of routes) {
214
+ for (const rel of Object.values(route.prerendered ?? {}))
215
+ once(join(outDir, rel))
216
+ }
217
+ await precompressFiles(pending, 256, options.root)
218
+ },
219
+ }
220
+ }
@@ -0,0 +1,126 @@
1
+ // The `.br` and `.gz` sidecars of a build, and the brotli they hold, cached by content under `.prunelle-cache/` so a build pays only for the files that changed.
2
+
3
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
+ import { availableParallelism } from 'node:os'
5
+ import { dirname, extname, join } from 'node:path'
6
+ import { promisify } from 'node:util'
7
+ import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
+ import { getAppContext } from '../plugins/context'
9
+
10
+ /** Brotli quality of the sidecars: written once per build, downloaded by every visitor, so the smallest the encoder makes. */
11
+ export const BROTLI_QUALITY = 11
12
+
13
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
14
+ const STALE_MS = 7 * 86_400_000
15
+
16
+ const compress = promisify(brotliCompress)
17
+ const optionsFor = (data: Uint8Array) => ({ params: { [zlibConstants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY, [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.byteLength } })
18
+ let tmpCount = 0
19
+
20
+ /** Where the app under `root` keeps the brotli of each content a build compressed. */
21
+ export function brotliCacheDir(root: string): string {
22
+ return join(root, '.prunelle-cache', `brotli-${BROTLI_QUALITY}`)
23
+ }
24
+
25
+ /** The cache of the app being built, if any. */
26
+ export function appBrotliCacheDir(): string | undefined {
27
+ const root = getAppContext()?.root
28
+ return root === undefined ? undefined : brotliCacheDir(root)
29
+ }
30
+
31
+ function entryFile(data: Uint8Array, cacheDir: string | undefined): string | undefined {
32
+ return cacheDir === undefined ? undefined : join(cacheDir, new Bun.CryptoHasher('sha256').update(data).digest('hex'))
33
+ }
34
+
35
+ function readEntry(file: string): Buffer | undefined {
36
+ try {
37
+ const packed = readFileSync(file)
38
+ const now = new Date()
39
+ utimesSync(file, now, now)
40
+ return packed
41
+ }
42
+ catch (error) {
43
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT')
44
+ return undefined
45
+ throw error
46
+ }
47
+ }
48
+
49
+ // Renamed into place, so a build running beside this one never reads half an entry.
50
+ function writeEntry(file: string, packed: Uint8Array): void {
51
+ mkdirSync(dirname(file), { recursive: true })
52
+ const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
+ writeFileSync(tmp, packed)
54
+ renameSync(tmp, file)
55
+ }
56
+
57
+ /** Brotli of `data` at `BROTLI_QUALITY`, off the main thread; with `cacheDir`, read from there when this content was compressed before. */
58
+ export async function brotli(data: Uint8Array, cacheDir?: string): Promise<Uint8Array> {
59
+ const file = entryFile(data, cacheDir)
60
+ const cached = file === undefined ? undefined : readEntry(file)
61
+ if (cached !== undefined)
62
+ return cached
63
+ const packed = await compress(data, optionsFor(data))
64
+ if (file !== undefined)
65
+ writeEntry(file, packed)
66
+ return packed
67
+ }
68
+
69
+ /** `brotli` on the main thread, for a caller that cannot wait. */
70
+ export function brotliSync(data: Uint8Array, cacheDir?: string): Uint8Array {
71
+ const file = entryFile(data, cacheDir)
72
+ const cached = file === undefined ? undefined : readEntry(file)
73
+ if (cached !== undefined)
74
+ return cached
75
+ const packed = brotliCompressSync(data, optionsFor(data))
76
+ if (file !== undefined)
77
+ writeEntry(file, packed)
78
+ return packed
79
+ }
80
+
81
+ /** Bytes of `content` in brotli at the quality the sidecars are written at, from the app's cache when a build compressed it before. */
82
+ export async function brotliSize(content: string | Uint8Array): Promise<number> {
83
+ return (await brotli(typeof content === 'string' ? Buffer.from(content) : content, appBrotliCacheDir())).byteLength
84
+ }
85
+
86
+ /** Removes the entries no build read for 7 days, and the temporary files of a build that died; returns how many went. */
87
+ export function pruneBrotliCache(cacheDir: string, now = Date.now()): number {
88
+ if (!existsSync(cacheDir))
89
+ return 0
90
+ let removed = 0
91
+ for (const name of readdirSync(cacheDir)) {
92
+ const file = join(cacheDir, name)
93
+ const stat = statSync(file, { throwIfNoEntry: false })
94
+ if (stat !== undefined && now - stat.mtimeMs > STALE_MS) {
95
+ rmSync(file, { force: true })
96
+ removed++
97
+ }
98
+ }
99
+ return removed
100
+ }
101
+
102
+ async function precompressFile(abs: string, minBytes: number, cacheDir: string): Promise<void> {
103
+ if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
104
+ return
105
+ const raw = readFileSync(abs)
106
+ if (raw.byteLength < minBytes)
107
+ return
108
+ const br = await brotli(raw, cacheDir)
109
+ if (br.byteLength < raw.byteLength)
110
+ writeFileSync(`${abs}.br`, br)
111
+ const gz = Bun.gzipSync(raw, { level: 9 })
112
+ if (gz.byteLength < raw.byteLength)
113
+ writeFileSync(`${abs}.gz`, gz)
114
+ }
115
+
116
+ /** Writes `.br` and `.gz` sidecars next to each compressible file of at least `minBytes`, when they come out smaller, one file per core at a time off the main thread, the brotli cached for the app under `root`. */
117
+ export async function precompressFiles(files: Iterable<string>, minBytes: number, root: string): Promise<void> {
118
+ const cacheDir = brotliCacheDir(root)
119
+ pruneBrotliCache(cacheDir)
120
+ const queue = [...files]
121
+ const next = async (): Promise<void> => {
122
+ for (let abs = queue.pop(); abs !== undefined; abs = queue.pop())
123
+ await precompressFile(abs, minBytes, cacheDir)
124
+ }
125
+ await Promise.all(Array.from({ length: Math.min(availableParallelism(), queue.length) }, next))
126
+ }