prunelle 0.8.0 → 0.9.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 (184) hide show
  1. package/llms.txt +61 -44
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +14 -6
  14. package/src/build/index.ts +20 -10
  15. package/src/build/islands.ts +4 -1
  16. package/src/build/key-types.ts +31 -0
  17. package/src/build/manifest.ts +19 -1
  18. package/src/build/plugin-host.ts +2 -0
  19. package/src/build/prerender.ts +2 -2
  20. package/src/build/reach.ts +14 -1
  21. package/src/build/report.ts +1 -1
  22. package/src/build/route-types.ts +16 -0
  23. package/src/build/routes.ts +24 -15
  24. package/src/build/seed-ids.ts +65 -0
  25. package/src/build/seed-writes.ts +111 -0
  26. package/src/build/static-headers.ts +2 -2
  27. package/src/build/static.ts +1 -1
  28. package/src/cli/check-cache.ts +51 -0
  29. package/src/cli/check-consent.ts +95 -0
  30. package/src/cli/check-forms.ts +2 -2
  31. package/src/cli/check-links-patterns.ts +101 -0
  32. package/src/cli/check-links.ts +16 -100
  33. package/src/cli/check-regions.ts +185 -0
  34. package/src/cli/check-security.ts +50 -6
  35. package/src/cli/check.ts +40 -18
  36. package/src/cli/commands.ts +134 -14
  37. package/src/cli/docs.ts +21 -2
  38. package/src/cli/index.ts +1 -1
  39. package/src/cli/inspect.ts +2 -0
  40. package/src/cli/mcp-tools.ts +2 -2
  41. package/src/cli/new.ts +9 -5
  42. package/src/cli/upgrade-names.ts +14 -2
  43. package/src/cli/upgrade.ts +3 -0
  44. package/src/compiler/analyze.ts +2 -2
  45. package/src/compiler/cacheability.ts +24 -2
  46. package/src/compiler/compliance-contrast.ts +284 -0
  47. package/src/compiler/compliance-empty.ts +24 -0
  48. package/src/compiler/compliance-rgaa-content.ts +95 -0
  49. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  50. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  51. package/src/compiler/compliance-rgaa.ts +19 -0
  52. package/src/compiler/compliance-third-party.ts +59 -0
  53. package/src/compiler/compliance-urls.ts +52 -0
  54. package/src/compiler/compliance.ts +70 -42
  55. package/src/compiler/cookie-inventory.ts +119 -0
  56. package/src/compiler/foreign-imports.ts +5 -3
  57. package/src/compiler/mistakes.ts +18 -9
  58. package/src/compiler/props-pattern.ts +211 -0
  59. package/src/compiler/props.ts +177 -346
  60. package/src/compiler/ssr-emit.ts +510 -0
  61. package/src/compiler/ssr-helpers.ts +170 -121
  62. package/src/compiler/ssr.ts +25 -440
  63. package/src/context.ts +14 -1
  64. package/src/dev/child.ts +1 -1
  65. package/src/dev/hot-islands.ts +71 -0
  66. package/src/dev/index.ts +31 -18
  67. package/src/dev/protocol.ts +1 -1
  68. package/src/dev/queue.ts +3 -2
  69. package/src/dev/reload.ts +1 -1
  70. package/src/dev/supervisor.ts +3 -1
  71. package/src/dev/watchers.ts +6 -2
  72. package/src/dom/action.ts +97 -14
  73. package/src/dom/extras.ts +2 -1
  74. package/src/dom/field-marks.ts +24 -0
  75. package/src/dom/hot.ts +9 -0
  76. package/src/dom/index.ts +25 -5
  77. package/src/dom/island-hot.ts +29 -0
  78. package/src/dom/island.ts +13 -2
  79. package/src/dom/prefetch.ts +132 -0
  80. package/src/dom/regions.ts +498 -0
  81. package/src/dom/swap.ts +245 -0
  82. package/src/dom/trusted.ts +22 -0
  83. package/src/dom/upload.ts +44 -0
  84. package/src/eco/declaration.ts +39 -40
  85. package/src/eco/index.ts +5 -5
  86. package/src/href.ts +31 -0
  87. package/src/index.ts +9 -3
  88. package/src/plugins/config.ts +1 -1
  89. package/src/plugins/context.ts +7 -1
  90. package/src/plugins/daily.ts +27 -0
  91. package/src/plugins/index.ts +3 -3
  92. package/src/plugins/order.ts +1 -1
  93. package/src/plugins/public.ts +8 -5
  94. package/src/plugins/services.ts +88 -14
  95. package/src/plugins/types.ts +120 -9
  96. package/src/reactivity/hmr.ts +90 -0
  97. package/src/reactivity/index.ts +38 -18
  98. package/src/reactivity/resource.ts +115 -0
  99. package/src/reactivity/seed.ts +39 -0
  100. package/src/reactivity/server-seed.ts +194 -0
  101. package/src/reactivity/store.ts +55 -1
  102. package/src/rgpd/draft.ts +171 -0
  103. package/src/rgpd/forms.ts +85 -0
  104. package/src/rgpd/index.ts +57 -0
  105. package/src/server/action-flash.ts +1 -0
  106. package/src/server/action-registry.ts +6 -8
  107. package/src/server/action.ts +51 -19
  108. package/src/server/app-secret.ts +14 -8
  109. package/src/server/cache-invalidation.ts +96 -0
  110. package/src/server/compress.ts +3 -1
  111. package/src/server/consent.ts +16 -2
  112. package/src/server/cookie-inventory.ts +78 -0
  113. package/src/server/cookies.ts +50 -0
  114. package/src/server/csp-report.ts +86 -0
  115. package/src/server/discard.ts +13 -0
  116. package/src/server/document.ts +2 -2
  117. package/src/server/env.ts +1 -1
  118. package/src/server/errors.ts +9 -2
  119. package/src/server/field-errors.ts +91 -0
  120. package/src/server/form-schema.ts +16 -11
  121. package/src/server/health.ts +33 -12
  122. package/src/server/http.ts +25 -10
  123. package/src/server/index.ts +101 -298
  124. package/src/server/loader.ts +1 -0
  125. package/src/server/page.ts +3 -9
  126. package/src/server/plugin-host.ts +26 -8
  127. package/src/server/public.ts +14 -3
  128. package/src/server/rate-limit.ts +39 -10
  129. package/src/server/region.ts +3 -0
  130. package/src/server/request-handler.ts +370 -0
  131. package/src/server/request-log.ts +94 -0
  132. package/src/server/route-cache.ts +41 -6
  133. package/src/server/route-input.ts +54 -0
  134. package/src/server/route-table.ts +35 -19
  135. package/src/server/routing.ts +12 -11
  136. package/src/server/sanitize-html.ts +1 -1
  137. package/src/server/security.ts +38 -8
  138. package/src/server/serve-handlers.ts +9 -5
  139. package/src/server/shared-store.ts +314 -0
  140. package/src/server/start.ts +12 -5
  141. package/src/server/static-dir.ts +14 -10
  142. package/src/server/stream.ts +2 -1
  143. package/src/server/surface.ts +39 -0
  144. package/src/server/webhook.ts +48 -0
  145. package/src/server/workers.ts +168 -0
  146. package/src/ssr/consent-banner.ts +20 -16
  147. package/src/ssr/consent-texts.ts +40 -0
  148. package/src/ssr/context.ts +26 -3
  149. package/src/ssr/cookie-table.ts +75 -0
  150. package/src/ssr/index.ts +23 -13
  151. package/src/ssr/navigation.ts +161 -14
  152. package/src/test/browser.ts +50 -22
  153. package/src/test/build-reuse.ts +70 -0
  154. package/src/test/index.ts +45 -6
  155. package/src/test/mount.ts +53 -0
  156. package/src/test/outside.ts +94 -0
  157. package/templates/_shared/AGENTS.md +1 -1
  158. package/templates/_shared/Dockerfile +22 -0
  159. package/templates/_shared/dockerignore +9 -0
  160. package/templates/_shared/gitignore +2 -0
  161. package/templates/app/.env.example +3 -1
  162. package/templates/app/compose.yaml +32 -0
  163. package/templates/app/db/migrations/001_notes.sql +7 -0
  164. package/templates/app/db/schema.ts +11 -0
  165. package/templates/app/package.json +1 -0
  166. package/templates/app/prunelle.config.ts +6 -0
  167. package/templates/app/src/actions/notes.ts +26 -0
  168. package/templates/app/src/auth.ts +4 -2
  169. package/templates/app/src/db.ts +5 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  171. package/templates/app/src/routes/privacy.tsx +6 -2
  172. package/templates/app/tests/app.test.ts +14 -3
  173. package/templates/plugin/AGENTS.md +11 -0
  174. package/templates/plugin/CLAUDE.md +1 -0
  175. package/templates/plugin/README.md +27 -0
  176. package/templates/plugin/gitignore +2 -0
  177. package/templates/plugin/llms.txt +19 -0
  178. package/templates/plugin/package.json +33 -0
  179. package/templates/plugin/src/index.ts +40 -0
  180. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  181. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  182. package/templates/plugin/tests/plugin.test.ts +42 -0
  183. package/templates/plugin/tsconfig.json +19 -0
  184. package/ts-plugin.cjs +3674 -2196
@@ -15,7 +15,7 @@ import { copyFileSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync,
15
15
  import { basename, dirname, join, relative, resolve } from 'node:path'
16
16
  import { checkAppForms } from '../cli/check-forms'
17
17
  import { findCachedRoutePrivateReads } from '../compiler/cacheability'
18
- import { collectProjectComplianceWarnings, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
18
+ import { collectProjectComplianceWarnings, pluginChecksTitle, pluginSetsLang, shouldEmitWarning } from '../compiler/compliance'
19
19
  import { formatCodeFrame, formatDiagnostic, formatLoc } from '../compiler/shared'
20
20
  import { createAppContext, loadConfig, resolvePlugins, runWithAppContext } from '../plugins/index'
21
21
  import { actionHash } from '../server/action'
@@ -28,7 +28,7 @@ import { ModuleGraph } from './graph'
28
28
  import { nodeEnvWarning, renderProblems, serverNodeEnvReads } from './render-rules'
29
29
  import { formatIslandValueWarnings } from './island-promote'
30
30
  import { planIslands } from './islands'
31
- import { buildActionEntries, buildRouteEntries } from './manifest'
31
+ import { appCookiesOf, buildActionEntries, buildRouteEntries, clientBuildId } from './manifest'
32
32
  import { createPluginHost, createPublicFiles } from './plugin-host'
33
33
  import { carryPreviousAssets } from './carry'
34
34
  import { assertOwnOutDir, processSuffix, removeDeadProcessDirs, removeStaleStages, stageDirFor, swapStage } from './output'
@@ -38,6 +38,7 @@ import { parseByteSize } from './byte-size'
38
38
  import { SERVER_ENTRY_FILE, serverEntrySource } from './server-entry'
39
39
  import { PRUNELLE_SRC_ROOT, resolvePrunelleSpecifier } from './resolve'
40
40
  import { ancestorFiles, assertNoRouteConflicts, discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, missingPathsProblem, normalizeRoutePattern, routeExportProblem, routeFileProblem, SPECIAL_ROUTE_FILES } from './routes'
41
+ import { writeRouteTypes } from './route-types'
41
42
  import { emitStaticNotFoundPages, exportStatic, normalizeAssetPrefix } from './static'
42
43
  import { findUnknownStatusPages } from './status-pages'
43
44
  import { consolidateStylesheets } from './style-bundles'
@@ -209,6 +210,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
209
210
  }
210
211
  }
211
212
 
213
+
212
214
  function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readonly string[]): void {
213
215
  for (const [file, analysis] of graph.analyses) {
214
216
  const rel = relPosix(run.root, file)
@@ -220,7 +222,7 @@ function emitBuildWarnings(run: BuildRun, graph: ModuleGraph, routeFiles: readon
220
222
  }
221
223
  }
222
224
  if (!run.isDev) {
223
- const projectWarnings = collectProjectComplianceWarnings({ root: run.root, srcDir: join(run.root, 'src'), routesDir: run.routesDir, publicDir: run.publicDir, routeFiles, analyses: graph.analyses, compliance: run.compliance, consentMaxAge: run.consentMaxAge, site: run.site, lang: run.lang, langFromPlugin: pluginSetsLang(run.plugins) })
225
+ const projectWarnings = collectProjectComplianceWarnings({ root: run.root, srcDir: join(run.root, 'src'), routesDir: run.routesDir, publicDir: run.publicDir, routeFiles, analyses: graph.analyses, compliance: run.compliance, consentMaxAge: run.consentMaxAge, site: run.site, lang: run.lang, langFromPlugin: pluginSetsLang(run.plugins), titleChecked: pluginChecksTitle(run.plugins) })
224
226
  for (const warning of projectWarnings)
225
227
  console.warn(warning)
226
228
  }
@@ -275,12 +277,7 @@ function refreshCacheWatches(cache: BuildCache, graph: ModuleGraph, extraFiles:
275
277
  const recordWatched = (file: string) => {
276
278
  if (!existsSync(file))
277
279
  return
278
- let real = file
279
- try {
280
- real = realpathSync(file)
281
- }
282
- catch {}
283
- watched.add(real)
280
+ watched.add(realOrSelf(file))
284
281
  }
285
282
  for (const f of graph.analyses.keys())
286
283
  recordWatched(f)
@@ -417,6 +414,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
417
414
  emitBuildWarnings(run, graph, allRouteFiles)
418
415
 
419
416
  const { pageFiles, customMatchers } = validateRoutesAndMatchers(root, routesDir, allRouteFiles, specialFiles, candidateFiles, graph)
417
+ writeRouteTypes(root, routesDir, pageFiles)
420
418
  const customMatcherFiles = [...new Set(customMatchers.values())]
421
419
 
422
420
  const actionsByFile = collectActionsByFile(graph, root, assetPrefix)
@@ -489,7 +487,7 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
489
487
  copyPublicFiles(run.publicDir, outPublicDir, publicFiles, options.copyPublic !== false)
490
488
 
491
489
  const host = createPluginHost({
492
- plugins, appCtx: run.appCtx, root, outDir, clientDir, outPublicDir, assetPrefix, site: run.site, minify: run.minify,
490
+ plugins, appCtx: run.appCtx, root, routesDir, outDir, clientDir, outPublicDir, assetPrefix, site: run.site, minify: run.minify,
493
491
  isStatic, isDev, routes, statusPages, routeSourceFiles, globalSourceFiles, publicFiles, assets, styleUrls: client.styleUrls, globalStyles,
494
492
  })
495
493
  await host.runBuild()
@@ -517,7 +515,9 @@ async function runBuild(run: BuildRun): Promise<BuildManifest> {
517
515
  assets,
518
516
  publicFiles: publicFiles.files,
519
517
  ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
518
+ ...appCookiesOf(graph),
520
519
  }
520
+ manifest.buildId = clientBuildId(manifest)
521
521
  const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
522
522
  writeManifest()
523
523
  const analyzeOrigins = wantsAnalyze
@@ -675,3 +675,13 @@ function relocateCache(cache: BuildCache | undefined, from: string, to: string):
675
675
  if (assets !== undefined)
676
676
  assets.clientDir = moved(assets.clientDir)
677
677
  }
678
+
679
+ // A file removed between the existence check and this call keeps the path it was found at.
680
+ function realOrSelf(file: string): string {
681
+ try {
682
+ return realpathSync(file)
683
+ }
684
+ catch {
685
+ return file
686
+ }
687
+ }
@@ -13,6 +13,7 @@ import { checkBareSignals } from '../compiler/signal-reads'
13
13
  import { clientNeeds, clientView } from './client-prune'
14
14
  import { isInNodeModules, isTsFile, relPosix } from './files'
15
15
  import { collectExportedSignals, createPromoter, resolveExportTarget } from './island-promote'
16
+ import { writesModuleState } from './seed-writes'
16
17
 
17
18
  /** A component that is not an island, as a module renders it. */
18
19
  export interface StaticTag { async: boolean }
@@ -59,6 +60,8 @@ export interface IslandPlan {
59
60
  valueUses: IslandValueUse[]
60
61
  /** Compiler warnings triggered once a route is promoted to an island across files. */
61
62
  promotedWarnings: PromotedWarning[]
63
+ /** Some module could write a module-level signal or store while an island renders on the server, so the page carries what it wrote. */
64
+ seedsModuleState: boolean
62
65
  }
63
66
 
64
67
  export interface AnalyzeIslandsOptions {
@@ -403,7 +406,7 @@ export function analyzeIslands(options: AnalyzeIslandsOptions): IslandPlan {
403
406
  }
404
407
 
405
408
  const { reach, clientFiles, cssFiles } = walkIslandReach(graph, load, [...rootFiles], clientKeep, options.checkLeaks === true, issues)
406
- return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues, valueUses, promotedWarnings }
409
+ return { targets, pageBindings, staticTags, cssFiles, reach, clientFiles, clientKeep, issues, valueUses, promotedWarnings, seedsModuleState: writesModuleState(graph) }
407
410
  }
408
411
 
409
412
  function clientKeepOf(targets: Iterable<IslandTarget>, load: LoadModule): Map<string, Set<string>> {
@@ -0,0 +1,31 @@
1
+ // Declaration files that give an interface one key per entry, written beside the app's routes folder: the route patterns, a plugin's message keys.
2
+ // Kept free of the compiler, so `prunelle/config` can export it to plugins.
3
+
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
5
+ import { dirname, join } from 'node:path'
6
+
7
+ export interface KeyTypes {
8
+ /** The file written beside the routes folder, such as `'prunelle-routes.d.ts'`. */
9
+ file: string
10
+ /** The first line, saying what wrote the file and from what. */
11
+ header: string
12
+ /** The module the interface augments, such as `'prunelle/server'`. */
13
+ module: string
14
+ interface: string
15
+ keys: readonly string[]
16
+ }
17
+
18
+ export function keyTypesSource({ header, module, interface: name, keys }: KeyTypes): string {
19
+ const entries = [...new Set(keys)].sort().map(key => ` ${JSON.stringify(key)}: true`)
20
+ return [`// ${header} Edits are overwritten.`, 'export {}', '', `declare module '${module}' {`, ` interface ${name} {`, ...entries, ' }', '}', ''].join('\n')
21
+ }
22
+
23
+ /** Writes the file beside the routes folder of an app with a tsconfig.json, only when it changed, so a dev rebuild never sets off another. */
24
+ export function writeKeyTypes(root: string, routesDir: string, types: KeyTypes): void {
25
+ if (!existsSync(join(root, 'tsconfig.json')))
26
+ return
27
+ const file = join(dirname(routesDir), types.file)
28
+ const source = keyTypesSource(types)
29
+ if (!existsSync(file) || readFileSync(file, 'utf8') !== source)
30
+ writeFileSync(file, source)
31
+ }
@@ -1,11 +1,13 @@
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 { AppCookie } from '../compiler/cookie-inventory'
3
4
  import type { RouteCacheSpec } from '../server/route-cache'
4
5
  import type { ModuleGraph } from './graph'
5
6
  import type { IslandPlan } from './islands'
6
7
  import type { StatusPageManifestEntry } from './status-pages'
7
8
  import { join } from 'node:path'
8
9
  import { isRouteCacheable } from '../compiler/cacheability'
10
+ import { mergeCookies, scanCookieSets } from '../compiler/cookie-inventory'
9
11
  import { isInside } from './is-inside'
10
12
  import { createReachWalker } from './reach'
11
13
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
@@ -55,8 +57,10 @@ export interface RouteManifestEntry {
55
57
  }
56
58
 
57
59
  export interface BuildManifest {
60
+ /** Names what the browser of this build loads, its hashed scripts and stylesheets: a page from another build cannot take this one's region markup. */
61
+ buildId?: string | undefined
58
62
  runtimeScript: string | undefined
59
- /** The plugins' `regionClientEntry`, loaded by the routes with `usesRegion`. */
63
+ /** The core `<Region>` client bundle, loaded by routes with `usesRegion`. */
60
64
  regionScript?: string | undefined
61
65
  /** The prop revivers, preloaded by a page whose island props hold a Date, Map, Set or another tagged value. */
62
66
  reviveScript?: string | undefined
@@ -81,6 +85,8 @@ export interface BuildManifest {
81
85
  actions: ActionManifestEntry[]
82
86
  islands: Record<string, string>
83
87
  assets: string[]
88
+ /** The app's cookies read from its `cookies.set` calls, for `<CookieTable>`. */
89
+ cookies?: AppCookie[] | undefined
84
90
  /** The previous build's client files this one dropped, kept one more deploy for pages loaded before it (#3663); never linked from a page. */
85
91
  carriedAssets?: string[] | undefined
86
92
  publicFiles: string[]
@@ -202,3 +208,15 @@ export function buildActionEntries(actionsByFile: Map<string, { exportName: stri
202
208
  }
203
209
  return entries
204
210
  }
211
+
212
+ /** The same for two builds whose pages load the same client files and head tags, each client file being named by its content hash. */
213
+ export function clientBuildId(manifest: BuildManifest): string {
214
+ return Bun.hash(JSON.stringify([manifest.assets.toSorted(), manifest.headTags])).toString(36)
215
+ }
216
+
217
+ /** What `<CookieTable>` lists of the app's own cookies, from each module's `cookies.set` calls. */
218
+ export function appCookiesOf(graph: ModuleGraph): Pick<BuildManifest, 'cookies'> {
219
+ const files = [...graph.analyses.keys()].sort()
220
+ const cookies = mergeCookies(files.flatMap(file => scanCookieSets(file, graph.source(file), graph.analyses.get(file)!.program)))
221
+ return cookies.length > 0 ? { cookies: cookies.map(({ file: _file, start: _start, ...cookie }) => cookie) } : {}
222
+ }
@@ -68,6 +68,7 @@ export interface PluginHostOptions {
68
68
  plugins: PrunellePlugin[]
69
69
  appCtx: AppRuntimeContext
70
70
  root: string
71
+ routesDir: string
71
72
  outDir: string
72
73
  clientDir: string
73
74
  outPublicDir: string
@@ -197,6 +198,7 @@ export function createPluginHost(options: PluginHostOptions) {
197
198
 
198
199
  const shared = {
199
200
  root: options.root,
201
+ routesDir: options.routesDir,
200
202
  outDir,
201
203
  assetPrefix,
202
204
  ...(options.site !== undefined ? { site: options.site } : {}),
@@ -4,7 +4,7 @@ import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { RouteManifestEntry } from './manifest'
5
5
  import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, extname, join, resolve } from 'node:path'
7
- import { FORM_TIMESTAMP_FIELD } from '../server/action-protect'
7
+ import { FORM_TIMESTAMP_FIELD, MAX_FORM_AGE_MS } from '../server/action-protect'
8
8
  import { prerenderOrigin } from '../server/prerendered'
9
9
  import { decodeRequestPath } from '../server/request-path'
10
10
  import { inlineStyleHashes, injectMetaCsp } from '../server/security'
@@ -256,7 +256,7 @@ export async function prerender(options: PrerenderOptions) {
256
256
  continue
257
257
  }
258
258
  failed = true
259
- throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused 24 h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
259
+ throw new Error(`prunelle build${isStatic ? ' --static' : ''}: "${u}" renders a form whose action uses protect.minTime, so its signed timestamp would be fixed at build time: every submit is refused ${MAX_FORM_AGE_MS / 3_600_000} h later and bots pass minTime at once. Serve the page from the server${isStatic ? ' instead of a static export' : ' (drop prerender = true)'}, or drop minTime and keep honeypot and rateLimit.`)
260
260
  }
261
261
  writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
262
262
  const hashes = inlineStyleHashes(html)
@@ -7,6 +7,19 @@ import { islandKey } from './islands'
7
7
 
8
8
  const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
9
9
 
10
+ function analysisImportsRegion(analysis: ModuleAnalysis): boolean {
11
+ return analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*'))
12
+ }
13
+
14
+ /** True when any analyzed module in the build graph imports `<Region>`. */
15
+ export function graphUsesRegion(graph: ModuleGraph): boolean {
16
+ for (const analysis of graph.analyses.values()) {
17
+ if (analysisImportsRegion(analysis))
18
+ return true
19
+ }
20
+ return false
21
+ }
22
+
10
23
  interface ModuleEdge {
11
24
  source: string
12
25
  specifiers?: readonly { local: string, imported: string }[] | undefined
@@ -127,7 +140,7 @@ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islan
127
140
  pruned = addIslandChunks(file, file === root, analysis, reach)
128
141
  if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
129
142
  reach.usesRenderContext = true
130
- if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
143
+ if (atImports && !reach.usesRegion && analysisImportsRegion(analysis))
131
144
  reach.usesRegion = true
132
145
 
133
146
  // The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
@@ -244,7 +244,7 @@ export function formatBundleReport(report: BundleReport): string {
244
244
  }
245
245
  lines.push('', 'First load is what a first visit downloads besides the page\'s HTML: CSS, eager JS and its imports, fonts, images and icons, brotli.')
246
246
  if (hasEco)
247
- lines.push('EcoIndex (A–G, 0–100) scores prerendered pages from DOM elements, first-visit requests and brotli transfer weight, with estimated gCO2e and water per view.')
247
+ lines.push('EcoIndex is a static estimate (A–G, 0–100): it scores prerendered pages from the build\'s HTML and files (DOM elements, first-visit requests, brotli transfer weight), not from a browser visit, with estimated gCO2e and water per view.')
248
248
  if (report.topModules.length > 0) {
249
249
  lines.push('', 'Top modules (minified output bytes):')
250
250
  for (const m of report.topModules.slice(0, 8))
@@ -0,0 +1,16 @@
1
+ // The app's route patterns as types, so `href()`, `RouteContext` and `PageProps` refuse a pattern no route file serves.
2
+
3
+ import { writeKeyTypes } from './key-types'
4
+ import { fileToRoutePattern } from './routes'
5
+
6
+ export const ROUTE_TYPES_FILE = 'prunelle-routes.d.ts'
7
+
8
+ export function writeRouteTypes(root: string, routesDir: string, pageFiles: readonly string[]): void {
9
+ writeKeyTypes(root, routesDir, {
10
+ file: ROUTE_TYPES_FILE,
11
+ header: 'Written by prunelle dev, build and check from the route files: the patterns href(), RouteContext and PageProps accept.',
12
+ module: 'prunelle/server',
13
+ interface: 'PrunelleRoutes',
14
+ keys: pageFiles.map(page => fileToRoutePattern(routesDir, page)),
15
+ })
16
+ }
@@ -5,6 +5,7 @@ import type { ModuleAnalysis } from '../compiler/index'
5
5
  import { existsSync } from 'node:fs'
6
6
  import { basename, dirname, join, relative } from 'node:path'
7
7
  import { parseCacheExport } from '../compiler/cacheability'
8
+ import { ASTRO_GUIDE, NEXT_GUIDE, withGuide } from '../compiler/mistakes'
8
9
  import { parseCacheDuration } from '../server/route-cache'
9
10
  import { BUILTIN_PARAM_MATCHER_NAMES, extractPatternMatchers, isBuiltinMatcher, parsePatternSegment } from '../server/param-matchers'
10
11
  import { relPosix } from './files'
@@ -108,19 +109,20 @@ export function routeFileProblem(analysis: ModuleAnalysis, file: string, routesR
108
109
  const LOAD_FIX = 'prunelle never calls it; export async function load() and read its data with the page\'s load prop'
109
110
  const PATHS_FIX = 'prunelle never calls it; export function paths() returning URL strings such as "/posts/a"'
110
111
  const HEAD_FIX = 'prunelle never reads it; render <Head> in the page'
111
- // Exports other frameworks read from a route file, and what prunelle wants instead.
112
+ // Exports other frameworks read from a route file, and what prunelle wants instead, with the guide for the framework that taught it.
112
113
  const FOREIGN_ROUTE_EXPORTS = new Map([
113
- ['getStaticProps', LOAD_FIX],
114
- ['getServerSideProps', LOAD_FIX],
115
- ['getInitialProps', LOAD_FIX],
114
+ ['getStaticProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
115
+ ['getServerSideProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
116
+ ['getInitialProps', withGuide(LOAD_FIX, NEXT_GUIDE)],
116
117
  ['loader', LOAD_FIX],
117
118
  ['clientLoader', LOAD_FIX],
118
- ['getStaticPaths', PATHS_FIX],
119
- ['generateStaticParams', PATHS_FIX],
120
- ['metadata', HEAD_FIX],
121
- ['generateMetadata', HEAD_FIX],
119
+ ['getStaticPaths', withGuide(PATHS_FIX, ASTRO_GUIDE)],
120
+ ['generateStaticParams', withGuide(PATHS_FIX, NEXT_GUIDE)],
121
+ ['metadata', withGuide(HEAD_FIX, NEXT_GUIDE)],
122
+ ['generateMetadata', withGuide(HEAD_FIX, NEXT_GUIDE)],
122
123
  ['meta', HEAD_FIX],
123
- ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, `prunelle never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`] as const),
124
+ ['revalidate', withGuide('prunelle never reads it; export const cache = \'60s\' (any duration), and call invalidateCache() where the data changes', NEXT_GUIDE)],
125
+ ...['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'all'].map(m => [m, withGuide(`prunelle never calls it; export function ${m === 'all' ? 'GET(), POST() or another method' : `${m.toUpperCase()}()`}`, ASTRO_GUIDE)] as const),
124
126
  ])
125
127
 
126
128
  function findExportOffset(analysis: ModuleAnalysis, exportName: string): number {
@@ -225,16 +227,23 @@ export function assertPathUrls(urls: unknown, file: string): asserts urls is str
225
227
  }
226
228
  }
227
229
 
228
- export function fileToRoutePath(routesDir: string, file: string): string {
229
- const rel = relPosix(routesDir, file).replace(TS_EXT_RE, '')
230
- const rawParts = rel.split('/')
230
+ // The URL segments of a route file, in its folder names' bracket form: `(group)` folders and a final `index` dropped.
231
+ function routeSegments(routesDir: string, file: string): string[] {
232
+ const rawParts = relPosix(routesDir, file).replace(TS_EXT_RE, '').split('/')
231
233
  const filePart = rawParts.pop()!
232
234
  const urlParts = rawParts.filter(part => !isRouteGroupSegment(part))
233
235
  if (filePart !== 'index')
234
236
  urlParts.push(filePart)
235
- if (urlParts.length === 0)
236
- return '/'
237
- return `/${urlParts.map(convertRouteSegment).join('/')}`
237
+ return urlParts
238
+ }
239
+
240
+ export function fileToRoutePath(routesDir: string, file: string): string {
241
+ return `/${routeSegments(routesDir, file).map(convertRouteSegment).join('/')}`
242
+ }
243
+
244
+ /** The pattern of a route file as `RouteContext`, `PageProps` and `href()` take it: `/posts/[slug]`. */
245
+ export function fileToRoutePattern(routesDir: string, file: string): string {
246
+ return `/${routeSegments(routesDir, file).join('/')}`
238
247
  }
239
248
 
240
249
  /** The shape two route paths conflict on: parameter names do not matter, but optionality and matcher names do. */
@@ -0,0 +1,65 @@
1
+ // Names each module-level `signal()` and `store()` for the page to seed: the server renders a value an island wrote, and the browser starts from it.
2
+
3
+ import { parseSync } from 'oxc-parser'
4
+
5
+ const CALL_RE = /\b(?:signal|store)\s*\(/
6
+ const TS_LANG_RE = /\.[cm]?ts$/i
7
+ const IMPORT = "import { seedSignal as __pruSeedSignal, seedStore as __pruSeedStore } from 'prunelle/internal/seed';"
8
+
9
+ interface Node { type: string, start: number, end: number, [key: string]: unknown }
10
+
11
+ /** The id a module's signal or store has on the server and in the browser, which agree on the file and the name. */
12
+ export function seedId(file: string, name: string): string {
13
+ return Bun.hash(`${file}#${name}`).toString(36).slice(0, 8)
14
+ }
15
+
16
+ /** Wraps each top-level `const x = signal(…)` or `store(…)` (the two imported from `prunelle`) in the seed call carrying its id. `file` is the project-relative path. */
17
+ export function nameModuleState(code: string, filename: string, file: string, target: 'server' | 'client'): string {
18
+ if (!CALL_RE.test(code))
19
+ return code
20
+ const parsed = parseSync(filename, code, { lang: TS_LANG_RE.test(filename) ? 'ts' : 'tsx', sourceType: 'module' })
21
+ if (parsed.errors.length > 0)
22
+ return code
23
+ const callees = new Map<string, 'signal' | 'store'>()
24
+ for (const stmt of parsed.program.body) {
25
+ if (stmt.type !== 'ImportDeclaration' || stmt.importKind === 'type' || stmt.source.value !== 'prunelle')
26
+ continue
27
+ for (const spec of stmt.specifiers) {
28
+ if (spec.type !== 'ImportSpecifier' || spec.importKind === 'type' || spec.imported.type !== 'Identifier')
29
+ continue
30
+ if (spec.imported.name === 'signal' || spec.imported.name === 'store')
31
+ callees.set(spec.local.name, spec.imported.name)
32
+ }
33
+ }
34
+ if (callees.size === 0)
35
+ return code
36
+
37
+ const edits: { at: number, text: string }[] = []
38
+ for (const stmt of parsed.program.body) {
39
+ const decl = (stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt) as Node | null | undefined
40
+ if (decl?.type !== 'VariableDeclaration' || decl.kind !== 'const')
41
+ continue
42
+ for (const d of decl.declarations as { id: Node & { name?: string }, init: (Node & { callee?: Node & { name?: string } }) | null }[]) {
43
+ const init = d.init
44
+ if (d.id.type !== 'Identifier' || init?.type !== 'CallExpression' || init.callee?.type !== 'Identifier')
45
+ continue
46
+ const kind = callees.get(init.callee.name!)
47
+ if (kind === undefined)
48
+ continue
49
+ const fn = kind === 'signal' ? '__pruSeedSignal' : '__pruSeedStore'
50
+ // The server names the signal in the errors a write it cannot carry throws; the browser has no use for the name.
51
+ const label = target === 'server' ? `, ${JSON.stringify(`${file}#${d.id.name}`)}` : ''
52
+ edits.push({ at: init.start, text: `${fn}(` }, { at: init.end, text: `, ${JSON.stringify(seedId(file, d.id.name!))}${label})` })
53
+ }
54
+ }
55
+ if (edits.length === 0)
56
+ return code
57
+ edits.sort((a, b) => a.at - b.at)
58
+ let out = ''
59
+ let cursor = 0
60
+ for (const e of edits) {
61
+ out += code.slice(cursor, e.at) + e.text
62
+ cursor = e.at
63
+ }
64
+ return `${out}${code.slice(cursor)}\n${IMPORT}\n`
65
+ }
@@ -0,0 +1,111 @@
1
+ // Tells whether the page could need seeds at all: only an app where some module writes state another module made, outside an event handler, ships the helper that carries it to the browser.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/analyze'
4
+ import type { ModuleGraph } from './graph'
5
+ import { walk } from '../compiler/ast'
6
+ import { isInNodeModules } from './files'
7
+
8
+ const MUTATORS = new Set(['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'add', 'delete', 'clear', 'assign'])
9
+ // What runs after the render: a handler, or the callback of one of these.
10
+ const LATER_CALLS = new Set(['onMount', 'effect', 'onCleanup'])
11
+
12
+ type Loose = Record<string, any>
13
+
14
+ // `cart.lines[0].qty` is rooted at `cart`.
15
+ function rootName(node: Loose | null | undefined): string | undefined {
16
+ let cur = node
17
+ while (cur != null) {
18
+ if (cur.type === 'Identifier')
19
+ return cur.name
20
+ if (cur.type === 'MemberExpression')
21
+ cur = cur.object
22
+ else if (cur.type === 'ChainExpression' || cur.type === 'ParenthesizedExpression')
23
+ cur = cur.expression
24
+ else if (cur.type === 'TSNonNullExpression' || cur.type === 'TSAsExpression')
25
+ cur = cur.expression
26
+ else
27
+ return undefined
28
+ }
29
+ return undefined
30
+ }
31
+
32
+ /** True when the module writes, outside a handler, `onMount` or `effect`, state it imports or made at its top level; aliases and bare hand-overs count too, so a doubt answers true. */
33
+ function writesState(analysis: ModuleAnalysis, graph: Pick<ModuleGraph, 'analyses' | 'resolve'>): boolean {
34
+ const roots = new Set<string>()
35
+ for (const imp of analysis.imports) {
36
+ const target = graph.analyses.get(graph.resolve(analysis.filename, imp.source) ?? '')
37
+ if (target === undefined)
38
+ continue
39
+ // A barrel re-exports state under names its own file does not hold.
40
+ for (const spec of imp.specifiers) {
41
+ if (spec.imported === '*' || target.reexports.length > 0 || target.stateExports.includes(spec.imported))
42
+ roots.add(spec.local)
43
+ }
44
+ }
45
+ for (const stmt of analysis.program.body as Loose[]) {
46
+ const decl = (stmt.type === 'ExportNamedDeclaration' ? stmt.declaration : stmt) as Loose | null
47
+ for (const d of decl?.type === 'VariableDeclaration' ? decl.declarations as Loose[] : []) {
48
+ if (d.id.type === 'Identifier' && d.init?.type === 'CallExpression' && (d.init.callee.name === 'signal' || d.init.callee.name === 'store'))
49
+ roots.add(d.id.name)
50
+ }
51
+ }
52
+ if (roots.size === 0)
53
+ return false
54
+ let found = false
55
+ walk(analysis.program, (n) => {
56
+ if (found)
57
+ return false
58
+ const node = n as unknown as Loose
59
+ switch (node.type) {
60
+ case 'JSXAttribute': {
61
+ const name = node.name.type === 'JSXIdentifier' ? node.name.name as string : ''
62
+ const value = node.value?.expression as Loose | undefined
63
+ if (/^on[A-Z]/.test(name) && (value?.type === 'ArrowFunctionExpression' || value?.type === 'FunctionExpression'))
64
+ return false
65
+ return undefined
66
+ }
67
+ case 'CallExpression': {
68
+ const callee = node.callee as Loose
69
+ if (callee.type === 'Identifier' && LATER_CALLS.has(callee.name))
70
+ return false
71
+ const base = rootName(callee.type === 'MemberExpression' ? callee.object : undefined)
72
+ if (callee.type === 'MemberExpression' && base !== undefined && roots.has(base) && MUTATORS.has(callee.property?.name))
73
+ found = true
74
+ if ((node.arguments as Loose[]).some(a => a.type === 'Identifier' && roots.has(a.name)))
75
+ found = true
76
+ return undefined
77
+ }
78
+ case 'AssignmentExpression':
79
+ found = rootName(node.left) !== undefined && roots.has(rootName(node.left)!)
80
+ return undefined
81
+ case 'UpdateExpression':
82
+ found = rootName(node.argument) !== undefined && roots.has(rootName(node.argument)!)
83
+ return undefined
84
+ case 'UnaryExpression':
85
+ if (node.operator === 'delete')
86
+ found = rootName(node.argument) !== undefined && roots.has(rootName(node.argument)!)
87
+ return undefined
88
+ case 'JSXExpressionContainer':
89
+ if (node.expression.type === 'Identifier' && roots.has(node.expression.name))
90
+ found = true
91
+ return undefined
92
+ case 'VariableDeclarator': {
93
+ const root = rootName(node.init)
94
+ if (node.id.type === 'Identifier' && root !== undefined && roots.has(root))
95
+ roots.add(node.id.name)
96
+ return undefined
97
+ }
98
+ default:
99
+ return undefined
100
+ }
101
+ })
102
+ return found
103
+ }
104
+
105
+ /** Whether a module of the app could write module-level state while an island renders on the server. */
106
+ export function writesModuleState(graph: Pick<ModuleGraph, 'analyses' | 'resolve'>): boolean {
107
+ const files = [...graph.analyses].filter(([file]) => !isInNodeModules(file))
108
+ if (!files.some(([, a]) => a.stateExports.length > 0))
109
+ return false
110
+ return files.some(([, a]) => writesState(a, graph))
111
+ }
@@ -3,7 +3,7 @@
3
3
  import type { SecurityHeadersOptions } from '../server/security'
4
4
  import { existsSync, readFileSync, writeFileSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
- import { buildSecurityHeaderEntries, resolveHstsValue } from '../server/security'
6
+ import { buildSecurityHeaderEntries, resolveHstsValue, withoutCspReports } from '../server/security'
7
7
 
8
8
  export const CADDY_SNIPPET = 'prunelle.caddy'
9
9
  export const NGINX_SNIPPET = 'prunelle.nginx.conf'
@@ -51,7 +51,7 @@ export function parseRedirects(text: string): StaticRedirect[] {
51
51
 
52
52
  function headerEntries(security: SecurityHeadersOptions | false | undefined): [string, string][] {
53
53
  const entries: [string, string][] = []
54
- for (const [name, value] of buildSecurityHeaderEntries(security)) {
54
+ for (const [name, value] of buildSecurityHeaderEntries(withoutCspReports(security))) {
55
55
  if (name !== 'content-security-policy') {
56
56
  entries.push([name, value])
57
57
  continue
@@ -177,7 +177,7 @@ export async function emitStaticNotFoundPages(options: StaticNotFoundOptions): P
177
177
  renderError ??= err
178
178
  }
179
179
  const document = createDocumentHooks({ plugins, lang, trustProxy, notifyError })
180
- const navigation = createNavigation(options.entry.prunelleConfig.navigation)
180
+ const navigation = createNavigation(options.entry.prunelleConfig.navigation, options.entry.prunelleConfig.assetPrefix)
181
181
  const htmlHeaders = createHtmlHeaders(options.entry.prunelleConfig.security, {}, navigation, plugins)
182
182
  const routesPrefix = inferRoutesServerPrefix(options.manifest)
183
183
  const paramMatchers = resolveParamMatchers(options.manifest.paramMatchers, options.entry.modules)
@@ -0,0 +1,51 @@
1
+ // `prunelle check` rules on the route cache: a tag `invalidateCache()` drops that no route declares.
2
+
3
+ import { parseSync } from 'oxc-parser'
4
+ import { walk } from '../compiler/ast'
5
+ import { formatDiagnostic, unwrapTsExpr } from '../compiler/shared'
6
+
7
+ /** One warning per `invalidateCache({ tag })` naming a tag outside `declared`, the tags of every route's `export const cache`. */
8
+ export function unknownCacheTagWarnings(files: readonly string[], read: (file: string) => string, locate: (file: string, offset: number) => string, declared: ReadonlySet<string>): string[] {
9
+ const warnings: string[] = []
10
+ for (const file of files) {
11
+ const code = read(file)
12
+ if (!code.includes('invalidateCache'))
13
+ continue
14
+ const parsed = parseSync(file, code, { lang: file.endsWith('.tsx') || file.endsWith('.jsx') ? 'tsx' : 'ts', sourceType: 'module' })
15
+ const names = new Set<string>()
16
+ for (const stmt of parsed.program.body) {
17
+ if (stmt.type !== 'ImportDeclaration' || stmt.source.value !== 'prunelle/server')
18
+ continue
19
+ for (const spec of stmt.specifiers) {
20
+ if (spec.type === 'ImportSpecifier' && (spec.imported.type === 'Identifier' ? spec.imported.name : spec.imported.value) === 'invalidateCache')
21
+ names.add(spec.local.name)
22
+ }
23
+ }
24
+ if (names.size === 0)
25
+ continue
26
+ walk(parsed.program, (node) => {
27
+ if (node.type !== 'CallExpression')
28
+ return
29
+ const callee = unwrapTsExpr(node.callee)
30
+ if (callee.type !== 'Identifier' || !names.has(callee.name))
31
+ return
32
+ for (const arg of node.arguments) {
33
+ const tag = arg.type === 'ObjectExpression' ? staticTag(arg) : undefined
34
+ if (tag !== undefined && !declared.has(tag))
35
+ warnings.push(formatDiagnostic(locate(file, arg.start), `[cache/unknown-tag] invalidateCache() drops the tag "${tag}", which no route declares, so it drops nothing: add it to the \`tags\` of a route's \`export const cache\`, or fix its name.`, 'warning'))
36
+ }
37
+ })
38
+ }
39
+ return warnings
40
+ }
41
+
42
+ function staticTag(object: Extract<ReturnType<typeof unwrapTsExpr>, { type: 'ObjectExpression' }>): string | undefined {
43
+ for (const prop of object.properties) {
44
+ if (prop.type !== 'Property' || prop.computed || prop.key.type !== 'Identifier' || prop.key.name !== 'tag')
45
+ continue
46
+ const value = unwrapTsExpr(prop.value)
47
+ if (value.type === 'Literal' && typeof value.value === 'string')
48
+ return value.value
49
+ }
50
+ return undefined
51
+ }