prunelle 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +15 -14
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +19 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +33 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +26 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +145 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +52 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +16 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +32 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -7,6 +7,7 @@ import { existsSync, mkdtempSync, rmSync, watch } from 'node:fs'
7
7
  import { tmpdir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
  import { recordDevCrashError } from './error-log'
10
+ import { createDevHostCheck } from './host-check'
10
11
  import { DEV_CHILD_ENV, DEV_CLIENT_IP_HEADER } from './protocol'
11
12
  import { buildErrorResponse, createReloadHub, makeDevReloadAssets } from './reload'
12
13
 
@@ -18,6 +19,8 @@ export interface DevSupervisorOptions {
18
19
  maxRequestBodySize?: number | undefined
19
20
  /** The app process is replaced once its RSS passes this after a rebuild. */
20
21
  maxRssMb?: number | undefined
22
+ /** Origins besides loopback and IP addresses the server answers under: the config's `site` and `trustedOrigins`. */
23
+ allowedOrigins?: readonly (string | undefined)[] | undefined
21
24
  }
22
25
 
23
26
  interface Child {
@@ -75,6 +78,7 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
75
78
  root,
76
79
  routesDir: options.routesDir,
77
80
  unix: socket,
81
+ hostname: options.hostname,
78
82
  ...(options.maxRequestBodySize !== undefined ? { maxRequestBodySize: options.maxRequestBodySize } : {}),
79
83
  maxRssMb: options.maxRssMb ?? DEFAULT_MAX_RSS_MB,
80
84
  }
@@ -140,12 +144,16 @@ export async function devSupervisor(options: DevSupervisorOptions): Promise<{ ur
140
144
  ready = spawnChild()
141
145
  await ready
142
146
 
147
+ const checkHost = createDevHostCheck(options.hostname, options.allowedOrigins ?? [])
143
148
  const server = Bun.serve({
144
149
  port: options.port ?? 3000,
145
150
  hostname: options.hostname ?? '127.0.0.1',
146
151
  idleTimeout: 30,
147
152
  maxRequestBodySize: options.maxRequestBodySize ?? DEFAULT_SUPERVISOR_MAX_BODY,
148
153
  async fetch(request, srv) {
154
+ const refused = checkHost(request)
155
+ if (refused !== undefined)
156
+ return refused
149
157
  const url = new URL(request.url)
150
158
  if (url.pathname === reloadAssets.eventsPath) {
151
159
  srv.timeout(request, 0)
@@ -21,9 +21,34 @@ export function srcChangeKind(name: string): ChangeKind {
21
21
  return CODE_FILE_RE.test(name) ? 'code' : 'full'
22
22
  }
23
23
 
24
+ type ScanLoader = 'js' | 'jsx' | 'ts' | 'tsx'
25
+
26
+ // A `.ts` file is read as TS, not TSX: there `<T>(x: T) => x` is a generic arrow, not a JSX tag (#108).
27
+ function scanLoader(file: string): ScanLoader {
28
+ if (file.endsWith('.tsx'))
29
+ return 'tsx'
30
+ if (file.endsWith('.jsx'))
31
+ return 'jsx'
32
+ return /\.[cm]?js$/.test(file) ? 'js' : 'ts'
33
+ }
34
+
24
35
  // The files outside node_modules that `entry` imports, transitively, `entry` left out.
25
36
  export function localImports(entry: string): string[] {
26
- const transpiler = new Bun.Transpiler({ loader: 'tsx' })
37
+ const transpilers = new Map<ScanLoader, Bun.Transpiler>()
38
+ const importsOf = (file: string, source: string): string[] => {
39
+ const loader = scanLoader(file)
40
+ let transpiler = transpilers.get(loader)
41
+ if (transpiler === undefined) {
42
+ transpiler = new Bun.Transpiler({ loader })
43
+ transpilers.set(loader, transpiler)
44
+ }
45
+ try {
46
+ return transpiler.scanImports(source).map(entry => entry.path)
47
+ }
48
+ catch {
49
+ return [] // a syntax error, which the config load reports itself
50
+ }
51
+ }
27
52
  const seen = new Set<string>([entry])
28
53
  const queue = [entry]
29
54
  for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
@@ -34,7 +59,7 @@ export function localImports(entry: string): string[] {
34
59
  catch {
35
60
  continue // deleted since it was resolved
36
61
  }
37
- for (const { path } of transpiler.scanImports(source)) {
62
+ for (const path of importsOf(file, source)) {
38
63
  let resolved: string
39
64
  try {
40
65
  resolved = Bun.resolveSync(path, dirname(file))
package/src/dom/action.ts CHANGED
@@ -148,6 +148,8 @@ export function actionStub<Input = unknown, Output = unknown>(url: string): Clie
148
148
  if (to) {
149
149
  if (typeof location !== 'undefined') {
150
150
  try {
151
+ if (typeof location.href === 'string' && h.get('x-pru-redirect-external') !== '1' && new URL(to, location.href).origin !== new URL(location.href).origin)
152
+ throw new Error('Redirect to another site refused')
151
153
  location.assign(to)
152
154
  }
153
155
  catch (err) {
@@ -155,7 +157,8 @@ export function actionStub<Input = unknown, Output = unknown>(url: string): Clie
155
157
  }
156
158
  if (isSameDocHash(to))
157
159
  return { ok: true, data: undefined as Output }
158
- return new Promise<never>(() => {})
160
+ // A navigation unloads the page first; when none happens (a refused prompt, a download) the caller gets an error instead of waiting forever.
161
+ return new Promise<ActionResult<Output>>(resolve => setTimeout(() => resolve(fail(0, 'Navigation did not complete')), 10000))
159
162
  }
160
163
  return fail(res.status || 302, to)
161
164
  }
package/src/dom/extras.ts CHANGED
@@ -4,10 +4,9 @@
4
4
  import type { CatchProps } from '../context'
5
5
  import type { Owned } from '../reactivity/graph'
6
6
  import type { Owner } from '../reactivity/index'
7
- import { DOM_PROPS } from '../attrs'
7
+ import { DOM_PROPS, isBlockedAttr } from '../attrs'
8
8
  import { batch, createOwner, disposeOwner, effect, getOwner, onCleanup, onEffectError, runOwned, runWithOwner, signal, untrack } from '../reactivity/index'
9
9
  import { assertRenderable } from '../unrenderable'
10
- import { isBlockedAttr } from '../attrs'
11
10
  import { setAttr, setClass, setProp, setStyle } from './attrs'
12
11
  import { claimInsert } from './claim'
13
12
  import { claimRange, delegate, hydrateCursor, isHydrating, moveCursor, skipRange } from './index'
package/src/dom/index.ts CHANGED
@@ -253,6 +253,7 @@ function dispatchEvent(event: Event): void {
253
253
  let current: EventTarget | null = null
254
254
  const prevDesc = Object.getOwnPropertyDescriptor(event, 'currentTarget')
255
255
  Object.defineProperty(event, 'currentTarget', { configurable: true, get: () => current })
256
+ const errors: unknown[] = []
256
257
 
257
258
  try {
258
259
  const path = event.composedPath?.()
@@ -263,9 +264,14 @@ function dispatchEvent(event: Event): void {
263
264
  const handler = node[key]
264
265
  if (typeof handler === 'function') {
265
266
  current = node
266
- batch(() => handler(event))
267
+ try {
268
+ batch(() => handler(event))
269
+ }
270
+ catch (err) {
271
+ errors.push(err)
272
+ }
267
273
  if (event.cancelBubble)
268
- return
274
+ break
269
275
  }
270
276
  node = (usePath ? path[++i] : (node as unknown as Node).parentNode) as (EventTarget & Record<string, ((e: Event) => void) | undefined>) | null | undefined
271
277
  }
@@ -276,6 +282,11 @@ function dispatchEvent(event: Event): void {
276
282
  else
277
283
  delete (event as unknown as Record<string, unknown>).currentTarget
278
284
  }
285
+ // Every handler ran: the first error is thrown as before, the others are reported.
286
+ for (let i = 1; i < errors.length; i++)
287
+ reportError(errors[i])
288
+ if (errors.length > 0)
289
+ throw errors[0]
279
290
  }
280
291
 
281
292
  export function delegate(events: string[]): void {
package/src/dom/island.ts CHANGED
@@ -90,7 +90,8 @@ function replayEvent(root: Element, ev: Event, target: EventTarget | null): void
90
90
  target.dispatchEvent(clone)
91
91
  }
92
92
 
93
- function watchInteraction(root: Element, onTrigger: (after: () => void) => void): () => void {
93
+ // A failed load keeps the listeners and drops the queued events: the next interaction loads the chunk again and is replayed once it is in.
94
+ function watchInteraction(root: Element, onTrigger: (after: () => void) => Promise<boolean>): () => void {
94
95
  const evs = ['pointerdown', 'click', 'focusin', 'keydown']
95
96
  const queued: { ev: Event, target: EventTarget | null }[] = []
96
97
  let loading = false
@@ -101,9 +102,14 @@ function watchInteraction(root: Element, onTrigger: (after: () => void) => void)
101
102
  queued.push({ ev, target: ev.target })
102
103
  if (!loading) {
103
104
  loading = true
104
- onTrigger(() => {
105
+ void onTrigger(() => {
105
106
  for (let i = 0; i < queued.length; i++)
106
107
  replayEvent(root, queued[i]!.ev, queued[i]!.target)
108
+ }).then((ok) => {
109
+ if (!ok) {
110
+ loading = false
111
+ queued.length = 0
112
+ }
107
113
  })
108
114
  }
109
115
  }
@@ -186,10 +192,10 @@ export function defineIslandElement(): void {
186
192
  return
187
193
  }
188
194
  if ((typeof PRUNELLE_IDLE === 'undefined' || PRUNELLE_IDLE) && h === 'idle') {
189
- const g = globalThis as { requestIdleCallback?: (cb: () => void) => number, cancelIdleCallback?: (id: number) => void }
195
+ const g = globalThis as { requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number, cancelIdleCallback?: (id: number) => void }
190
196
  const run = () => void this._l(false, token)
191
197
  if (g.requestIdleCallback) {
192
- const id = g.requestIdleCallback(run)
198
+ const id = g.requestIdleCallback(run, { timeout: 2000 })
193
199
  this._c = () => g.cancelIdleCallback?.(id)
194
200
  }
195
201
  else {
@@ -199,7 +205,7 @@ export function defineIslandElement(): void {
199
205
  return
200
206
  }
201
207
  if ((typeof PRUNELLE_INTERACTION === 'undefined' || PRUNELLE_INTERACTION) && h === 'interaction') {
202
- this._c = watchInteraction(this, after => void this._l(false, token, true, after))
208
+ this._c = watchInteraction(this, after => this._l(false, token, true, after))
203
209
  return
204
210
  }
205
211
  if ((typeof PRUNELLE_MEDIA === 'undefined' || PRUNELLE_MEDIA) && h !== null && h.startsWith('media(')) {
@@ -234,13 +240,16 @@ export function defineIslandElement(): void {
234
240
  })
235
241
  }
236
242
 
237
- async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<void> {
243
+ // Resolves false when the chunk failed to load or hydrate.
244
+ async _l(clientOnly: boolean, token: number, keepStrategy = false, after?: () => void): Promise<boolean> {
238
245
  if (!keepStrategy)
239
246
  this._clearStrategy()
240
247
  const chunk = this.getAttribute('c')
241
248
  if (!chunk || !isAllowedChunkUrl(chunk) || token !== this._t || !this.isConnected || this._d !== undefined) {
249
+ if (chunk && !isAllowedChunkUrl(chunk))
250
+ console.error(`[pru-island] refused chunk URL ${chunk}: it must be on this origin.`)
242
251
  this._clearStrategy()
243
- return
252
+ return true
244
253
  }
245
254
 
246
255
  let dispose: (() => void) | undefined
@@ -256,7 +265,7 @@ export function defineIslandElement(): void {
256
265
  mod = loaded
257
266
  if (!this.isConnected || token !== this._t || this._d !== undefined) {
258
267
  this._clearStrategy()
259
- return
268
+ return true
260
269
  }
261
270
  this._clearStrategy()
262
271
 
@@ -273,16 +282,19 @@ export function defineIslandElement(): void {
273
282
  : loaded.hydrate(this, render, idPrefix)
274
283
  if (!this.isConnected || token !== this._t) {
275
284
  dispose()
276
- return
285
+ return true
277
286
  }
278
287
  this._d = dispose
279
288
  after?.()
289
+ return true
280
290
  }
281
291
  catch (err) {
282
- this._clearStrategy()
292
+ if (!keepStrategy)
293
+ this._clearStrategy()
283
294
  dispose?.()
284
295
  // The chunk URL is a hash; in dev the component's own name says which island failed.
285
296
  console.error(`[pru-island] failed to hydrate ${process.env.NODE_ENV !== 'production' && mod?.default?.name ? `<${mod.default.name}> (${chunk})` : chunk}:`, err)
297
+ return false
286
298
  }
287
299
  }
288
300
  }
package/src/dom/loop.ts CHANGED
@@ -84,7 +84,7 @@ type RenderRow<T> = (item: Signal<T>, index?: Signal<number>) => Node | Document
84
84
 
85
85
 
86
86
  // While hydrating, a row that rendered no node of its own takes the server nodes the cursor moved over since `before`.
87
- function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null, prevSib: Node | null): void {
87
+ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before: Node | null, prevSib: Node | null): boolean {
88
88
  const afterCursor = hydrateCursor()
89
89
  if (row.node === null && before !== null && before !== afterCursor) {
90
90
  const start = before.parentNode === parent ? before : prevSib !== null ? prevSib.nextSibling : parent.firstChild
@@ -104,39 +104,48 @@ function adoptRowNodes<T>(parent: Node, marker: Node | null, row: Row<T>, before
104
104
  }
105
105
  else if (row.node !== null && row.node.parentNode !== parent) {
106
106
  insertRow(parent, row, marker)
107
+ return true
107
108
  }
109
+ return false
108
110
  }
109
111
 
110
- // Server rows past the browser's last one: the data changed between the render and hydration, so they would stay in the DOM outside `rows`.
111
- function dropServerRows(from: Node | null, marker: Node | null): void {
112
- if (process.env.NODE_ENV !== 'production' && from !== null && from !== marker) {
113
- let removed = 0
114
- for (let n: Node | null = from; n !== null && n !== marker; n = n.nextSibling)
115
- removed++
116
- console.warn(`prunelle: hydration removed ${removed} server node(s) past the list's last row: the island's data changed after the server rendered it.`)
117
- }
118
- while (from !== null && from !== marker) {
119
- const next: Node | null = from.nextSibling
120
- ;(from as ChildNode).remove()
121
- from = next
122
- }
112
+ // Server nodes no client row claimed (stepped over mid-list, or past the last row): the data changed between the render and hydration, so they would stay in the DOM outside `rows`. They are removed, and the island hears `pru:hydration-mismatch`.
113
+ function dropServerRows(parent: Node, leftover: Node[], from: Node | null, marker: Node | null, added: number): void {
114
+ for (let n = from; n !== null && n !== marker; n = n.nextSibling)
115
+ leftover.push(n)
116
+ if (leftover.length === 0 && added === 0)
117
+ return
118
+ if (process.env.NODE_ENV !== 'production')
119
+ console.warn(`prunelle: hydration mismatch in a list: removed ${leftover.length} server node(s) and added ${added} client row(s): the island's data changed after the server rendered it.`)
120
+ for (const n of leftover)
121
+ (n as ChildNode).remove()
122
+ const { CustomEvent: Mismatch } = parent.ownerDocument!.defaultView!
123
+ parent.dispatchEvent(new Mismatch('pru:hydration-mismatch', { bubbles: true, detail: { removed: leftover.length, added } }))
123
124
  }
124
125
 
125
126
  // The first rows: claimed from the server's while hydrating, else rendered into a fragment inserted at once.
126
127
  function createRows<T>(parent: Node, marker: Node | null, items: readonly T[], newRow: (item: T, index: number) => Row<T>, skip: number, startMarker: Node | null | undefined): Row<T>[] {
127
128
  const created = new Array<Row<T>>(items.length)
128
129
  let end: Node | null = null
130
+ const leftover: Node[] = []
131
+ let added = 0
129
132
  if (claimLoop(parent, () => {
130
133
  for (let i = 0; i < items.length; i++) {
131
134
  const before = hydrateCursor()
132
135
  const prevSib = before?.previousSibling ?? null
133
136
  const row = newRow(items[i]!, i)
134
- adoptRowNodes(parent, marker, row, before, prevSib)
137
+ // A row that claimed a node past the cursor stepped over the server nodes between.
138
+ if (before !== null && row.node !== null && row.node.parentNode === parent) {
139
+ for (let n: Node | null = before; n !== null && n !== row.node; n = n.nextSibling)
140
+ leftover.push(n)
141
+ }
142
+ if (adoptRowNodes(parent, marker, row, before, prevSib))
143
+ added++
135
144
  created[i] = row
136
145
  }
137
146
  end = hydrateCursor()
138
147
  }, skip, startMarker)) {
139
- dropServerRows(end, marker)
148
+ dropServerRows(parent, leftover, end, marker, added)
140
149
  return created
141
150
  }
142
151
  if (items.length > 0) {
@@ -0,0 +1,257 @@
1
+ // Drafts an editable French RGESN 2024 eco-design declaration page, shaped like the State's declaration tool, from what a build and `prunelle check` measure.
2
+
3
+ import type { BundleReport } from '../build/report'
4
+ import { mkdirSync, writeFileSync } from 'node:fs'
5
+ import { dirname, join, resolve } from 'node:path'
6
+ import { escapeAttr, escapeJsxText, formatFrenchDate, layoutRendersMain, STATEMENT_PLACEHOLDER } from '../a11y/declaration'
7
+ import { relPosix } from '../build/files'
8
+ import { fileToRoutePath } from '../build/routes'
9
+
10
+ export const DEFAULT_ECO_DECLARATION_PATH = 'src/routes/ecoconception.tsx'
11
+ const RGESN_URL = 'https://ecoresponsable.numerique.gouv.fr/publications/referentiel-general-ecoconception/'
12
+
13
+ /** What prunelle knows about an app when it drafts the declaration. */
14
+ export interface EcoFacts {
15
+ report: BundleReport
16
+ /** `prunelle check` warnings, as it prints them. */
17
+ warnings: readonly string[]
18
+ assetPrefix: string
19
+ compress: boolean
20
+ /** `budget.firstLoad` in bytes, when the config sets one. */
21
+ firstLoadBudget: number | undefined
22
+ }
23
+
24
+ export type EcoVerdict = 'Validé' | 'Non validé'
25
+
26
+ export interface EcoCriterion {
27
+ id: string
28
+ /** The criterion's wording in the RGESN 2024. */
29
+ label: string
30
+ priority: 'Prioritaire' | 'Recommandé' | 'Modéré'
31
+ /** Absent when prunelle measures part of the criterion and a person has to judge the rest. */
32
+ verdict?: EcoVerdict | undefined
33
+ evidence: string
34
+ }
35
+
36
+ export interface EcoDeclarationOptions {
37
+ root: string
38
+ /** Destination relative to `root` (or absolute). Default: `'src/routes/ecoconception.tsx'`. */
39
+ outPath?: string | undefined
40
+ facts: EcoFacts
41
+ service?: string | undefined
42
+ organization?: string | undefined
43
+ contactEmail?: string | undefined
44
+ date?: Date | undefined
45
+ /** Write the page to disk (default: `true`). */
46
+ write?: boolean | undefined
47
+ }
48
+
49
+ export interface EcoDeclarationResult {
50
+ path: string
51
+ relativePath: string
52
+ criteria: EcoCriterion[]
53
+ content: string
54
+ }
55
+
56
+ const WARNING_RE = /^(.+?):\d+:\d+: warning: \[([a-z]+\/[a-z-]+)\]/
57
+ const ABSOLUTE_URL_RE = /^(?:[a-z][a-z\d+.-]*:)?\/\//i
58
+ const frNumber = new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 1 })
59
+
60
+ function ko(bytes: number): string {
61
+ return `${frNumber.format(bytes / 1000)} ko`
62
+ }
63
+
64
+ function filesWarnedFor(warnings: readonly string[], rule: string): string[] {
65
+ const files = new Set<string>()
66
+ for (const warning of warnings) {
67
+ const match = WARNING_RE.exec(warning)
68
+ if (match !== null && match[2] === rule)
69
+ files.add(match[1]!)
70
+ }
71
+ return [...files].sort()
72
+ }
73
+
74
+ function fill(what: string): string {
75
+ return `${STATEMENT_PLACEHOLDER} : ${what}]`
76
+ }
77
+
78
+ /** The RGESN 2024 criteria prunelle can judge, or measure in part, from the build, `prunelle check` and the config. */
79
+ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
80
+ const autoplay = filesWarnedFor(facts.warnings, 'rgesn/autoplay')
81
+ const thirdParty = filesWarnedFor(facts.warnings, 'rgpd/third-party-url')
82
+ const measured = facts.report.routes.flatMap(r => r.ecoIndex === undefined ? [] : [r.ecoIndex])
83
+ const requests = Math.max(0, ...measured.map(e => e.requests))
84
+ const mostRequests = measured.length === 0 ? '' : ` La page la plus sollicitée fait ${requests} requête${requests > 1 ? 's' : ''} ;`
85
+ const total = facts.report.routes.length
86
+ const noJs = facts.report.routes.filter(r => r.jsGzip === 0).length
87
+ const assetOrigin = ABSOLUTE_URL_RE.test(facts.assetPrefix) ? facts.assetPrefix : undefined
88
+ return [
89
+ {
90
+ id: '4.1',
91
+ label: 'Le service numérique comporte-t-il uniquement des animations, vidéos et sons dont la lecture automatique est désactivée ?',
92
+ priority: 'Prioritaire',
93
+ verdict: autoplay.length === 0 ? 'Validé' : 'Non validé',
94
+ evidence: autoplay.length === 0
95
+ ? 'Aucune vidéo ni aucun son du code source ne se lance seul (prunelle check, règle rgesn/autoplay).'
96
+ : `Une lecture automatique reste dans : ${autoplay.join(', ')}.`,
97
+ },
98
+ {
99
+ id: '4.4',
100
+ label: 'Le service numérique permet-il à l\'utilisateur de décider de l\'activation d\'un service tiers ?',
101
+ priority: 'Recommandé',
102
+ verdict: thirdParty.length === 0 ? 'Validé' : 'Non validé',
103
+ evidence: thirdParty.length === 0
104
+ ? 'Aucune ressource tierce n\'est chargée avant le consentement du visiteur : chacune attend son accord (prunelle check, règle rgpd/third-party-url).'
105
+ : `Des ressources tierces se chargent sans consentement dans : ${thirdParty.join(', ')}.`,
106
+ },
107
+ {
108
+ id: '6.1',
109
+ label: 'Le service numérique s\'astreint-il à un poids maximum et une limite de requête par écran ?',
110
+ priority: 'Recommandé',
111
+ verdict: facts.firstLoadBudget === undefined ? 'Non validé' : undefined,
112
+ evidence: facts.firstLoadBudget === undefined
113
+ ? 'Aucun poids maximum par écran n\'est fixé.'
114
+ : `Le premier chargement de chaque page est plafonné à ${frNumber.format(facts.firstLoadBudget / 1024)} Kio, vérifié à chaque build.${mostRequests} ${fill('limite de requêtes par écran')}.`,
115
+ },
116
+ {
117
+ id: '6.3',
118
+ label: 'Le service numérique a-t-il mis en place des techniques de compression pour les ressources transférées dont il a le contrôle ?',
119
+ priority: 'Modéré',
120
+ verdict: facts.compress ? 'Validé' : 'Non validé',
121
+ evidence: facts.compress
122
+ ? 'Le JavaScript et les feuilles de style sont minifiés ; les fichiers sont précompressés en brotli et gzip au build, et les réponses dynamiques compressées à l\'envoi.'
123
+ : `La compression du serveur est désactivée (compress: false) ; ${fill('compression assurée en amont, le cas échéant')}.`,
124
+ },
125
+ {
126
+ id: '6.5',
127
+ label: 'Le service numérique évite-t-il de déclencher le chargement de ressources et de contenus inutilisés pour chaque fonctionnalité ?',
128
+ priority: 'Recommandé',
129
+ evidence: `${noJs === total ? 'Aucune page n\'envoie de JavaScript.' : `${noJs} page${noJs <= 1 ? '' : 's'} sur ${total} n'${noJs <= 1 ? 'envoie' : 'envoient'} aucun JavaScript ; les autres ne chargent que le code de leurs composants interactifs.`} ${fill('images, polices et données chargées sans être affichées')}.`,
130
+ },
131
+ {
132
+ id: '6.7',
133
+ label: 'Le service numérique héberge-t-il toutes les ressources statiques transférées dont il est l\'émetteur sur un même domaine ?',
134
+ priority: 'Modéré',
135
+ verdict: assetOrigin === undefined ? 'Validé' : 'Non validé',
136
+ evidence: assetOrigin === undefined
137
+ ? 'Les scripts, feuilles de style, polices et images sont servis par le domaine des pages.'
138
+ : `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
139
+ },
140
+ ]
141
+ }
142
+
143
+ function measuresSection(report: BundleReport): string {
144
+ const rows = report.routes.flatMap((r) => {
145
+ const e = r.ecoIndex
146
+ if (e === undefined)
147
+ return []
148
+ const url = e.url ?? r.path
149
+ return [` <tr><th scope="row"><code>${escapeJsxText(url)}</code></th><td>${e.grade} (${e.score})</td><td>${ko(e.weightBytes)}</td><td>${e.requests}</td><td>${frNumber.format(e.ghgGrams)}</td><td>${frNumber.format(e.waterCl)}</td></tr>`]
150
+ })
151
+ if (rows.length === 0)
152
+ return ` <p>${fill('mesures des pages représentatives : aucune page n\'est prérendue, prunelle n\'a rien mesuré')}</p>`
153
+ return [
154
+ ' <table>',
155
+ ' <caption>EcoIndex de chaque page prérendue, mesuré par prunelle build, avec les gaz à effet de serre (gCO2e) et l\'eau (cl) d\'une visite</caption>',
156
+ ' <thead>',
157
+ ' <tr><th scope="col">Page</th><th scope="col">EcoIndex</th><th scope="col">Poids</th><th scope="col">Requêtes</th><th scope="col">GES</th><th scope="col">Eau</th></tr>',
158
+ ' </thead>',
159
+ ' <tbody>',
160
+ ...rows,
161
+ ' </tbody>',
162
+ ' </table>',
163
+ ].join('\n')
164
+ }
165
+
166
+ function criteriaSections(criteria: readonly EcoCriterion[]): string {
167
+ return criteria.map(c => [
168
+ ` <h3>${c.id}. ${escapeJsxText(c.label)}</h3>`,
169
+ ' <dl>',
170
+ ` <dt>Priorité</dt><dd>${c.priority}</dd>`,
171
+ ` <dt>Évaluation</dt><dd>${escapeJsxText(c.verdict ?? fill('Validé, Non validé ou Non applicable'))}</dd>`,
172
+ ` <dt>Justification</dt><dd>${escapeJsxText(c.evidence)}</dd>`,
173
+ ' </dl>',
174
+ ].join('\n')).join('\n')
175
+ }
176
+
177
+ /** Generates (and by default writes) a draft RGESN 2024 eco-design declaration page in TSX. */
178
+ export function draftEcoDeclaration(options: EcoDeclarationOptions): EcoDeclarationResult {
179
+ const root = resolve(options.root)
180
+ const dest = resolve(root, options.outPath ?? DEFAULT_ECO_DECLARATION_PATH)
181
+ const relativePath = relPosix(root, dest)
182
+ // A second run finds the declaration among the built pages: it is not part of the service it describes.
183
+ const ownPath = fileToRoutePath(join(root, 'src/routes'), dest)
184
+ const report = { ...options.facts.report, routes: options.facts.report.routes.filter(r => r.path !== ownPath) }
185
+ const criteria = evaluateEcoCriteria({ ...options.facts, report })
186
+ const { iso, human } = formatFrenchDate(options.date ?? new Date())
187
+ const service = options.service?.trim() || fill('nom du service')
188
+ const org = options.organization?.trim() || fill('entité qui procède à l\'évaluation')
189
+ const contact = options.contactEmail?.trim()
190
+ const pages = report.routes.map(r => r.ecoIndex?.url ?? r.path)
191
+ const wrapper = layoutRendersMain(root, dest) ? 'article' : 'main'
192
+
193
+ const content = `// Brouillon de déclaration d'écoconception RGESN 2024 généré par \`prunelle eco --declaration\`.
194
+ // prunelle évalue les critères qu'il mesure ; les autres, et chaque mention entre crochets, sont à compléter avant publication : \`prunelle check\` signale celles qui restent.
195
+
196
+ import { Head } from 'prunelle'
197
+
198
+ export const prerender = true
199
+
200
+ export default function Ecoconception() {
201
+ return (
202
+ <>
203
+ <Head>
204
+ <title>Déclaration d'écoconception</title>
205
+ </Head>
206
+ <${wrapper} lang="fr">
207
+ <h1>Déclaration d'écoconception</h1>
208
+ <p>
209
+ <strong>${escapeJsxText(service)}</strong> s'inscrit dans une démarche d'écoconception visant à réduire ses impacts environnementaux.
210
+ Cette déclaration suit le <a href="${RGESN_URL}">référentiel général de l'écoconception des services numériques</a> (RGESN, version 2024).
211
+ </p>
212
+ <dl>
213
+ <dt>Service évalué</dt>
214
+ <dd>${escapeJsxText(service)}</dd>
215
+ <dt>Échantillon de pages</dt>
216
+ <dd>${escapeJsxText(pages.length > 0 ? pages.join(', ') : fill('pages représentatives des fonctionnalités principales'))}</dd>
217
+ <dt>Entité qui procède à l'évaluation</dt>
218
+ <dd>${escapeJsxText(org)}</dd>
219
+ <dt>Responsable de l'évaluation</dt>
220
+ <dd>${escapeJsxText(fill('nom du ou de la référente en écoconception'))}</dd>
221
+ <dt>Contact</dt>
222
+ <dd>${contact ? `<a href="mailto:${escapeAttr(contact)}">${escapeJsxText(contact)}</a>` : escapeJsxText(fill('adresse de contact'))}</dd>
223
+ <dt>Date de l'évaluation</dt>
224
+ <dd><time dateTime="${iso}">${human}</time></dd>
225
+ <dt>Score global</dt>
226
+ <dd>${escapeJsxText(fill('part des critères applicables validés, en %'))}</dd>
227
+ <dt>Profil matériel minimum</dt>
228
+ <dd>${escapeJsxText(fill('plus ancien terminal et navigateur sur lesquels le service fonctionne'))}</dd>
229
+ </dl>
230
+
231
+ <section>
232
+ <h2>Mesures</h2>
233
+ ${measuresSection(report)}
234
+ </section>
235
+
236
+ <section>
237
+ <h2>Objectifs et plan d'action</h2>
238
+ <p>${escapeJsxText(fill('objectifs de réduction des impacts, actions envisagées et fréquence des revues'))}</p>
239
+ </section>
240
+
241
+ <section>
242
+ <h2>Critères évalués</h2>
243
+ ${criteriaSections(criteria)}
244
+ <p>${escapeJsxText(fill('évaluation des autres critères applicables du RGESN 2024, avec leur justification'))}</p>
245
+ </section>
246
+ </${wrapper}>
247
+ </>
248
+ )
249
+ }
250
+ `
251
+
252
+ if (options.write !== false) {
253
+ mkdirSync(dirname(dest), { recursive: true })
254
+ writeFileSync(dest, content)
255
+ }
256
+ return { path: dest, relativePath, criteria, content }
257
+ }
@@ -0,0 +1,65 @@
1
+ // `prunelle eco`: builds the app, then judges the RGESN 2024 criteria prunelle can measure and, with --declaration, drafts the declaration page.
2
+
3
+ import type { BundleReport } from '../build/report'
4
+ import type { EcoCriterion, EcoDeclarationResult, EcoFacts } from './declaration'
5
+ import { parseByteSize } from '../build/byte-size'
6
+ import { loadConfig } from '../plugins/load'
7
+ import { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
8
+
9
+ export { DEFAULT_ECO_DECLARATION_PATH, draftEcoDeclaration, evaluateEcoCriteria } from './declaration'
10
+ export type { EcoCriterion, EcoDeclarationOptions, EcoDeclarationResult, EcoFacts, EcoVerdict } from './declaration'
11
+
12
+ export interface EcoRunOptions {
13
+ root: string
14
+ /** Write the declaration page, at this path (`''` for `src/routes/ecoconception.tsx`). */
15
+ declaration?: string | undefined
16
+ service?: string | undefined
17
+ organization?: string | undefined
18
+ contactEmail?: string | undefined
19
+ }
20
+
21
+ export interface EcoRunResult {
22
+ criteria: EcoCriterion[]
23
+ declaration?: EcoDeclarationResult | undefined
24
+ }
25
+
26
+ export async function collectEcoFacts(root: string): Promise<EcoFacts> {
27
+ const { build } = await import('../build/index')
28
+ const { checkProject } = await import('../cli/check')
29
+ let report: BundleReport = { routes: [], totalJsGzip: 0, totalCssGzip: 0, topModules: [] }
30
+ await build({ root, onAnalyze: (built) => { report = built } })
31
+ const { warnings } = await checkProject(root, { skipTypecheck: true })
32
+ const config = await loadConfig(root)
33
+ return {
34
+ report,
35
+ warnings,
36
+ assetPrefix: config.assetPrefix ?? '/_pru',
37
+ compress: config.compress !== false,
38
+ firstLoadBudget: config.budget?.firstLoad === undefined ? undefined : parseByteSize(config.budget.firstLoad),
39
+ }
40
+ }
41
+
42
+ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
43
+ const facts = await collectEcoFacts(options.root)
44
+ if (options.declaration === undefined)
45
+ return { criteria: evaluateEcoCriteria(facts) }
46
+ const declaration = draftEcoDeclaration({
47
+ root: options.root,
48
+ outPath: options.declaration === '' ? DEFAULT_ECO_DECLARATION_PATH : options.declaration,
49
+ facts,
50
+ service: options.service,
51
+ organization: options.organization,
52
+ contactEmail: options.contactEmail,
53
+ })
54
+ return { criteria: declaration.criteria, declaration }
55
+ }
56
+
57
+ export function formatEcoResult(result: EcoRunResult): string {
58
+ const lines = ['prunelle eco: the RGESN 2024 criteria prunelle can judge from the build, prunelle check and the config']
59
+ for (const c of result.criteria)
60
+ lines.push(` ${c.id.padEnd(4)} ${(c.verdict ?? 'to judge').padEnd(10)} ${c.evidence}`)
61
+ lines.push(result.declaration === undefined
62
+ ? 'The other criteria are for a person to judge: prunelle eco --declaration drafts the page that holds them all.'
63
+ : `prunelle eco: drafted the RGESN 2024 eco-design declaration at ${result.declaration.relativePath}: fill in each [à compléter ...] before publishing it.`)
64
+ return lines.join('\n')
65
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
- export { Catch, ConsentGate, createContext, Head, provideContext, Region, Suspense, useContext, useId } from './context'
2
- export type { CatchProps, ConsentGateProps, Context, RegionProps } from './context'
1
+ export { Catch, ConsentBanner, ConsentGate, ConsentPreferences, createContext, Head, provideContext, Region, Suspense, useContext, useId } from './context'
2
+ export type { CatchProps, ConsentBannerProps, ConsentGateProps, ConsentTexts, Context, RegionProps } from './context'
3
3
  export {
4
4
  batch,
5
5
  computed,