prunelle 0.1.1 → 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 (105) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  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/attrs.ts +11 -3
  7. package/src/build/bundle.ts +80 -36
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +56 -6
  11. package/src/build/compile.ts +11 -9
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +174 -108
  14. package/src/build/islands.ts +2 -2
  15. package/src/build/manifest.ts +66 -5
  16. package/src/build/output.ts +2 -2
  17. package/src/build/plugin-host.ts +91 -33
  18. package/src/build/precompress.ts +15 -2
  19. package/src/build/prerender.ts +128 -46
  20. package/src/build/report.ts +23 -2
  21. package/src/build/resolve.ts +8 -6
  22. package/src/build/routes.ts +175 -10
  23. package/src/build/static.ts +137 -39
  24. package/src/build/status-pages.ts +127 -0
  25. package/src/build/style-bundles.ts +526 -0
  26. package/src/cli/check-forms.ts +654 -0
  27. package/src/cli/check-links.ts +619 -0
  28. package/src/cli/check.ts +52 -5
  29. package/src/cli/commands.ts +86 -4
  30. package/src/cli/docs.ts +402 -0
  31. package/src/cli/inspect.ts +31 -2
  32. package/src/cli/mcp-tools.ts +480 -0
  33. package/src/cli/mcp.ts +205 -0
  34. package/src/cli/new.ts +2 -2
  35. package/src/cli/render.ts +261 -0
  36. package/src/cli/upgrade-names.ts +73 -13
  37. package/src/cli/upgrade.ts +137 -16
  38. package/src/compiler/analyze.ts +20 -6
  39. package/src/compiler/cacheability.ts +592 -0
  40. package/src/compiler/compliance-rgaa.ts +502 -0
  41. package/src/compiler/compliance.ts +120 -221
  42. package/src/compiler/dev-source.ts +87 -0
  43. package/src/compiler/dom-attrs.ts +138 -65
  44. package/src/compiler/dom.ts +12 -11
  45. package/src/compiler/expr-context.ts +167 -57
  46. package/src/compiler/props.ts +87 -36
  47. package/src/compiler/scope.ts +56 -17
  48. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  49. package/src/compiler/ssr.ts +216 -84
  50. package/src/dev/error-log.ts +151 -0
  51. package/src/dev/index.ts +84 -34
  52. package/src/dev/open-editor.ts +204 -0
  53. package/src/dev/protocol.ts +1 -0
  54. package/src/dev/reload.ts +5 -3
  55. package/src/dev/supervisor.ts +42 -25
  56. package/src/dev/watchers.ts +47 -11
  57. package/src/dom/action.ts +4 -1
  58. package/src/dom/attrs.ts +15 -3
  59. package/src/dom/extras.ts +2 -2
  60. package/src/dom/island.ts +11 -10
  61. package/src/plugins/config.ts +4 -4
  62. package/src/plugins/index.ts +2 -2
  63. package/src/plugins/public.ts +5 -2
  64. package/src/plugins/services.ts +62 -0
  65. package/src/plugins/types.ts +32 -0
  66. package/src/server/action-protect.ts +198 -0
  67. package/src/server/action-registry.ts +1 -1
  68. package/src/server/action.ts +82 -27
  69. package/src/server/assets.ts +34 -2
  70. package/src/server/compress.ts +91 -9
  71. package/src/server/errors.ts +303 -65
  72. package/src/server/form-schema.ts +343 -0
  73. package/src/server/health.ts +244 -0
  74. package/src/server/http.ts +128 -31
  75. package/src/server/index.ts +230 -260
  76. package/src/server/loader.ts +5 -0
  77. package/src/server/param-matchers.ts +112 -0
  78. package/src/server/plugin-host.ts +123 -88
  79. package/src/server/public.ts +3 -3
  80. package/src/server/rate-limit.ts +58 -35
  81. package/src/server/request-body.ts +1 -1
  82. package/src/server/route-cache.ts +423 -0
  83. package/src/server/route-table.ts +339 -8
  84. package/src/server/router.ts +125 -40
  85. package/src/server/routing.ts +196 -63
  86. package/src/server/security.ts +208 -32
  87. package/src/server/serve-handlers.ts +21 -7
  88. package/src/server/start.ts +60 -16
  89. package/src/server/static-dir.ts +61 -8
  90. package/src/server/stream.ts +41 -22
  91. package/src/ssr/context.ts +85 -3
  92. package/src/ssr/index.ts +120 -1
  93. package/src/ssr/region.ts +31 -19
  94. package/src/test/browser.ts +6 -0
  95. package/src/test/index.ts +17 -3
  96. package/src/ts-plugin/diagnostics.ts +378 -0
  97. package/src/ts-plugin/fixes.ts +364 -0
  98. package/src/ts-plugin/index.ts +194 -0
  99. package/templates/_shared/AGENTS.md +2 -2
  100. package/templates/_shared/mcp.json +11 -0
  101. package/templates/_shared/src/routes/legal.tsx +5 -0
  102. package/templates/_shared/tsconfig.json +5 -0
  103. package/templates/blog/prunelle.config.ts +1 -1
  104. package/templates/blog/src/routes/index.tsx +4 -0
  105. package/ts-plugin.cjs +4277 -0
@@ -12,11 +12,13 @@ import type { BuildManifest } from './manifest'
12
12
  import type { PublicFiles } from './plugin-host'
13
13
  import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
14
  import { basename, dirname, join, relative, resolve } from 'node:path'
15
+ import { checkAppForms } from '../cli/check-forms'
16
+ import { findCachedRoutePrivateReads } from '../compiler/cacheability'
15
17
  import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
16
18
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
17
19
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
18
20
  import { actionHash } from '../server/action'
19
- import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, standaloneCssFiles } from './bundle'
21
+ import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, setPrunedClientCss, standaloneCssFiles } from './bundle'
20
22
  import { compileExecutable } from './compile'
21
23
  import { assertSafeOutDir, fileSize, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
22
24
  import { isInside } from './is-inside'
@@ -31,14 +33,16 @@ import { prerender } from './prerender'
31
33
  import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
32
34
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
33
35
  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
+ 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'
36
40
 
37
41
  export type { BuildCache } from './graph'
38
42
  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'
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'
42
46
  export { resolvePrunelleSpecifier } from './resolve'
43
47
 
44
48
  export interface BuildOptions {
@@ -56,12 +60,16 @@ export interface BuildOptions {
56
60
  analyze?: boolean | undefined
57
61
  /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
58
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
59
65
  /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
60
66
  maxJs?: number | undefined
61
67
  /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
62
68
  static?: boolean | undefined
63
69
  /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
64
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
65
73
  /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
66
74
  copyPublic?: boolean | undefined
67
75
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
@@ -93,10 +101,16 @@ function restoreCachedPluginAssets(cache: BuildCache | undefined, clientDir: str
93
101
  }
94
102
  }
95
103
 
96
- function recordCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: readonly string[], builtClientAssets: ReadonlySet<string>): void {
104
+ function recordCachedPluginAssets(
105
+ cache: BuildCache | undefined,
106
+ clientDir: string,
107
+ assets: readonly string[],
108
+ builtClientAssets: ReadonlySet<string>,
109
+ consolidatedCssAssets: ReadonlySet<string>,
110
+ ): void {
97
111
  if (cache === undefined)
98
112
  return
99
- const files = assets.filter(rel => !builtClientAssets.has(rel))
113
+ const files = assets.filter(rel => !builtClientAssets.has(rel) && !consolidatedCssAssets.has(rel))
100
114
  if (files.length > 0)
101
115
  cachedPluginAssets.set(cache, { clientDir, files })
102
116
  else
@@ -121,7 +135,9 @@ interface BuildRun {
121
135
  stageSuffix: string
122
136
  assetPrefix: string
123
137
  site: string | undefined
138
+ defaultPort: number | undefined
124
139
  compliance: ComplianceConfig | undefined
140
+ autoPrerender: boolean
125
141
  minify: boolean
126
142
  isDev: boolean
127
143
  nodeEnv: string | undefined
@@ -179,7 +195,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
179
195
  stageSuffix,
180
196
  assetPrefix,
181
197
  site,
198
+ defaultPort: fileConfig.port,
182
199
  compliance: fileConfig.compliance,
200
+ autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
183
201
  minify: options.minify ?? true,
184
202
  isDev,
185
203
  nodeEnv: effectiveNodeEnv,
@@ -246,6 +264,15 @@ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph,
246
264
  if (missing !== undefined)
247
265
  place(file, missing.offset, `prunelle build: ${missing.message}`)
248
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)
249
276
  if (placed.length > 0)
250
277
  throw new Error(placed.join('\n\n'))
251
278
  return islands
@@ -281,6 +308,78 @@ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles:
281
308
  }
282
309
  }
283
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
+
284
383
  async function runBuild(run: BuildRun): Promise<BuildManifest> {
285
384
  const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
286
385
  const clientDir = join(outDir, 'client')
@@ -306,30 +405,12 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
306
405
  graph.load(f)
307
406
  emitBuildWarnings(run, graph, allRouteFiles)
308
407
 
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
- }
408
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
409
+ const customMatcherFiles = [...new Set(customMatchers.values())]
331
410
 
411
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
332
412
  const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
413
+ await validateAppForms(root, routesDir, allRouteFiles, graph, isDev)
333
414
 
334
415
  mkdirSync(clientDir, { recursive: true })
335
416
  mkdirSync(serverDir, { recursive: true })
@@ -337,19 +418,21 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
337
418
  .flatMap(p => p.css ?? [])
338
419
  .map(c => resolve(root, c))
339
420
  .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 }
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 }
341
423
 
342
424
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
343
425
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
344
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.
345
- const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...(hasConfigFile ? [configSrc] : [])]
346
- const serverRoot = standaloneActionFiles.length > 0 || hasConfigFile ? root : routesDir
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
347
430
  const toOutRel = (srcFile: string): string =>
348
431
  relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
349
432
  const serverEntry = {
350
433
  file: join(serverRoot, SERVER_ENTRY_FILE),
351
434
  source: serverEntrySource({
352
- modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
435
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
353
436
  config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
354
437
  assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
355
438
  }),
@@ -376,60 +459,31 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
376
459
  if (options.cache !== undefined)
377
460
  refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
378
461
 
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)
462
+ const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, client.assetFiles)
389
463
 
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,
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,
401
467
  })
468
+ const paramMatchers = customMatchers.size > 0
469
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
470
+ : undefined
402
471
 
403
472
  // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
404
473
  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
- }
474
+ copyPublicFiles(run.publicDir, outPublicDir, publicFiles, options.copyPublic !== false)
412
475
 
413
476
  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,
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,
430
479
  })
431
480
  await host.runBuild()
432
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)
433
487
  await host.precompressOutput()
434
488
 
435
489
  const manifest: BuildManifest = {
@@ -438,10 +492,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
438
492
  globalStyles,
439
493
  ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
440
494
  routes,
441
-
442
495
  ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
443
496
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
444
497
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
498
+ ...(statusPages.length > 0 ? { statusPages } : {}),
499
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
445
500
  actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
446
501
  islands: Object.fromEntries(client.islandChunks),
447
502
  assets,
@@ -450,17 +505,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
450
505
  }
451
506
  const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
452
507
  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
- }
508
+ const analyzeOrigins = wantsAnalyze
509
+ ? islandOrigins(islands, client.islandChunks, graph, root)
510
+ : undefined
462
511
 
463
- await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile })
512
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets: consolidated.emitted, hasNotFoundFile, metafile: client.metafile, analyzeOrigins, outPublicDir })
464
513
  return manifest
465
514
  }
466
515
 
@@ -471,13 +520,35 @@ interface BuiltOutput {
471
520
  env: Parameters<typeof pluginBunPlugins>[0]
472
521
  assets: string[]
473
522
  builtClientAssets: ReadonlySet<string>
523
+ consolidatedCssAssets: ReadonlySet<string>
474
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)
475
546
  }
476
547
 
477
548
  /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
478
549
  async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
479
550
  const { options, root, plugins, outDir, assetPrefix, isDev, publicFiles } = run
480
- const { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile } = built
551
+ const { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets, hasNotFoundFile } = built
481
552
  const clientDir = join(outDir, 'client')
482
553
  const isStatic = options.static === true
483
554
 
@@ -489,30 +560,24 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
489
560
  : undefined
490
561
 
491
562
  try {
492
- const ranAfterPrerender = await host.runAfterPrerender()
493
- recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets)
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)
494
571
  await host.precompressOutput()
495
572
  if (Object.keys(host.pluginData).length > 0)
496
573
  manifest.pluginData = host.pluginData
574
+ emitBundleAnalysis(run, built, clientDir, prerendered !== undefined ? (isStatic ? prerenderDir : outDir) : undefined)
497
575
 
498
576
  if (isStatic) {
499
577
  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,
578
+ ...staticNotFoundOpts,
579
+ root: run.root, finalOutDir: run.finalOutDir, outDir, clientDir, assetPrefix, assets, publicFiles,
580
+ notFoundEmitted: true, stageSuffix: run.stageSuffix,
516
581
  })
517
582
  }
518
583
  else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
@@ -539,6 +604,7 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
539
604
  manifest,
540
605
  assetPrefix,
541
606
  site: options.site !== undefined ? run.site : undefined,
607
+ defaultPort: run.defaultPort,
542
608
  outfile: compileOutfile(options.compile, root, outDir, run.finalOutDir),
543
609
 
544
610
  resolvePrunelleSpecifier,
@@ -526,8 +526,8 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
526
526
  const load: LoadModule = options.load ?? (file => graph.load(file))
527
527
  const issues: IslandIssue[] = []
528
528
  const targets = new Map<string, IslandTarget>()
529
- // Reserve 'runtime' so an island named Runtime.tsx never overwrites entriesDir/runtime.ts.
530
- const usedIds = new Set<string>(['runtime'])
529
+ // Reserve 'runtime' and 'regions' so an island named Runtime.tsx or Regions.tsx never overwrites entriesDir/runtime.ts or entriesDir/regions.ts.
530
+ const usedIds = new Set<string>(['runtime', 'regions'])
531
531
  const pageSet = new Set(pageFiles)
532
532
 
533
533
  function registerIsland(file: string, exportName: string, local?: string): IslandTarget {
@@ -1,11 +1,17 @@
1
1
  // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
2
 
3
+ import type { RouteCacheSpec } from '../server/route-cache'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
6
+ import type { StatusPageManifestEntry } from './status-pages'
5
7
  import { join } from 'node:path'
8
+ import { isRouteCacheable } from '../compiler/cacheability'
6
9
  import { isInside } from './is-inside'
7
10
  import { islandKey } from './islands'
8
11
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
12
+ import { buildStatusPageEntries } from './status-pages'
13
+
14
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
9
15
 
10
16
  const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
17
 
@@ -38,6 +44,10 @@ export interface RouteManifestEntry {
38
44
  /** The route, a layout or a component it renders imports `<Region>`. */
39
45
  usesRegion?: boolean | undefined
40
46
  prerender?: boolean | undefined
47
+ /** Route response cache policy from `export const cache = ...`. */
48
+ cache?: RouteCacheSpec | undefined
49
+ /** True when static analysis proves the page reads nothing from the request or clock. */
50
+ cacheable?: boolean | undefined
41
51
  prerendered?: Record<string, string> | undefined
42
52
  /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
43
53
  prerenderedStyleHashes?: Record<string, string[]> | undefined
@@ -63,6 +73,10 @@ export interface BuildManifest {
63
73
  rootLayoutFile?: string | undefined
64
74
  errorFile?: string | undefined
65
75
  notFoundFile?: string | undefined
76
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
77
+ statusPages?: StatusPageManifestEntry[] | undefined
78
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
79
+ paramMatchers?: Record<string, string> | undefined
66
80
  actions: ActionManifestEntry[]
67
81
  islands: Record<string, string>
68
82
  assets: string[]
@@ -78,6 +92,8 @@ interface FileReach {
78
92
  chunks: Set<string>
79
93
  eager: Set<string>
80
94
  styles: Set<string>
95
+ /** All reachable source files (`.ts`/`.tsx`) walked from this file. */
96
+ files: Set<string>
81
97
  usesRenderContext: boolean
82
98
  usesRegion: boolean
83
99
  }
@@ -167,14 +183,25 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
167
183
  || graph.localDeps(file).some(dep => walkRegion(dep, seen))
168
184
  }
169
185
 
186
+ function walkFiles(file: string, seen: Set<string>): void {
187
+ if (seen.has(file))
188
+ return
189
+ seen.add(file)
190
+ for (const target of islands.pageBindings.get(file)?.values() ?? [])
191
+ walkFiles(target.file, seen)
192
+ for (const dep of graph.localDeps(file))
193
+ walkFiles(dep, seen)
194
+ }
195
+
170
196
  // Layouts are shared by many routes, so each file is walked once.
171
197
  const memo = new Map<string, FileReach>()
172
198
  return (file: string): FileReach => {
173
199
  let reach = memo.get(file)
174
200
  if (reach === undefined) {
175
- reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
201
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), files: new Set(), usesRenderContext: false, usesRegion: false }
176
202
  walkIslands(file, new Set(), reach)
177
203
  walkStyles(file, new Set(), reach.styles)
204
+ walkFiles(file, reach.files)
178
205
  reach.usesRenderContext = walkRenderContext(file, new Set())
179
206
  reach.usesRegion = walkRegion(file, new Set())
180
207
  memo.set(file, reach)
@@ -185,10 +212,15 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
185
212
 
186
213
  export interface RouteEntries {
187
214
  routes: RouteManifestEntry[]
215
+ statusPages: StatusPageManifestEntry[]
188
216
  /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
217
  globalStyles: string[]
190
218
  /** The plugins' CSS alone. */
191
219
  globalPluginStyles: string[]
220
+ /** Reachable source files for each route path (layouts + page + islands + local deps). */
221
+ routeSourceFiles: Map<string, string[]>
222
+ /** Reachable source files of the root layout and status/error pages. */
223
+ globalSourceFiles: string[]
192
224
  }
193
225
 
194
226
  export function buildRouteEntries(options: {
@@ -199,8 +231,11 @@ export function buildRouteEntries(options: {
199
231
  islandCssUrl: Map<string, string>
200
232
  routesDir: string
201
233
  pageFiles: string[]
234
+ specialFiles?: readonly string[] | undefined
202
235
  pluginCssFiles: string[]
203
236
  isStatic: boolean
237
+ /** Automatically prerender static cacheable pages (no middleware, not `prerender = false`, no `cache` export). */
238
+ autoPrerender?: boolean | undefined
204
239
  /** Maps a source file to its compiled module, relative to the out dir. */
205
240
  toOutRel: (srcFile: string) => string
206
241
  }): RouteEntries {
@@ -210,6 +245,8 @@ export function buildRouteEntries(options: {
210
245
  const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
211
246
  const rootLayout = join(routesDir, '_layout.tsx')
212
247
  const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
248
+ const routeSourceFiles = new Map<string, string[]>()
249
+ const globalSourceSet = new Set<string>(graph.analyses.has(rootLayout) ? reachOf(rootLayout).files : [])
213
250
 
214
251
  const routes = options.pageFiles.map((file): RouteManifestEntry => {
215
252
  const analysis = graph.analyses.get(file)
@@ -218,6 +255,7 @@ export function buildRouteEntries(options: {
218
255
  const chunks = new Set<string>()
219
256
  const eagerChunks = new Set<string>()
220
257
  const styles = new Set<string>(globalPluginStyles)
258
+ const reachableFiles = new Set<string>()
221
259
  let usesRenderContext = false
222
260
  let usesRegion = false
223
261
  for (const src of [...layoutSrcs, file]) {
@@ -228,14 +266,22 @@ export function buildRouteEntries(options: {
228
266
  eagerChunks.add(chunk)
229
267
  for (const style of reach.styles)
230
268
  styles.add(style)
269
+ for (const f of reach.files)
270
+ reachableFiles.add(f)
231
271
  usesRenderContext ||= reach.usesRenderContext
232
272
  usesRegion ||= reach.usesRegion
233
273
  }
274
+ const routePath = fileToRoutePath(routesDir, file)
275
+ routeSourceFiles.set(routePath, [...reachableFiles])
276
+ const middlewareSrcs = ancestorFiles(routesDir, file, MIDDLEWARE_NAMES)
277
+ const cacheable = isRouteCacheable({ graph, islands, file, layoutSrcs, middlewareCount: middlewareSrcs.length, routePath })
278
+ const cache = analysis?.cache
279
+ const autoPre = options.autoPrerender === true && cacheable && cache === undefined
234
280
  return {
235
- path: fileToRoutePath(routesDir, file),
281
+ path: routePath,
236
282
  file: toOutRel(file),
237
283
  layouts: layoutSrcs.map(toOutRel),
238
- middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
284
+ middlewares: middlewareSrcs.map(toOutRel),
239
285
  hasLoad: analysis?.hasLoadExport,
240
286
  isIsland: page?.interactive,
241
287
  islandChunk: islandChunks.get(`${file}#default`),
@@ -246,10 +292,25 @@ export function buildRouteEntries(options: {
246
292
  styles: [...styles],
247
293
  usesRenderContext,
248
294
  usesRegion,
249
- prerender: analysis?.hasPrerender || options.isStatic,
295
+ prerender: analysis?.hasPrerender || options.isStatic || autoPre,
296
+ ...(cache !== undefined ? { cache } : {}),
297
+ ...(cacheable ? { cacheable: true } : {}),
250
298
  }
251
299
  })
252
- return { routes, globalStyles, globalPluginStyles }
300
+ for (const special of options.specialFiles ?? []) {
301
+ if (graph.analyses.has(special)) {
302
+ for (const f of reachOf(special).files)
303
+ globalSourceSet.add(f)
304
+ }
305
+ }
306
+ const statusPages = buildStatusPageEntries({
307
+ routesDir,
308
+ specialFiles: options.specialFiles ?? [],
309
+ globalPluginStyles,
310
+ reachOf,
311
+ toOutRel,
312
+ })
313
+ return { routes, statusPages, globalStyles, globalPluginStyles, routeSourceFiles, globalSourceFiles: [...globalSourceSet] }
253
314
  }
254
315
 
255
316
  export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
@@ -16,9 +16,9 @@ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: strin
16
16
  const names = new Set(readdirSync(outDir))
17
17
  if (names.size === 0 || names.has(OUTPUT_MARKER))
18
18
  return
19
- // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder.
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder (including a kay v2 export's `_kay/`).
20
20
  const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
- if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
22
22
  return
23
23
  throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
24
  }