prunelle 0.1.1 → 0.5.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 (88) hide show
  1. package/llms.txt +23 -19
  2. package/package.json +8 -2
  3. package/src/a11y/declaration.ts +335 -0
  4. package/src/a11y/index.ts +446 -0
  5. package/src/a11y/rgaa-map.ts +184 -0
  6. package/src/attrs.ts +11 -3
  7. package/src/build/bundle.ts +3 -2
  8. package/src/build/client-entries.ts +3 -2
  9. package/src/build/client-plugin.ts +8 -4
  10. package/src/build/client-prune.ts +11 -2
  11. package/src/build/compile.ts +2 -1
  12. package/src/build/ecoindex.ts +229 -0
  13. package/src/build/index.ts +121 -44
  14. package/src/build/manifest.ts +66 -5
  15. package/src/build/output.ts +2 -2
  16. package/src/build/plugin-host.ts +91 -33
  17. package/src/build/precompress.ts +15 -2
  18. package/src/build/prerender.ts +2 -2
  19. package/src/build/report.ts +23 -2
  20. package/src/build/resolve.ts +4 -3
  21. package/src/build/routes.ts +175 -10
  22. package/src/build/static.ts +71 -17
  23. package/src/build/status-pages.ts +127 -0
  24. package/src/build/style-bundles.ts +338 -0
  25. package/src/cli/check-forms.ts +654 -0
  26. package/src/cli/check-links.ts +619 -0
  27. package/src/cli/check.ts +52 -5
  28. package/src/cli/commands.ts +86 -4
  29. package/src/cli/docs.ts +402 -0
  30. package/src/cli/inspect.ts +31 -2
  31. package/src/cli/mcp-tools.ts +480 -0
  32. package/src/cli/mcp.ts +205 -0
  33. package/src/cli/new.ts +2 -2
  34. package/src/cli/render.ts +261 -0
  35. package/src/cli/upgrade-names.ts +73 -13
  36. package/src/cli/upgrade.ts +137 -16
  37. package/src/compiler/analyze.ts +17 -3
  38. package/src/compiler/cacheability.ts +592 -0
  39. package/src/compiler/compliance-rgaa.ts +502 -0
  40. package/src/compiler/compliance.ts +120 -221
  41. package/src/compiler/dev-source.ts +87 -0
  42. package/src/compiler/dom.ts +7 -7
  43. package/src/compiler/ssr.ts +135 -37
  44. package/src/dev/error-log.ts +151 -0
  45. package/src/dev/index.ts +60 -29
  46. package/src/dev/open-editor.ts +204 -0
  47. package/src/dev/reload.ts +5 -3
  48. package/src/dev/supervisor.ts +3 -0
  49. package/src/dom/action.ts +4 -1
  50. package/src/dom/island.ts +11 -10
  51. package/src/plugins/config.ts +4 -4
  52. package/src/plugins/index.ts +2 -2
  53. package/src/plugins/public.ts +5 -2
  54. package/src/plugins/services.ts +62 -0
  55. package/src/plugins/types.ts +32 -0
  56. package/src/server/action-protect.ts +198 -0
  57. package/src/server/action-registry.ts +1 -1
  58. package/src/server/action.ts +82 -27
  59. package/src/server/errors.ts +291 -62
  60. package/src/server/form-schema.ts +343 -0
  61. package/src/server/health.ts +244 -0
  62. package/src/server/http.ts +86 -19
  63. package/src/server/index.ts +158 -219
  64. package/src/server/param-matchers.ts +112 -0
  65. package/src/server/plugin-host.ts +40 -14
  66. package/src/server/public.ts +3 -3
  67. package/src/server/rate-limit.ts +58 -35
  68. package/src/server/request-body.ts +1 -1
  69. package/src/server/route-cache.ts +365 -0
  70. package/src/server/route-table.ts +302 -6
  71. package/src/server/router.ts +125 -40
  72. package/src/server/routing.ts +187 -61
  73. package/src/server/security.ts +208 -32
  74. package/src/server/serve-handlers.ts +21 -7
  75. package/src/ssr/context.ts +49 -0
  76. package/src/ssr/index.ts +120 -1
  77. package/src/test/browser.ts +6 -0
  78. package/src/test/index.ts +17 -3
  79. package/src/ts-plugin/diagnostics.ts +378 -0
  80. package/src/ts-plugin/fixes.ts +364 -0
  81. package/src/ts-plugin/index.ts +194 -0
  82. package/templates/_shared/AGENTS.md +2 -2
  83. package/templates/_shared/mcp.json +11 -0
  84. package/templates/_shared/src/routes/legal.tsx +5 -0
  85. package/templates/_shared/tsconfig.json +5 -0
  86. package/templates/blog/prunelle.config.ts +1 -1
  87. package/templates/blog/src/routes/index.tsx +4 -0
  88. package/ts-plugin.cjs +4277 -0
@@ -1,11 +1,17 @@
1
1
  // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
2
 
3
+ import type { RouteCacheSpec } from '../server/route-cache'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
6
+ import type { StatusPageManifestEntry } from './status-pages'
5
7
  import { join } from 'node:path'
8
+ import { isRouteCacheable } from '../compiler/cacheability'
6
9
  import { isInside } from './is-inside'
7
10
  import { islandKey } from './islands'
8
11
  import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
12
+ import { buildStatusPageEntries } from './status-pages'
13
+
14
+ export type { StatusPageKind, StatusPageManifestEntry } from './status-pages'
9
15
 
10
16
  const REGION_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
11
17
 
@@ -38,6 +44,10 @@ export interface RouteManifestEntry {
38
44
  /** The route, a layout or a component it renders imports `<Region>`. */
39
45
  usesRegion?: boolean | undefined
40
46
  prerender?: boolean | undefined
47
+ /** Route response cache policy from `export const cache = ...`. */
48
+ cache?: RouteCacheSpec | undefined
49
+ /** True when static analysis proves the page reads nothing from the request or clock. */
50
+ cacheable?: boolean | undefined
41
51
  prerendered?: Record<string, string> | undefined
42
52
  /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
43
53
  prerenderedStyleHashes?: Record<string, string[]> | undefined
@@ -63,6 +73,10 @@ export interface BuildManifest {
63
73
  rootLayoutFile?: string | undefined
64
74
  errorFile?: string | undefined
65
75
  notFoundFile?: string | undefined
76
+ /** Discovered status/error pages (`_401`, `_403`, `_404`, `_429`, `_503`, `_error`), root and nested. */
77
+ statusPages?: StatusPageManifestEntry[] | undefined
78
+ /** Custom app param matchers (`src/params/<name>.ts`), mapping matcher name to compiled module key. */
79
+ paramMatchers?: Record<string, string> | undefined
66
80
  actions: ActionManifestEntry[]
67
81
  islands: Record<string, string>
68
82
  assets: string[]
@@ -78,6 +92,8 @@ interface FileReach {
78
92
  chunks: Set<string>
79
93
  eager: Set<string>
80
94
  styles: Set<string>
95
+ /** All reachable source files (`.ts`/`.tsx`) walked from this file. */
96
+ files: Set<string>
81
97
  usesRenderContext: boolean
82
98
  usesRegion: boolean
83
99
  }
@@ -167,14 +183,25 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
167
183
  || graph.localDeps(file).some(dep => walkRegion(dep, seen))
168
184
  }
169
185
 
186
+ function walkFiles(file: string, seen: Set<string>): void {
187
+ if (seen.has(file))
188
+ return
189
+ seen.add(file)
190
+ for (const target of islands.pageBindings.get(file)?.values() ?? [])
191
+ walkFiles(target.file, seen)
192
+ for (const dep of graph.localDeps(file))
193
+ walkFiles(dep, seen)
194
+ }
195
+
170
196
  // Layouts are shared by many routes, so each file is walked once.
171
197
  const memo = new Map<string, FileReach>()
172
198
  return (file: string): FileReach => {
173
199
  let reach = memo.get(file)
174
200
  if (reach === undefined) {
175
- reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false, usesRegion: false }
201
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), files: new Set(), usesRenderContext: false, usesRegion: false }
176
202
  walkIslands(file, new Set(), reach)
177
203
  walkStyles(file, new Set(), reach.styles)
204
+ walkFiles(file, reach.files)
178
205
  reach.usesRenderContext = walkRenderContext(file, new Set())
179
206
  reach.usesRegion = walkRegion(file, new Set())
180
207
  memo.set(file, reach)
@@ -185,10 +212,15 @@ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks
185
212
 
186
213
  export interface RouteEntries {
187
214
  routes: RouteManifestEntry[]
215
+ statusPages: StatusPageManifestEntry[]
188
216
  /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
189
217
  globalStyles: string[]
190
218
  /** The plugins' CSS alone. */
191
219
  globalPluginStyles: string[]
220
+ /** Reachable source files for each route path (layouts + page + islands + local deps). */
221
+ routeSourceFiles: Map<string, string[]>
222
+ /** Reachable source files of the root layout and status/error pages. */
223
+ globalSourceFiles: string[]
192
224
  }
193
225
 
194
226
  export function buildRouteEntries(options: {
@@ -199,8 +231,11 @@ export function buildRouteEntries(options: {
199
231
  islandCssUrl: Map<string, string>
200
232
  routesDir: string
201
233
  pageFiles: string[]
234
+ specialFiles?: readonly string[] | undefined
202
235
  pluginCssFiles: string[]
203
236
  isStatic: boolean
237
+ /** Automatically prerender static cacheable pages (no middleware, not `prerender = false`, no `cache` export). */
238
+ autoPrerender?: boolean | undefined
204
239
  /** Maps a source file to its compiled module, relative to the out dir. */
205
240
  toOutRel: (srcFile: string) => string
206
241
  }): RouteEntries {
@@ -210,6 +245,8 @@ export function buildRouteEntries(options: {
210
245
  const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
211
246
  const rootLayout = join(routesDir, '_layout.tsx')
212
247
  const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
248
+ const routeSourceFiles = new Map<string, string[]>()
249
+ const globalSourceSet = new Set<string>(graph.analyses.has(rootLayout) ? reachOf(rootLayout).files : [])
213
250
 
214
251
  const routes = options.pageFiles.map((file): RouteManifestEntry => {
215
252
  const analysis = graph.analyses.get(file)
@@ -218,6 +255,7 @@ export function buildRouteEntries(options: {
218
255
  const chunks = new Set<string>()
219
256
  const eagerChunks = new Set<string>()
220
257
  const styles = new Set<string>(globalPluginStyles)
258
+ const reachableFiles = new Set<string>()
221
259
  let usesRenderContext = false
222
260
  let usesRegion = false
223
261
  for (const src of [...layoutSrcs, file]) {
@@ -228,14 +266,22 @@ export function buildRouteEntries(options: {
228
266
  eagerChunks.add(chunk)
229
267
  for (const style of reach.styles)
230
268
  styles.add(style)
269
+ for (const f of reach.files)
270
+ reachableFiles.add(f)
231
271
  usesRenderContext ||= reach.usesRenderContext
232
272
  usesRegion ||= reach.usesRegion
233
273
  }
274
+ const routePath = fileToRoutePath(routesDir, file)
275
+ routeSourceFiles.set(routePath, [...reachableFiles])
276
+ const middlewareSrcs = ancestorFiles(routesDir, file, MIDDLEWARE_NAMES)
277
+ const cacheable = isRouteCacheable({ graph, islands, file, layoutSrcs, middlewareCount: middlewareSrcs.length, routePath })
278
+ const cache = analysis?.cache
279
+ const autoPre = options.autoPrerender === true && cacheable && cache === undefined
234
280
  return {
235
- path: fileToRoutePath(routesDir, file),
281
+ path: routePath,
236
282
  file: toOutRel(file),
237
283
  layouts: layoutSrcs.map(toOutRel),
238
- middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
284
+ middlewares: middlewareSrcs.map(toOutRel),
239
285
  hasLoad: analysis?.hasLoadExport,
240
286
  isIsland: page?.interactive,
241
287
  islandChunk: islandChunks.get(`${file}#default`),
@@ -246,10 +292,25 @@ export function buildRouteEntries(options: {
246
292
  styles: [...styles],
247
293
  usesRenderContext,
248
294
  usesRegion,
249
- prerender: analysis?.hasPrerender || options.isStatic,
295
+ prerender: analysis?.hasPrerender || options.isStatic || autoPre,
296
+ ...(cache !== undefined ? { cache } : {}),
297
+ ...(cacheable ? { cacheable: true } : {}),
250
298
  }
251
299
  })
252
- return { routes, globalStyles, globalPluginStyles }
300
+ for (const special of options.specialFiles ?? []) {
301
+ if (graph.analyses.has(special)) {
302
+ for (const f of reachOf(special).files)
303
+ globalSourceSet.add(f)
304
+ }
305
+ }
306
+ const statusPages = buildStatusPageEntries({
307
+ routesDir,
308
+ specialFiles: options.specialFiles ?? [],
309
+ globalPluginStyles,
310
+ reachOf,
311
+ toOutRel,
312
+ })
313
+ return { routes, statusPages, globalStyles, globalPluginStyles, routeSourceFiles, globalSourceFiles: [...globalSourceSet] }
253
314
  }
254
315
 
255
316
  export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
@@ -16,9 +16,9 @@ export function assertOwnOutDir(root: string, outDir: string, assetPrefix: strin
16
16
  const names = new Set(readdirSync(outDir))
17
17
  if (names.size === 0 || names.has(OUTPUT_MARKER))
18
18
  return
19
- // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder.
19
+ // A build made before the marker existed: a server build's manifest beside its server/ folder, or a static export's asset folder (including a kay v2 export's `_kay/`).
20
20
  const assetDir = assetPrefix.replace(LEADING_SLASH_RE, '').split('/')[0] ?? ''
21
- if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)))
21
+ if ((names.has('manifest.json') && names.has('server')) || (assetDir !== '' && names.has(assetDir)) || names.has('_kay'))
22
22
  return
23
23
  throw new Error(`prunelle build: refusing to replace "${relPosix(root, outDir)}": it holds files prunelle did not build. Delete it, or set \`outDir\` in prunelle.config.ts to a folder of its own.`)
24
24
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { AppRuntimeContext } from '../plugins/context'
4
4
  import type { BuildPluginContext, FinalizeBuildContext, PrunellePlugin } from '../plugins/index'
5
- import type { RouteManifestEntry } from './manifest'
5
+ import type { RouteManifestEntry, StatusPageManifestEntry } from './manifest'
6
6
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
7
7
  import { dirname, join } from 'node:path'
8
8
  import { precompressFiles } from './precompress'
@@ -66,6 +66,9 @@ export interface PluginHostOptions {
66
66
  isStatic: boolean
67
67
  isDev: boolean
68
68
  routes: RouteManifestEntry[]
69
+ statusPages?: StatusPageManifestEntry[] | undefined
70
+ routeSourceFiles?: ReadonlyMap<string, readonly string[]> | undefined
71
+ globalSourceFiles?: readonly string[] | undefined
69
72
  publicFiles: PublicFiles
70
73
  /** Client files already emitted, relative to the client dir. */
71
74
  assets: string[]
@@ -73,14 +76,88 @@ export interface PluginHostOptions {
73
76
  globalStyles: string[]
74
77
  }
75
78
 
76
- export function createPluginHost(options: PluginHostOptions) {
77
- const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
78
- const assetSet = new Set(assets)
79
+ function createStyleMutators(
80
+ styleUrls: string[],
81
+ globalStyles: string[],
82
+ routes: RouteManifestEntry[],
83
+ statusPages: StatusPageManifestEntry[],
84
+ ) {
79
85
  const styleSet = new Set(styleUrls)
80
86
  const globalStyleSet = new Set(globalStyles)
87
+ let prependedGlobalCount = 0
88
+
89
+ const addStyleUrl = (href: string): void => {
90
+ if (!styleSet.has(href)) {
91
+ styleSet.add(href)
92
+ styleUrls.push(href)
93
+ }
94
+ }
95
+
96
+ return {
97
+ addStyle(href: string) {
98
+ addStyleUrl(href)
99
+ if (!globalStyleSet.has(href)) {
100
+ globalStyleSet.add(href)
101
+ globalStyles.push(href)
102
+ }
103
+ for (const r of routes) {
104
+ if (r.styles !== undefined && !r.styles.includes(href))
105
+ r.styles.push(href)
106
+ }
107
+ for (const sp of statusPages) {
108
+ if (!sp.styles.includes(href))
109
+ sp.styles.push(href)
110
+ }
111
+ },
112
+ prependStyle(href: string) {
113
+ addStyleUrl(href)
114
+ const insertAt = prependedGlobalCount
115
+ if (!globalStyleSet.has(href)) {
116
+ globalStyleSet.add(href)
117
+ globalStyles.splice(insertAt, 0, href)
118
+ prependedGlobalCount++
119
+ }
120
+ for (const r of routes) {
121
+ if (r.styles !== undefined && !r.styles.includes(href))
122
+ r.styles.splice(Math.min(insertAt, r.styles.length), 0, href)
123
+ }
124
+ for (const sp of statusPages) {
125
+ if (!sp.styles.includes(href))
126
+ sp.styles.splice(Math.min(insertAt, sp.styles.length), 0, href)
127
+ }
128
+ },
129
+ addRouteStyle(routePath: string, href: string) {
130
+ addStyleUrl(href)
131
+ const route = routes.find(r => r.path === routePath)
132
+ if (route !== undefined) {
133
+ route.styles ??= [...globalStyles]
134
+ if (!route.styles.includes(href))
135
+ route.styles.push(href)
136
+ }
137
+ },
138
+ prependRouteStyle(routePath: string, href: string) {
139
+ addStyleUrl(href)
140
+ const route = routes.find(r => r.path === routePath)
141
+ if (route !== undefined) {
142
+ route.styles ??= [...globalStyles]
143
+ if (!route.styles.includes(href)) {
144
+ let idx = 0
145
+ while (idx < route.styles.length && globalStyleSet.has(route.styles[idx]!))
146
+ idx++
147
+ route.styles.splice(idx, 0, href)
148
+ }
149
+ }
150
+ },
151
+ }
152
+ }
153
+
154
+ export function createPluginHost(options: PluginHostOptions) {
155
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, statusPages = [], assets, styleUrls, globalStyles } = options
156
+ const assetSet = new Set(assets)
81
157
  const headTags: string[] = []
82
158
  const pluginData: Record<string, Record<string, unknown>> = {}
83
159
  const precompressed = new Set<string>()
160
+ const styles = createStyleMutators(styleUrls, globalStyles, routes, statusPages)
84
161
 
85
162
  function emitAsset(relPath: string, content: string | Uint8Array): string {
86
163
  const clean = cleanRel(relPath)
@@ -102,13 +179,6 @@ export function createPluginHost(options: PluginHostOptions) {
102
179
  return `/${clean}`
103
180
  }
104
181
 
105
- function addStyleUrl(href: string): void {
106
- if (!styleSet.has(href)) {
107
- styleSet.add(href)
108
- styleUrls.push(href)
109
- }
110
- }
111
-
112
182
  // resolvePlugins() refuses two plugins sharing a name, so each name has one owner.
113
183
  const setDataFor = (plugin: PrunellePlugin) => (data: Record<string, unknown>): void => {
114
184
  pluginData[plugin.name] = { ...pluginData[plugin.name], ...data }
@@ -131,26 +201,9 @@ export function createPluginHost(options: PluginHostOptions) {
131
201
 
132
202
  const buildCtx = {
133
203
  ...shared,
134
- addStyle(href: string) {
135
- addStyleUrl(href)
136
- if (!globalStyleSet.has(href)) {
137
- globalStyleSet.add(href)
138
- globalStyles.push(href)
139
- }
140
- for (const r of routes) {
141
- if (r.styles !== undefined && !r.styles.includes(href))
142
- r.styles.push(href)
143
- }
144
- },
145
- addRouteStyle(routePath: string, href: string) {
146
- addStyleUrl(href)
147
- const route = routes.find(r => r.path === routePath)
148
- if (route !== undefined) {
149
- route.styles ??= [...globalStyles]
150
- if (!route.styles.includes(href))
151
- route.styles.push(href)
152
- }
153
- },
204
+ ...(options.routeSourceFiles !== undefined ? { routeSourceFiles: options.routeSourceFiles } : {}),
205
+ ...(options.globalSourceFiles !== undefined ? { globalSourceFiles: options.globalSourceFiles } : {}),
206
+ ...styles,
154
207
  addHead(html: string) {
155
208
  if (html !== '')
156
209
  headTags.push(html)
@@ -176,12 +229,17 @@ export function createPluginHost(options: PluginHostOptions) {
176
229
  },
177
230
 
178
231
  /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
179
- async runAfterPrerender(): Promise<boolean> {
232
+ async runAfterPrerender(prerenderDir?: string): Promise<boolean> {
180
233
  let ran = false
181
234
  for (const plugin of plugins) {
182
235
  if (plugin.afterPrerender !== undefined) {
183
236
  ran = true
184
- const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin) }
237
+ const ctx: FinalizeBuildContext = {
238
+ ...shared,
239
+ ...(prerenderDir !== undefined ? { prerenderDir } : {}),
240
+ publicFiles: options.publicFiles.files,
241
+ setData: setDataFor(plugin),
242
+ }
185
243
  await runPluginHook(plugin, 'afterPrerender', () => plugin.afterPrerender!(ctx))
186
244
  }
187
245
  }
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
4
4
  import { availableParallelism } from 'node:os'
5
- import { dirname, extname, join } from 'node:path'
5
+ import { basename, dirname, extname, join } from 'node:path'
6
6
  import { promisify } from 'node:util'
7
7
  import { brotliCompress, brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
8
  import { getAppContext } from '../plugins/context'
@@ -46,9 +46,22 @@ function readEntry(file: string): Buffer | undefined {
46
46
  }
47
47
  }
48
48
 
49
+ /** Writes a self-ignoring `.gitignore` inside `.prunelle-cache/` so git never lists cached files as untracked (#39). */
50
+ export function ensureCacheGitignore(cacheRoot: string): void {
51
+ const file = join(cacheRoot, '.gitignore')
52
+ if (existsSync(file))
53
+ return
54
+ mkdirSync(cacheRoot, { recursive: true })
55
+ writeFileSync(file, '*\n')
56
+ }
57
+
49
58
  // Renamed into place, so a build running beside this one never reads half an entry.
50
59
  function writeEntry(file: string, packed: Uint8Array): void {
51
- mkdirSync(dirname(file), { recursive: true })
60
+ const dir = dirname(file)
61
+ mkdirSync(dir, { recursive: true })
62
+ const parent = dirname(dir)
63
+ if (basename(parent) === '.prunelle-cache')
64
+ ensureCacheGitignore(parent)
52
65
  const tmp = `${file}.${process.pid}-${tmpCount++}.tmp`
53
66
  writeFileSync(tmp, packed)
54
67
  renameSync(tmp, file)
@@ -5,7 +5,7 @@ import type { RouteManifestEntry } from './manifest'
5
5
  import { mkdirSync, writeFileSync } from 'node:fs'
6
6
  import { dirname, extname, resolve } from 'node:path'
7
7
  import { prerenderOrigin } from '../server/prerendered'
8
- import { inlineStyleHashes } from '../server/security'
8
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
9
9
  import { relPosix } from './files'
10
10
  import { runPluginHook } from './plugin-host'
11
11
  import { assertPathUrls } from './routes'
@@ -132,7 +132,7 @@ export async function prerender(options: PrerenderOptions) {
132
132
  mkdirSync(dirname(absOut), { recursive: true })
133
133
  if ((ct ?? '').toLowerCase().includes('text/html')) {
134
134
  const html = await res.text()
135
- writeFileSync(absOut, html)
135
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
136
136
  const hashes = inlineStyleHashes(html)
137
137
  if (hashes.length > 0)
138
138
  styleHashes[u] = hashes
@@ -1,13 +1,18 @@
1
1
  // The `--analyze` report and the `--max-js` budget: eager JS and CSS weight per route, from the manifest and the client metafile (or the chunks' own imports), and the islands behind it.
2
2
 
3
+ import type { EcoIndexGrade, RouteEcoIndex } from './ecoindex'
3
4
  import type { ModuleGraph } from './graph'
4
5
  import type { IslandPlan } from './islands'
5
6
  import type { BuildManifest } from './manifest'
6
7
  import { existsSync, readFileSync } from 'node:fs'
7
8
  import { join, posix } from 'node:path'
9
+ import { computeEcoIndex, countDomElements, measureRouteEcoIndex } from './ecoindex'
8
10
  import { relPosix } from './files'
9
11
  import { distLocator, firstLoadUrls, measureFirstLoad, STATIC_CHUNK_IMPORT_RE } from './first-load'
10
12
 
13
+ export type { EcoIndexGrade, RouteEcoIndex }
14
+ export { computeEcoIndex, countDomElements }
15
+
11
16
  export interface IslandOrigin {
12
17
  /** The component's export name, `default` for a page or a default export. */
13
18
  name: string
@@ -35,6 +40,8 @@ export interface RouteBundleMetrics {
35
40
  /** Everything a first visit fetches except the HTML (CSS, eager JS and its imports, fonts, images, icons), brotli. */
36
41
  firstLoad: number
37
42
  islands: RouteIsland[]
43
+ /** GreenIT EcoIndex score and footprint measured on prerendered HTML output (worst URL for dynamic routes). */
44
+ ecoIndex?: RouteEcoIndex | undefined
38
45
  }
39
46
 
40
47
  export interface BundleReport {
@@ -65,6 +72,7 @@ export function analyzeBundleWeights(
65
72
  metafile?: Bun.BuildOutput['metafile'],
66
73
  origins = new Map<string, IslandOrigin>(),
67
74
  publicDirs: readonly string[] = [],
75
+ prerenderBaseDir?: string | undefined,
68
76
  ): BundleReport {
69
77
  const locate = distLocator({ clientDir, assetPrefix, publicDirs })
70
78
  const prefix = `${assetPrefix.replace(/\/$/, '')}/`
@@ -166,6 +174,9 @@ export function analyzeBundleWeights(
166
174
 
167
175
  const headUrls = firstLoadUrls([...manifest.headTags ?? [], ...r.headTags ?? []].join(''))
168
176
  const load = measureFirstLoad([...cssList, ...eagerJsRoots, ...headUrls], locate)
177
+ const ecoIndex = prerenderBaseDir !== undefined
178
+ ? measureRouteEcoIndex(r, { prerenderBaseDir, locate })
179
+ : undefined
169
180
 
170
181
  return {
171
182
  path: r.path,
@@ -178,6 +189,7 @@ export function analyzeBundleWeights(
178
189
  jsFiles: jsSet.size,
179
190
  cssFiles: cssList.length,
180
191
  islands,
192
+ ...(ecoIndex !== undefined ? { ecoIndex } : {}),
181
193
  }
182
194
  })
183
195
 
@@ -203,25 +215,34 @@ const kb = (b: number): string => `${(b / 1024).toFixed(2)} KB`
203
215
  const islandLine = (island: RouteIsland): string => `${island.name} (${island.file}) ${island.reason}`
204
216
 
205
217
  export function formatBundleReport(report: BundleReport): string {
218
+ const hasEco = report.routes.some(r => r.ecoIndex !== undefined)
206
219
  const lines = [
207
220
  '\n=== PRUNELLE BUNDLE WEIGHT REPORT ===',
208
221
  `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
209
222
  '',
210
- 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10),
223
+ 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Fonts (br)'.padStart(14) + 'First load (br)'.padStart(18) + 'Files'.padStart(10) + (hasEco ? 'EcoIndex'.padStart(12) : ''),
211
224
  ]
212
225
  for (const r of report.routes) {
226
+ const ecoCell = hasEco
227
+ ? (r.ecoIndex !== undefined ? `${r.ecoIndex.grade} (${Math.round(r.ecoIndex.score)})` : '-').padStart(12)
228
+ : ''
213
229
  lines.push(
214
230
  r.path.padEnd(28)
215
231
  + kb(r.jsGzip).padStart(16)
216
232
  + kb(r.cssGzip).padStart(14)
217
233
  + kb(r.fonts).padStart(14)
218
234
  + kb(r.firstLoad).padStart(18)
219
- + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
235
+ + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10)
236
+ + ecoCell,
220
237
  )
238
+ if (r.ecoIndex?.url !== undefined)
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)`)
221
240
  for (const island of r.islands)
222
241
  lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
223
242
  }
224
243
  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.')
244
+ if (hasEco)
245
+ 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.')
225
246
  if (report.topModules.length > 0) {
226
247
  lines.push('', 'Top modules (minified output bytes):')
227
248
  for (const m of report.topModules.slice(0, 8))
@@ -36,15 +36,16 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
36
36
  }
37
37
  }
38
38
 
39
+ const PRUNELLE_PKG_ROOT = resolve(PRUNELLE_SRC_ROOT, '..')
40
+
39
41
  const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
40
42
  Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
41
43
  subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
42
- target.replace(/^\.\/src\//, ''),
44
+ resolve(PRUNELLE_PKG_ROOT, target),
43
45
  ]),
44
46
  )
45
47
 
46
48
  /** Maps `prunelle` and its subpaths to their source file. */
47
49
  export function resolvePrunelleSpecifier(specifier: string): string | undefined {
48
- const file = PRUNELLE_SPECIFIER_FILES.get(specifier)
49
- return file === undefined ? undefined : join(PRUNELLE_SRC_ROOT, file)
50
+ return PRUNELLE_SPECIFIER_FILES.get(specifier)
50
51
  }