prunelle 0.0.0-stage → 0.5.2

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 (200) hide show
  1. package/llms.txt +152 -0
  2. package/package.json +59 -4
  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/ambient.d.ts +6 -0
  7. package/src/attrs.ts +43 -0
  8. package/src/build/bundle.ts +657 -0
  9. package/src/build/carry.ts +57 -0
  10. package/src/build/client-entries.ts +107 -0
  11. package/src/build/client-plugin.ts +173 -0
  12. package/src/build/client-prune.ts +168 -0
  13. package/src/build/compile.ts +129 -0
  14. package/src/build/ecoindex.ts +229 -0
  15. package/src/build/files.ts +156 -0
  16. package/src/build/first-load.ts +164 -0
  17. package/src/build/graph.ts +247 -0
  18. package/src/build/index.ts +641 -0
  19. package/src/build/is-inside.ts +12 -0
  20. package/src/build/islands.ts +641 -0
  21. package/src/build/manifest.ts +325 -0
  22. package/src/build/output.ts +84 -0
  23. package/src/build/plugin-host.ts +278 -0
  24. package/src/build/precompress.ts +139 -0
  25. package/src/build/prerender.ts +232 -0
  26. package/src/build/render-rules.ts +205 -0
  27. package/src/build/report.ts +268 -0
  28. package/src/build/resolve.ts +52 -0
  29. package/src/build/routes.ts +342 -0
  30. package/src/build/server-entry.ts +38 -0
  31. package/src/build/static.ts +207 -0
  32. package/src/build/status-pages.ts +127 -0
  33. package/src/build/style-bundles.ts +526 -0
  34. package/src/cli/check-forms.ts +654 -0
  35. package/src/cli/check-links.ts +619 -0
  36. package/src/cli/check.ts +381 -0
  37. package/src/cli/commands.ts +345 -0
  38. package/src/cli/docs.ts +402 -0
  39. package/src/cli/index.ts +70 -0
  40. package/src/cli/inspect.ts +345 -0
  41. package/src/cli/mcp-tools.ts +480 -0
  42. package/src/cli/mcp.ts +205 -0
  43. package/src/cli/new.ts +41 -0
  44. package/src/cli/render.ts +261 -0
  45. package/src/cli/upgrade-names.ts +209 -0
  46. package/src/cli/upgrade.ts +354 -0
  47. package/src/compiler/analyze.ts +632 -0
  48. package/src/compiler/ast.ts +82 -0
  49. package/src/compiler/browser-globals.ts +127 -0
  50. package/src/compiler/cacheability.ts +592 -0
  51. package/src/compiler/compliance-rgaa.ts +502 -0
  52. package/src/compiler/compliance.ts +497 -0
  53. package/src/compiler/data-keys.ts +295 -0
  54. package/src/compiler/dev-source.ts +87 -0
  55. package/src/compiler/dom-attrs.ts +452 -0
  56. package/src/compiler/dom.ts +567 -0
  57. package/src/compiler/emit.ts +131 -0
  58. package/src/compiler/expr-context.ts +518 -0
  59. package/src/compiler/index.ts +8 -0
  60. package/src/compiler/interactivity.ts +366 -0
  61. package/src/compiler/mistakes.ts +499 -0
  62. package/src/compiler/node-env.ts +50 -0
  63. package/src/compiler/patch.ts +97 -0
  64. package/src/compiler/props.ts +511 -0
  65. package/src/compiler/scope.ts +607 -0
  66. package/src/compiler/server-only.ts +326 -0
  67. package/src/compiler/shared.ts +369 -0
  68. package/src/compiler/signal-reads.ts +242 -0
  69. package/src/compiler/slots.ts +227 -0
  70. package/src/compiler/ssr-helpers.ts +555 -0
  71. package/src/compiler/ssr-island.ts +90 -0
  72. package/src/compiler/ssr-prunelle-tags.ts +69 -0
  73. package/src/compiler/ssr.ts +526 -0
  74. package/src/context.ts +165 -0
  75. package/src/dev/child.ts +30 -0
  76. package/src/dev/error-log.ts +151 -0
  77. package/src/dev/index.ts +258 -0
  78. package/src/dev/modules.ts +68 -0
  79. package/src/dev/open-editor.ts +204 -0
  80. package/src/dev/protocol.ts +22 -0
  81. package/src/dev/queue.ts +79 -0
  82. package/src/dev/reload.ts +159 -0
  83. package/src/dev/supervisor.ts +204 -0
  84. package/src/dev/watchers.ts +251 -0
  85. package/src/dom/action.ts +164 -0
  86. package/src/dom/attrs.ts +84 -0
  87. package/src/dom/claim.ts +120 -0
  88. package/src/dom/extras.ts +562 -0
  89. package/src/dom/index.ts +289 -0
  90. package/src/dom/island.ts +285 -0
  91. package/src/dom/loop.ts +450 -0
  92. package/src/dom/revive.ts +36 -0
  93. package/src/index.ts +22 -0
  94. package/src/jsx-runtime.ts +566 -0
  95. package/src/plugins/config.ts +86 -0
  96. package/src/plugins/context.ts +66 -0
  97. package/src/plugins/index.ts +14 -0
  98. package/src/plugins/load.ts +70 -0
  99. package/src/plugins/order.ts +111 -0
  100. package/src/plugins/public.ts +15 -0
  101. package/src/plugins/requires.ts +47 -0
  102. package/src/plugins/services.ts +97 -0
  103. package/src/plugins/types.ts +261 -0
  104. package/src/reactivity/graph.ts +249 -0
  105. package/src/reactivity/index.ts +533 -0
  106. package/src/reactivity/selector.ts +51 -0
  107. package/src/reactivity/store.ts +208 -0
  108. package/src/server/action-protect.ts +198 -0
  109. package/src/server/action-registry.ts +78 -0
  110. package/src/server/action.ts +530 -0
  111. package/src/server/app-entry.ts +23 -0
  112. package/src/server/assets.ts +168 -0
  113. package/src/server/compress.ts +642 -0
  114. package/src/server/consent.ts +253 -0
  115. package/src/server/cookies.ts +139 -0
  116. package/src/server/document.ts +271 -0
  117. package/src/server/env.ts +33 -0
  118. package/src/server/errors.ts +391 -0
  119. package/src/server/form-schema.ts +343 -0
  120. package/src/server/health.ts +244 -0
  121. package/src/server/http.ts +538 -0
  122. package/src/server/index.ts +586 -0
  123. package/src/server/lifecycle.ts +75 -0
  124. package/src/server/loader.ts +123 -0
  125. package/src/server/page.ts +107 -0
  126. package/src/server/param-matchers.ts +112 -0
  127. package/src/server/plugin-host.ts +265 -0
  128. package/src/server/prerendered.ts +71 -0
  129. package/src/server/public.ts +19 -0
  130. package/src/server/rate-limit.ts +156 -0
  131. package/src/server/region.ts +96 -0
  132. package/src/server/request-body.ts +27 -0
  133. package/src/server/request-path.ts +73 -0
  134. package/src/server/request-scope.ts +22 -0
  135. package/src/server/route-cache.ts +423 -0
  136. package/src/server/route-table.ts +410 -0
  137. package/src/server/router.ts +261 -0
  138. package/src/server/routing.ts +472 -0
  139. package/src/server/security.ts +499 -0
  140. package/src/server/serve-handlers.ts +83 -0
  141. package/src/server/served-file.ts +128 -0
  142. package/src/server/standard-schema.ts +87 -0
  143. package/src/server/start.ts +143 -0
  144. package/src/server/static-dir.ts +220 -0
  145. package/src/server/stream.ts +211 -0
  146. package/src/ssr/context.ts +383 -0
  147. package/src/ssr/index.ts +596 -0
  148. package/src/ssr/navigation.ts +96 -0
  149. package/src/ssr/region.ts +183 -0
  150. package/src/style.ts +33 -0
  151. package/src/test/browser.ts +192 -0
  152. package/src/test/index.ts +191 -0
  153. package/src/ts-plugin/diagnostics.ts +378 -0
  154. package/src/ts-plugin/fixes.ts +364 -0
  155. package/src/ts-plugin/index.ts +194 -0
  156. package/src/unrenderable.ts +35 -0
  157. package/templates/_shared/AGENTS.md +10 -0
  158. package/templates/_shared/CLAUDE.md +1 -0
  159. package/templates/_shared/gitignore +3 -0
  160. package/templates/_shared/mcp.json +11 -0
  161. package/templates/_shared/public/robots.txt +2 -0
  162. package/templates/_shared/src/routes/legal.tsx +13 -0
  163. package/templates/_shared/tsconfig.json +25 -0
  164. package/templates/app/.env.example +4 -0
  165. package/templates/app/package.json +21 -0
  166. package/templates/app/prunelle.config.ts +11 -0
  167. package/templates/app/src/auth.ts +14 -0
  168. package/templates/app/src/routes/_layout.tsx +32 -0
  169. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  170. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  171. package/templates/app/src/routes/index.tsx +15 -0
  172. package/templates/app/src/routes/login.tsx +34 -0
  173. package/templates/app/src/styles/app.css +7 -0
  174. package/templates/app/tests/app.test.ts +32 -0
  175. package/templates/blog/content/posts/welcome.md +9 -0
  176. package/templates/blog/package.json +22 -0
  177. package/templates/blog/prunelle.config.ts +23 -0
  178. package/templates/blog/src/posts.ts +26 -0
  179. package/templates/blog/src/routes/_layout.tsx +20 -0
  180. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  181. package/templates/blog/src/routes/index.tsx +33 -0
  182. package/templates/blog/src/styles/app.css +10 -0
  183. package/templates/fullstack/package.json +19 -0
  184. package/templates/fullstack/prunelle.config.ts +6 -0
  185. package/templates/fullstack/src/actions/greet.ts +19 -0
  186. package/templates/fullstack/src/components/Counter.tsx +10 -0
  187. package/templates/fullstack/src/components/GreetForm.tsx +27 -0
  188. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  189. package/templates/fullstack/src/routes/api/health.ts +5 -0
  190. package/templates/fullstack/src/routes/index.tsx +13 -0
  191. package/templates/fullstack/src/styles/app.css +29 -0
  192. package/templates/fullstack/tests/app.test.ts +37 -0
  193. package/templates/minimal/package.json +19 -0
  194. package/templates/minimal/prunelle.config.ts +6 -0
  195. package/templates/minimal/src/components/Counter.tsx +10 -0
  196. package/templates/minimal/src/routes/_layout.tsx +14 -0
  197. package/templates/minimal/src/routes/index.tsx +11 -0
  198. package/templates/minimal/src/styles/app.css +22 -0
  199. package/ts-plugin.cjs +4277 -0
  200. package/README.md +0 -3
@@ -0,0 +1,229 @@
1
+ // GreenIT EcoIndex score, grade (A–G), GHG emissions and water footprint for prerendered pages.
2
+
3
+ import type { Locate } from './first-load'
4
+ import type { RouteManifestEntry } from './manifest'
5
+ import { existsSync, readFileSync, statSync } from 'node:fs'
6
+ import { extname, join } from 'node:path'
7
+ import { firstLoadUrls, measureFirstLoad } from './first-load'
8
+ import { appBrotliCacheDir, brotliSync } from './precompress'
9
+
10
+ export type EcoIndexGrade = 'A' | 'B' | 'C' | 'D' | 'E' | 'F' | 'G'
11
+
12
+ export interface EcoIndexInputs {
13
+ dom: number
14
+ requests: number
15
+ weightBytes: number
16
+ }
17
+
18
+ export interface RouteEcoIndex {
19
+ grade: EcoIndexGrade
20
+ score: number
21
+ dom: number
22
+ requests: number
23
+ weightBytes: number
24
+ ghgGrams: number
25
+ waterCl: number
26
+ url?: string | undefined
27
+ }
28
+
29
+ // Official GreenIT EcoIndex 20-quantile reference tables (DOM elements, HTTP requests, transfer size in KB).
30
+ const QUANTILES_DOM = [
31
+ 0, 47, 75, 159, 233, 298, 358, 417, 476, 537, 603,
32
+ 674, 753, 843, 949, 1076, 1237, 1459, 1801, 2479, 594601,
33
+ ] as const
34
+
35
+ const QUANTILES_REQ = [
36
+ 0, 2, 15, 25, 34, 42, 49, 56, 63, 70, 78,
37
+ 86, 95, 105, 117, 130, 147, 170, 205, 281, 3920,
38
+ ] as const
39
+
40
+ const QUANTILES_SIZE = [
41
+ 0, 1.37, 144.7, 319.53, 479.46, 631.97, 783.38, 937.91, 1098.62, 1265.47, 1448.32,
42
+ 1648.27, 1876.08, 2142.06, 2465.37, 2866.31, 3401.59, 4155.73, 5400.08, 8037.54, 223212.26,
43
+ ] as const
44
+
45
+ const RAW_CLOSE_RE: Record<string, RegExp> = {
46
+ script: /<\/script(?:\s[^>]*)?>/gi,
47
+ style: /<\/style(?:\s[^>]*)?>/gi,
48
+ textarea: /<\/textarea(?:\s[^>]*)?>/gi,
49
+ title: /<\/title(?:\s[^>]*)?>/gi,
50
+ }
51
+
52
+ const isAsciiAlpha = (c: number): boolean => (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
53
+
54
+ const isTagNameChar = (c: number): boolean =>
55
+ isAsciiAlpha(c) || (c >= 48 && c <= 57) || c === 45 || c === 95 || c === 58 || c === 46
56
+
57
+ const isTagDelimiter = (c: number): boolean =>
58
+ c === 62 || c === 47 || c === 32 || c === 9 || c === 10 || c === 13 || c === 12
59
+
60
+ function findTagEnd(html: string, start: number): number {
61
+ let quote = 0
62
+ for (let i = start; i < html.length; i++) {
63
+ const c = html.charCodeAt(i)
64
+ if (quote !== 0) {
65
+ if (c === quote)
66
+ quote = 0
67
+ }
68
+ else if (c === 34 || c === 39) {
69
+ quote = c
70
+ }
71
+ else if (c === 62) {
72
+ return i
73
+ }
74
+ }
75
+ return -1
76
+ }
77
+
78
+ function skipBangConstruct(html: string, lt: number): number {
79
+ if (html.startsWith('<!--', lt)) {
80
+ const end = html.indexOf('-->', lt + 4)
81
+ return end === -1 ? html.length : end + 3
82
+ }
83
+ if (html.startsWith('<![CDATA[', lt)) {
84
+ const end = html.indexOf(']]>', lt + 9)
85
+ return end === -1 ? html.length : end + 3
86
+ }
87
+ const end = html.indexOf('>', lt + 2)
88
+ return end === -1 ? html.length : end + 1
89
+ }
90
+
91
+ /** Counts HTML element nodes by scanning opening tags, ignoring DOCTYPE, comments, closing tags and raw text inside script/style/textarea/title. */
92
+ export function countDomElements(html: string): number {
93
+ let count = 0
94
+ let i = 0
95
+ const len = html.length
96
+ while (i < len) {
97
+ const lt = html.indexOf('<', i)
98
+ if (lt === -1)
99
+ break
100
+ const next = html.charCodeAt(lt + 1)
101
+ if (next === 33) {
102
+ i = skipBangConstruct(html, lt)
103
+ continue
104
+ }
105
+ if (next === 47 || next === 63) {
106
+ const end = html.indexOf('>', lt + 2)
107
+ i = end === -1 ? len : end + 1
108
+ continue
109
+ }
110
+ if (!isAsciiAlpha(next)) {
111
+ i = lt + 1
112
+ continue
113
+ }
114
+ let nameEnd = lt + 2
115
+ while (nameEnd < len && isTagNameChar(html.charCodeAt(nameEnd)))
116
+ nameEnd++
117
+ if (nameEnd >= len || !isTagDelimiter(html.charCodeAt(nameEnd))) {
118
+ i = lt + 1
119
+ continue
120
+ }
121
+ const tagEnd = findTagEnd(html, nameEnd)
122
+ if (tagEnd === -1)
123
+ break
124
+ count++
125
+ i = tagEnd + 1
126
+ const closeRe = RAW_CLOSE_RE[html.slice(lt + 1, nameEnd).toLowerCase()]
127
+ if (closeRe !== undefined) {
128
+ closeRe.lastIndex = i
129
+ const match = closeRe.exec(html)
130
+ i = match === null ? len : closeRe.lastIndex
131
+ }
132
+ }
133
+ return count
134
+ }
135
+
136
+ function computeQuantile(quantiles: readonly number[], value: number): number {
137
+ if (value <= quantiles[0]!)
138
+ return 0
139
+ for (let i = 1; i < quantiles.length; i++) {
140
+ const hi = quantiles[i]!
141
+ if (value < hi) {
142
+ const lo = quantiles[i - 1]!
143
+ return (i - 1) + (value - lo) / (hi - lo)
144
+ }
145
+ }
146
+ return quantiles.length - 1
147
+ }
148
+
149
+ function gradeForScore(score: number): EcoIndexGrade {
150
+ if (score > 75)
151
+ return 'A'
152
+ if (score > 65)
153
+ return 'B'
154
+ if (score > 50)
155
+ return 'C'
156
+ if (score > 35)
157
+ return 'D'
158
+ if (score > 20)
159
+ return 'E'
160
+ if (score > 5)
161
+ return 'F'
162
+ return 'G'
163
+ }
164
+
165
+ /** Computes the GreenIT EcoIndex score (0–100), grade (A–G), GHG emissions (gCO2e) and water consumption (cl) per view. */
166
+ export function computeEcoIndex(inputs: EcoIndexInputs): Omit<RouteEcoIndex, 'url'> {
167
+ const dom = Math.max(0, inputs.dom)
168
+ const requests = Math.max(0, inputs.requests)
169
+ const weightBytes = Math.max(0, inputs.weightBytes)
170
+ const qDom = computeQuantile(QUANTILES_DOM, dom)
171
+ const qReq = computeQuantile(QUANTILES_REQ, requests)
172
+ const qSize = computeQuantile(QUANTILES_SIZE, weightBytes / 1024)
173
+ const raw = 100 - (5 * (3 * qDom + 2 * qReq + qSize)) / 6
174
+ const score = Math.round(Math.min(100, Math.max(0, raw)) * 10) / 10
175
+ const ghgGrams = Math.round((2 + (2 * (50 - score)) / 100) * 100) / 100
176
+ const waterCl = Math.round((3 + (3 * (50 - score)) / 100) * 100) / 100
177
+ return { grade: gradeForScore(score), score, dom, requests, weightBytes, ghgGrams, waterCl }
178
+ }
179
+
180
+ function htmlServedSize(abs: string, raw: Uint8Array): number {
181
+ const sidecar = `${abs}.br`
182
+ if (existsSync(sidecar))
183
+ return statSync(sidecar).size
184
+ const packed = brotliSync(raw, appBrotliCacheDir()).byteLength
185
+ return Math.min(packed, raw.byteLength)
186
+ }
187
+
188
+ function isWorse(candidate: Omit<RouteEcoIndex, 'url'>, current: Omit<RouteEcoIndex, 'url'>): boolean {
189
+ if (candidate.score !== current.score)
190
+ return candidate.score < current.score
191
+ if (candidate.weightBytes !== current.weightBytes)
192
+ return candidate.weightBytes > current.weightBytes
193
+ return candidate.dom > current.dom
194
+ }
195
+
196
+ /** Measures EcoIndex across a route's prerendered HTML files, returning the worst (lowest) score for multi-URL routes. */
197
+ export function measureRouteEcoIndex(route: RouteManifestEntry, options: { prerenderBaseDir: string, locate: Locate }): RouteEcoIndex | undefined {
198
+ if (route.prerendered === undefined)
199
+ return undefined
200
+ const entries = Object.entries(route.prerendered).sort(([a], [b]) => a.localeCompare(b))
201
+ let worst: Omit<RouteEcoIndex, 'url'> | undefined
202
+ let worstUrl: string | undefined
203
+ let measured = 0
204
+
205
+ for (const [url, relFile] of entries) {
206
+ const abs = join(options.prerenderBaseDir, relFile)
207
+ const ext = extname(abs).toLowerCase()
208
+ if ((ext !== '.html' && ext !== '.htm') || !existsSync(abs))
209
+ continue
210
+ const raw = readFileSync(abs)
211
+ const html = raw.toString('utf8')
212
+ const htmlBytes = htmlServedSize(abs, raw)
213
+ const load = measureFirstLoad(firstLoadUrls(html), options.locate, htmlBytes)
214
+ const eco = computeEcoIndex({
215
+ dom: countDomElements(html),
216
+ requests: 1 + load.files,
217
+ weightBytes: load.total,
218
+ })
219
+ measured++
220
+ if (worst === undefined || isWorse(eco, worst)) {
221
+ worst = eco
222
+ worstUrl = url
223
+ }
224
+ }
225
+
226
+ if (worst === undefined || worstUrl === undefined)
227
+ return undefined
228
+ return measured > 1 || worstUrl !== route.path ? { ...worst, url: worstUrl } : worst
229
+ }
@@ -0,0 +1,156 @@
1
+ // File-system helpers of the build: directory walks and the outDir safety check.
2
+
3
+ import type { Dirent } from 'node:fs'
4
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
7
+ import { isInside } from './is-inside'
8
+
9
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
10
+ const BACKSLASH_RE = /\\/g
11
+ const NODE_MODULES_RE = /[\\/]node_modules[\\/]/
12
+
13
+ /** `relative(from, to)` with forward slashes, the form manifests and messages use. */
14
+ export function relPosix(from: string, to: string): string {
15
+ return relative(from, to).replace(BACKSLASH_RE, '/')
16
+ }
17
+
18
+ /** Whether `file` sits under a `node_modules` folder, with either path separator. */
19
+ export function isInNodeModules(file: string): boolean {
20
+ return NODE_MODULES_RE.test(file)
21
+ }
22
+
23
+ export function isTsFile(file: string): boolean {
24
+ return file.endsWith('.tsx') || file.endsWith('.ts')
25
+ }
26
+
27
+ /** The size of a file in bytes, or undefined when it does not exist. */
28
+ export function fileSize(file: string): number | undefined {
29
+ try {
30
+ return statSync(file).size
31
+ }
32
+ catch {
33
+ return undefined
34
+ }
35
+ }
36
+
37
+ interface WalkOptions {
38
+ skipDir?: (name: string) => boolean
39
+ keep?: (entry: Dirent) => boolean
40
+ }
41
+
42
+ /** Every kept file under `dir`, depth first; a missing `dir` is empty. */
43
+ export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
44
+ if (!existsSync(dir))
45
+ return out
46
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
47
+ const full = join(dir, entry.name)
48
+ if (entry.isDirectory()) {
49
+ if (options.skipDir?.(entry.name) !== true)
50
+ walkFiles(full, options, out)
51
+ }
52
+ else if (options.keep === undefined || options.keep(entry)) {
53
+ out.push(full)
54
+ }
55
+ }
56
+ return out
57
+ }
58
+
59
+ /** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
60
+ export function walkRoutes(dir: string): string[] {
61
+ return walkFiles(dir, {
62
+ skipDir: name => name.startsWith('_'),
63
+ keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
64
+ })
65
+ }
66
+
67
+ /** Folders that never hold an app's own source: its dependencies, its build, and dot folders such as `.git` and `.prunelle-cache`. */
68
+ export function isNotSourceDir(name: string): boolean {
69
+ return name === 'node_modules' || name === 'dist' || name.startsWith('.')
70
+ }
71
+
72
+ export function walkAllFiles(dir: string): string[] {
73
+ return walkFiles(dir, { keep: entry => entry.isFile() })
74
+ }
75
+
76
+
77
+ export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
78
+ // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
79
+ if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
80
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
81
+ }
82
+ if (isInside(outDir, root, { orSame: true })) {
83
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
84
+ }
85
+ if (existsSync(outDir)) {
86
+ try {
87
+ const realRoot = realpathSync(root)
88
+ const realOut = realpathSync(outDir)
89
+ if (dirname(realOut) === realOut || isInside(realOut, realRoot, { orSame: true })) {
90
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
91
+ }
92
+ }
93
+ catch (err) {
94
+ if (err instanceof Error && err.message.startsWith('prunelle build: refusing unsafe outDir'))
95
+ throw err
96
+ }
97
+ }
98
+ const protectedTargets: [string, string][] = [
99
+ ['src', resolve(root, 'src')],
100
+ ['routesDir', routesDir],
101
+ ['publicDir', publicDir],
102
+ ['prunelle.config.ts', resolve(root, 'prunelle.config.ts')],
103
+ ['package.json', resolve(root, 'package.json')],
104
+ ]
105
+ for (const [label, target] of protectedTargets) {
106
+ if (isInside(outDir, target, { orSame: true })) {
107
+ throw new Error(`prunelle build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
108
+ }
109
+ }
110
+ // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
111
+ if (!isInside(root, outDir) && existsSync(outDir)) {
112
+ for (const marker of ['package.json', 'prunelle.config.ts', 'src']) {
113
+ if (existsSync(join(outDir, marker))) {
114
+ throw new Error(`prunelle build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ export interface BunBuildLogLike {
121
+ message?: string | undefined
122
+ level?: string | undefined
123
+ position?: {
124
+ file?: string | undefined
125
+ line?: number | undefined
126
+ column?: number | undefined
127
+ length?: number | undefined
128
+ lineText?: string | undefined
129
+ } | null | undefined
130
+ }
131
+
132
+ /** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
133
+ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
134
+ return logs.map((raw) => {
135
+ if (raw === null || typeof raw !== 'object')
136
+ return String(raw)
137
+ const log = raw as BunBuildLogLike
138
+ const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
139
+ const pos = log.position
140
+ if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
141
+ const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
142
+ const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
143
+ const severity = log.level === 'warning' ? 'warning' : 'error'
144
+ const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
145
+ if (typeof pos.lineText === 'string') {
146
+ const lineStr = String(pos.line)
147
+ const pad = ' '.repeat(lineStr.length)
148
+ const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
149
+ const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
150
+ return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
151
+ }
152
+ return header
153
+ }
154
+ return msg
155
+ }).join('\n')
156
+ }
@@ -0,0 +1,164 @@
1
+ // What a first visit downloads, as served: the page, the files it links, and the files those pull in (a script's static imports, a stylesheet's `url()`s), each counted once. The docs footer and `prunelle build --analyze` both measure with this.
2
+
3
+ import { existsSync, readFileSync, statSync } from 'node:fs'
4
+ import { extname, join, posix } from 'node:path'
5
+ import { appBrotliCacheDir, brotliSync } from './precompress'
6
+
7
+ // A static `import ... from "./x.js"` or `import "./x.js"` of an emitted chunk; `import("./x.js")` stays lazy and is left out.
8
+ export const STATIC_CHUNK_IMPORT_RE = /\b(?:import|export)\s*(?:[^"'();]*?\bfrom\s*)?["'](\.\.?\/[^"']+\.js)["']/g
9
+
10
+ const TAG_RE = /<(img|script|link)\b[^>]*>/g
11
+ const SRC_RE = /\bsrc="([^"]+)"/
12
+ const HREF_RE = /\bhref="([^"]+)"/
13
+ const REL_RE = /\brel="([^"]+)"/
14
+ const TYPE_RE = /\btype="([^"]+)"/
15
+ const LAZY_RE = /\bloading="lazy"/
16
+ const FONT_FACE_RE = /@font-face\s*\{[^}]*\}/g
17
+ const CSS_URL_RE = /url\(\s*(["']?)([^)"']+)\1\s*\)/g
18
+ const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?["']([^"']+)["']/g
19
+ const FETCHED_RELS = new Set(['stylesheet', 'modulepreload', 'preload'])
20
+ const COMPRESSED_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
21
+ const FONT_EXTS = new Set(['.woff2', '.woff', '.ttf', '.otf'])
22
+ const IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.svg', '.ico'])
23
+ const SKIPPED_URL_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i
24
+
25
+ export interface FirstLoad {
26
+ /** The page's own HTML, brotli, as given by the caller. */
27
+ html: number
28
+ css: number
29
+ js: number
30
+ fonts: number
31
+ images: number
32
+ other: number
33
+ total: number
34
+ /** The part of `total` a browser keeps in its cache for the next page: the files `cacheable` accepts. */
35
+ cached: number
36
+ /** Files counted besides the page. */
37
+ files: number
38
+ }
39
+
40
+ /** Turns a URL the page links into the file that serves it, or `undefined` when no file does. */
41
+ export type Locate = (url: string) => string | undefined
42
+
43
+ /** The URLs a browser fetches from this markup: stylesheets, preloads, scripts, one icon, and images that are not lazy. */
44
+ export function firstLoadUrls(html: string): string[] {
45
+ const urls = new Set<string>()
46
+ const icons: string[] = []
47
+ let svgIcon: string | undefined
48
+ for (const [element, name] of html.matchAll(TAG_RE)) {
49
+ if (name === 'link') {
50
+ const url = HREF_RE.exec(element)?.[1]
51
+ const relation = REL_RE.exec(element)?.[1] ?? ''
52
+ if (url === undefined)
53
+ continue
54
+ if (relation === 'icon') {
55
+ icons.push(url)
56
+ svgIcon ??= TYPE_RE.exec(element)?.[1] === 'image/svg+xml' ? url : undefined
57
+ }
58
+ else if (FETCHED_RELS.has(relation)) {
59
+ urls.add(url)
60
+ }
61
+ continue
62
+ }
63
+ const url = SRC_RE.exec(element)?.[1]
64
+ if (url !== undefined && !LAZY_RE.test(element))
65
+ urls.add(url)
66
+ }
67
+ // A browser that draws SVG icons fetches that one alone; the others are for browsers that do not.
68
+ for (const icon of svgIcon === undefined ? icons : [svgIcon])
69
+ urls.add(icon)
70
+ return [...urls]
71
+ }
72
+
73
+ /** The locator for a build's output: `/_pru/x` is `clientDir/x`, anything else is looked up in each public dir. */
74
+ export function distLocator(options: { clientDir: string, assetPrefix: string, publicDirs: readonly string[] }): Locate {
75
+ const prefix = `${options.assetPrefix.replace(/\/$/, '')}/`
76
+ return (url) => {
77
+ const path = url.split(/[?#]/)[0]!
78
+ if (path.startsWith(prefix)) {
79
+ const file = join(options.clientDir, path.slice(prefix.length))
80
+ return existsSync(file) ? file : undefined
81
+ }
82
+ if (!path.startsWith('/'))
83
+ return undefined
84
+ return options.publicDirs.map(dir => join(dir, path.slice(1))).find(file => existsSync(file))
85
+ }
86
+ }
87
+
88
+ const brotliCache = new Map<string, number>()
89
+
90
+ /** Bytes on the wire: the `.br` sidecar prunelle wrote, else brotli of a compressible file, else the file as it is. */
91
+ function servedSize(file: string): number {
92
+ const sidecar = `${file}.br`
93
+ if (existsSync(sidecar))
94
+ return statSync(sidecar).size
95
+ const raw = readFileSync(file)
96
+ if (!COMPRESSED_EXTS.has(extname(file).toLowerCase()))
97
+ return raw.byteLength
98
+ const key = `${file}:${raw.byteLength}`
99
+ let packed = brotliCache.get(key)
100
+ if (packed === undefined) {
101
+ packed = brotliSync(raw, appBrotliCacheDir()).byteLength
102
+ brotliCache.set(key, packed)
103
+ }
104
+ return Math.min(packed, raw.byteLength)
105
+ }
106
+
107
+ // A browser takes the first source of an @font-face it can use, so only that one is fetched; every other url() is.
108
+ function cssUrls(css: string): string[] {
109
+ const urls: string[] = []
110
+ const rest = css.replace(FONT_FACE_RE, (face) => {
111
+ const first = new RegExp(CSS_URL_RE.source).exec(face)?.[2]
112
+ if (first !== undefined)
113
+ urls.push(first)
114
+ return ''
115
+ })
116
+ for (const match of rest.matchAll(CSS_URL_RE))
117
+ urls.push(match[2]!)
118
+ for (const match of rest.matchAll(CSS_IMPORT_RE))
119
+ urls.push(match[1]!)
120
+ return urls.filter(url => !SKIPPED_URL_RE.test(url))
121
+ }
122
+
123
+ /** What a file pulls in beside itself: a script's static imports and a stylesheet's `url()`s, as URLs. */
124
+ function dependenciesOf(url: string, file: string): string[] {
125
+ const ext = extname(file).toLowerCase()
126
+ if (ext !== '.js' && ext !== '.css')
127
+ return []
128
+ const text = readFileSync(file, 'utf8')
129
+ const base = posix.dirname(url.split(/[?#]/)[0]!)
130
+ const raw = ext === '.js' ? [...text.matchAll(STATIC_CHUNK_IMPORT_RE)].map(m => m[1]!) : cssUrls(text)
131
+ return raw.map(dep => (dep.startsWith('/') ? dep : posix.join(base, dep)))
132
+ }
133
+
134
+ /** Adds up what a first visit fetches from these root URLs and what they pull in; `htmlBytes` is the page itself, brotli; `cacheable` names the URLs served for long caching (prunelle's hashed assets). */
135
+ export function measureFirstLoad(roots: Iterable<string>, locate: Locate, htmlBytes = 0, cacheable: (url: string) => boolean = () => false): FirstLoad {
136
+ const result: FirstLoad = { html: htmlBytes, css: 0, js: 0, fonts: 0, images: 0, other: 0, total: htmlBytes, cached: 0, files: 0 }
137
+ const seen = new Set<string>()
138
+ const stack = [...roots]
139
+ while (stack.length > 0) {
140
+ const url = stack.pop()!
141
+ const file = locate(url)
142
+ if (file === undefined || seen.has(file))
143
+ continue
144
+ seen.add(file)
145
+ const ext = extname(file).toLowerCase()
146
+ const size = servedSize(file)
147
+ if (ext === '.css')
148
+ result.css += size
149
+ else if (ext === '.js' || ext === '.mjs')
150
+ result.js += size
151
+ else if (FONT_EXTS.has(ext))
152
+ result.fonts += size
153
+ else if (IMAGE_EXTS.has(ext))
154
+ result.images += size
155
+ else
156
+ result.other += size
157
+ result.total += size
158
+ if (cacheable(url))
159
+ result.cached += size
160
+ result.files++
161
+ stack.push(...dependenciesOf(url, file))
162
+ }
163
+ return result
164
+ }