prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -6,19 +6,23 @@
6
6
  import type { ComplianceConfig } from '../compiler/compliance'
7
7
  import type { AppRuntimeContext } from '../plugins/context'
8
8
  import type { PrunellePlugin } from '../plugins/index'
9
+ import type { BudgetConfig } from '../plugins/types'
9
10
  import type { BuildCache } from './graph'
10
11
  import type { ActionsByFile } from './islands'
11
12
  import type { BuildManifest } from './manifest'
12
13
  import type { PublicFiles } from './plugin-host'
13
14
  import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
14
15
  import { basename, dirname, join, relative, resolve } from 'node:path'
15
- import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
16
+ import { checkAppForms } from '../cli/check-forms'
17
+ import { findCachedRoutePrivateReads } from '../compiler/cacheability'
18
+ import { collectProjectComplianceWarnings, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
16
19
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
17
20
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
18
21
  import { actionHash } from '../server/action'
19
- import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, standaloneCssFiles } from './bundle'
22
+ import { devFromEnv } from '../server/env'
23
+ import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, setPrunedClientCss, standaloneCssFiles } from './bundle'
20
24
  import { compileExecutable } from './compile'
21
- import { assertSafeOutDir, fileSize, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
25
+ import { assertSafeOutDir, fileSize, isHiddenPublicPath, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
22
26
  import { isInside } from './is-inside'
23
27
  import { ModuleGraph } from './graph'
24
28
  import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
@@ -28,17 +32,20 @@ import { createPluginHost, createPublicFiles } from './plugin-host'
28
32
  import { carryPreviousAssets } from './carry'
29
33
  import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
30
34
  import { prerender } from './prerender'
31
- import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
35
+ import { analyzeBundleWeights, checkFirstLoadBudget, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
36
+ import { parseByteSize } from './byte-size'
32
37
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
33
38
  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'
39
+ import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
40
+ import { emitStaticNotFoundPages, exportStatic } from './static'
41
+ import { findUnknownStatusPages } from './status-pages'
42
+ import { consolidateStylesheets } from './style-bundles'
36
43
 
37
44
  export type { BuildCache } from './graph'
38
45
  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'
46
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry, StatusPageKind, StatusPageManifestEntry } from './manifest'
47
+ export { analyzeBundleWeights, checkJsBudget, computeEcoIndex, countDomElements, formatBundleReport, formatBundleReportJson } from './report'
48
+ export type { BundleReport, EcoIndexGrade, RouteBundleMetrics, RouteEcoIndex, RouteIsland } from './report'
42
49
  export { resolvePrunelleSpecifier } from './resolve'
43
50
 
44
51
  export interface BuildOptions {
@@ -49,6 +56,8 @@ export interface BuildOptions {
49
56
  minify?: boolean | undefined
50
57
  assetPrefix?: string | undefined
51
58
  site?: string | undefined
59
+ /** `<html lang>` of every page; defaults to `lang` in `prunelle.config.ts`. */
60
+ lang?: string | undefined
52
61
  plugins?: PrunellePlugin[] | undefined
53
62
  /** Reusable incremental cache for `prunelle dev` (skips re-parsing/re-compiling unchanged files). */
54
63
  cache?: BuildCache | undefined
@@ -56,12 +65,16 @@ export interface BuildOptions {
56
65
  analyze?: boolean | undefined
57
66
  /** Print the `--analyze` bundle weight report as JSON instead of a human-readable table. */
58
67
  analyzeJson?: boolean | undefined
68
+ /** Receives the computed `BundleReport` in-process without printing to stdout (used by `prunelle mcp`). */
69
+ onAnalyze?: ((report: import('./report').BundleReport) => void) | undefined
59
70
  /** Fail the build when a route's eager JS, gzipped, is over this many bytes, naming the route and its islands. */
60
71
  maxJs?: number | undefined
61
72
  /** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
62
73
  static?: boolean | undefined
63
74
  /** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `prunelle dev`). */
64
75
  prerender?: boolean | undefined
76
+ /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
77
+ autoPrerender?: boolean | undefined
65
78
  /** Copy `public/` files into `outDir/public` (default: true; disabled in `prunelle dev` where `public/` is served directly). */
66
79
  copyPublic?: boolean | undefined
67
80
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
@@ -93,10 +106,16 @@ function restoreCachedPluginAssets(cache: BuildCache | undefined, clientDir: str
93
106
  }
94
107
  }
95
108
 
96
- function recordCachedPluginAssets(cache: BuildCache | undefined, clientDir: string, assets: readonly string[], builtClientAssets: ReadonlySet<string>): void {
109
+ function recordCachedPluginAssets(
110
+ cache: BuildCache | undefined,
111
+ clientDir: string,
112
+ assets: readonly string[],
113
+ builtClientAssets: ReadonlySet<string>,
114
+ consolidatedCssAssets: ReadonlySet<string>,
115
+ ): void {
97
116
  if (cache === undefined)
98
117
  return
99
- const files = assets.filter(rel => !builtClientAssets.has(rel))
118
+ const files = assets.filter(rel => !builtClientAssets.has(rel) && !consolidatedCssAssets.has(rel))
100
119
  if (files.length > 0)
101
120
  cachedPluginAssets.set(cache, { clientDir, files })
102
121
  else
@@ -121,7 +140,13 @@ interface BuildRun {
121
140
  stageSuffix: string
122
141
  assetPrefix: string
123
142
  site: string | undefined
143
+ lang: string | undefined
144
+ /** Byte caps from `budget` in `prunelle.config.ts`, `--max-js` taking over `js`. */
145
+ budget: { js: number | undefined, jsSource: string, firstLoad: number | undefined }
146
+ defaultPort: number | undefined
124
147
  compliance: ComplianceConfig | undefined
148
+ consentMaxAge: number | undefined
149
+ autoPrerender: boolean
125
150
  minify: boolean
126
151
  isDev: boolean
127
152
  nodeEnv: string | undefined
@@ -135,7 +160,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
135
160
  }
136
161
 
137
162
  const root = resolve(options.root)
138
- const isDev = options.dev ?? (process.env.PRUNELLE_DEV === '1')
163
+ const isDev = options.dev ?? devFromEnv()
139
164
  const effectiveNodeEnv = options.nodeEnv ?? (isDev ? undefined : (process.env.NODE_ENV ?? 'production'))
140
165
  const fileConfig = await loadConfig(root, { dev: isDev, nodeEnv: effectiveNodeEnv })
141
166
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
@@ -179,7 +204,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
179
204
  stageSuffix,
180
205
  assetPrefix,
181
206
  site,
207
+ lang: options.lang ?? fileConfig.lang,
208
+ budget: resolveBudget(options.maxJs, fileConfig.budget),
209
+ defaultPort: fileConfig.port,
182
210
  compliance: fileConfig.compliance,
211
+ consentMaxAge: fileConfig.consent?.maxAge,
212
+ autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
183
213
  minify: options.minify ?? true,
184
214
  isDev,
185
215
  nodeEnv: effectiveNodeEnv,
@@ -215,7 +245,10 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
215
245
  routeFiles,
216
246
  analyses: graph.analyses,
217
247
  compliance: run.compliance,
248
+ consentMaxAge: run.consentMaxAge,
218
249
  site: run.site,
250
+ lang: run.lang,
251
+ langFromPlugin: pluginSetsLang(run.plugins),
219
252
  })
220
253
  for (const warning of projectWarnings)
221
254
  console.warn(warning)
@@ -246,6 +279,15 @@ function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph,
246
279
  if (missing !== undefined)
247
280
  place(file, missing.offset, `prunelle build: ${missing.message}`)
248
281
  }
282
+ const cacheProblems = findCachedRoutePrivateReads({
283
+ graph,
284
+ pageFiles,
285
+ layoutsFor: file => ancestorFiles(routesDir, file, ['_layout.tsx']),
286
+ toRel: file => relPosix(root, file),
287
+ tool: 'prunelle build',
288
+ })
289
+ for (const problem of cacheProblems)
290
+ place(problem.file, problem.offset, problem.message)
249
291
  if (placed.length > 0)
250
292
  throw new Error(placed.join('\n\n'))
251
293
  return islands
@@ -281,6 +323,81 @@ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles:
281
323
  }
282
324
  }
283
325
 
326
+ function validateRoutesAndMatchers(root: string, routesDir: string, allRouteFiles: readonly string[], specialFiles: readonly string[], candidateFiles: readonly string[], graph: ModuleGraph): { pageFiles: string[], customMatchers: Map<string, string> } {
327
+ const unknownStatus = findUnknownStatusPages(root, allRouteFiles)
328
+ if (unknownStatus.length > 0)
329
+ throw new Error(`prunelle build: ${unknownStatus[0]!.message}`)
330
+ const routesRel = relPosix(root, routesDir)
331
+ for (const f of [...specialFiles, ...candidateFiles]) {
332
+ const analysis = graph.analyses.get(f)!
333
+ const problem = routeFileProblem(analysis, relPosix(root, f), routesRel) ?? routeExportProblem(analysis, relPosix(root, f))
334
+ if (problem !== undefined)
335
+ throw new Error(`prunelle build: ${problem}`)
336
+ }
337
+ // A file exporting only actions stays in routes/ for its folder's middleware.
338
+ const pageFiles = candidateFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
339
+ assertNoRouteConflicts(root, routesDir, pageFiles)
340
+ const { customFiles, problems } = discoverRouteMatchers({
341
+ root,
342
+ routesDir,
343
+ routeFiles: [...specialFiles, ...pageFiles],
344
+ loadAnalysis: file => graph.load(file),
345
+ })
346
+ if (problems.length > 0)
347
+ throw new Error(`prunelle build: ${problems[0]!.message}`)
348
+ return { pageFiles, customMatchers: customFiles }
349
+ }
350
+
351
+ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: string): ActionsByFile {
352
+ const actionsByFile: ActionsByFile = new Map()
353
+ for (const [file, analysis] of graph.analyses) {
354
+ if (analysis.exportedActions.length > 0) {
355
+ const rel = relPosix(root, file)
356
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
357
+ exportName,
358
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
359
+ })))
360
+ }
361
+ }
362
+ return actionsByFile
363
+ }
364
+
365
+ function copyPublicFiles(publicDir: string, outPublicDir: string, publicFiles: PublicFiles, copyPublic: boolean): void {
366
+ for (const abs of walkAllFiles(publicDir).sort()) {
367
+ const rel = relative(publicDir, abs)
368
+ if (isHiddenPublicPath(rel))
369
+ continue
370
+ publicFiles.register(rel)
371
+ if (copyPublic) {
372
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
373
+ copyFileSync(abs, join(outPublicDir, rel))
374
+ }
375
+ }
376
+ }
377
+
378
+ function collectNonEmptyClientAssets(clientDir: string, assetFiles: readonly string[]): { assets: string[], builtClientAssets: Set<string> } {
379
+ const assets: string[] = []
380
+ for (const rel of 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
+ return { assets, builtClientAssets: new Set(assets) }
389
+ }
390
+
391
+ async function validateAppForms(run: BuildRun, routeFiles: readonly string[], graph: ModuleGraph): Promise<void> {
392
+ const formCheck = await checkAppForms({ root: run.root, routesDir: run.routesDir, routeFiles, graph, compliance: run.compliance })
393
+ if (formCheck.errors.length > 0)
394
+ throw new Error(formCheck.errors.join('\n'))
395
+ if (!run.isDev) {
396
+ for (const warning of formCheck.warnings)
397
+ console.warn(warning)
398
+ }
399
+ }
400
+
284
401
  async function runBuild(run: BuildRun): Promise<BuildManifest> {
285
402
  const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
286
403
  const clientDir = join(outDir, 'client')
@@ -306,30 +423,12 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
306
423
  graph.load(f)
307
424
  emitBuildWarnings(run, graph, allRouteFiles)
308
425
 
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
- }
426
+ const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
427
+ const customMatcherFiles = [...new Set(customMatchers.values())]
331
428
 
429
+ const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
332
430
  const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
431
+ await validateAppForms(run, allRouteFiles, graph)
333
432
 
334
433
  mkdirSync(clientDir, { recursive: true })
335
434
  mkdirSync(serverDir, { recursive: true })
@@ -337,19 +436,21 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
337
436
  .flatMap(p => p.css ?? [])
338
437
  .map(c => resolve(root, c))
339
438
  .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 }
439
+ const wantsAnalyze = wantsBundleAnalysis(run)
440
+ 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 }
341
441
 
342
442
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
343
443
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
344
444
  // `_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
445
+ const bundledModules = [...specialFiles, ...pageFiles, ...standaloneActionFiles, ...customMatcherFiles]
446
+ const serverEntries = [...bundledModules, ...(hasConfigFile ? [configSrc] : [])]
447
+ const serverRoot = standaloneActionFiles.length > 0 || customMatcherFiles.length > 0 || hasConfigFile ? root : routesDir
347
448
  const toOutRel = (srcFile: string): string =>
348
449
  relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
349
450
  const serverEntry = {
350
451
  file: join(serverRoot, SERVER_ENTRY_FILE),
351
452
  source: serverEntrySource({
352
- modules: [...specialFiles, ...pageFiles, ...standaloneActionFiles].map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
453
+ modules: bundledModules.map(file => ({ file, key: toOutRel(file), source: relPosix(root, file) })),
353
454
  config: hasConfigFile ? { file: configSrc, source: relPosix(root, configSrc) } : undefined,
354
455
  assembler: join(PRUNELLE_SRC_ROOT, 'server/app-entry.ts'),
355
456
  }),
@@ -376,60 +477,31 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
376
477
  if (options.cache !== undefined)
377
478
  refreshCacheWatches(options.cache, graph, [...pluginCssFiles, ...(hasConfigFile ? [configSrc] : [])])
378
479
 
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)
480
+ const { assets, builtClientAssets } = collectNonEmptyClientAssets(clientDir, client.assetFiles)
389
481
 
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,
482
+ const { routes, statusPages, globalStyles, routeSourceFiles, globalSourceFiles } = buildRouteEntries({
483
+ graph, islands, islandChunks: client.islandChunks, srcCssToUrl: client.srcCssToUrl, islandCssUrl: client.islandCssUrl,
484
+ routesDir, pageFiles, specialFiles, pluginCssFiles, isStatic, autoPrerender: run.autoPrerender, toOutRel,
401
485
  })
486
+ const paramMatchers = customMatchers.size > 0
487
+ ? Object.fromEntries([...customMatchers.entries()].map(([name, file]) => [name, toOutRel(file)]))
488
+ : undefined
402
489
 
403
490
  // public/ files are listed in the manifest and copied into outDir/public (`prunelle dev` serves public/ directly instead)
404
491
  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
- }
492
+ copyPublicFiles(run.publicDir, outPublicDir, publicFiles, options.copyPublic !== false)
412
493
 
413
494
  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,
495
+ plugins, appCtx: run.appCtx, root, outDir, clientDir, outPublicDir, assetPrefix, site: run.site, minify: run.minify,
496
+ isStatic, isDev, routes, statusPages, routeSourceFiles, globalSourceFiles, publicFiles, assets, styleUrls: client.styleUrls, globalStyles,
430
497
  })
431
498
  await host.runBuild()
432
499
  restoreCachedPluginAssets(options.cache, clientDir, assets, anyPassSkipped)
500
+ const consolidated = consolidateStylesheets({
501
+ clientDir, assetPrefix, minify: run.minify, isDev, srcCssToUrl: client.srcCssToUrl, capturePruned: options.cache !== undefined,
502
+ routes, statusPages, globalStyles, assets, styleUrls: client.styleUrls,
503
+ })
504
+ setPrunedClientCss(options.cache, consolidated.pruned)
433
505
  await host.precompressOutput()
434
506
 
435
507
  const manifest: BuildManifest = {
@@ -438,10 +510,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
438
510
  globalStyles,
439
511
  ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
440
512
  routes,
441
-
442
513
  ...(hasRootLayout ? { rootLayoutFile: toOutRel(rootLayoutSrc) } : {}),
443
514
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
444
515
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
516
+ ...(statusPages.length > 0 ? { statusPages } : {}),
517
+ ...(paramMatchers !== undefined ? { paramMatchers } : {}),
445
518
  actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
446
519
  islands: Object.fromEntries(client.islandChunks),
447
520
  assets,
@@ -450,17 +523,11 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
450
523
  }
451
524
  const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
452
525
  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
- }
526
+ const analyzeOrigins = wantsAnalyze
527
+ ? islandOrigins(islands, client.islandChunks, graph, root)
528
+ : undefined
462
529
 
463
- await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile })
530
+ await landBuild(run, { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets: consolidated.emitted, hasNotFoundFile, metafile: client.metafile, analyzeOrigins, outPublicDir })
464
531
  return manifest
465
532
  }
466
533
 
@@ -471,13 +538,56 @@ interface BuiltOutput {
471
538
  env: Parameters<typeof pluginBunPlugins>[0]
472
539
  assets: string[]
473
540
  builtClientAssets: ReadonlySet<string>
541
+ consolidatedCssAssets: ReadonlySet<string>
474
542
  hasNotFoundFile: boolean
543
+ metafile: Bun.BuildOutput['metafile']
544
+ analyzeOrigins: ReturnType<typeof islandOrigins> | undefined
545
+ outPublicDir: string
546
+ }
547
+
548
+ function budgetBytes(value: number | string | undefined, key: string): number | undefined {
549
+ if (value === undefined)
550
+ return undefined
551
+ const bytes = parseByteSize(value)
552
+ if (bytes === undefined)
553
+ 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\''}.`)
554
+ return bytes
555
+ }
556
+
557
+ function resolveBudget(maxJs: number | undefined, budget: BudgetConfig | undefined): BuildRun['budget'] {
558
+ const js = budgetBytes(budget?.js, 'budget.js')
559
+ return {
560
+ js: maxJs ?? js,
561
+ jsSource: maxJs !== undefined ? '--max-js' : 'budget.js',
562
+ firstLoad: budgetBytes(budget?.firstLoad, 'budget.firstLoad'),
563
+ }
564
+ }
565
+
566
+ function wantsBundleAnalysis(run: BuildRun): boolean {
567
+ const { options, budget } = run
568
+ return options.analyze === true || options.analyzeJson === true || budget.js !== undefined || budget.firstLoad !== undefined || options.onAnalyze !== undefined
569
+ }
570
+
571
+ function emitBundleAnalysis(run: BuildRun, built: BuiltOutput, clientDir: string, prerenderBaseDir: string | undefined): void {
572
+ const { options, assetPrefix, budget } = run
573
+ if (!wantsBundleAnalysis(run))
574
+ return
575
+ const report = analyzeBundleWeights(built.manifest, clientDir, assetPrefix, built.metafile, built.analyzeOrigins, [built.outPublicDir, run.publicDir], prerenderBaseDir)
576
+ options.onAnalyze?.(report)
577
+ if (options.analyzeJson === true)
578
+ console.log(formatBundleReportJson(report))
579
+ else if (options.analyze === true)
580
+ console.log(formatBundleReport(report))
581
+ if (budget.js !== undefined)
582
+ checkJsBudget(report, budget.js, budget.jsSource)
583
+ if (budget.firstLoad !== undefined)
584
+ checkFirstLoadBudget(report, budget.firstLoad)
475
585
  }
476
586
 
477
587
  /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
478
588
  async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
479
589
  const { options, root, plugins, outDir, assetPrefix, isDev, publicFiles } = run
480
- const { manifest, writeManifest, host, env, assets, builtClientAssets, hasNotFoundFile } = built
590
+ const { manifest, writeManifest, host, env, assets, builtClientAssets, consolidatedCssAssets, hasNotFoundFile } = built
481
591
  const clientDir = join(outDir, 'client')
482
592
  const isStatic = options.static === true
483
593
 
@@ -485,34 +595,28 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
485
595
  const prerenderRoutes = options.prerender !== false || isStatic ? manifest.routes.filter(r => r.prerender) : []
486
596
  const prerenderDir = isStatic ? run.stageDir : join(outDir, 'prerendered')
487
597
  const prerendered = prerenderRoutes.length > 0 || isStatic
488
- ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes })
598
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes, routesDir: run.routesDir })
489
599
  : undefined
490
600
 
491
601
  try {
492
- const ranAfterPrerender = await host.runAfterPrerender()
493
- recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets)
602
+ const staticNotFoundOpts = {
603
+ stageDir: prerenderDir, site: run.site, isDev, manifest, entry: prerendered?.entry,
604
+ pluginOverride: options.plugins, app: prerendered?.app, errorFor: prerendered?.errorFor, hasNotFoundFile,
605
+ }
606
+ if (isStatic)
607
+ await emitStaticNotFoundPages(staticNotFoundOpts)
608
+ const ranAfterPrerender = await host.runAfterPrerender(isStatic ? prerenderDir : outDir)
609
+ recordCachedPluginAssets(options.cache, clientDir, assets, builtClientAssets, consolidatedCssAssets)
494
610
  await host.precompressOutput()
495
611
  if (Object.keys(host.pluginData).length > 0)
496
612
  manifest.pluginData = host.pluginData
613
+ emitBundleAnalysis(run, built, clientDir, prerendered !== undefined ? (isStatic ? prerenderDir : outDir) : undefined)
497
614
 
498
615
  if (isStatic) {
499
616
  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,
617
+ ...staticNotFoundOpts,
618
+ root: run.root, finalOutDir: run.finalOutDir, outDir, clientDir, assetPrefix, assets, publicFiles,
619
+ notFoundEmitted: true, stageSuffix: run.stageSuffix,
516
620
  })
517
621
  }
518
622
  else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
@@ -539,6 +643,7 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
539
643
  manifest,
540
644
  assetPrefix,
541
645
  site: options.site !== undefined ? run.site : undefined,
646
+ defaultPort: run.defaultPort,
542
647
  outfile: compileOutfile(options.compile, root, outDir, run.finalOutDir),
543
648
 
544
649
  resolvePrunelleSpecifier,