prunelle 0.6.0 → 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 (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 +15 -14
  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 +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -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 +19 -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 +33 -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 +26 -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 +145 -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 +52 -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 +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  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 +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  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 +16 -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 +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -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 +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  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 +32 -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,8 +2,9 @@
2
2
 
3
3
  import type { PrunellePlugin } from '../plugins/index'
4
4
  import type { RouteManifestEntry } from './manifest'
5
- import { mkdirSync, writeFileSync } from 'node:fs'
6
- import { dirname, extname, resolve } from 'node:path'
5
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
6
+ import { dirname, extname, join, resolve } from 'node:path'
7
+ import { FORM_TIMESTAMP_FIELD } from '../server/action-protect'
7
8
  import { prerenderOrigin } from '../server/prerendered'
8
9
  import { decodeRequestPath } from '../server/request-path'
9
10
  import { inlineStyleHashes, injectMetaCsp } from '../server/security'
@@ -100,6 +101,17 @@ export interface PrerenderOptions {
100
101
  /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
101
102
  prerenderDir: string
102
103
  routes: RouteManifestEntry[]
104
+ /** The app's routes folder, to name a route's source file in messages. */
105
+ routesDir: string
106
+ }
107
+
108
+ const ROUTE_SOURCE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js', '.mdx', '.md']
109
+
110
+ // The source file of a built route module (`server/posts/[slug].js` is `src/routes/posts/[slug].tsx`), as messages name it.
111
+ function routeSource(options: PrerenderOptions, route: RouteManifestEntry): string {
112
+ const stem = join(options.routesDir, route.file.replace(/^server\//, '').replace(/\.js$/, ''))
113
+ const source = ROUTE_SOURCE_EXTENSIONS.map(ext => `${stem}${ext}`).find(file => existsSync(file))
114
+ return source === undefined ? route.file : relPosix(options.root, source)
103
115
  }
104
116
 
105
117
  // The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
@@ -114,6 +126,67 @@ export function pageFailure(head: string, error: unknown): Error {
114
126
  return new Error(`${head}: ${error.message}${frames}`, { cause: error })
115
127
  }
116
128
 
129
+ const TIMESTAMP_INPUT = `name="${FORM_TIMESTAMP_FIELD}"`
130
+
131
+ interface RenderTask {
132
+ route: RouteManifestEntry
133
+ url: string
134
+ relOut?: string | undefined
135
+ hashes?: string[] | undefined
136
+ /** The page holds a `protect.minTime` form, whose token must be signed per request. */
137
+ signsTimestamp?: boolean | undefined
138
+ }
139
+
140
+ // A route's paths(), whose throw names the route it came from.
141
+ async function namedPathsError(route: RouteManifestEntry, source: string, paths: () => Promise<string[]> | string[]): Promise<unknown> {
142
+ try {
143
+ return await paths()
144
+ }
145
+ catch (error) {
146
+ throw new Error(`prunelle build: paths() of "${route.path}" (${source}) threw: ${error instanceof Error ? error.message : String(error)}`, { cause: error })
147
+ }
148
+ }
149
+
150
+ /** The URLs to render for each route: its own path, or what its `paths()` and the plugins' `prerenderPaths` return. */
151
+ async function planRoutes(options: PrerenderOptions, modules: Record<string, unknown> | undefined): Promise<{ route: RouteManifestEntry, tasks: RenderTask[] }[]> {
152
+ const routePlans: { route: RouteManifestEntry, tasks: RenderTask[] }[] = []
153
+ for (const route of options.routes) {
154
+ let urls: string[] = []
155
+ let hasPathsFn = false
156
+ if (!route.path.includes(':') && !route.path.includes('*')) {
157
+ urls = [route.path]
158
+ }
159
+ else {
160
+ const mod = modules?.[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
161
+ if (typeof mod.paths === 'function') {
162
+ hasPathsFn = true
163
+ const returned: unknown = await namedPathsError(route, routeSource(options, route), mod.paths)
164
+ assertPathUrls(returned, route.file)
165
+ urls = returned
166
+ }
167
+ else {
168
+ console.warn(`prunelle build${options.isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${routeSource(options, route)}) because it does not export a paths() function.`)
169
+ }
170
+ }
171
+
172
+ for (const plugin of options.plugins) {
173
+ if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
174
+ urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
175
+ }
176
+
177
+ urls = [...new Set(urls.map(normalizePrerenderUrl))]
178
+
179
+ if (urls.length === 0) {
180
+ if (hasPathsFn)
181
+ route.prerendered = {}
182
+ continue
183
+ }
184
+
185
+ routePlans.push({ route, tasks: urls.map(url => ({ route, url })) })
186
+ }
187
+ return routePlans
188
+ }
189
+
117
190
  /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
118
191
  export async function prerender(options: PrerenderOptions) {
119
192
  const { root, outDir, prerenderDir, isStatic } = options
@@ -128,49 +201,8 @@ export async function prerender(options: PrerenderOptions) {
128
201
  const origin = prerenderOrigin(options.site)
129
202
  mkdirSync(prerenderDir, { recursive: true })
130
203
 
131
- interface RenderTask {
132
- url: string
133
- relOut?: string | undefined
134
- hashes?: string[] | undefined
135
- }
136
- const routePlans: { route: RouteManifestEntry, tasks: RenderTask[] }[] = []
137
-
138
204
  try {
139
- for (const route of options.routes) {
140
- let urls: string[] = []
141
- let hasPathsFn = false
142
- if (!route.path.includes(':') && !route.path.includes('*')) {
143
- urls = [route.path]
144
- }
145
- else {
146
- const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
147
- if (typeof mod.paths === 'function') {
148
- hasPathsFn = true
149
- const returned: unknown = await mod.paths()
150
- assertPathUrls(returned, route.file)
151
- urls = returned
152
- }
153
- else {
154
- console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
155
- }
156
- }
157
-
158
- for (const plugin of options.plugins) {
159
- if (plugin.prerenderPaths !== undefined && (urls.length > 0 || hasPathsFn))
160
- urls = await runPluginHook(plugin, 'prerenderPaths', () => plugin.prerenderPaths!(urls, route))
161
- }
162
-
163
- urls = [...new Set(urls.map(normalizePrerenderUrl))]
164
-
165
- if (urls.length === 0) {
166
- if (hasPathsFn)
167
- route.prerendered = {}
168
- continue
169
- }
170
-
171
- routePlans.push({ route, tasks: urls.map(url => ({ url })) })
172
- }
173
-
205
+ const routePlans = await planRoutes(options, entry?.modules)
174
206
  const allTasks = routePlans.flatMap(plan => plan.tasks)
175
207
  let nextIdx = 0
176
208
  let failed = false
@@ -189,6 +221,9 @@ export async function prerender(options: PrerenderOptions) {
189
221
  failed = true
190
222
  throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
191
223
  }
224
+ // A page prunelle chose to prerender by itself falls back to request time quietly; one the app asked for is told.
225
+ if (task.route.autoPrerender !== true)
226
+ console.warn(`prunelle build: prerender route "${u}" (${routeSource(options, task.route)}) answered HTTP ${res.status}, ${task.route.path === u ? 'so it renders at request time instead: drop `prerender = true`' : 'so it is not prerendered and answers 404 in production: leave it out of paths()'}, or have it answer 200.`)
192
227
  continue
193
228
  }
194
229
  const ct = res.headers.get('content-type')
@@ -196,6 +231,14 @@ export async function prerender(options: PrerenderOptions) {
196
231
  mkdirSync(dirname(absOut), { recursive: true })
197
232
  if ((ct ?? '').toLowerCase().includes('text/html')) {
198
233
  const html = await res.text()
234
+ if (html.includes(TIMESTAMP_INPUT)) {
235
+ if (task.route.autoPrerender === true) {
236
+ task.signsTimestamp = true
237
+ continue
238
+ }
239
+ failed = true
240
+ 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.`)
241
+ }
199
242
  writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
200
243
  const hashes = inlineStyleHashes(html)
201
244
  if (hashes.length > 0)
@@ -212,6 +255,16 @@ export async function prerender(options: PrerenderOptions) {
212
255
  await Promise.all(Array.from({ length: workers }, () => runWorker()))
213
256
 
214
257
  for (const { route, tasks } of routePlans) {
258
+ if (tasks.some(task => task.signsTimestamp === true)) {
259
+ // A protect.minTime form signs its timestamp on each request: the whole route renders at request time.
260
+ for (const task of tasks) {
261
+ if (task.relOut !== undefined)
262
+ rmSync(join(outDir, task.relOut), { force: true })
263
+ }
264
+ route.prerender = false
265
+ route.autoPrerender = undefined
266
+ continue
267
+ }
215
268
  const map: Record<string, string> = {}
216
269
  const styleHashes: Record<string, string[]> = {}
217
270
  for (const task of tasks) {
@@ -0,0 +1,136 @@
1
+ // What a page reaches through its imports and the islands it renders: island chunks, stylesheets, files, render-context and region use.
2
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import type { ModuleGraph } from './graph'
5
+ import type { IslandPlan } from './islands'
6
+ import { islandKey } from './islands'
7
+
8
+ const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
9
+
10
+ export interface FileReach {
11
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
12
+ chunks: Set<string>
13
+ eager: Set<string>
14
+ styles: Set<string>
15
+ /** All reachable source files (`.ts`/`.tsx`) walked from this file. */
16
+ files: Set<string>
17
+ usesRenderContext: boolean
18
+ usesRegion: boolean
19
+ }
20
+
21
+ // How far a visit reaches. Level 0 follows imports, stopping at an island that renders nothing static (its imports ship inside it): island chunks.
22
+ // Level 1 follows every import: render-context and region use. Level 2 also follows the islands a module renders: files and styles.
23
+ // Each level reaches a superset of the one before, so a visit at a level also counts for the levels after it.
24
+ const ISLANDS = 0
25
+ const IMPORTS = 1
26
+ const RENDERED = 2
27
+
28
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it, in one pass per page. */
29
+ export function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
30
+ const { analyses } = graph
31
+ const depsMemo = new Map<string, string[]>()
32
+ const depsOf = (file: string): string[] => {
33
+ let deps = depsMemo.get(file)
34
+ if (deps === undefined) {
35
+ deps = graph.localDeps(file)
36
+ depsMemo.set(file, deps)
37
+ }
38
+ return deps
39
+ }
40
+
41
+ /** Adds the island chunks of a file reached at level 0; true when its imports ship inside the island and the level stops there. */
42
+ function addIslandChunks(file: string, analysis: ModuleAnalysis, reach: FileReach): boolean {
43
+ if (analysis.isInteractive) {
44
+ const chunk = islandChunks.get(`${file}#default`)
45
+ if (chunk !== undefined) {
46
+ reach.chunks.add(chunk)
47
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
48
+ reach.eager.add(chunk)
49
+ }
50
+ // Imports rendered only inside the module's islands ship within them; a static component beside an island renders its own.
51
+ if (analysis.staticJsxTags.size === 0)
52
+ return true
53
+ }
54
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
55
+ const chunk = islandChunks.get(islandKey(target))
56
+ if (chunk === undefined)
57
+ continue
58
+ reach.chunks.add(chunk)
59
+ const isDeferred = analysis.deferredIslandTags.has(localName)
60
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
61
+ if (!isDeferred)
62
+ reach.eager.add(chunk)
63
+ }
64
+ return false
65
+ }
66
+
67
+ function walk(root: string): FileReach {
68
+ const reach: FileReach = { chunks: new Set(), eager: new Set(), styles: new Set(), files: new Set(), usesRenderContext: false, usesRegion: false }
69
+ const seen = [new Set<string>(), new Set<string>(), new Set<string>()]
70
+
71
+ function visit(file: string, level: number): void {
72
+ const atIslands = level === ISLANDS && !seen[ISLANDS]!.has(file)
73
+ const atImports = level <= IMPORTS && !seen[IMPORTS]!.has(file)
74
+ const atRendered = !seen[RENDERED]!.has(file)
75
+ if (!atIslands && !atImports && !atRendered)
76
+ return
77
+ if (atIslands)
78
+ seen[ISLANDS]!.add(file)
79
+ if (atImports)
80
+ seen[IMPORTS]!.add(file)
81
+ if (atRendered)
82
+ seen[RENDERED]!.add(file)
83
+ const analysis = analyses.get(file)
84
+ if (atRendered)
85
+ reach.files.add(file)
86
+ if (analysis === undefined)
87
+ return
88
+
89
+ let pruned = false
90
+ if (atIslands)
91
+ pruned = addIslandChunks(file, analysis, reach)
92
+ if (atImports && !reach.usesRenderContext && analysis.usesRenderContext)
93
+ reach.usesRenderContext = true
94
+ if (atImports && !reach.usesRegion && analysis.imports.some(imp => REGION_SOURCES.has(imp.source) && imp.specifiers.some(s => s.imported === 'Region' || s.imported === '*')))
95
+ reach.usesRegion = true
96
+
97
+ if (atRendered) {
98
+ if (analysis.isInteractive) {
99
+ const islCss = islandCssUrl.get(`${file}#default`)
100
+ if (islCss !== undefined)
101
+ reach.styles.add(islCss)
102
+ }
103
+ for (const target of islands.pageBindings.get(file)?.values() ?? []) {
104
+ const islCss = islandCssUrl.get(islandKey(target))
105
+ if (islCss !== undefined)
106
+ reach.styles.add(islCss)
107
+ visit(target.file, RENDERED)
108
+ }
109
+ for (const imp of analysis.imports) {
110
+ const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
111
+ if (cssUrl !== undefined)
112
+ reach.styles.add(cssUrl)
113
+ }
114
+ }
115
+
116
+ // The imports follow at the lowest level this visit newly covers; a pruned island's imports are still walked for the levels after it.
117
+ const next = atIslands ? (pruned ? IMPORTS : ISLANDS) : atImports ? IMPORTS : RENDERED
118
+ for (const dep of depsOf(file))
119
+ visit(dep, next)
120
+ }
121
+
122
+ visit(root, ISLANDS)
123
+ return reach
124
+ }
125
+
126
+ // Layouts are shared by many routes, so each file is walked once.
127
+ const memo = new Map<string, FileReach>()
128
+ return (file: string): FileReach => {
129
+ let reach = memo.get(file)
130
+ if (reach === undefined) {
131
+ reach = walk(file)
132
+ memo.set(file, reach)
133
+ }
134
+ return reach
135
+ }
136
+ }
@@ -6,7 +6,7 @@ import type { IslandPlan, StaticTag } from './islands'
6
6
  import { isInNodeModules } from './files'
7
7
  import { visitorKeys } from 'oxc-parser'
8
8
  import { walk } from '../compiler/ast'
9
- import { mistake } from '../compiler/mistakes'
9
+ import { hydrateMistake } from '../compiler/mistakes'
10
10
  import { collectPatternNames, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from '../compiler/shared'
11
11
 
12
12
  const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
@@ -126,7 +126,7 @@ function staticTagProblems(element: Extract<Node, { type: 'JSXOpeningElement' }>
126
126
  continue
127
127
  const attrName = attr.name.name
128
128
  if (attrName === '$hydrate')
129
- problems.push({ offset: attr.start, message: mistake(`$hydrate on <${tag}>`, rel, `${tag} is not an island, so it never hydrates; drop $hydrate, or give ${tag} state or handlers`).message })
129
+ problems.push({ offset: attr.start, message: hydrateMistake(tag, rel, true).message })
130
130
  else if (found !== undefined && EVENT_PROP_RE.test(attrName) && isFunctionValue(attr, isLocalFn))
131
131
  problems.push({ offset: attr.start, message: `${command}: cannot pass event handler "${attrName}" to <${tag}>, which is not an island: the server renders it as HTML, so the handler never runs. Write the handler inside <${tag}>, or render <${tag}> from an island.` })
132
132
  }
@@ -237,6 +237,8 @@ export function formatBundleReport(report: BundleReport): string {
237
237
  )
238
238
  if (r.ecoIndex?.url !== undefined)
239
239
  lines.push(` worst page: ${r.ecoIndex.url} (${r.ecoIndex.dom} DOM, ${r.ecoIndex.requests} req, ${kb(r.ecoIndex.weightBytes)} br, ${r.ecoIndex.ghgGrams} gCO2e)`)
240
+ if (r.ecoIndex?.external !== undefined)
241
+ lines.push(` ${r.ecoIndex.external} third-party request${r.ecoIndex.external === 1 ? '' : 's'} counted in the EcoIndex but not weighed${r.ecoIndex.url === undefined ? '' : ` (on ${r.ecoIndex.url})`}`)
240
242
  for (const island of r.islands)
241
243
  lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
242
244
  }
@@ -255,8 +257,10 @@ export function formatBundleReportJson(report: BundleReport): string {
255
257
  return JSON.stringify(report, null, 2)
256
258
  }
257
259
 
258
- /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
259
- export function checkJsBudget(report: BundleReport, maxBytes: number): void {
260
+ const routeCount = (n: number): string => (n === 1 ? 'one route' : `${n} routes`)
261
+
262
+ /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page; `source` is the setting that set it. */
263
+ export function checkJsBudget(report: BundleReport, maxBytes: number, source = '--max-js'): void {
260
264
  const over = report.routes.filter(r => r.jsGzip > maxBytes)
261
265
  if (over.length === 0)
262
266
  return
@@ -264,5 +268,17 @@ export function checkJsBudget(report: BundleReport, maxBytes: number): void {
264
268
  const eager = r.islands.filter(island => island.eager).map(islandLine)
265
269
  return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the prunelle runtime alone'}`
266
270
  })
267
- throw new Error(`prunelle build: eager JS over --max-js ${kb(maxBytes)} (gzip) on ${over.length === 1 ? 'one route' : `${over.length} routes`}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise --max-js.`)
271
+ throw new Error(`prunelle build: eager JS over ${source} ${kb(maxBytes)} (gzip) on ${routeCount(over.length)}:\n${lines.join('\n')}\nDefer an island with export const hydrate = 'visible', move its state into fewer components, or raise ${source}.`)
272
+ }
273
+
274
+ /** What a route's first visit downloads: its stylesheets, scripts and fonts, or, on a prerendered page, the heaviest page with its HTML and images. */
275
+ export const routeFirstLoad = (r: RouteBundleMetrics): number => Math.max(r.firstLoad, r.ecoIndex?.weightBytes ?? 0)
276
+
277
+ /** Throws naming each route whose first load, brotli, is over `budget.firstLoad`. */
278
+ export function checkFirstLoadBudget(report: BundleReport, maxBytes: number): void {
279
+ const over = report.routes.filter(r => routeFirstLoad(r) > maxBytes)
280
+ if (over.length === 0)
281
+ return
282
+ const lines = over.map(r => ` ${r.ecoIndex?.url ?? r.path} downloads ${kb(routeFirstLoad(r))} on a first visit`)
283
+ throw new Error(`prunelle build: first load over budget.firstLoad ${kb(maxBytes)} (brotli) on ${routeCount(over.length)}:\n${lines.join('\n')}\nResize or compress the heaviest images with @prunellejs/images, subset the fonts, defer islands, or raise budget.firstLoad in prunelle.config.ts.`)
268
284
  }
@@ -0,0 +1,93 @@
1
+ // What a `--static` export tells the host that serves it: a `_headers` file (Netlify, Cloudflare Pages) and `prunelle.caddy` / `prunelle.nginx.conf` snippets, each carrying the security headers and the `_redirects` rules.
2
+
3
+ import type { SecurityHeadersOptions } from '../server/security'
4
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
5
+ import { join } from 'node:path'
6
+ import { buildSecurityHeaderEntries, resolveHstsValue } from '../server/security'
7
+
8
+ export const CADDY_SNIPPET = 'prunelle.caddy'
9
+ export const NGINX_SNIPPET = 'prunelle.nginx.conf'
10
+
11
+ // A page carries its own script and style policy as a `<meta>` tag with the hashes of that page, so the headers keep only the directives a `<meta>` tag cannot set or a page never varies.
12
+ const HEADER_CSP_DIRECTIVES = new Set(['frame-ancestors', 'base-uri', 'form-action', 'object-src'])
13
+ const WHITESPACE_RE = /\s+/
14
+ const DYNAMIC_PATH_RE = /[*:]/
15
+ const FORCE_MARK_RE = /!$/
16
+
17
+ export interface StaticRedirect {
18
+ from: string
19
+ to: string
20
+ status: number
21
+ }
22
+
23
+ /** The `from to [status]` lines of a `_redirects` file that a snippet can state: an exact path, no splat or placeholder. */
24
+ export function parseRedirects(text: string): StaticRedirect[] {
25
+ const rules: StaticRedirect[] = []
26
+ for (const line of text.split('\n')) {
27
+ const fields = line.trim().split(WHITESPACE_RE)
28
+ const [from, to, status = '301'] = fields
29
+ const code = Number(status.replace(FORCE_MARK_RE, ''))
30
+ if (from === undefined || to === undefined || from.startsWith('#') || DYNAMIC_PATH_RE.test(from) || !Number.isInteger(code))
31
+ continue
32
+ rules.push({ from, to, status: code })
33
+ }
34
+ return rules
35
+ }
36
+
37
+ function headerEntries(security: SecurityHeadersOptions | false | undefined): [string, string][] {
38
+ const entries: [string, string][] = []
39
+ for (const [name, value] of buildSecurityHeaderEntries(security)) {
40
+ if (name !== 'content-security-policy') {
41
+ entries.push([name, value])
42
+ continue
43
+ }
44
+ const kept = value.split(';').map(part => part.trim()).filter(part => HEADER_CSP_DIRECTIVES.has(part.split(WHITESPACE_RE)[0]!.toLowerCase()))
45
+ if (kept.length > 0)
46
+ entries.push([name, kept.join('; ')])
47
+ }
48
+ const hsts = resolveHstsValue(security)
49
+ if (hsts !== undefined && security !== false)
50
+ entries.push(['strict-transport-security', hsts])
51
+ return entries
52
+ }
53
+
54
+ function titleCase(name: string): string {
55
+ return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join('-')
56
+ }
57
+
58
+ const quote = (value: string): string => `"${value.replaceAll('\\', '\\\\').replaceAll('"', '\\"')}"`
59
+
60
+ export function netlifyHeaders(security: SecurityHeadersOptions | false | undefined): string {
61
+ const lines = headerEntries(security).map(([name, value]) => ` ${titleCase(name)}: ${value}`)
62
+ return lines.length === 0 ? '' : `/*\n${lines.join('\n')}\n`
63
+ }
64
+
65
+ export function caddySnippet(security: SecurityHeadersOptions | false | undefined, redirects: readonly StaticRedirect[]): string {
66
+ const lines = ['# Written by `prunelle build --static`. Inside a site block: `import /path/to/dist/prunelle.caddy`.']
67
+ const entries = headerEntries(security)
68
+ if (entries.length > 0)
69
+ lines.push('header {', ...entries.map(([name, value]) => `\t${titleCase(name)} ${quote(value)}`), '}')
70
+ for (const rule of redirects)
71
+ lines.push(`redir ${rule.from} ${rule.to} ${rule.status}`)
72
+ return `${lines.join('\n')}\n`
73
+ }
74
+
75
+ export function nginxSnippet(security: SecurityHeadersOptions | false | undefined, redirects: readonly StaticRedirect[]): string {
76
+ const lines = ['# Written by `prunelle build --static`. Inside a server block: `include /path/to/dist/prunelle.nginx.conf;`.', '# A location block that sets its own add_header drops these: repeat the include there.']
77
+ for (const [name, value] of headerEntries(security))
78
+ lines.push(`add_header ${titleCase(name)} ${quote(value)} always;`)
79
+ for (const rule of redirects)
80
+ lines.push(`location = ${rule.from} { return ${rule.status} ${rule.to}; }`)
81
+ return `${lines.join('\n')}\n`
82
+ }
83
+
84
+ /** Writes the header files into the stage; a `_headers` or snippet the app ships in `public/` is left as it is. */
85
+ export function writeStaticHostFiles(stageDir: string, security: SecurityHeadersOptions | false | undefined): void {
86
+ const redirectsFile = join(stageDir, '_redirects')
87
+ const redirects = existsSync(redirectsFile) ? parseRedirects(readFileSync(redirectsFile, 'utf8')) : []
88
+ const files: [string, string][] = [['_headers', netlifyHeaders(security)], [CADDY_SNIPPET, caddySnippet(security, redirects)], [NGINX_SNIPPET, nginxSnippet(security, redirects)]]
89
+ for (const [name, text] of files) {
90
+ if (text !== '' && !existsSync(join(stageDir, name)))
91
+ writeFileSync(join(stageDir, name), text)
92
+ }
93
+ }
@@ -19,6 +19,7 @@ import { walkAllFiles } from './files'
19
19
  import { swapStage } from './output'
20
20
  import { precompressFiles } from './precompress'
21
21
  import { pageFailure } from './prerender'
22
+ import { writeStaticHostFiles } from './static-headers'
22
23
 
23
24
  const LEADING_SLASH_RE = /^\//
24
25
 
@@ -198,6 +199,7 @@ export async function exportStatic(options: StaticExportOptions): Promise<void>
198
199
  publicFiles.register(relative(outPublicDir, abs))
199
200
  for (const rel of publicFiles.files)
200
201
  copyInto(stageDir, rel, join(outPublicDir, rel))
202
+ writeStaticHostFiles(stageDir, options.entry?.prunelleConfig.security)
201
203
  await precompressFiles(walkAllFiles(stageDir), 128, options.root)
202
204
  if (!options.isDev)
203
205
  carryPreviousAssets(finalOutDir, stageDir, relative(stageDir, assetDir), options.assets)