prunelle 0.0.0-stage → 0.7.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 (222) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +245 -0
  3. package/package.json +62 -4
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/ambient.d.ts +6 -0
  8. package/src/attrs.ts +43 -0
  9. package/src/build/bundle.ts +661 -0
  10. package/src/build/byte-size.ts +11 -0
  11. package/src/build/carry.ts +57 -0
  12. package/src/build/client-entries.ts +107 -0
  13. package/src/build/client-plugin.ts +175 -0
  14. package/src/build/client-prune.ts +168 -0
  15. package/src/build/compile.ts +130 -0
  16. package/src/build/ecoindex.ts +238 -0
  17. package/src/build/files.ts +171 -0
  18. package/src/build/first-load.ts +235 -0
  19. package/src/build/graph.ts +237 -0
  20. package/src/build/index.ts +678 -0
  21. package/src/build/is-inside.ts +12 -0
  22. package/src/build/island-promote.ts +311 -0
  23. package/src/build/islands.ts +452 -0
  24. package/src/build/manifest.ts +204 -0
  25. package/src/build/output.ts +81 -0
  26. package/src/build/plugin-host.ts +294 -0
  27. package/src/build/precompress.ts +139 -0
  28. package/src/build/prerender.ts +288 -0
  29. package/src/build/reach.ts +200 -0
  30. package/src/build/render-rules.ts +205 -0
  31. package/src/build/report.ts +290 -0
  32. package/src/build/resolve.ts +52 -0
  33. package/src/build/routes.ts +342 -0
  34. package/src/build/server-entry.ts +38 -0
  35. package/src/build/static-headers.ts +112 -0
  36. package/src/build/static.ts +209 -0
  37. package/src/build/status-pages.ts +127 -0
  38. package/src/build/style-bundles.ts +526 -0
  39. package/src/cli/check-forms.ts +636 -0
  40. package/src/cli/check-imports.ts +31 -0
  41. package/src/cli/check-links.ts +632 -0
  42. package/src/cli/check-security.ts +64 -0
  43. package/src/cli/check.ts +409 -0
  44. package/src/cli/commands.ts +372 -0
  45. package/src/cli/docs.ts +403 -0
  46. package/src/cli/index.ts +70 -0
  47. package/src/cli/inspect.ts +406 -0
  48. package/src/cli/mcp-tools.ts +492 -0
  49. package/src/cli/mcp.ts +205 -0
  50. package/src/cli/new.ts +52 -0
  51. package/src/cli/render.ts +416 -0
  52. package/src/cli/upgrade-names.ts +209 -0
  53. package/src/cli/upgrade.ts +367 -0
  54. package/src/compiler/analyze.ts +651 -0
  55. package/src/compiler/ast.ts +82 -0
  56. package/src/compiler/browser-globals.ts +250 -0
  57. package/src/compiler/cacheability-private.ts +566 -0
  58. package/src/compiler/cacheability.ts +335 -0
  59. package/src/compiler/compliance-eco.ts +71 -0
  60. package/src/compiler/compliance-rgaa.ts +614 -0
  61. package/src/compiler/compliance-urls.ts +148 -0
  62. package/src/compiler/compliance.ts +653 -0
  63. package/src/compiler/data-keys.ts +302 -0
  64. package/src/compiler/dev-source.ts +87 -0
  65. package/src/compiler/dom-attrs.ts +452 -0
  66. package/src/compiler/dom.ts +641 -0
  67. package/src/compiler/emit.ts +131 -0
  68. package/src/compiler/expr-context.ts +587 -0
  69. package/src/compiler/foreign-imports.ts +88 -0
  70. package/src/compiler/index.ts +8 -0
  71. package/src/compiler/interactivity.ts +366 -0
  72. package/src/compiler/mistakes.ts +520 -0
  73. package/src/compiler/node-env.ts +50 -0
  74. package/src/compiler/patch.ts +97 -0
  75. package/src/compiler/props-body.ts +60 -0
  76. package/src/compiler/props.ts +511 -0
  77. package/src/compiler/scope.ts +635 -0
  78. package/src/compiler/server-only.ts +365 -0
  79. package/src/compiler/shared.ts +397 -0
  80. package/src/compiler/signal-reads.ts +246 -0
  81. package/src/compiler/slots.ts +227 -0
  82. package/src/compiler/spread-handlers.ts +295 -0
  83. package/src/compiler/ssr-helpers.ts +555 -0
  84. package/src/compiler/ssr-island.ts +90 -0
  85. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  86. package/src/compiler/ssr.ts +525 -0
  87. package/src/context.ts +199 -0
  88. package/src/dev/child.ts +30 -0
  89. package/src/dev/error-log.ts +177 -0
  90. package/src/dev/host-check.ts +32 -0
  91. package/src/dev/index.ts +268 -0
  92. package/src/dev/modules.ts +68 -0
  93. package/src/dev/open-editor.ts +228 -0
  94. package/src/dev/protocol.ts +24 -0
  95. package/src/dev/queue.ts +79 -0
  96. package/src/dev/reload.ts +159 -0
  97. package/src/dev/supervisor.ts +212 -0
  98. package/src/dev/watchers.ts +276 -0
  99. package/src/dom/action.ts +187 -0
  100. package/src/dom/attrs.ts +84 -0
  101. package/src/dom/claim.ts +120 -0
  102. package/src/dom/extras.ts +579 -0
  103. package/src/dom/index.ts +329 -0
  104. package/src/dom/island.ts +318 -0
  105. package/src/dom/loop.ts +484 -0
  106. package/src/dom/revive.ts +36 -0
  107. package/src/eco/declaration.ts +328 -0
  108. package/src/eco/index.ts +69 -0
  109. package/src/index.ts +22 -0
  110. package/src/jsx-runtime.ts +566 -0
  111. package/src/plugins/config.ts +92 -0
  112. package/src/plugins/context.ts +109 -0
  113. package/src/plugins/index.ts +14 -0
  114. package/src/plugins/load.ts +90 -0
  115. package/src/plugins/order.ts +148 -0
  116. package/src/plugins/public.ts +15 -0
  117. package/src/plugins/requires.ts +47 -0
  118. package/src/plugins/services.ts +119 -0
  119. package/src/plugins/types.ts +278 -0
  120. package/src/reactivity/graph.ts +259 -0
  121. package/src/reactivity/index.ts +541 -0
  122. package/src/reactivity/selector.ts +78 -0
  123. package/src/reactivity/store.ts +252 -0
  124. package/src/server/action-flash.ts +158 -0
  125. package/src/server/action-protect.ts +199 -0
  126. package/src/server/action-registry.ts +78 -0
  127. package/src/server/action.ts +511 -0
  128. package/src/server/app-entry.ts +23 -0
  129. package/src/server/app-secret.ts +63 -0
  130. package/src/server/assets.ts +168 -0
  131. package/src/server/compress.ts +646 -0
  132. package/src/server/consent.ts +290 -0
  133. package/src/server/cookies.ts +153 -0
  134. package/src/server/document.ts +286 -0
  135. package/src/server/env.ts +47 -0
  136. package/src/server/errors.ts +396 -0
  137. package/src/server/form-schema.ts +337 -0
  138. package/src/server/health.ts +275 -0
  139. package/src/server/http.ts +588 -0
  140. package/src/server/index.ts +615 -0
  141. package/src/server/lifecycle.ts +75 -0
  142. package/src/server/loader.ts +131 -0
  143. package/src/server/page.ts +122 -0
  144. package/src/server/param-matchers.ts +112 -0
  145. package/src/server/plugin-host.ts +267 -0
  146. package/src/server/prerendered.ts +71 -0
  147. package/src/server/public.ts +20 -0
  148. package/src/server/rate-limit.ts +199 -0
  149. package/src/server/region.ts +96 -0
  150. package/src/server/request-body.ts +27 -0
  151. package/src/server/request-path.ts +73 -0
  152. package/src/server/request-scope.ts +22 -0
  153. package/src/server/route-cache.ts +541 -0
  154. package/src/server/route-table.ts +424 -0
  155. package/src/server/router.ts +261 -0
  156. package/src/server/routing.ts +388 -0
  157. package/src/server/sanitize-html.ts +309 -0
  158. package/src/server/security.ts +550 -0
  159. package/src/server/serve-handlers.ts +93 -0
  160. package/src/server/served-file.ts +128 -0
  161. package/src/server/standard-schema.ts +104 -0
  162. package/src/server/start.ts +143 -0
  163. package/src/server/static-dir.ts +246 -0
  164. package/src/server/stream.ts +233 -0
  165. package/src/ssr/consent-banner.ts +58 -0
  166. package/src/ssr/context.ts +399 -0
  167. package/src/ssr/index.ts +624 -0
  168. package/src/ssr/navigation.ts +96 -0
  169. package/src/ssr/region.ts +192 -0
  170. package/src/style.ts +96 -0
  171. package/src/test/browser.ts +201 -0
  172. package/src/test/index.ts +262 -0
  173. package/src/ts-plugin/diagnostics.ts +505 -0
  174. package/src/ts-plugin/fixes.ts +364 -0
  175. package/src/ts-plugin/index.ts +194 -0
  176. package/src/unrenderable.ts +35 -0
  177. package/templates/_shared/AGENTS.md +10 -0
  178. package/templates/_shared/CLAUDE.md +1 -0
  179. package/templates/_shared/gitignore +8 -0
  180. package/templates/_shared/mcp.json +11 -0
  181. package/templates/_shared/public/robots.txt +2 -0
  182. package/templates/_shared/src/routes/legal.tsx +22 -0
  183. package/templates/_shared/tsconfig.json +25 -0
  184. package/templates/app/.env.example +8 -0
  185. package/templates/app/package.json +22 -0
  186. package/templates/app/prunelle.config.ts +13 -0
  187. package/templates/app/src/auth.ts +12 -0
  188. package/templates/app/src/mail.ts +4 -0
  189. package/templates/app/src/routes/_layout.tsx +40 -0
  190. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  191. package/templates/app/src/routes/dashboard/index.tsx +47 -0
  192. package/templates/app/src/routes/index.tsx +15 -0
  193. package/templates/app/src/routes/login.tsx +53 -0
  194. package/templates/app/src/routes/privacy.tsx +25 -0
  195. package/templates/app/src/styles/app.css +14 -0
  196. package/templates/app/tests/app.test.ts +73 -0
  197. package/templates/blog/content/posts/welcome.md +9 -0
  198. package/templates/blog/package.json +22 -0
  199. package/templates/blog/prunelle.config.ts +23 -0
  200. package/templates/blog/src/posts.ts +26 -0
  201. package/templates/blog/src/routes/_layout.tsx +25 -0
  202. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  203. package/templates/blog/src/routes/index.tsx +33 -0
  204. package/templates/blog/src/styles/app.css +15 -0
  205. package/templates/fullstack/package.json +19 -0
  206. package/templates/fullstack/prunelle.config.ts +6 -0
  207. package/templates/fullstack/src/actions/greet.ts +19 -0
  208. package/templates/fullstack/src/components/Counter.tsx +10 -0
  209. package/templates/fullstack/src/components/GreetForm.tsx +28 -0
  210. package/templates/fullstack/src/routes/_layout.tsx +18 -0
  211. package/templates/fullstack/src/routes/api/health.ts +5 -0
  212. package/templates/fullstack/src/routes/index.tsx +13 -0
  213. package/templates/fullstack/src/styles/app.css +39 -0
  214. package/templates/fullstack/tests/app.test.ts +37 -0
  215. package/templates/minimal/package.json +19 -0
  216. package/templates/minimal/prunelle.config.ts +6 -0
  217. package/templates/minimal/src/components/Counter.tsx +10 -0
  218. package/templates/minimal/src/routes/_layout.tsx +18 -0
  219. package/templates/minimal/src/routes/index.tsx +11 -0
  220. package/templates/minimal/src/styles/app.css +32 -0
  221. package/ts-plugin.cjs +4277 -0
  222. package/README.md +0 -3
@@ -0,0 +1,678 @@
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 { BudgetConfig } from '../plugins/types'
10
+ import type { BuildCache } from './graph'
11
+ import type { ActionsByFile } from './islands'
12
+ import type { BuildManifest } from './manifest'
13
+ import type { PublicFiles } from './plugin-host'
14
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
15
+ import { basename, dirname, join, relative, resolve } from 'node:path'
16
+ import { checkAppForms } from '../cli/check-forms'
17
+ import { findCachedRoutePrivateReads } from '../compiler/cacheability'
18
+ import { collectProjectComplianceWarnings, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
19
+ import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
20
+ import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
21
+ import { actionHash } from '../server/action'
22
+ import { devFromEnv } from '../server/env'
23
+ import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, setPrunedClientCss, standaloneCssFiles } from './bundle'
24
+ import { compileExecutable } from './compile'
25
+ import { assertSafeOutDir, fileSize, isHiddenPublicPath, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
26
+ import { isInside } from './is-inside'
27
+ import { ModuleGraph } from './graph'
28
+ import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
29
+ import { formatIslandValueWarnings } from './island-promote'
30
+ import { planIslands } from './islands'
31
+ import { buildActionEntries, buildRouteEntries } from './manifest'
32
+ import { createPluginHost, createPublicFiles } from './plugin-host'
33
+ import { carryPreviousAssets } from './carry'
34
+ import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
35
+ import { prerender } from './prerender'
36
+ import { analyzeBundleWeights, checkFirstLoadBudget, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
37
+ import { parseByteSize } from './byte-size'
38
+ import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
39
+ import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
40
+ import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
41
+ import { emitStaticNotFoundPages, exportStatic } from './static'
42
+ import { findUnknownStatusPages } from './status-pages'
43
+ import { consolidateStylesheets } from './style-bundles'
44
+
45
+ export type { BuildCache } from './graph'
46
+ export { createBuildCache } from './graph'
47
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry, StatusPageKind, StatusPageManifestEntry } from './manifest'
48
+ export { analyzeBundleWeights, checkJsBudget, computeEcoIndex, countDomElements, formatBundleReport, formatBundleReportJson } from './report'
49
+ export type { BundleReport, EcoIndexGrade, RouteBundleMetrics, RouteEcoIndex, RouteIsland } from './report'
50
+ export { resolvePrunelleSpecifier } from './resolve'
51
+
52
+ export interface BuildOptions {
53
+ root: string
54
+ routesDir?: string | undefined
55
+ outDir?: string | undefined
56
+ publicDir?: string | undefined
57
+ minify?: boolean | undefined
58
+ assetPrefix?: string | undefined
59
+ site?: string | undefined
60
+ /** `<html lang>` of every page; defaults to `lang` in `prunelle.config.ts`. */
61
+ lang?: string | undefined
62
+ plugins?: PrunellePlugin[] | undefined
63
+ /** Reusable incremental cache for `prunelle dev` (skips re-parsing/re-compiling unchanged files). */
64
+ cache?: BuildCache | undefined
65
+ /** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
66
+ analyze?: boolean | undefined
67
+ /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
68
+ analyzeJson?: boolean | undefined
69
+ /** Receives the computed `BundleReport` in-process without printing to stdout (used by `prunelle mcp`). */
70
+ onAnalyze?: ((report: import('./report').BundleReport) => void) | undefined
71
+ /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
72
+ maxJs?: number | undefined
73
+ /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
74
+ static?: boolean | undefined
75
+ /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
76
+ prerender?: boolean | undefined
77
+ /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
78
+ autoPrerender?: boolean | undefined
79
+ /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
80
+ copyPublic?: boolean | undefined
81
+ /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
82
+ compile?: string | boolean | undefined
83
+ /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via PRUNELLE_DEV=1). */
84
+ dev?: boolean | undefined
85
+ /** Explicit NODE_ENV threaded through AppRuntimeContext and client defines without mutating process.env. */
86
+ nodeEnv?: string | undefined
87
+ }
88
+
89
+ const cachedPluginAssets = new WeakMap<BuildCache, { clientDir: string, files: string[] }>()
90
+
91
+ function restoreCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: string[], anyPassSkipped: boolean): void {
92
+ if (cache === undefined || !anyPassSkipped)
93
+ return
94
+ const prev = cachedPluginAssets.get(cache)
95
+ if (prev === undefined || prev.clientDir === clientDir)
96
+ return
97
+ const existing = new Set(assets)
98
+ for (const rel of prev.files) {
99
+ if (existing.has(rel))
100
+ continue
101
+ const from = join(prev.clientDir, rel)
102
+ if (!existsSync(from))
103
+ continue
104
+ linkOrCopyFile(from, join(clientDir, rel))
105
+ existing.add(rel)
106
+ assets.push(rel)
107
+ }
108
+ }
109
+
110
+ function recordCachedPluginAssets(
111
+ cache: BuildCache | undefined,
112
+ clientDir: string,
113
+ assets: readonly string[],
114
+ builtClientAssets: ReadonlySet<string>,
115
+ consolidatedCssAssets: ReadonlySet<string>,
116
+ ): void {
117
+ if (cache === undefined)
118
+ return
119
+ const files = assets.filter(rel => !builtClientAssets.has(rel) && !consolidatedCssAssets.has(rel))
120
+ if (files.length > 0)
121
+ cachedPluginAssets.set(cache, { clientDir, files })
122
+ else
123
+ cachedPluginAssets.delete(cache)
124
+ }
125
+
126
+ /** The server build a static export renders its pages from, under `.prunelle-cache/`. */
127
+ const STATIC_STAGE_PREFIX = '.static-stage-'
128
+
129
+ /** Everything one build run needs, resolved once from the options and `prunelle.config.ts`. */
130
+ interface BuildRun {
131
+ options: BuildOptions
132
+ root: string
133
+ plugins: PrunellePlugin[]
134
+ routesDir: string
135
+ publicDir: string
136
+ finalOutDir: string
137
+ /** The folder swapped in as `finalOutDir` once every step passed. */
138
+ stageDir: string
139
+ /** Where the build writes: `stageDir`, or for a static export a server build in `.prunelle-cache/` that `stageDir` takes pages from. */
140
+ outDir: string
141
+ stageSuffix: string
142
+ assetPrefix: string
143
+ site: string | undefined
144
+ lang: string | undefined
145
+ /** Byte caps from `budget` in `prunelle.config.ts`, `--max-js` taking over `js`. */
146
+ budget: { js: number | undefined, jsSource: string, firstLoad: number | undefined }
147
+ defaultPort: number | undefined
148
+ compliance: ComplianceConfig | undefined
149
+ consentMaxAge: number | undefined
150
+ autoPrerender: boolean
151
+ minify: boolean
152
+ isDev: boolean
153
+ nodeEnv: string | undefined
154
+ appCtx: AppRuntimeContext
155
+ publicFiles: PublicFiles
156
+ }
157
+
158
+ export async function build(options: BuildOptions): Promise<BuildManifest> {
159
+ if (options.static && options.compile) {
160
+ throw new Error('prunelle build: --static and --compile cannot be used together (static export produces HTML/assets without a server binary).')
161
+ }
162
+
163
+ const root = resolve(options.root)
164
+ const isDev = options.dev ?? devFromEnv()
165
+ const effectiveNodeEnv = options.nodeEnv ?? (isDev ? undefined : (process.env.NODE_ENV ?? 'production'))
166
+ const fileConfig = await loadConfig(root, { dev: isDev, nodeEnv: effectiveNodeEnv })
167
+ const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
168
+ const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
169
+ const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
170
+
171
+ assertSafeOutDir(root, finalOutDir, routesDir, publicDir)
172
+
173
+ const cacheBaseDir = join(root, '.prunelle-cache')
174
+ const cacheExisted = existsSync(cacheBaseDir)
175
+ const stageSuffix = processSuffix()
176
+ const stageDir = stageDirFor(finalOutDir, stageSuffix)
177
+ const outDir = options.static ? join(cacheBaseDir, `${STATIC_STAGE_PREFIX}${stageSuffix}`) : stageDir
178
+ const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_pru').replace(/\/$/, '')
179
+ assertOwnOutDir(root, finalOutDir, assetPrefix)
180
+ removeStaleStages(finalOutDir)
181
+ removeDeadProcessDirs(cacheBaseDir, STATIC_STAGE_PREFIX)
182
+ const site = (options.site ?? fileConfig.site)?.replace(/\/$/, '') || undefined
183
+ const publicFiles = createPublicFiles()
184
+ const appCtx = createAppContext({
185
+ root,
186
+ outDir,
187
+ publicDir: join(outDir, 'public'),
188
+ assetPrefix,
189
+ site,
190
+ dev: isDev,
191
+ nodeEnv: effectiveNodeEnv,
192
+ onRegisterPublicFile: publicFiles.register,
193
+ })
194
+
195
+ try {
196
+ return await runWithAppContext(appCtx, () => runBuild({
197
+ options,
198
+ root,
199
+ plugins: resolvePlugins(options.plugins ?? fileConfig.plugins),
200
+ routesDir,
201
+ publicDir,
202
+ finalOutDir,
203
+ stageDir,
204
+ outDir,
205
+ stageSuffix,
206
+ assetPrefix,
207
+ site,
208
+ lang: options.lang ?? fileConfig.lang,
209
+ budget: resolveBudget(options.maxJs, fileConfig.budget),
210
+ defaultPort: fileConfig.port,
211
+ compliance: fileConfig.compliance,
212
+ consentMaxAge: fileConfig.consent?.maxAge,
213
+ autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
214
+ minify: options.minify ?? true,
215
+ isDev,
216
+ nodeEnv: effectiveNodeEnv,
217
+ appCtx,
218
+ publicFiles,
219
+ }))
220
+ }
221
+ finally {
222
+ rmSync(stageDir, { recursive: true, force: true })
223
+ if (options.static) {
224
+ rmSync(outDir, { recursive: true, force: true })
225
+ if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
226
+ rmSync(cacheBaseDir, { recursive: true, force: true })
227
+ }
228
+ }
229
+ }
230
+
231
+ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readonly string[]): void {
232
+ for (const [file, analysis] of graph.analyses) {
233
+ const rel = relPosix(run.root, file)
234
+ for (const warning of analysis.warnings) {
235
+ if (!shouldEmitWarning(warning, run.compliance, run.site))
236
+ continue
237
+ const loc = formatLoc(rel, graph.source(file), warning.start)
238
+ console.warn(formatDiagnostic(loc, warning.message.replaceAll(file, rel), 'warning'))
239
+ }
240
+ }
241
+ if (!run.isDev) {
242
+ const projectWarnings = collectProjectComplianceWarnings({ root: run.root, srcDir: join(run.root, 'src'), routesDir: run.routesDir, publicDir: run.publicDir, routeFiles, analyses: graph.analyses, compliance: run.compliance, consentMaxAge: run.consentMaxAge, site: run.site, lang: run.lang, langFromPlugin: pluginSetsLang(run.plugins) })
243
+ for (const warning of projectWarnings)
244
+ console.warn(warning)
245
+ }
246
+ }
247
+
248
+
249
+ /** 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. */
250
+ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph, pageFiles: string[], specialFiles: string[], isStatic: boolean): ReturnType<typeof planIslands> {
251
+ const islands = planIslands(graph, root, pageFiles, specialFiles)
252
+ for (const { file, warning } of islands.promotedWarnings) {
253
+ const rel = relPosix(root, file)
254
+ console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), warning.start), warning.message.replaceAll(file, rel), 'warning'))
255
+ }
256
+ const placed: string[] = []
257
+ const place = (file: string, offset: number, message: string): void => {
258
+ const source = graph.source(file)
259
+ placed.push(`${formatDiagnostic(formatLoc(relPosix(root, file), source, offset), message)}\n${formatCodeFrame(source, offset)}`)
260
+ }
261
+ const configFile = join(root, 'prunelle.config.ts')
262
+ for (const [file, analysis] of graph.analyses) {
263
+ const rel = relPosix(root, file)
264
+ for (const offset of file === configFile ? [] : serverNodeEnvReads(analysis, islands, file))
265
+ console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), offset), nodeEnvWarning(rel), 'warning'))
266
+ if (!file.endsWith('.tsx') || isInNodeModules(file))
267
+ continue
268
+ for (const problem of renderProblems(analysis, islands, file, rel, 'prunelle build'))
269
+ place(file, problem.offset, problem.message)
270
+ }
271
+ for (const file of pageFiles) {
272
+ const missing = missingPathsProblem(graph.analyses.get(file)!, normalizeRoutePattern(fileToRoutePath(routesDir, file)), isStatic)
273
+ if (missing !== undefined)
274
+ place(file, missing.offset, `prunelle build: ${missing.message}`)
275
+ }
276
+ const cacheProblems = findCachedRoutePrivateReads({
277
+ graph,
278
+ pageFiles,
279
+ layoutsFor: file => ancestorFiles(routesDir, file, ['_layout.tsx']),
280
+ toRel: file => relPosix(root, file),
281
+ tool: 'prunelle build',
282
+ })
283
+ for (const problem of cacheProblems)
284
+ place(problem.file, problem.offset, problem.message)
285
+ if (placed.length > 0)
286
+ throw new Error(placed.join('\n\n'))
287
+ return islands
288
+ }
289
+
290
+ /** 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. */
291
+ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles: readonly string[]): void {
292
+ const watched = cache.watchedFiles
293
+ watched.clear()
294
+ const recordWatched = (file: string) => {
295
+ if (!existsSync(file))
296
+ return
297
+ let real = file
298
+ try {
299
+ real = realpathSync(file)
300
+ }
301
+ catch {}
302
+ watched.add(real)
303
+ }
304
+ for (const f of graph.analyses.keys())
305
+ recordWatched(f)
306
+ for (const f of cache.lastClient?.inputStamps.keys() ?? [])
307
+ recordWatched(f)
308
+ for (const f of cache.lastServer?.inputStamps.keys() ?? [])
309
+ recordWatched(f)
310
+ for (const f of extraFiles)
311
+ recordWatched(f)
312
+ for (const compiled of [cache.analyses, cache.domCompiled, cache.ssrCompiled]) {
313
+ for (const f of [...compiled.keys()]) {
314
+ if (!existsSync(f))
315
+ compiled.delete(f)
316
+ }
317
+ }
318
+ }
319
+
320
+ function validateRoutesAndMatchers(root: string, routesDir: string, allRouteFiles: readonly string[], specialFiles: readonly string[], candidateFiles: readonly string[], graph: ModuleGraph): { pageFiles: string[], customMatchers: Map<string, string> } {
321
+ const unknownStatus = findUnknownStatusPages(root, allRouteFiles)
322
+ if (unknownStatus.length > 0)
323
+ throw new Error(`prunelle build: ${unknownStatus[0]!.message}`)
324
+ const routesRel = relPosix(root, routesDir)
325
+ for (const f of [...specialFiles, ...candidateFiles]) {
326
+ const analysis = graph.analyses.get(f)!
327
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
328
+ if (problem !== undefined)
329
+ throw new Error(`prunelle build: ${problem}`)
330
+ }
331
+ // A file exporting only actions stays in routes/ for its folder's middleware.
332
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
333
+ assertNoRouteConflicts(root, routesDir, pageFiles)
334
+ const { customFiles, problems } = discoverRouteMatchers({
335
+ root,
336
+ routesDir,
337
+ routeFiles: [...specialFiles, ...pageFiles],
338
+ loadAnalysis: file => graph.load(file),
339
+ })
340
+ if (problems.length > 0)
341
+ throw new Error(`prunelle build: ${problems[0]!.message}`)
342
+ return { pageFiles, customMatchers: customFiles }
343
+ }
344
+
345
+ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: string): ActionsByFile {
346
+ const actionsByFile: ActionsByFile = new Map()
347
+ for (const [file, analysis] of graph.analyses) {
348
+ if (analysis.exportedActions.length > 0) {
349
+ const rel = relPosix(root, file)
350
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
351
+ exportName,
352
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
353
+ })))
354
+ }
355
+ }
356
+ return actionsByFile
357
+ }
358
+
359
+ function copyPublicFiles(publicDir: string, outPublicDir: string, publicFiles: PublicFiles, copyPublic: boolean): void {
360
+ for (const abs of walkAllFiles(publicDir).sort()) {
361
+ const rel = relative(publicDir, abs)
362
+ if (isHiddenPublicPath(rel))
363
+ continue
364
+ publicFiles.register(rel)
365
+ if (copyPublic) {
366
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
367
+ copyFileSync(abs, join(outPublicDir, rel))
368
+ }
369
+ }
370
+ }
371
+
372
+ function collectNonEmptyClientAssets(clientDir: string, assetFiles: readonly string[]): { assets: string[], builtClientAssets: Set<string> } {
373
+ const assets: string[] = []
374
+ for (const rel of assetFiles) {
375
+ const abs = join(clientDir, rel)
376
+ const size = fileSize(abs)
377
+ if (size === 0)
378
+ rmSync(abs, { force: true })
379
+ else if (size !== undefined)
380
+ assets.push(rel)
381
+ }
382
+ return { assets, builtClientAssets: new Set(assets) }
383
+ }
384
+
385
+ async function validateAppForms(run: BuildRun, routeFiles: readonly string[], graph: ModuleGraph): Promise<void> {
386
+ const formCheck = await checkAppForms({ root: run.root, routesDir: run.routesDir, routeFiles, graph, compliance: run.compliance })
387
+ if (formCheck.errors.length > 0)
388
+ throw new Error(formCheck.errors.join('\n'))
389
+ if (!run.isDev) {
390
+ for (const warning of formCheck.warnings)
391
+ console.warn(warning)
392
+ }
393
+ }
394
+
395
+ async function runBuild(run: BuildRun): Promise<BuildManifest> {
396
+ const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
397
+ const clientDir = join(outDir, 'client')
398
+ const serverDir = join(outDir, 'server')
399
+ const isStatic = options.static === true
400
+
401
+ const allRouteFiles = walkRoutes(routesDir).sort()
402
+ const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
403
+ const candidateFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
404
+ const rootLayoutSrc = join(routesDir, '_layout.tsx')
405
+ const errorSrc = join(routesDir, '_error.tsx')
406
+ const notFoundSrc = join(routesDir, '_404.tsx')
407
+ const hasRootLayout = existsSync(rootLayoutSrc)
408
+ const hasErrorFile = existsSync(errorSrc)
409
+ const hasNotFoundFile = existsSync(notFoundSrc)
410
+
411
+ // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
412
+ // prunelle.config.ts enters the graph too, so an action or component reached only from it is analyzed and gets its URL.
413
+ const configSrc = join(root, 'prunelle.config.ts')
414
+ const hasConfigFile = existsSync(configSrc)
415
+ const graph = new ModuleGraph(root, options.cache)
416
+ for (const f of [...specialFiles, ...candidateFiles, ...(hasConfigFile ? [configSrc] : [])])
417
+ graph.load(f)
418
+ emitBuildWarnings(run, graph, allRouteFiles)
419
+
420
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
421
+ const customMatcherFiles = [...new Set(customMatchers.values())]
422
+
423
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
424
+ const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
425
+ if (!isDev) {
426
+ for (const warning of formatIslandValueWarnings(islands.valueUses, root, graph, f => graph.source(f), run.compliance))
427
+ console.warn(warning)
428
+ }
429
+ await validateAppForms(run, allRouteFiles, graph)
430
+
431
+ mkdirSync(clientDir, { recursive: true })
432
+ mkdirSync(serverDir, { recursive: true })
433
+ const pluginCssFiles = plugins
434
+ .flatMap(p => p.css ?? [])
435
+ .map(c => resolve(root, c))
436
+ .filter(c => existsSync(c))
437
+ const wantsAnalyze = wantsBundleAnalysis(run)
438
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, lang: run.lang, minify: run.minify, isDev, nodeEnv: run.nodeEnv, analyze: wantsAnalyze, graph, cache: options.cache, plugins, actionsByFile, islands }
439
+
440
+ const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
441
+ const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
442
+ // `_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.
443
+ const bundledModules = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...customMatcherFiles]
444
+ const serverEntries = [...bundledModules, ...(hasConfigFile ? [configSrc] : [])]
445
+ const serverRoot = standaloneActionFiles.length > 0 || customMatcherFiles.length > 0 || hasConfigFile ? root : routesDir
446
+ const toOutRel = (srcFile: string): string =>
447
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
448
+ const serverEntry = {
449
+ file: join(serverRoot, SERVER_ENTRY_FILE),
450
+ source: serverEntrySource({
451
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
452
+ config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
453
+ assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
454
+ }),
455
+ }
456
+ if (existsSync(serverEntry.file))
457
+ throw new Error(`prunelle build: ${relPosix(root, serverEntry.file)} is the path of prunelle's server entry; rename that file.`)
458
+
459
+ // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
460
+ const clientSkipsBefore = options.cache?.stats.clientSkips ?? 0
461
+ const serverSkipsBefore = options.cache?.stats.serverSkips ?? 0
462
+ const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
463
+ let client: Awaited<ReturnType<typeof clientPass>>
464
+ if (islands.targets.size === 0) {
465
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map(), serverEntry)])
466
+ client = built
467
+ }
468
+ else {
469
+ client = await clientPass()
470
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks, serverEntry)
471
+ }
472
+ const anyPassSkipped = options.cache !== undefined
473
+ && (options.cache.stats.clientSkips > clientSkipsBefore || options.cache.stats.serverSkips > serverSkipsBefore)
474
+
475
+ if (options.cache !== undefined)
476
+ refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
477
+
478
+ const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, client.assetFiles)
479
+
480
+ const { routes, statusPages, globalStyles, routeSourceFiles, globalSourceFiles } = buildRouteEntries({
481
+ graph, islands, islandChunks: client.islandChunks, srcCssToUrl: client.srcCssToUrl, islandCssUrl: client.islandCssUrl,
482
+ routesDir, pageFiles, specialFiles, pluginCssFiles, isStatic, autoPrerender: run.autoPrerender, toOutRel,
483
+ })
484
+ const paramMatchers = customMatchers.size > 0
485
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
486
+ : undefined
487
+
488
+ // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
489
+ const outPublicDir = join(outDir, 'public')
490
+ copyPublicFiles(run.publicDir, outPublicDir, publicFiles, options.copyPublic !== false)
491
+
492
+ const host = createPluginHost({
493
+ plugins, appCtx: run.appCtx, root, outDir, clientDir, outPublicDir, assetPrefix, site: run.site, minify: run.minify,
494
+ isStatic, isDev, routes, statusPages, routeSourceFiles, globalSourceFiles, publicFiles, assets, styleUrls: client.styleUrls, globalStyles,
495
+ })
496
+ await host.runBuild()
497
+ restoreCachedPluginAssets(options.cache, clientDir, assets, anyPassSkipped)
498
+ const consolidated = consolidateStylesheets({
499
+ clientDir, assetPrefix, minify: run.minify, isDev, srcCssToUrl: client.srcCssToUrl, capturePruned: options.cache !== undefined,
500
+ routes, statusPages, globalStyles, assets, styleUrls: client.styleUrls,
501
+ })
502
+ setPrunedClientCss(options.cache, consolidated.pruned)
503
+ await host.precompressOutput()
504
+
505
+ const manifest: BuildManifest = {
506
+ runtimeScript: client.runtimeScript, regionScript: client.regionScript, reviveScript: client.reviveScript, chunkImports: client.chunkImports, runtimeOnEveryPage: plugins.some(p => Boolean(p.clientEntry)),
507
+ styles: client.styleUrls,
508
+ globalStyles,
509
+ ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
510
+ routes,
511
+ ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
512
+ errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
513
+ notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
514
+ ...(statusPages.length > 0 ? { statusPages } : {}),
515
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
516
+ actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
517
+ islands: Object.fromEntries(client.islandChunks),
518
+ assets,
519
+ publicFiles: publicFiles.files,
520
+ ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
521
+ }
522
+ const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
523
+ writeManifest()
524
+ const analyzeOrigins = wantsAnalyze
525
+ ? islandOrigins(islands, client.islandChunks, graph, root)
526
+ : undefined
527
+
528
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets: consolidated.emitted, hasNotFoundFile, metafile: client.metafile, analyzeOrigins, outPublicDir })
529
+ return manifest
530
+ }
531
+
532
+ interface BuiltOutput {
533
+ manifest: BuildManifest
534
+ writeManifest: () => void
535
+ host: ReturnType<typeof createPluginHost>
536
+ env: Parameters<typeof pluginBunPlugins>[0]
537
+ assets: string[]
538
+ builtClientAssets: ReadonlySet<string>
539
+ consolidatedCssAssets: ReadonlySet<string>
540
+ hasNotFoundFile: boolean
541
+ metafile: Bun.BuildOutput['metafile']
542
+ analyzeOrigins: ReturnType<typeof islandOrigins> | undefined
543
+ outPublicDir: string
544
+ }
545
+
546
+ function budgetBytes(value: number | string | undefined, key: string): number | undefined {
547
+ if (value === undefined)
548
+ return undefined
549
+ const bytes = parseByteSize(value)
550
+ if (bytes === undefined)
551
+ throw new Error(`prunelle: ${key} in prunelle.config.ts is ${JSON.stringify(value)}, not a size: give bytes or KB, e.g. ${key.endsWith('js') ? '\'40kb\'' : '\'500kb\''}.`)
552
+ return bytes
553
+ }
554
+
555
+ function resolveBudget(maxJs: number | undefined, budget: BudgetConfig | undefined): BuildRun['budget'] {
556
+ const js = budgetBytes(budget?.js, 'budget.js')
557
+ return {
558
+ js: maxJs ?? js,
559
+ jsSource: maxJs !== undefined ? '--max-js' : 'budget.js',
560
+ firstLoad: budgetBytes(budget?.firstLoad, 'budget.firstLoad'),
561
+ }
562
+ }
563
+
564
+ function wantsBundleAnalysis(run: BuildRun): boolean {
565
+ const { options, budget } = run
566
+ return options.analyze === true || options.analyzeJson === true || budget.js !== undefined || budget.firstLoad !== undefined || options.onAnalyze !== undefined
567
+ }
568
+
569
+ function emitBundleAnalysis(run: BuildRun, built: BuiltOutput, clientDir: string, prerenderBaseDir: string | undefined): void {
570
+ const { options, assetPrefix, budget } = run
571
+ if (!wantsBundleAnalysis(run))
572
+ return
573
+ const report = analyzeBundleWeights(built.manifest, clientDir, assetPrefix, built.metafile, built.analyzeOrigins, [built.outPublicDir, run.publicDir], prerenderBaseDir)
574
+ options.onAnalyze?.(report)
575
+ if (options.analyzeJson === true)
576
+ console.log(formatBundleReportJson(report))
577
+ else if (options.analyze === true)
578
+ console.log(formatBundleReport(report))
579
+ if (budget.js !== undefined)
580
+ checkJsBudget(report, budget.js, budget.jsSource)
581
+ if (budget.firstLoad !== undefined)
582
+ checkFirstLoadBudget(report, budget.firstLoad)
583
+ }
584
+
585
+ /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
586
+ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
587
+ const { options, root, plugins, outDir, assetPrefix, isDev, publicFiles } = run
588
+ const { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets, hasNotFoundFile } = built
589
+ const clientDir = join(outDir, 'client')
590
+ const isStatic = options.static === true
591
+
592
+ // Hybrid prerendering / static export (skipped in `prunelle dev`, where routes render on-demand)
593
+ const prerenderRoutes = options.prerender !== false || isStatic ? manifest.routes.filter(r => r.prerender) : []
594
+ const prerenderDir = isStatic ? run.stageDir : join(outDir, 'prerendered')
595
+ const prerendered = prerenderRoutes.length > 0 || isStatic
596
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes, routesDir: run.routesDir })
597
+ : undefined
598
+
599
+ try {
600
+ const staticNotFoundOpts = {
601
+ stageDir: prerenderDir, site: run.site, isDev, manifest, entry: prerendered?.entry,
602
+ pluginOverride: options.plugins, app: prerendered?.app, errorFor: prerendered?.errorFor, hasNotFoundFile,
603
+ }
604
+ if (isStatic)
605
+ await emitStaticNotFoundPages(staticNotFoundOpts)
606
+ const ranAfterPrerender = await host.runAfterPrerender(isStatic ? prerenderDir : outDir)
607
+ recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets, consolidatedCssAssets)
608
+ await host.precompressOutput()
609
+ if (Object.keys(host.pluginData).length > 0)
610
+ manifest.pluginData = host.pluginData
611
+ emitBundleAnalysis(run, built, clientDir, prerendered !== undefined ? (isStatic ? prerenderDir : outDir) : undefined)
612
+
613
+ if (isStatic) {
614
+ await exportStatic({
615
+ ...staticNotFoundOpts,
616
+ root: run.root, finalOutDir: run.finalOutDir, outDir, clientDir, assetPrefix, assets, publicFiles,
617
+ notFoundEmitted: true, stageSuffix: run.stageSuffix,
618
+ })
619
+ }
620
+ else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
621
+ writeManifest()
622
+ }
623
+ }
624
+ finally {
625
+ await prerendered?.app?.dispose?.()
626
+ }
627
+
628
+ if (!isStatic && !isDev) {
629
+ const carried = carryPreviousAssets(run.finalOutDir, outDir, 'client', manifest.assets)
630
+ if (carried.length > 0) {
631
+ manifest.carriedAssets = carried
632
+ writeManifest()
633
+ }
634
+ }
635
+
636
+ if (options.compile) {
637
+ await compileExecutable({
638
+ root,
639
+ outDir,
640
+ clientDir,
641
+ manifest,
642
+ assetPrefix,
643
+ site: options.site !== undefined ? run.site : undefined,
644
+ defaultPort: run.defaultPort,
645
+ outfile: compileOutfile(options.compile, root, outDir, run.finalOutDir),
646
+
647
+ resolvePrunelleSpecifier,
648
+ bunPlugins: pluginBunPlugins(env, 'compile'),
649
+ })
650
+ }
651
+
652
+ if (!isStatic) {
653
+ swapStage(outDir, run.finalOutDir, run.stageSuffix)
654
+ relocateCache(options.cache, outDir, run.finalOutDir)
655
+ }
656
+ }
657
+
658
+ /** Where `--compile` writes the binary: a path inside the output folder goes into the stage, so the swap keeps it. */
659
+ function compileOutfile(compile: string | true, root: string, stageDir: string, finalOutDir: string): string {
660
+ if (compile === true)
661
+ return join(stageDir, 'server-bin')
662
+ const outfile = resolve(root, compile)
663
+ return isInside(finalOutDir, outfile) ? join(stageDir, relative(finalOutDir, outfile)) : outfile
664
+ }
665
+
666
+ /** Points the cache's reusable folders at where the swap moved them, so the next build links from there. */
667
+ function relocateCache(cache: BuildCache | undefined, from: string, to: string): void {
668
+ if (cache === undefined)
669
+ return
670
+ const moved = (dir: string): string => dir.startsWith(from) ? to + dir.slice(from.length) : dir
671
+ if (cache.lastClient !== undefined)
672
+ cache.lastClient.clientDir = moved(cache.lastClient.clientDir)
673
+ if (cache.lastServer !== undefined)
674
+ cache.lastServer.serverDir = moved(cache.lastServer.serverDir)
675
+ const assets = cachedPluginAssets.get(cache)
676
+ if (assets !== undefined)
677
+ assets.clientDir = moved(assets.clientDir)
678
+ }