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,575 @@
1
+ // Prunelle single-pass builder:
2
+ // - Discovers file routes, nested _layout.tsx, _middleware.ts, _error.tsx, _404.tsx, actions, and automatic islands
3
+ // - Builds client (1 pass, minimal runtime + island chunks + action stubs) and server (1 pass)
4
+ // - Supports hybrid prerender, --static export, and --compile single-executable builds
5
+
6
+ import type { ComplianceConfig } from '../compiler/compliance'
7
+ import type { AppRuntimeContext } from '../plugins/context'
8
+ import type { PrunellePlugin } from '../plugins/index'
9
+ import type { BuildCache } from './graph'
10
+ import type { ActionsByFile } from './islands'
11
+ import type { BuildManifest } from './manifest'
12
+ import type { PublicFiles } from './plugin-host'
13
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
+ import { basename, dirname, join, relative, resolve } from 'node:path'
15
+ import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
16
+ import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
17
+ import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
18
+ import { actionHash } from '../server/action'
19
+ import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, standaloneCssFiles } from './bundle'
20
+ import { compileExecutable } from './compile'
21
+ import { assertSafeOutDir, fileSize, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
22
+ import { isInside } from './is-inside'
23
+ import { ModuleGraph } from './graph'
24
+ import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
25
+ import { planIslands } from './islands'
26
+ import { buildActionEntries, buildRouteEntries } from './manifest'
27
+ import { createPluginHost, createPublicFiles } from './plugin-host'
28
+ import { carryPreviousAssets } from './carry'
29
+ import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
30
+ import { prerender } from './prerender'
31
+ import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
32
+ import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
33
+ import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
34
+ import { assertNoRouteConflicts, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
35
+ import { exportStatic } from './static'
36
+
37
+ export type { BuildCache } from './graph'
38
+ export { createBuildCache } from './graph'
39
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
40
+ export { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson } from './report'
41
+ export type { BundleReport, RouteBundleMetrics, RouteIsland } from './report'
42
+ export { resolvePrunelleSpecifier } from './resolve'
43
+
44
+ export interface BuildOptions {
45
+ root: string
46
+ routesDir?: string | undefined
47
+ outDir?: string | undefined
48
+ publicDir?: string | undefined
49
+ minify?: boolean | undefined
50
+ assetPrefix?: string | undefined
51
+ site?: string | undefined
52
+ plugins?: PrunellePlugin[] | undefined
53
+ /** Reusable incremental cache for `prunelle dev` (skips re-parsing/re-compiling unchanged files). */
54
+ cache?: BuildCache | undefined
55
+ /** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
56
+ analyze?: boolean | undefined
57
+ /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
58
+ analyzeJson?: boolean | undefined
59
+ /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
60
+ maxJs?: number | undefined
61
+ /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
62
+ static?: boolean | undefined
63
+ /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
64
+ prerender?: boolean | undefined
65
+ /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
66
+ copyPublic?: boolean | undefined
67
+ /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
68
+ compile?: string | boolean | undefined
69
+ /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via PRUNELLE_DEV=1). */
70
+ dev?: boolean | undefined
71
+ /** Explicit NODE_ENV threaded through AppRuntimeContext and client defines without mutating process.env. */
72
+ nodeEnv?: string | undefined
73
+ }
74
+
75
+ const cachedPluginAssets = new WeakMap<BuildCache, { clientDir: string, files: string[] }>()
76
+
77
+ function restoreCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: string[], anyPassSkipped: boolean): void {
78
+ if (cache === undefined || !anyPassSkipped)
79
+ return
80
+ const prev = cachedPluginAssets.get(cache)
81
+ if (prev === undefined || prev.clientDir === clientDir)
82
+ return
83
+ const existing = new Set(assets)
84
+ for (const rel of prev.files) {
85
+ if (existing.has(rel))
86
+ continue
87
+ const from = join(prev.clientDir, rel)
88
+ if (!existsSync(from))
89
+ continue
90
+ linkOrCopyFile(from, join(clientDir, rel))
91
+ existing.add(rel)
92
+ assets.push(rel)
93
+ }
94
+ }
95
+
96
+ function recordCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: readonly string[], builtClientAssets: ReadonlySet<string>): void {
97
+ if (cache === undefined)
98
+ return
99
+ const files = assets.filter(rel => !builtClientAssets.has(rel))
100
+ if (files.length > 0)
101
+ cachedPluginAssets.set(cache, { clientDir, files })
102
+ else
103
+ cachedPluginAssets.delete(cache)
104
+ }
105
+
106
+ /** The server build a static export renders its pages from, under `.prunelle-cache/`. */
107
+ const STATIC_STAGE_PREFIX = '.static-stage-'
108
+
109
+ /** Everything one build run needs, resolved once from the options and `prunelle.config.ts`. */
110
+ interface BuildRun {
111
+ options: BuildOptions
112
+ root: string
113
+ plugins: PrunellePlugin[]
114
+ routesDir: string
115
+ publicDir: string
116
+ finalOutDir: string
117
+ /** The folder swapped in as `finalOutDir` once every step passed. */
118
+ stageDir: string
119
+ /** Where the build writes: `stageDir`, or for a static export a server build in `.prunelle-cache/` that `stageDir` takes pages from. */
120
+ outDir: string
121
+ stageSuffix: string
122
+ assetPrefix: string
123
+ site: string | undefined
124
+ compliance: ComplianceConfig | undefined
125
+ minify: boolean
126
+ isDev: boolean
127
+ nodeEnv: string | undefined
128
+ appCtx: AppRuntimeContext
129
+ publicFiles: PublicFiles
130
+ }
131
+
132
+ export async function build(options: BuildOptions): Promise<BuildManifest> {
133
+ if (options.static && options.compile) {
134
+ throw new Error('prunelle build: --static and --compile cannot be used together (static export produces HTML/assets without a server binary).')
135
+ }
136
+
137
+ const root = resolve(options.root)
138
+ const isDev = options.dev ?? (process.env.PRUNELLE_DEV === '1')
139
+ const effectiveNodeEnv = options.nodeEnv ?? (isDev ? undefined : (process.env.NODE_ENV ?? 'production'))
140
+ const fileConfig = await loadConfig(root, { dev: isDev, nodeEnv: effectiveNodeEnv })
141
+ const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
142
+ const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
143
+ const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
144
+
145
+ assertSafeOutDir(root, finalOutDir, routesDir, publicDir)
146
+
147
+ const cacheBaseDir = join(root, '.prunelle-cache')
148
+ const cacheExisted = existsSync(cacheBaseDir)
149
+ const stageSuffix = processSuffix()
150
+ const stageDir = stageDirFor(finalOutDir, stageSuffix)
151
+ const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
152
+ const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru').replace(/\/$/, '')
153
+ assertOwnOutDir(root, finalOutDir, assetPrefix)
154
+ removeStaleStages(finalOutDir)
155
+ removeDeadProcessDirs(cacheBaseDir, STATIC_STAGE_PREFIX)
156
+ const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
157
+ const publicFiles = createPublicFiles()
158
+ const appCtx = createAppContext({
159
+ root,
160
+ outDir,
161
+ publicDir: join(outDir, 'public'),
162
+ assetPrefix,
163
+ site,
164
+ dev: isDev,
165
+ nodeEnv: effectiveNodeEnv,
166
+ onRegisterPublicFile: publicFiles.register,
167
+ })
168
+
169
+ try {
170
+ return await runWithAppContext(appCtx, () => runBuild({
171
+ options,
172
+ root,
173
+ plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
174
+ routesDir,
175
+ publicDir,
176
+ finalOutDir,
177
+ stageDir,
178
+ outDir,
179
+ stageSuffix,
180
+ assetPrefix,
181
+ site,
182
+ compliance: fileConfig.compliance,
183
+ minify: options.minify ?? true,
184
+ isDev,
185
+ nodeEnv: effectiveNodeEnv,
186
+ appCtx,
187
+ publicFiles,
188
+ }))
189
+ }
190
+ finally {
191
+ rmSync(stageDir, { recursive: true, force: true })
192
+ if (options.static) {
193
+ rmSync(outDir, { recursive: true, force: true })
194
+ if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
195
+ rmSync(cacheBaseDir, { recursive: true, force: true })
196
+ }
197
+ }
198
+ }
199
+
200
+ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readonly string[]): void {
201
+ for (const [file, analysis] of graph.analyses) {
202
+ const rel = relPosix(run.root, file)
203
+ for (const warning of analysis.warnings) {
204
+ if (!shouldEmitWarning(warning, run.compliance, run.site))
205
+ continue
206
+ const loc = formatLoc(rel, graph.source(file), warning.start)
207
+ console.warn(formatDiagnostic(loc, warning.message.replaceAll(file, rel), 'warning'))
208
+ }
209
+ }
210
+ if (!run.isDev) {
211
+ const projectWarnings = collectProjectComplianceWarnings({
212
+ root: run.root,
213
+ srcDir: join(run.root, 'src'),
214
+ routesDir: run.routesDir,
215
+ routeFiles,
216
+ analyses: graph.analyses,
217
+ compliance: run.compliance,
218
+ site: run.site,
219
+ })
220
+ for (const warning of projectWarnings)
221
+ console.warn(warning)
222
+ }
223
+ }
224
+
225
+
226
+ /** Plans the islands, then runs the rules `prunelle check` also runs on the whole graph: what server code renders wrong, and dynamic prerendered routes with no `paths()`. Throws them all at once, each placed with a code frame. */
227
+ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph, pageFiles: string[], specialFiles: string[], isStatic: boolean): ReturnType<typeof planIslands> {
228
+ const islands = planIslands(graph, root, pageFiles, specialFiles)
229
+ const placed: string[] = []
230
+ const place = (file: string, offset: number, message: string): void => {
231
+ const source = graph.source(file)
232
+ placed.push(`${formatDiagnostic(formatLoc(relPosix(root, file), source, offset), message)}\n${formatCodeFrame(source, offset)}`)
233
+ }
234
+ const configFile = join(root, 'prunelle.config.ts')
235
+ for (const [file, analysis] of graph.analyses) {
236
+ const rel = relPosix(root, file)
237
+ for (const offset of file === configFile ? [] : serverNodeEnvReads(analysis, islands, file))
238
+ console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), offset), nodeEnvWarning(rel), 'warning'))
239
+ if (!file.endsWith('.tsx') || isInNodeModules(file))
240
+ continue
241
+ for (const problem of renderProblems(analysis, islands, file, rel, 'prunelle build'))
242
+ place(file, problem.offset, problem.message)
243
+ }
244
+ for (const file of pageFiles) {
245
+ const missing = missingPathsProblem(graph.analyses.get(file)!, normalizeRoutePattern(fileToRoutePath(routesDir, file)), isStatic)
246
+ if (missing !== undefined)
247
+ place(file, missing.offset, `prunelle build: ${missing.message}`)
248
+ }
249
+ if (placed.length > 0)
250
+ throw new Error(placed.join('\n\n'))
251
+ return islands
252
+ }
253
+
254
+ /** Lists the files `prunelle dev` watches for the next rebuild, and drops the cached compiles of deleted files so a long session stays flat in memory. */
255
+ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles: readonly string[]): void {
256
+ const watched = cache.watchedFiles
257
+ watched.clear()
258
+ const recordWatched = (file: string) => {
259
+ if (!existsSync(file))
260
+ return
261
+ let real = file
262
+ try {
263
+ real = realpathSync(file)
264
+ }
265
+ catch {}
266
+ watched.add(real)
267
+ }
268
+ for (const f of graph.analyses.keys())
269
+ recordWatched(f)
270
+ for (const f of cache.lastClient?.inputStamps.keys() ?? [])
271
+ recordWatched(f)
272
+ for (const f of cache.lastServer?.inputStamps.keys() ?? [])
273
+ recordWatched(f)
274
+ for (const f of extraFiles)
275
+ recordWatched(f)
276
+ for (const compiled of [cache.analyses, cache.domCompiled, cache.ssrCompiled]) {
277
+ for (const f of [...compiled.keys()]) {
278
+ if (!existsSync(f))
279
+ compiled.delete(f)
280
+ }
281
+ }
282
+ }
283
+
284
+ async function runBuild(run: BuildRun): Promise<BuildManifest> {
285
+ const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
286
+ const clientDir = join(outDir, 'client')
287
+ const serverDir = join(outDir, 'server')
288
+ const isStatic = options.static === true
289
+
290
+ const allRouteFiles = walkRoutes(routesDir).sort()
291
+ const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
292
+ const candidateFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
293
+ const rootLayoutSrc = join(routesDir, '_layout.tsx')
294
+ const errorSrc = join(routesDir, '_error.tsx')
295
+ const notFoundSrc = join(routesDir, '_404.tsx')
296
+ const hasRootLayout = existsSync(rootLayoutSrc)
297
+ const hasErrorFile = existsSync(errorSrc)
298
+ const hasNotFoundFile = existsSync(notFoundSrc)
299
+
300
+ // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
301
+ // prunelle.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
302
+ const configSrc = join(root, 'prunelle.config.ts')
303
+ const hasConfigFile = existsSync(configSrc)
304
+ const graph = new ModuleGraph(root, options.cache)
305
+ for (const f of [...specialFiles, ...candidateFiles, ...(hasConfigFile ? [configSrc] : [])])
306
+ graph.load(f)
307
+ emitBuildWarnings(run, graph, allRouteFiles)
308
+
309
+ const routesRel = relPosix(root, routesDir)
310
+ for (const f of [...specialFiles, ...candidateFiles]) {
311
+ const analysis = graph.analyses.get(f)!
312
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
313
+ if (problem !== undefined)
314
+ throw new Error(`prunelle build: ${problem}`)
315
+ }
316
+ // A file exporting only actions stays in routes/ for its folder's middleware.
317
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
318
+ assertNoRouteConflicts(root, routesDir, pageFiles)
319
+
320
+ // Server actions, keyed by source file
321
+ const actionsByFile: ActionsByFile = new Map()
322
+ for (const [file, analysis] of graph.analyses) {
323
+ if (analysis.exportedActions.length > 0) {
324
+ const rel = relPosix(root, file)
325
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
326
+ exportName,
327
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
328
+ })))
329
+ }
330
+ }
331
+
332
+ const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
333
+
334
+ mkdirSync(clientDir, { recursive: true })
335
+ mkdirSync(serverDir, { recursive: true })
336
+ const pluginCssFiles = plugins
337
+ .flatMap(p => p.css ?? [])
338
+ .map(c => resolve(root, c))
339
+ .filter(c => existsSync(c))
340
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined, graph, cache: options.cache, plugins, actionsByFile, islands }
341
+
342
+ const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
343
+ const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
344
+ // `_entry.js` imports all of these; each stays an entrypoint so its code lands in a content-named chunk that `prunelle dev` keeps loaded while it is unchanged.
345
+ const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
346
+ const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
347
+ const toOutRel = (srcFile: string): string =>
348
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
349
+ const serverEntry = {
350
+ file: join(serverRoot, SERVER_ENTRY_FILE),
351
+ source: serverEntrySource({
352
+ modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
353
+ config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
354
+ assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
355
+ }),
356
+ }
357
+ if (existsSync(serverEntry.file))
358
+ throw new Error(`prunelle build: ${relPosix(root, serverEntry.file)} is the path of prunelle's server entry; rename that file.`)
359
+
360
+ // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
361
+ const clientSkipsBefore = options.cache?.stats.clientSkips ?? 0
362
+ const serverSkipsBefore = options.cache?.stats.serverSkips ?? 0
363
+ const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
364
+ let client: Awaited<ReturnType<typeof clientPass>>
365
+ if (islands.targets.size === 0) {
366
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map(), serverEntry)])
367
+ client = built
368
+ }
369
+ else {
370
+ client = await clientPass()
371
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks, serverEntry)
372
+ }
373
+ const anyPassSkipped = options.cache !== undefined
374
+ && (options.cache.stats.clientSkips > clientSkipsBefore || options.cache.stats.serverSkips > serverSkipsBefore)
375
+
376
+ if (options.cache !== undefined)
377
+ refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
378
+
379
+ const assets: string[] = []
380
+ for (const rel of client.assetFiles) {
381
+ const abs = join(clientDir, rel)
382
+ const size = fileSize(abs)
383
+ if (size === 0)
384
+ rmSync(abs, { force: true })
385
+ else if (size !== undefined)
386
+ assets.push(rel)
387
+ }
388
+ const builtClientAssets = new Set(assets)
389
+
390
+ const { routes, globalStyles } = buildRouteEntries({
391
+ graph,
392
+ islands,
393
+ islandChunks: client.islandChunks,
394
+ srcCssToUrl: client.srcCssToUrl,
395
+ islandCssUrl: client.islandCssUrl,
396
+ routesDir,
397
+ pageFiles,
398
+ pluginCssFiles,
399
+ isStatic,
400
+ toOutRel,
401
+ })
402
+
403
+ // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
404
+ const outPublicDir = join(outDir, 'public')
405
+ for (const abs of walkAllFiles(run.publicDir).sort()) {
406
+ const rel = publicFiles.register(relative(run.publicDir, abs))
407
+ if (options.copyPublic !== false) {
408
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
409
+ copyFileSync(abs, join(outPublicDir, rel))
410
+ }
411
+ }
412
+
413
+ const host = createPluginHost({
414
+ plugins,
415
+ appCtx: run.appCtx,
416
+ root,
417
+ outDir,
418
+ clientDir,
419
+ outPublicDir,
420
+ assetPrefix,
421
+ site: run.site,
422
+ minify: run.minify,
423
+ isStatic,
424
+ isDev,
425
+ routes,
426
+ publicFiles,
427
+ assets,
428
+ styleUrls: client.styleUrls,
429
+ globalStyles,
430
+ })
431
+ await host.runBuild()
432
+ restoreCachedPluginAssets(options.cache, clientDir, assets, anyPassSkipped)
433
+ await host.precompressOutput()
434
+
435
+ const manifest: BuildManifest = {
436
+ runtimeScript: client.runtimeScript, regionScript: client.regionScript, reviveScript: client.reviveScript, chunkImports: client.chunkImports, runtimeOnEveryPage: plugins.some(p => Boolean(p.clientEntry)),
437
+ styles: client.styleUrls,
438
+ globalStyles,
439
+ ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
440
+ routes,
441
+
442
+ ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
443
+ errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
444
+ notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
445
+ actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
446
+ islands: Object.fromEntries(client.islandChunks),
447
+ assets,
448
+ publicFiles: publicFiles.files,
449
+ ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
450
+ }
451
+ const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
452
+ writeManifest()
453
+ if (options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined) {
454
+ const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, client.metafile, islandOrigins(islands, client.islandChunks, graph, root), [outPublicDir, run.publicDir])
455
+ if (options.analyzeJson === true)
456
+ console.log(formatBundleReportJson(report))
457
+ else if (options.analyze === true)
458
+ console.log(formatBundleReport(report))
459
+ if (options.maxJs !== undefined)
460
+ checkJsBudget(report, options.maxJs)
461
+ }
462
+
463
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile })
464
+ return manifest
465
+ }
466
+
467
+ interface BuiltOutput {
468
+ manifest: BuildManifest
469
+ writeManifest: () => void
470
+ host: ReturnType<typeof createPluginHost>
471
+ env: Parameters<typeof pluginBunPlugins>[0]
472
+ assets: string[]
473
+ builtClientAssets: ReadonlySet<string>
474
+ hasNotFoundFile: boolean
475
+ }
476
+
477
+ /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
478
+ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
479
+ const { options, root, plugins, outDir, assetPrefix, isDev, publicFiles } = run
480
+ const { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile } = built
481
+ const clientDir = join(outDir, 'client')
482
+ const isStatic = options.static === true
483
+
484
+ // Hybrid prerendering / static export (skipped in `prunelle dev`, where routes render on-demand)
485
+ const prerenderRoutes = options.prerender !== false || isStatic ? manifest.routes.filter(r => r.prerender) : []
486
+ const prerenderDir = isStatic ? run.stageDir : join(outDir, 'prerendered')
487
+ const prerendered = prerenderRoutes.length > 0 || isStatic
488
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes })
489
+ : undefined
490
+
491
+ try {
492
+ const ranAfterPrerender = await host.runAfterPrerender()
493
+ recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets)
494
+ await host.precompressOutput()
495
+ if (Object.keys(host.pluginData).length > 0)
496
+ manifest.pluginData = host.pluginData
497
+
498
+ if (isStatic) {
499
+ await exportStatic({
500
+ root: run.root,
501
+ stageDir: prerenderDir,
502
+ finalOutDir: run.finalOutDir,
503
+ outDir,
504
+ clientDir,
505
+ assetPrefix,
506
+ site: run.site,
507
+ isDev,
508
+ manifest,
509
+ entry: prerendered?.entry,
510
+ pluginOverride: options.plugins,
511
+ assets,
512
+ publicFiles,
513
+ app: prerendered?.app,
514
+ hasNotFoundFile,
515
+ stageSuffix: run.stageSuffix,
516
+ })
517
+ }
518
+ else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
519
+ writeManifest()
520
+ }
521
+ }
522
+ finally {
523
+ await prerendered?.app?.dispose?.()
524
+ }
525
+
526
+ if (!isStatic && !isDev) {
527
+ const carried = carryPreviousAssets(run.finalOutDir, outDir, 'client', manifest.assets)
528
+ if (carried.length > 0) {
529
+ manifest.carriedAssets = carried
530
+ writeManifest()
531
+ }
532
+ }
533
+
534
+ if (options.compile) {
535
+ await compileExecutable({
536
+ root,
537
+ outDir,
538
+ clientDir,
539
+ manifest,
540
+ assetPrefix,
541
+ site: options.site !== undefined ? run.site : undefined,
542
+ outfile: compileOutfile(options.compile, root, outDir, run.finalOutDir),
543
+
544
+ resolvePrunelleSpecifier,
545
+ bunPlugins: pluginBunPlugins(env, 'compile'),
546
+ })
547
+ }
548
+
549
+ if (!isStatic) {
550
+ swapStage(outDir, run.finalOutDir, run.stageSuffix)
551
+ relocateCache(options.cache, outDir, run.finalOutDir)
552
+ }
553
+ }
554
+
555
+ /** Where `--compile` writes the binary: a path inside the output folder goes into the stage, so the swap keeps it. */
556
+ function compileOutfile(compile: string | true, root: string, stageDir: string, finalOutDir: string): string {
557
+ if (compile === true)
558
+ return join(stageDir, 'server-bin')
559
+ const outfile = resolve(root, compile)
560
+ return isInside(finalOutDir, outfile) ? join(stageDir, relative(finalOutDir, outfile)) : outfile
561
+ }
562
+
563
+ /** Points the cache's reusable folders at where the swap moved them, so the next build links from there. */
564
+ function relocateCache(cache: BuildCache | undefined, from: string, to: string): void {
565
+ if (cache === undefined)
566
+ return
567
+ const moved = (dir: string): string => dir.startsWith(from) ? to + dir.slice(from.length) : dir
568
+ if (cache.lastClient !== undefined)
569
+ cache.lastClient.clientDir = moved(cache.lastClient.clientDir)
570
+ if (cache.lastServer !== undefined)
571
+ cache.lastServer.serverDir = moved(cache.lastServer.serverDir)
572
+ const assets = cachedPluginAssets.get(cache)
573
+ if (assets !== undefined)
574
+ assets.clientDir = moved(assets.clientDir)
575
+ }
@@ -0,0 +1,12 @@
1
+ // Path confinement, on its own so the server can check a path without loading the build's file helpers and `node:zlib` with them.
2
+
3
+ import { isAbsolute, relative } from 'node:path'
4
+
5
+ /** Whether `target` lies under `dir`, or is `dir` itself with `orSame`. Paths are compared as written: realpath both first to follow symlinks. */
6
+ export function isInside(dir: string, target: string, options: { orSame?: boolean } = {}): boolean {
7
+ const rel = relative(dir, target)
8
+ if (rel === '')
9
+ return options.orSame === true
10
+ // `..x` is a name inside `dir`; only `..` itself, as a whole segment, leaves it.
11
+ return rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') && !isAbsolute(rel)
12
+ }