prunelle 0.0.0-stage → 0.5.2

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