prunelle 0.6.0 → 0.7.1

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 (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +25 -16
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +61 -18
  16. package/src/build/island-promote.ts +250 -0
  17. package/src/build/islands.ts +12 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +25 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +37 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +27 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +146 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +60 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +32 -0
  54. package/src/dev/index.ts +17 -7
  55. package/src/dev/open-editor.ts +36 -12
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +28 -6
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +60 -27
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +44 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +56 -8
  86. package/src/server/index.ts +59 -30
  87. package/src/server/loader.ts +10 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +73 -22
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +31 -5
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +64 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -2,10 +2,13 @@
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
4
  import { existsSync, readFileSync, statSync } from 'node:fs'
5
+ import { parseTsx } from '../compiler/analyze'
6
+ import { computeJsxNodes } from '../compiler/ast'
5
7
  import { analyzeModule } from '../compiler/index'
6
8
  import { PrunelleMistake } from '../compiler/mistakes'
7
9
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
8
10
  import { isTsFile, relPosix } from './files'
11
+ import { resolveExportTarget } from './island-promote'
9
12
  import { resolveImportPath } from './resolve'
10
13
 
11
14
  export interface FileStamp {
@@ -41,8 +44,28 @@ export interface BuildCacheStats {
41
44
  serverSkips: number
42
45
  }
43
46
 
47
+ /** An analysis without the AST and what is keyed by its nodes: the cache outlives a build, the AST (many times the size of the source) does not need to. */
48
+ export type SlimAnalysis = Omit<ModuleAnalysis, 'program' | 'jsxNodes' | 'exprContext'>
49
+
50
+ export function slimAnalysis(analysis: ModuleAnalysis): SlimAnalysis {
51
+ const { program: _program, jsxNodes: _jsxNodes, exprContext: _exprContext, ...slim } = analysis
52
+ return slim
53
+ }
54
+
55
+ /** The analysis again, its program and JSX node set parsed together on first use: the node set only matches the program it was computed from. */
56
+ export function reviveAnalysis(slim: SlimAnalysis, code: string): ModuleAnalysis {
57
+ let program: ModuleAnalysis['program'] | undefined
58
+ let jsxNodes: ModuleAnalysis['jsxNodes'] | undefined
59
+ const parsed = (): ModuleAnalysis['program'] => program ??= parseTsx(slim.filename, code)
60
+ return Object.defineProperties({ ...slim } as ModuleAnalysis, {
61
+ program: { get: parsed, enumerable: true, configurable: true },
62
+ jsxNodes: { get: () => jsxNodes ??= slim.hasJsx ? computeJsxNodes(parsed()) : new WeakSet(), enumerable: true, configurable: true },
63
+ exprContext: { value: undefined, writable: true, enumerable: true, configurable: true },
64
+ })
65
+ }
66
+
44
67
  export interface BuildCache {
45
- analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
68
+ analyses: Map<string, FileStamp & { code: string, analysis: SlimAnalysis }>
46
69
  domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
47
70
  ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
48
71
  lastClient?: CachedClientBuild | undefined
@@ -101,7 +124,6 @@ export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolea
101
124
  return true
102
125
  }
103
126
 
104
- const MAX_REEXPORT_DEPTH = 8
105
127
 
106
128
  export class ModuleGraph {
107
129
  readonly analyses = new Map<string, ModuleAnalysis>()
@@ -175,14 +197,14 @@ export class ModuleGraph {
175
197
  const cached = stamp === undefined ? undefined : this.cache?.analyses.get(file)
176
198
  let analysis: ModuleAnalysis
177
199
  if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
178
- analysis = cached.analysis
200
+ analysis = reviveAnalysis(cached.analysis, cached.code)
179
201
  this.sources.set(file, cached.code)
180
202
  }
181
203
  else {
182
204
  const code = this.source(file)
183
205
  analysis = this.analyze(file, code)
184
206
  if (this.cache !== undefined && stamp !== undefined)
185
- this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
207
+ this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis: slimAnalysis(analysis) })
186
208
  }
187
209
  this.analyses.set(file, analysis)
188
210
  for (const dep of this.localDeps(file))
@@ -208,40 +230,8 @@ export class ModuleGraph {
208
230
  }
209
231
  }
210
232
 
211
- /** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
212
- exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
213
- if (depth > MAX_REEXPORT_DEPTH)
214
- return { file, exportName }
215
- const key = `${file}\0${exportName}`
216
- if (seen.has(key))
217
- return { file, exportName }
218
- seen.add(key)
219
-
220
- const analysis = this.load(file)
221
- const direct = analysis.reexports.find(r => r.exported === exportName)
222
- if (direct !== undefined) {
223
- const next = this.resolve(file, direct.source)
224
- if (next !== undefined && isTsFile(next))
225
- return this.exportTarget(next, direct.local, depth + 1, seen)
226
- }
227
-
228
- if (analysis.exportedNames.includes(exportName))
229
- return { file, exportName }
230
-
231
- // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
232
- if (exportName !== 'default') {
233
- for (const re of analysis.reexports) {
234
- if (re.exported !== '*')
235
- continue
236
- const next = this.resolve(file, re.source)
237
- if (next === undefined || !isTsFile(next))
238
- continue
239
- const candidate = this.exportTarget(next, exportName, depth + 1, seen)
240
- if (this.load(candidate.file).exportedNames.includes(candidate.exportName))
241
- return candidate
242
- }
243
- }
244
-
245
- return { file, exportName }
233
+ /** The module that declares `exportName`, following re-export chains and loading each file (parse errors are never swallowed). */
234
+ exportTarget(file: string, exportName: string): { file: string, exportName: string } {
235
+ return resolveExportTarget(this, f => this.load(f), file, exportName) ?? { file, exportName }
246
236
  }
247
237
  }
@@ -6,6 +6,7 @@
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'
@@ -14,13 +15,14 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync,
14
15
  import { basename, dirname, join, relative, resolve } from 'node:path'
15
16
  import { checkAppForms } from '../cli/check-forms'
16
17
  import { findCachedRoutePrivateReads } from '../compiler/cacheability'
17
- import { collectProjectComplianceWarnings, shouldEmitWarning } from '../compiler/compliance'
18
+ import { collectProjectComplianceWarnings, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
18
19
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
19
20
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
20
21
  import { actionHash } from '../server/action'
22
+ import { devFromEnv } from '../server/env'
21
23
  import { buildClient, buildServer, linkOrCopyFile, pluginBunPlugins, setPrunedClientCss, standaloneCssFiles } from './bundle'
22
24
  import { compileExecutable } from './compile'
23
- import { assertSafeOutDir, fileSize, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
25
+ import { assertSafeOutDir, fileSize, isHiddenPublicPath, isInNodeModules, relPosix, walkAllFiles, walkRoutes } from './files'
24
26
  import { isInside } from './is-inside'
25
27
  import { ModuleGraph } from './graph'
26
28
  import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
@@ -30,7 +32,8 @@ import { createPluginHost, createPublicFiles } from './plugin-host'
30
32
  import { carryPreviousAssets } from './carry'
31
33
  import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
32
34
  import { prerender } from './prerender'
33
- import { analyzeBundleWeights, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
35
+ import { analyzeBundleWeights, checkFirstLoadBudget, checkJsBudget, formatBundleReport, formatBundleReportJson, islandOrigins } from './report'
36
+ import { parseByteSize } from './byte-size'
34
37
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
35
38
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
36
39
  import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
@@ -53,6 +56,8 @@ export interface BuildOptions {
53
56
  minify?: boolean | undefined
54
57
  assetPrefix?: string | undefined
55
58
  site?: string | undefined
59
+ /** `<html lang>` of every page; defaults to `lang` in `prunelle.config.ts`. */
60
+ lang?: string | undefined
56
61
  plugins?: PrunellePlugin[] | undefined
57
62
  /** Reusable incremental cache for `prunelle dev` (skips re-parsing/re-compiling unchanged files). */
58
63
  cache?: BuildCache | undefined
@@ -135,8 +140,12 @@ interface BuildRun {
135
140
  stageSuffix: string
136
141
  assetPrefix: string
137
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 }
138
146
  defaultPort: number | undefined
139
147
  compliance: ComplianceConfig | undefined
148
+ consentMaxAge: number | undefined
140
149
  autoPrerender: boolean
141
150
  minify: boolean
142
151
  isDev: boolean
@@ -151,7 +160,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
151
160
  }
152
161
 
153
162
  const root = resolve(options.root)
154
- const isDev = options.dev ?? (process.env.PRUNELLE_DEV === '1')
163
+ const isDev = options.dev ?? devFromEnv()
155
164
  const effectiveNodeEnv = options.nodeEnv ?? (isDev ? undefined : (process.env.NODE_ENV ?? 'production'))
156
165
  const fileConfig = await loadConfig(root, { dev: isDev, nodeEnv: effectiveNodeEnv })
157
166
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
@@ -195,8 +204,11 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
195
204
  stageSuffix,
196
205
  assetPrefix,
197
206
  site,
207
+ lang: options.lang ?? fileConfig.lang,
208
+ budget: resolveBudget(options.maxJs, fileConfig.budget),
198
209
  defaultPort: fileConfig.port,
199
210
  compliance: fileConfig.compliance,
211
+ consentMaxAge: fileConfig.consent?.maxAge,
200
212
  autoPrerender: options.autoPrerender ?? fileConfig.autoPrerender ?? false,
201
213
  minify: options.minify ?? true,
202
214
  isDev,
@@ -233,7 +245,10 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
233
245
  routeFiles,
234
246
  analyses: graph.analyses,
235
247
  compliance: run.compliance,
248
+ consentMaxAge: run.consentMaxAge,
236
249
  site: run.site,
250
+ lang: run.lang,
251
+ langFromPlugin: pluginSetsLang(run.plugins),
237
252
  })
238
253
  for (const warning of projectWarnings)
239
254
  console.warn(warning)
@@ -244,6 +259,10 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
244
259
  /** 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
260
  function planCheckedIslands(root: string, routesDir: string, graph: ModuleGraph, pageFiles: string[], specialFiles: string[], isStatic: boolean): ReturnType<typeof planIslands> {
246
261
  const islands = planIslands(graph, root, pageFiles, specialFiles)
262
+ for (const { file, warning } of islands.promotedWarnings) {
263
+ const rel = relPosix(root, file)
264
+ console.warn(formatDiagnostic(formatLoc(rel, graph.source(file), warning.start), warning.message.replaceAll(file, rel), 'warning'))
265
+ }
247
266
  const placed: string[] = []
248
267
  const place = (file: string, offset: number, message: string): void => {
249
268
  const source = graph.source(file)
@@ -349,7 +368,10 @@ function collectActionsByFile(graph: ModuleGraph, root: string, assetPrefix: str
349
368
 
350
369
  function copyPublicFiles(publicDir: string, outPublicDir: string, publicFiles: PublicFiles, copyPublic: boolean): void {
351
370
  for (const abs of walkAllFiles(publicDir).sort()) {
352
- const rel = publicFiles.register(relative(publicDir, abs))
371
+ const rel = relative(publicDir, abs)
372
+ if (isHiddenPublicPath(rel))
373
+ continue
374
+ publicFiles.register(rel)
353
375
  if (copyPublic) {
354
376
  mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
355
377
  copyFileSync(abs, join(outPublicDir, rel))
@@ -370,11 +392,11 @@ function collectNonEmptyClientAssets(clientDir: string, assetFiles: readonly str
370
392
  return { assets, builtClientAssets: new Set(assets) }
371
393
  }
372
394
 
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 })
395
+ async function validateAppForms(run: BuildRun, routeFiles: readonly string[], graph: ModuleGraph): Promise<void> {
396
+ const formCheck = await checkAppForms({ root: run.root, routesDir: run.routesDir, routeFiles, graph, compliance: run.compliance })
375
397
  if (formCheck.errors.length > 0)
376
398
  throw new Error(formCheck.errors.join('\n'))
377
- if (!isDev) {
399
+ if (!run.isDev) {
378
400
  for (const warning of formCheck.warnings)
379
401
  console.warn(warning)
380
402
  }
@@ -410,7 +432,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
410
432
 
411
433
  const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
412
434
  const islands = planCheckedIslands(root, routesDir, graph, pageFiles, specialFiles, isStatic)
413
- await validateAppForms(root, routesDir, allRouteFiles, graph, isDev)
435
+ await validateAppForms(run, allRouteFiles, graph)
414
436
 
415
437
  mkdirSync(clientDir, { recursive: true })
416
438
  mkdirSync(serverDir, { recursive: true })
@@ -418,8 +440,8 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
418
440
  .flatMap(p => p.css ?? [])
419
441
  .map(c => resolve(root, c))
420
442
  .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 }
443
+ const wantsAnalyze = wantsBundleAnalysis(run)
444
+ 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 }
423
445
 
424
446
  const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
425
447
  const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
@@ -527,13 +549,32 @@ interface BuiltOutput {
527
549
  outPublicDir: string
528
550
  }
529
551
 
530
- function wantsBundleAnalysis(options: BuildOptions): boolean {
531
- return options.analyze === true || options.analyzeJson === true || options.maxJs !== undefined || options.onAnalyze !== undefined
552
+ function budgetBytes(value: number | string | undefined, key: string): number | undefined {
553
+ if (value === undefined)
554
+ return undefined
555
+ const bytes = parseByteSize(value)
556
+ if (bytes === undefined)
557
+ 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\''}.`)
558
+ return bytes
559
+ }
560
+
561
+ function resolveBudget(maxJs: number | undefined, budget: BudgetConfig | undefined): BuildRun['budget'] {
562
+ const js = budgetBytes(budget?.js, 'budget.js')
563
+ return {
564
+ js: maxJs ?? js,
565
+ jsSource: maxJs !== undefined ? '--max-js' : 'budget.js',
566
+ firstLoad: budgetBytes(budget?.firstLoad, 'budget.firstLoad'),
567
+ }
568
+ }
569
+
570
+ function wantsBundleAnalysis(run: BuildRun): boolean {
571
+ const { options, budget } = run
572
+ return options.analyze === true || options.analyzeJson === true || budget.js !== undefined || budget.firstLoad !== undefined || options.onAnalyze !== undefined
532
573
  }
533
574
 
534
575
  function emitBundleAnalysis(run: BuildRun, built: BuiltOutput, clientDir: string, prerenderBaseDir: string | undefined): void {
535
- const { options, assetPrefix } = run
536
- if (!wantsBundleAnalysis(options))
576
+ const { options, assetPrefix, budget } = run
577
+ if (!wantsBundleAnalysis(run))
537
578
  return
538
579
  const report = analyzeBundleWeights(built.manifest, clientDir, assetPrefix, built.metafile, built.analyzeOrigins, [built.outPublicDir, run.publicDir], prerenderBaseDir)
539
580
  options.onAnalyze?.(report)
@@ -541,8 +582,10 @@ function emitBundleAnalysis(run: BuildRun, built: BuiltOutput, clientDir: string
541
582
  console.log(formatBundleReportJson(report))
542
583
  else if (options.analyze === true)
543
584
  console.log(formatBundleReport(report))
544
- if (options.maxJs !== undefined)
545
- checkJsBudget(report, options.maxJs)
585
+ if (budget.js !== undefined)
586
+ checkJsBudget(report, budget.js, budget.jsSource)
587
+ if (budget.firstLoad !== undefined)
588
+ checkFirstLoadBudget(report, budget.firstLoad)
546
589
  }
547
590
 
548
591
  /** Prerenders, runs the plugins' after-prerender hooks, exports or carries the previous build's dropped files, compiles, then swaps the stage in. */
@@ -556,7 +599,7 @@ async function landBuild(run: BuildRun, built: BuiltOutput): Promise<void> {
556
599
  const prerenderRoutes = options.prerender !== false || isStatic ? manifest.routes.filter(r => r.prerender) : []
557
600
  const prerenderDir = isStatic ? run.stageDir : join(outDir, 'prerendered')
558
601
  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 })
602
+ ? await prerender({ root, outDir, assetPrefix, site: run.site, plugins, pluginOverride: options.plugins, isDev, nodeEnv: run.nodeEnv, isStatic, prerenderDir, routes: prerenderRoutes, routesDir: run.routesDir })
560
603
  : undefined
561
604
 
562
605
  try {
@@ -0,0 +1,250 @@
1
+ // Which modules run in the browser: following re-exports to the binding they name, and promoting what reads an interactive import.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/analyze'
4
+ import type { CompilerWarning } from '../compiler/mistakes'
5
+ import type { IslandIssue } from './islands'
6
+ import type { ModuleGraph } from './graph'
7
+ import { wholeLoadShippedWarning } from '../compiler/analyze'
8
+ import { withStateReads } from '../compiler/interactivity'
9
+ import { isInNodeModules, isTsFile } from './files'
10
+
11
+ export type LoadModule = (file: string) => ModuleAnalysis | undefined
12
+
13
+ export const MAX_REEXPORT_DEPTH = 8
14
+
15
+ /** Follows `export { x } from './y'` and `export * from './y'` chains using `load` so parse errors are never swallowed. */
16
+ export function resolveExportTarget(
17
+ graph: ModuleGraph,
18
+ load: LoadModule,
19
+ file: string,
20
+ exportName: string,
21
+ depth = 0,
22
+ seen = new Set<string>(),
23
+ ): { file: string, exportName: string } | undefined {
24
+ if (depth > MAX_REEXPORT_DEPTH)
25
+ return { file, exportName }
26
+ const key = `${file}\0${exportName}`
27
+ if (seen.has(key))
28
+ return { file, exportName }
29
+ seen.add(key)
30
+
31
+ const analysis = load(file)
32
+ if (analysis === undefined)
33
+ return undefined
34
+ const direct = analysis.reexports.find(r => r.exported === exportName)
35
+ if (direct !== undefined) {
36
+ const next = graph.resolve(file, direct.source)
37
+ if (next !== undefined && isTsFile(next))
38
+ return resolveExportTarget(graph, load, next, direct.local, depth + 1, seen)
39
+ }
40
+
41
+ if (analysis.exportedNames.includes(exportName))
42
+ return { file, exportName }
43
+
44
+ // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
45
+ if (exportName !== 'default') {
46
+ for (const re of analysis.reexports) {
47
+ if (re.exported !== '*')
48
+ continue
49
+ const next = graph.resolve(file, re.source)
50
+ if (next === undefined || !isTsFile(next))
51
+ continue
52
+ const candidate = resolveExportTarget(graph, load, next, exportName, depth + 1, seen)
53
+ if (candidate !== undefined && load(candidate.file)?.exportedNames.includes(candidate.exportName))
54
+ return candidate
55
+ }
56
+ }
57
+
58
+ return { file, exportName }
59
+ }
60
+
61
+ export function moduleHasInteractiveExport(graph: ModuleGraph, load: LoadModule, file: string, seen = new Set<string>()): boolean {
62
+ if (seen.has(file))
63
+ return false
64
+ seen.add(file)
65
+ const analysis = graph.analyses.get(file) ?? load(file)
66
+ if (analysis === undefined)
67
+ return false
68
+ if (analysis.stateExports.length > 0 || [...analysis.exports.values()].some(e => e.interactive))
69
+ return true
70
+ for (const re of analysis.reexports) {
71
+ const next = graph.resolve(file, re.source)
72
+ if (next === undefined || !isTsFile(next))
73
+ continue
74
+ if (re.exported === '*') {
75
+ if (moduleHasInteractiveExport(graph, load, next, seen))
76
+ return true
77
+ }
78
+ else {
79
+ const target = resolveExportTarget(graph, load, next, re.local)
80
+ const targetAnalysis = target === undefined ? undefined : (graph.analyses.get(target.file) ?? load(target.file))
81
+ if (target !== undefined && (targetAnalysis?.stateExports.includes(target.exportName) === true || targetAnalysis?.exports.get(target.exportName)?.interactive === true))
82
+ return true
83
+ }
84
+ }
85
+ return false
86
+ }
87
+
88
+ export function collectExportedSignals(graph: ModuleGraph, load: LoadModule, file: string, out: Set<string>, seen = new Set<string>()): void {
89
+ if (seen.has(file))
90
+ return
91
+ seen.add(file)
92
+ const analysis = graph.analyses.get(file) ?? load(file)
93
+ if (analysis === undefined)
94
+ return
95
+ for (const name of analysis.signalExports)
96
+ out.add(name)
97
+ for (const re of analysis.reexports) {
98
+ const next = graph.resolve(file, re.source)
99
+ if (next === undefined || !isTsFile(next))
100
+ continue
101
+ if (re.exported === '*') {
102
+ collectExportedSignals(graph, load, next, out, seen)
103
+ }
104
+ else {
105
+ const target = resolveExportTarget(graph, load, next, re.local)
106
+ if (target !== undefined && (graph.analyses.get(target.file) ?? load(target.file))?.signalExports.includes(target.exportName) === true)
107
+ out.add(re.exported)
108
+ }
109
+ }
110
+ }
111
+
112
+ function interactivityChanged(prev: ModuleAnalysis, next: { isInteractive: boolean, exports: Map<string, { interactive: boolean }>, localIslands: Map<string, unknown> }): boolean {
113
+ if (prev.isInteractive !== next.isInteractive)
114
+ return true
115
+ for (const [name, fact] of next.exports) {
116
+ if (prev.exports.get(name)?.interactive !== fact.interactive)
117
+ return true
118
+ }
119
+ return next.localIslands.size !== prev.localIslands.size || [...next.localIslands.keys()].some(name => !prev.localIslands.has(name))
120
+ }
121
+
122
+ /** An imported island a module reads as a value (`const D = Counter`, `{ C: Counter }`, `c={Counter}`), which makes what holds it an island. */
123
+ export interface IslandValueUse { file: string, offset: number, name: string }
124
+
125
+ /** A compiler warning that only applies once a module is promoted to an island across files. */
126
+ export interface PromotedWarning { file: string, warning: CompilerWarning }
127
+
128
+ const COMPONENT_NAME_RE = /^[A-Z]/
129
+
130
+ // The first place `analysis` reads `local` as a value, its bindings being in source order.
131
+ const firstValueRead = (analysis: ModuleAnalysis, local: string): number | undefined => analysis.bindings.map(b => b.valueRefs.get(local)).find(offset => offset !== undefined)
132
+
133
+ export function createPromoter(
134
+ graph: ModuleGraph,
135
+ load: LoadModule,
136
+ issues: IslandIssue[],
137
+ valueUses: IslandValueUse[] = [],
138
+ promotedWarnings: PromotedWarning[] = [],
139
+ ): { promoteAll: () => void, loadPromoted: LoadModule } {
140
+ const initialAsyncInteractive = new Set<string>()
141
+ const initialServerOnly = new Set<string>()
142
+ const reportedAsync = new Set<string>()
143
+ const reportedServerOnly = new Set<string>()
144
+ const reportedWholeLoad = new Set<string>()
145
+
146
+ const recordInitial = (file: string, a: ModuleAnalysis): void => {
147
+ if (a.hasAsyncDefault && a.exports.get('default')?.interactive === true)
148
+ initialAsyncInteractive.add(file)
149
+ if (a.serverOnly !== undefined)
150
+ initialServerOnly.add(file)
151
+ }
152
+ for (const [file, a] of graph.analyses)
153
+ recordInitial(file, a)
154
+
155
+ // What an import names: reactive state, an interactive export (a component or a hook), or neither.
156
+ const interactiveKind = (file: string, source: string, imported: string): 'state' | 'export' | undefined => {
157
+ const resolved = graph.resolve(file, source)
158
+ if (resolved === undefined || !isTsFile(resolved))
159
+ return undefined
160
+ if (imported === '*')
161
+ return moduleHasInteractiveExport(graph, load, resolved) ? 'export' : undefined
162
+ const target = resolveExportTarget(graph, load, resolved, imported)
163
+ if (target === undefined)
164
+ return undefined
165
+ const targetAnalysis = graph.analyses.get(target.file) ?? load(target.file)
166
+ if (targetAnalysis?.stateExports.includes(target.exportName) === true)
167
+ return 'state'
168
+ return targetAnalysis?.exports.get(target.exportName)?.interactive === true ? 'export' : undefined
169
+ }
170
+ const isInteractiveTarget = (file: string, source: string, imported: string): boolean => interactiveKind(file, source, imported) !== undefined
171
+
172
+ const reportedValueUses = new Set<string>()
173
+ const recordValueUses = (file: string, analysis: ModuleAnalysis): void => {
174
+ for (const imp of analysis.imports) {
175
+ for (const spec of imp.specifiers) {
176
+ const offset = spec.imported === '*' || !COMPONENT_NAME_RE.test(spec.local) ? undefined : firstValueRead(analysis, spec.local)
177
+ if (offset === undefined || reportedValueUses.has(`${file}#${spec.local}`) || interactiveKind(file, imp.source, spec.imported) !== 'export')
178
+ continue
179
+ reportedValueUses.add(`${file}#${spec.local}`)
180
+ valueUses.push({ file, offset, name: spec.local })
181
+ }
182
+ }
183
+ }
184
+
185
+ const promoteOne = (file: string): boolean => {
186
+ if (isInNodeModules(file) || !isTsFile(file))
187
+ return false
188
+ const analysis = graph.analyses.get(file)
189
+ if (analysis === undefined)
190
+ return false
191
+ const promoted = withStateReads(analysis, (imp, imported) => isInteractiveTarget(file, imp.source, imported))
192
+ if (promoted === undefined)
193
+ return false
194
+ const page = promoted.exports.get('default')
195
+ if (analysis.hasAsyncDefault && page?.interactive === true) {
196
+ if (!initialAsyncInteractive.has(file) && !reportedAsync.has(file)) {
197
+ reportedAsync.add(file)
198
+ issues.push({ kind: 'async-interactive', file, offset: page.offset ?? 0, reason: page.reason })
199
+ }
200
+ return false
201
+ }
202
+ if (promoted.serverOnly !== undefined) {
203
+ if (!initialServerOnly.has(file) && !reportedServerOnly.has(file)) {
204
+ reportedServerOnly.add(file)
205
+ issues.push({ kind: 'server-only-tag', file, serverOnly: promoted.serverOnly })
206
+ }
207
+ return false
208
+ }
209
+ if (!interactivityChanged(analysis, promoted))
210
+ return false
211
+ recordValueUses(file, analysis)
212
+ let nextWarnings = analysis.warnings
213
+ if (analysis.exports.get('default')?.interactive !== true && page?.interactive === true && analysis.hasLoadExport && analysis.defaultDataKeys === undefined && !analysis.exportedNames.includes('clientData') && !reportedWholeLoad.has(file)) {
214
+ reportedWholeLoad.add(file)
215
+ const defaultName = analysis.exportLocals.get('default')
216
+ const start = analysis.bindings.find(b => b.name === defaultName)?.start ?? page.offset ?? 0
217
+ const warning = wholeLoadShippedWarning(file, start)
218
+ promotedWarnings.push({ file, warning })
219
+ nextWarnings = [...analysis.warnings, warning]
220
+ }
221
+ graph.analyses.set(file, { ...analysis, ...promoted, warnings: nextWarnings })
222
+ return true
223
+ }
224
+
225
+ const promoteAll = (): void => {
226
+ for (let pass = 0; pass < MAX_REEXPORT_DEPTH; pass++) {
227
+ let changed = false
228
+ for (const file of [...graph.analyses.keys()]) {
229
+ if (promoteOne(file))
230
+ changed = true
231
+ }
232
+ if (!changed)
233
+ break
234
+ }
235
+ }
236
+
237
+ const loadPromoted: LoadModule = (file: string): ModuleAnalysis | undefined => {
238
+ const existed = graph.analyses.has(file)
239
+ const analysis = graph.analyses.get(file) ?? load(file)
240
+ if (analysis === undefined)
241
+ return undefined
242
+ if (!existed) {
243
+ recordInitial(file, analysis)
244
+ promoteAll()
245
+ }
246
+ return graph.analyses.get(file) ?? analysis
247
+ }
248
+
249
+ return { promoteAll, loadPromoted }
250
+ }