prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -2,10 +2,12 @@
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
- import { inlineStyleHashes } from '../server/security'
9
+ import { decodeRequestPath } from '../server/request-path'
10
+ import { inlineStyleHashes, injectMetaCsp } from '../server/security'
9
11
  import { relPosix } from './files'
10
12
  import { runPluginHook } from './plugin-host'
11
13
  import { assertPathUrls } from './routes'
@@ -14,18 +16,60 @@ const CONCURRENCY = 8
14
16
  const SLASH_EDGES_RE = /^\/|\/$/g
15
17
  const TRAILING_SLASHES_RE = /\/+$/
16
18
 
19
+ const CONTENT_TYPE_EXT: Record<string, string> = {
20
+ 'application/json': '.json',
21
+ 'application/xml': '.xml',
22
+ 'text/xml': '.xml',
23
+ 'application/rss+xml': '.rss',
24
+ 'application/atom+xml': '.atom',
25
+ 'text/plain': '.txt',
26
+ 'image/svg+xml': '.svg',
27
+ 'text/calendar': '.ics',
28
+ 'text/csv': '.csv',
29
+ }
30
+
31
+ function extForContentType(contentType: string | null): string {
32
+ if (contentType === null)
33
+ return ''
34
+ const semi = contentType.indexOf(';')
35
+ const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
36
+ return CONTENT_TYPE_EXT[mime] ?? ''
37
+ }
38
+
39
+ function assertSafePrerenderPath(raw: string, original: string): string {
40
+ const decoded = decodeRequestPath(raw)
41
+ if (decoded?.staticPath === undefined)
42
+ throw new Error(`prunelle build: unsafe or malformed prerender path "${original}".`)
43
+ if (decoded.staticPath.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
44
+ throw new Error(`prunelle build: prerender path "${original}" escapes output directory.`)
45
+ return decoded.staticPath
46
+ }
17
47
 
18
48
  function normalizePrerenderUrl(urlStr: string): string {
19
- const pathname = new URL(urlStr, 'http://localhost').pathname
20
- return pathname.length > 1 && pathname.endsWith('/') ? (pathname.replace(TRAILING_SLASHES_RE, '') || '/') : pathname
49
+ assertSafePrerenderPath(urlStr.split(/[?#]/, 1)[0] ?? '', urlStr)
50
+ let pathname: string
51
+ try {
52
+ pathname = new URL(urlStr, 'http://localhost').pathname
53
+ }
54
+ catch {
55
+ throw new Error(`prunelle build: invalid prerender path "${urlStr}".`)
56
+ }
57
+ const staticPath = assertSafePrerenderPath(pathname, urlStr)
58
+ return staticPath.length > 1 && staticPath.endsWith('/') ? (staticPath.replace(TRAILING_SLASHES_RE, '') || '/') : staticPath
21
59
  }
22
60
 
23
- function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: boolean, contentType: string | null): string {
24
- const pathname = new URL(urlStr, 'http://localhost').pathname
61
+ function encodeUrlPath(pathname: string): string {
62
+ return pathname.split('/').map(encodeURIComponent).join('/')
63
+ }
64
+
65
+ function resolvePrerenderPath(prerenderDir: string, pathname: string, isStatic: boolean, contentType: string | null): string {
25
66
  const trimmed = pathname.replace(SLASH_EDGES_RE, '')
67
+ if (trimmed.split('/').some(seg => seg === '..' || seg.includes('\\') || seg.includes('\0')))
68
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
26
69
  const lastSeg = trimmed.slice(trimmed.lastIndexOf('/') + 1)
27
70
  const ext = extname(lastSeg).toLowerCase()
28
71
  const isHtml = (contentType ?? '').toLowerCase().includes('text/html')
72
+ const inferredExt = !isStatic && !isHtml && ext === '' ? extForContentType(contentType) : ''
29
73
  const preserveFile = ext !== '' && (ext === '.html' || ext === '.htm' || !isHtml)
30
74
  const rel = pathname === '/'
31
75
  ? 'index.html'
@@ -33,11 +77,13 @@ function resolvePrerenderPath(prerenderDir: string, urlStr: string, isStatic: bo
33
77
  ? '404.html'
34
78
  : preserveFile
35
79
  ? trimmed
36
- : `${trimmed}/index.html`
80
+ : inferredExt !== ''
81
+ ? `${trimmed}${inferredExt}`
82
+ : `${trimmed}/index.html`
37
83
  const absRoot = resolve(prerenderDir)
38
84
  const abs = resolve(absRoot, rel)
39
85
  if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
40
- throw new Error(`prunelle build: prerender path "${urlStr}" escapes output directory.`)
86
+ throw new Error(`prunelle build: prerender path "${pathname}" escapes output directory.`)
41
87
  return abs
42
88
  }
43
89
 
@@ -55,6 +101,17 @@ export interface PrerenderOptions {
55
101
  /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
56
102
  prerenderDir: string
57
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)
58
115
  }
59
116
 
60
117
  // The build fails through the CLI, which prints only the message: the page's own error and its stack go in it.
@@ -69,20 +126,30 @@ export function pageFailure(head: string, error: unknown): Error {
69
126
  return new Error(`${head}: ${error.message}${frames}`, { cause: error })
70
127
  }
71
128
 
72
- /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
73
- export async function prerender(options: PrerenderOptions) {
74
- const { root, outDir, prerenderDir, isStatic } = options
75
- // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
76
- const { startBuiltApp } = await import('../server/loader')
77
- const pageErrors = new Map<string, unknown>()
78
- const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
79
- if (!pageErrors.has(request.url))
80
- pageErrors.set(request.url, error)
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()
81
144
  }
82
- const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true })
83
- const origin = prerenderOrigin(options.site)
84
- mkdirSync(prerenderDir, { recursive: true })
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
+ }
85
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[] }[] = []
86
153
  for (const route of options.routes) {
87
154
  let urls: string[] = []
88
155
  let hasPathsFn = false
@@ -90,15 +157,15 @@ export async function prerender(options: PrerenderOptions) {
90
157
  urls = [route.path]
91
158
  }
92
159
  else {
93
- const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
160
+ const mod = modules?.[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
94
161
  if (typeof mod.paths === 'function') {
95
162
  hasPathsFn = true
96
- const returned: unknown = await mod.paths()
163
+ const returned: unknown = await namedPathsError(route, routeSource(options, route), mod.paths)
97
164
  assertPathUrls(returned, route.file)
98
165
  urls = returned
99
166
  }
100
167
  else {
101
- console.warn(`prunelle build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
168
+ console.warn(`prunelle build${options.isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${routeSource(options, route)}) because it does not export a paths() function.`)
102
169
  }
103
170
  }
104
171
 
@@ -115,36 +182,104 @@ export async function prerender(options: PrerenderOptions) {
115
182
  continue
116
183
  }
117
184
 
118
- const map: Record<string, string> = {}
119
- const styleHashes: Record<string, string[]> = {}
120
- for (let i = 0; i < urls.length; i += CONCURRENCY) {
121
- await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
122
- const request = new Request(`${origin}${u}`)
185
+ routePlans.push({ route, tasks: urls.map(url => ({ route, url })) })
186
+ }
187
+ return routePlans
188
+ }
189
+
190
+ /** Renders every route to HTML, records `route.prerendered`, and returns the server and entry the pages were rendered with. */
191
+ export async function prerender(options: PrerenderOptions) {
192
+ const { root, outDir, prerenderDir, isStatic } = options
193
+ // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
194
+ const { startBuiltApp } = await import('../server/loader')
195
+ const pageErrors = new Map<string, unknown>()
196
+ const errorSink = ({ error, request }: { error: unknown, request: Request }): void => {
197
+ if (!pageErrors.has(request.url))
198
+ pageErrors.set(request.url, error)
199
+ }
200
+ const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev, nodeEnv: options.nodeEnv, errorSink, prerender: true, static: isStatic })
201
+ const origin = prerenderOrigin(options.site)
202
+ mkdirSync(prerenderDir, { recursive: true })
203
+
204
+ try {
205
+ const routePlans = await planRoutes(options, entry?.modules)
206
+ const allTasks = routePlans.flatMap(plan => plan.tasks)
207
+ let nextIdx = 0
208
+ let failed = false
209
+ const runWorker = async (): Promise<void> => {
210
+ while (!failed) {
211
+ const idx = nextIdx++
212
+ if (idx >= allTasks.length)
213
+ return
214
+ const task = allTasks[idx]!
215
+ const u = task.url
216
+ const request = new Request(`${origin}${encodeUrlPath(u)}`)
123
217
  const res = await app.handle(request)
124
218
  const isExplicit404 = u === '/404' && res.status === 404
125
219
  if (res.status !== 200 && !isExplicit404) {
126
- if (isStatic || res.status >= 500)
220
+ if (isStatic || res.status >= 500) {
221
+ failed = true
127
222
  throw pageFailure(`prunelle build: prerender route "${u}" answered HTTP ${res.status}`, pageErrors.get(request.url))
128
- return
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.`)
227
+ continue
129
228
  }
130
229
  const ct = res.headers.get('content-type')
131
230
  const absOut = resolvePrerenderPath(prerenderDir, u, isStatic, ct)
132
231
  mkdirSync(dirname(absOut), { recursive: true })
133
232
  if ((ct ?? '').toLowerCase().includes('text/html')) {
134
233
  const html = await res.text()
135
- writeFileSync(absOut, html)
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
+ }
242
+ writeFileSync(absOut, isStatic ? injectMetaCsp(html, res.headers.get('content-security-policy')) : html)
136
243
  const hashes = inlineStyleHashes(html)
137
244
  if (hashes.length > 0)
138
- styleHashes[u] = hashes
245
+ task.hashes = hashes
139
246
  }
140
247
  else {
141
248
  writeFileSync(absOut, new Uint8Array(await res.arrayBuffer()))
142
249
  }
143
- map[u] = relPosix(isStatic ? prerenderDir : outDir, absOut)
144
- }))
250
+ task.relOut = relPosix(isStatic ? prerenderDir : outDir, absOut)
251
+ }
145
252
  }
146
- route.prerendered = map
147
- route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
253
+
254
+ const workers = Math.min(CONCURRENCY, allTasks.length)
255
+ await Promise.all(Array.from({ length: workers }, () => runWorker()))
256
+
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
+ }
268
+ const map: Record<string, string> = {}
269
+ const styleHashes: Record<string, string[]> = {}
270
+ for (const task of tasks) {
271
+ if (task.relOut !== undefined)
272
+ map[task.url] = task.relOut
273
+ if (task.hashes !== undefined)
274
+ styleHashes[task.url] = task.hashes
275
+ }
276
+ route.prerendered = map
277
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
278
+ }
279
+ }
280
+ catch (err) {
281
+ await app.dispose?.()
282
+ throw err
148
283
  }
149
- return { app, entry }
284
+ return { app, entry, errorFor: (url: string) => pageErrors.get(url) }
150
285
  }
@@ -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
  }
@@ -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,36 @@ 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)`)
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})`}`)
221
242
  for (const island of r.islands)
222
243
  lines.push(` ${island.eager ? 'island' : 'island, deferred'}: ${islandLine(island)}`)
223
244
  }
224
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
+ 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.')
225
248
  if (report.topModules.length > 0) {
226
249
  lines.push('', 'Top modules (minified output bytes):')
227
250
  for (const m of report.topModules.slice(0, 8))
@@ -234,8 +257,10 @@ export function formatBundleReportJson(report: BundleReport): string {
234
257
  return JSON.stringify(report, null, 2)
235
258
  }
236
259
 
237
- /** Throws naming each route whose eager JS, gzipped, is over `maxBytes`, with the islands it loads with the page. */
238
- 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 {
239
264
  const over = report.routes.filter(r => r.jsGzip > maxBytes)
240
265
  if (over.length === 0)
241
266
  return
@@ -243,5 +268,17 @@ export function checkJsBudget(report: BundleReport, maxBytes: number): void {
243
268
  const eager = r.islands.filter(island => island.eager).map(islandLine)
244
269
  return ` ${r.path} ships ${kb(r.jsGzip)} of eager JS: ${eager.length > 0 ? eager.join('; ') : 'the prunelle runtime alone'}`
245
270
  })
246
- 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.`)
247
284
  }
@@ -1,4 +1,4 @@
1
- // Resolves an import the way prunelle build follows it: relative files, then packages through Bun's resolver; prunelle, node:, bun and ~ aliases stay unresolved.
1
+ // Resolves an import the way prunelle build follows it: relative files, then packages and tsconfig aliases through Bun's resolver; prunelle, node:, bun and virtual prefixes stay unresolved.
2
2
 
3
3
  import { statSync } from 'node:fs'
4
4
  import { dirname, join, resolve } from 'node:path'
@@ -23,28 +23,30 @@ export function resolveImportPath(fromFile: string, specifier: string): string |
23
23
  || specifier.startsWith('node:')
24
24
  || specifier === 'bun'
25
25
  || specifier.startsWith('bun:')
26
- || specifier.startsWith('~')
26
+ || specifier.startsWith('~icons/')
27
+ || specifier.startsWith('virtual:')
27
28
  ) {
28
29
  return undefined
29
30
  }
30
31
  try {
31
32
  const resolved = Bun.resolveSync(specifier, dirname(fromFile))
32
- return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
33
+ return resolved.endsWith('.tsx') || resolved.endsWith('.ts') || resolved.endsWith('.css') ? resolved : undefined
33
34
  }
34
35
  catch {
35
36
  return undefined
36
37
  }
37
38
  }
38
39
 
40
+ const PRUNELLE_PKG_ROOT = resolve(PRUNELLE_SRC_ROOT, '..')
41
+
39
42
  const PRUNELLE_SPECIFIER_FILES = new Map<string, string>(
40
43
  Object.entries(pkg.exports as Record<string, string>).map(([subpath, target]) => [
41
44
  subpath === '.' ? 'prunelle' : `prunelle/${subpath.slice(2)}`,
42
- target.replace(/^\.\/src\//, ''),
45
+ resolve(PRUNELLE_PKG_ROOT, target),
43
46
  ]),
44
47
  )
45
48
 
46
49
  /** Maps `prunelle` and its subpaths to their source file. */
47
50
  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)
51
+ return PRUNELLE_SPECIFIER_FILES.get(specifier)
50
52
  }