prunelle 0.1.1 → 0.7.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 (177) 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 +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  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 +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -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 +636 -0
  36. package/src/cli/check-imports.ts +31 -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 +101 -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 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,328 @@
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 { isInside } from '../build/is-inside'
9
+ import { fileToRoutePath } from '../build/routes'
10
+ import { parseOrigin } from '../compiler/compliance-urls'
11
+
12
+ export const DEFAULT_ECO_DECLARATION_PATH = 'src/routes/ecoconception.tsx'
13
+ const RGESN_URL = 'https://ecoresponsable.numerique.gouv.fr/publications/referentiel-general-ecoconception/'
14
+
15
+ /** What prunelle knows about an app when it drafts the declaration. */
16
+ export interface EcoFacts {
17
+ report: BundleReport
18
+ /** `prunelle check` warnings, as it prints them. */
19
+ warnings: readonly string[]
20
+ assetPrefix: string
21
+ compress: boolean
22
+ /** `budget.firstLoad` in bytes, when the config sets one. */
23
+ firstLoadBudget: number | undefined
24
+ /** Public site URL (`config.site`), used to tell a same-origin `assetPrefix` from another domain. */
25
+ site?: string | undefined
26
+ /** Compliance rules listed in `config.compliance.ignore`. */
27
+ ignoredRules?: readonly string[] | undefined
28
+ /** Configured `routesDir` relative to `root` (or absolute), when different from `'src/routes'`. */
29
+ routesDir?: string | undefined
30
+ }
31
+
32
+ export type EcoVerdict = 'Validé' | 'Non validé'
33
+
34
+ export interface EcoCriterion {
35
+ id: string
36
+ /** The criterion's wording in the RGESN 2024. */
37
+ label: string
38
+ priority: 'Prioritaire' | 'Recommandé' | 'Modéré'
39
+ /** Absent when prunelle measures part of the criterion and a person has to judge the rest. */
40
+ verdict?: EcoVerdict | undefined
41
+ evidence: string
42
+ }
43
+
44
+ export interface EcoDeclarationOptions {
45
+ root: string
46
+ /** Destination relative to `root` (or absolute). Default: `'<routesDir>/ecoconception.tsx'` (`'src/routes/ecoconception.tsx'`). */
47
+ outPath?: string | undefined
48
+ /** Routes directory relative to `root` (or absolute). Default: `'src/routes'`. */
49
+ routesDir?: string | undefined
50
+ facts: EcoFacts
51
+ service?: string | undefined
52
+ organization?: string | undefined
53
+ contactEmail?: string | undefined
54
+ date?: Date | undefined
55
+ /** Write the page to disk (default: `true`). */
56
+ write?: boolean | undefined
57
+ }
58
+
59
+ export interface EcoDeclarationResult {
60
+ path: string
61
+ relativePath: string
62
+ criteria: EcoCriterion[]
63
+ content: string
64
+ }
65
+
66
+ const WARNING_RE = /^(.+?):\d+:\d+: warning: \[([a-z]+\/[a-z-]+)\]/
67
+ const ABSOLUTE_URL_RE = /^(?:[a-z][a-z\d+.-]*:)?\/\//i
68
+ const frNumber = new Intl.NumberFormat('fr-FR', { maximumFractionDigits: 1 })
69
+
70
+ function ko(bytes: number): string {
71
+ return `${frNumber.format(bytes / 1000)} ko`
72
+ }
73
+
74
+ function filesWarnedFor(warnings: readonly string[], rule: string): string[] {
75
+ const files = new Set<string>()
76
+ for (const warning of warnings) {
77
+ const match = WARNING_RE.exec(warning)
78
+ if (match !== null && match[2] === rule)
79
+ files.add(match[1]!)
80
+ }
81
+ return [...files].sort()
82
+ }
83
+
84
+ function fill(what: string): string {
85
+ return `${STATEMENT_PLACEHOLDER} : ${what}]`
86
+ }
87
+
88
+ function foreignAssetPrefix(assetPrefix: string, site: string | undefined): string | undefined {
89
+ if (!ABSOLUTE_URL_RE.test(assetPrefix))
90
+ return undefined
91
+ const siteOrigin = parseOrigin(site)
92
+ if (siteOrigin !== undefined) {
93
+ const prefixUrl = assetPrefix.startsWith('//') ? `${new URL(siteOrigin).protocol}${assetPrefix}` : assetPrefix
94
+ if (parseOrigin(prefixUrl) === siteOrigin)
95
+ return undefined
96
+ }
97
+ return assetPrefix
98
+ }
99
+
100
+ function checkRuleVerdict(
101
+ files: readonly string[],
102
+ ignored: boolean,
103
+ rule: string,
104
+ validText: string,
105
+ invalidPrefix: string,
106
+ manualPrompt: string,
107
+ ): Pick<EcoCriterion, 'verdict' | 'evidence'> {
108
+ if (files.length > 0)
109
+ return { verdict: 'Non validé', evidence: `${invalidPrefix}${files.join(', ')}.` }
110
+ if (ignored)
111
+ return { verdict: undefined, evidence: `La règle ${rule} est ignorée dans prunelle.config.ts (compliance.ignore) ; ${fill(manualPrompt)}.` }
112
+ return { verdict: 'Validé', evidence: validText }
113
+ }
114
+
115
+ function sameDomainVerdict(assetOrigin: string | undefined, externalPages: readonly string[]): Pick<EcoCriterion, 'verdict' | 'evidence'> {
116
+ if (assetOrigin === undefined && externalPages.length === 0) {
117
+ return {
118
+ verdict: 'Validé',
119
+ evidence: 'Les scripts, feuilles de style, polices et images sont servis par le domaine des pages.',
120
+ }
121
+ }
122
+ if (assetOrigin !== undefined && externalPages.length === 0) {
123
+ return {
124
+ verdict: 'Non validé',
125
+ evidence: `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages.`,
126
+ }
127
+ }
128
+ const externalNote = `des ressources statiques sont chargées depuis un autre domaine sur : ${externalPages.join(', ')}`
129
+ return {
130
+ verdict: 'Non validé',
131
+ evidence: assetOrigin === undefined
132
+ ? `${externalNote[0]!.toUpperCase()}${externalNote.slice(1)}.`
133
+ : `Les scripts et feuilles de style sont servis depuis ${assetOrigin}, un autre domaine que celui des pages ; ${externalNote}.`,
134
+ }
135
+ }
136
+
137
+ /** The RGESN 2024 criteria prunelle can judge, or measure in part, from the build, `prunelle check` and the config. */
138
+ export function evaluateEcoCriteria(facts: EcoFacts): EcoCriterion[] {
139
+ const autoplay = filesWarnedFor(facts.warnings, 'rgesn/autoplay')
140
+ const thirdParty = filesWarnedFor(facts.warnings, 'rgpd/third-party-url')
141
+ const ignored = new Set(facts.ignoredRules ?? [])
142
+ const measured = facts.report.routes.flatMap(r => r.ecoIndex === undefined ? [] : [r.ecoIndex])
143
+ const requests = Math.max(0, ...measured.map(e => e.requests))
144
+ const mostRequests = measured.length === 0 ? '' : ` La page la plus sollicitée fait ${requests} requête${requests > 1 ? 's' : ''} ;`
145
+ const total = facts.report.routes.length
146
+ const noJs = facts.report.routes.filter(r => r.jsGzip === 0).length
147
+ const assetOrigin = foreignAssetPrefix(facts.assetPrefix, facts.site)
148
+ const externalPages = [...new Set(
149
+ facts.report.routes
150
+ .filter(r => (r.ecoIndex?.external ?? 0) > 0)
151
+ .map(r => r.ecoIndex?.url ?? r.path),
152
+ )].sort()
153
+ return [
154
+ {
155
+ id: '4.1',
156
+ label: 'Le service numérique comporte-t-il uniquement des animations, vidéos et sons dont la lecture automatique est désactivée ?',
157
+ priority: 'Prioritaire',
158
+ ...checkRuleVerdict(
159
+ autoplay,
160
+ ignored.has('rgesn/autoplay'),
161
+ 'rgesn/autoplay',
162
+ 'Aucune vidéo ni aucun son du code source ne se lance seul (prunelle check, règle rgesn/autoplay).',
163
+ 'Une lecture automatique reste dans : ',
164
+ 'vérification manuelle de la lecture automatique',
165
+ ),
166
+ },
167
+ {
168
+ id: '4.4',
169
+ label: 'Le service numérique permet-il à l\'utilisateur de décider de l\'activation d\'un service tiers ?',
170
+ priority: 'Recommandé',
171
+ ...checkRuleVerdict(
172
+ thirdParty,
173
+ ignored.has('rgpd/third-party-url'),
174
+ 'rgpd/third-party-url',
175
+ 'Aucune ressource tierce n\'est chargée avant le consentement du visiteur : chacune attend son accord (prunelle check, règle rgpd/third-party-url).',
176
+ 'Des ressources tierces se chargent sans consentement dans : ',
177
+ 'vérification manuelle des services tiers',
178
+ ),
179
+ },
180
+ {
181
+ id: '6.1',
182
+ label: 'Le service numérique s\'astreint-il à un poids maximum et une limite de requête par écran ?',
183
+ priority: 'Recommandé',
184
+ verdict: facts.firstLoadBudget === undefined ? 'Non validé' : undefined,
185
+ evidence: facts.firstLoadBudget === undefined
186
+ ? 'Aucun poids maximum par écran n\'est fixé.'
187
+ : `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')}.`,
188
+ },
189
+ {
190
+ id: '6.3',
191
+ 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 ?',
192
+ priority: 'Modéré',
193
+ verdict: facts.compress ? 'Validé' : 'Non validé',
194
+ evidence: facts.compress
195
+ ? '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.'
196
+ : `La compression du serveur est désactivée (compress: false) ; ${fill('compression assurée en amont, le cas échéant')}.`,
197
+ },
198
+ {
199
+ id: '6.5',
200
+ label: 'Le service numérique évite-t-il de déclencher le chargement de ressources et de contenus inutilisés pour chaque fonctionnalité ?',
201
+ priority: 'Recommandé',
202
+ 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')}.`,
203
+ },
204
+ {
205
+ id: '6.7',
206
+ 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 ?',
207
+ priority: 'Modéré',
208
+ ...sameDomainVerdict(assetOrigin, externalPages),
209
+ },
210
+ ]
211
+ }
212
+
213
+ function measuresSection(report: BundleReport): string {
214
+ const rows = report.routes.flatMap((r) => {
215
+ const e = r.ecoIndex
216
+ if (e === undefined)
217
+ return []
218
+ const url = e.url ?? r.path
219
+ 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>`]
220
+ })
221
+ if (rows.length === 0)
222
+ return ` <p>${fill('mesures des pages représentatives : aucune page n\'est prérendue, prunelle n\'a rien mesuré')}</p>`
223
+ return [
224
+ ' <table>',
225
+ ' <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>',
226
+ ' <thead>',
227
+ ' <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>',
228
+ ' </thead>',
229
+ ' <tbody>',
230
+ ...rows,
231
+ ' </tbody>',
232
+ ' </table>',
233
+ ].join('\n')
234
+ }
235
+
236
+ function criteriaSections(criteria: readonly EcoCriterion[]): string {
237
+ return criteria.map(c => [
238
+ ` <h3>${c.id}. ${escapeJsxText(c.label)}</h3>`,
239
+ ' <dl>',
240
+ ` <dt>Priorité</dt><dd>${c.priority}</dd>`,
241
+ ` <dt>Évaluation</dt><dd>${escapeJsxText(c.verdict ?? fill('Validé, Non validé ou Non applicable'))}</dd>`,
242
+ ` <dt>Justification</dt><dd>${escapeJsxText(c.evidence)}</dd>`,
243
+ ' </dl>',
244
+ ].join('\n')).join('\n')
245
+ }
246
+
247
+ /** Generates (and by default writes) a draft RGESN 2024 eco-design declaration page in TSX. */
248
+ export function draftEcoDeclaration(options: EcoDeclarationOptions): EcoDeclarationResult {
249
+ const root = resolve(options.root)
250
+ const routesDir = resolve(root, options.routesDir ?? options.facts.routesDir ?? 'src/routes')
251
+ const dest = options.outPath !== undefined ? resolve(root, options.outPath) : join(routesDir, 'ecoconception.tsx')
252
+ const relativePath = relPosix(root, dest)
253
+ // A second run finds the declaration among the built pages: it is not part of the service it describes.
254
+ const ownPath = isInside(routesDir, dest) ? fileToRoutePath(routesDir, dest) : undefined
255
+ const report = { ...options.facts.report, routes: options.facts.report.routes.filter(r => r.path !== ownPath) }
256
+ const criteria = evaluateEcoCriteria({ ...options.facts, report })
257
+ const { iso, human } = formatFrenchDate(options.date ?? new Date())
258
+ const service = options.service?.trim() || fill('nom du service')
259
+ const org = options.organization?.trim() || fill('entité qui procède à l\'évaluation')
260
+ const contact = options.contactEmail?.trim()
261
+ const pages = report.routes.map(r => r.ecoIndex?.url ?? r.path)
262
+ const wrapper = layoutRendersMain(root, dest) ? 'article' : 'main'
263
+
264
+ const content = `// Brouillon de déclaration d'écoconception RGESN 2024 généré par \`prunelle eco --declaration\`.
265
+ // 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.
266
+
267
+ import { Head } from 'prunelle'
268
+
269
+ export const prerender = true
270
+
271
+ export default function Ecoconception() {
272
+ return (
273
+ <>
274
+ <Head>
275
+ <title>Déclaration d'écoconception</title>
276
+ </Head>
277
+ <${wrapper} lang="fr">
278
+ <h1>Déclaration d'écoconception</h1>
279
+ <p>
280
+ <strong>${escapeJsxText(service)}</strong> s'inscrit dans une démarche d'écoconception visant à réduire ses impacts environnementaux.
281
+ 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).
282
+ </p>
283
+ <dl>
284
+ <dt>Service évalué</dt>
285
+ <dd>${escapeJsxText(service)}</dd>
286
+ <dt>Échantillon de pages</dt>
287
+ <dd>${escapeJsxText(pages.length > 0 ? pages.join(', ') : fill('pages représentatives des fonctionnalités principales'))}</dd>
288
+ <dt>Entité qui procède à l'évaluation</dt>
289
+ <dd>${escapeJsxText(org)}</dd>
290
+ <dt>Responsable de l'évaluation</dt>
291
+ <dd>${escapeJsxText(fill('nom du ou de la référente en écoconception'))}</dd>
292
+ <dt>Contact</dt>
293
+ <dd>${contact ? `<a href="mailto:${escapeAttr(contact)}">${escapeJsxText(contact)}</a>` : escapeJsxText(fill('adresse de contact'))}</dd>
294
+ <dt>Date de l'évaluation</dt>
295
+ <dd><time dateTime="${iso}">${human}</time></dd>
296
+ <dt>Score global</dt>
297
+ <dd>${escapeJsxText(fill('part des critères applicables validés, en %'))}</dd>
298
+ <dt>Profil matériel minimum</dt>
299
+ <dd>${escapeJsxText(fill('plus ancien terminal et navigateur sur lesquels le service fonctionne'))}</dd>
300
+ </dl>
301
+
302
+ <section>
303
+ <h2>Mesures</h2>
304
+ ${measuresSection(report)}
305
+ </section>
306
+
307
+ <section>
308
+ <h2>Objectifs et plan d'action</h2>
309
+ <p>${escapeJsxText(fill('objectifs de réduction des impacts, actions envisagées et fréquence des revues'))}</p>
310
+ </section>
311
+
312
+ <section>
313
+ <h2>Critères évalués</h2>
314
+ ${criteriaSections(criteria)}
315
+ <p>${escapeJsxText(fill('évaluation des autres critères applicables du RGESN 2024, avec leur justification'))}</p>
316
+ </section>
317
+ </${wrapper}>
318
+ </>
319
+ )
320
+ }
321
+ `
322
+
323
+ if (options.write !== false) {
324
+ mkdirSync(dirname(dest), { recursive: true })
325
+ writeFileSync(dest, content)
326
+ }
327
+ return { path: dest, relativePath, criteria, content }
328
+ }
@@ -0,0 +1,69 @@
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 { 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 `<routesDir>/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
+ site: config.site,
40
+ ignoredRules: config.compliance?.ignore,
41
+ routesDir: config.routesDir,
42
+ }
43
+ }
44
+
45
+ export async function runEco(options: EcoRunOptions): Promise<EcoRunResult> {
46
+ const facts = await collectEcoFacts(options.root)
47
+ if (options.declaration === undefined)
48
+ return { criteria: evaluateEcoCriteria(facts) }
49
+ const declaration = draftEcoDeclaration({
50
+ root: options.root,
51
+ outPath: options.declaration === '' ? undefined : options.declaration,
52
+ routesDir: facts.routesDir,
53
+ facts,
54
+ service: options.service,
55
+ organization: options.organization,
56
+ contactEmail: options.contactEmail,
57
+ })
58
+ return { criteria: declaration.criteria, declaration }
59
+ }
60
+
61
+ export function formatEcoResult(result: EcoRunResult): string {
62
+ const lines = ['prunelle eco: the RGESN 2024 criteria prunelle can judge from the build, prunelle check and the config']
63
+ for (const c of result.criteria)
64
+ lines.push(` ${c.id.padEnd(4)} ${(c.verdict ?? 'to judge').padEnd(10)} ${c.evidence}`)
65
+ lines.push(result.declaration === undefined
66
+ ? 'The other criteria are for a person to judge: prunelle eco --declaration drafts the page that holds them all.'
67
+ : `prunelle eco: drafted the RGESN 2024 eco-design declaration at ${result.declaration.relativePath}: fill in each [à compléter ...] before publishing it.`)
68
+ return lines.join('\n')
69
+ }
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,
@@ -35,11 +35,11 @@ export function Fragment(props: { children?: PrunelleChild }): PrunelleChild {
35
35
  return props.children
36
36
  }
37
37
 
38
- // Runtime fallbacks (only used if JSX isn't compiled, e.g. quick tests)
38
+ // Only a component call reaches this: prunelle's compiler turns every element into HTML or DOM calls, so an element here means the file skipped it.
39
39
  export function jsx(tag: unknown, props: Record<string, unknown>): PrunelleChild | Promise<PrunelleChild> {
40
40
  if (typeof tag === 'function')
41
41
  return (tag as Component)(props)
42
- return null
42
+ throw new Error(`prunelle: <${String(tag)}> reached the JSX runtime, so this file was not compiled by prunelle: run it with prunelle dev, build or prunelle/test, and check that nothing else (a bundler, a test runner, a tsconfig \`jsxImportSource\`) compiles the TSX first.`)
43
43
  }
44
44
 
45
45
  export const jsxs = jsx
@@ -6,20 +6,25 @@ export function defineConfig(config: PrunelleConfig): PrunelleConfig {
6
6
  return config
7
7
  }
8
8
 
9
- /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`, `compliance`). */
9
+ // Typed as records so that a key added to the config types without being listed here fails the typecheck.
10
+ const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, routeCache: true, healthCheck: true, onError: true, plugins: true }
11
+ const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
12
+ const BUILD_KEY_SET = new Set<string>(Object.keys(BUILD_KEYS))
13
+ const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
14
+ const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
15
+
16
+ /** Forwards every runtime key from `prunelle.config.ts`, stripping build/CLI-only keys (`BUILD_KEYS`). */
10
17
  export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRuntimeConfig {
11
18
  if (config === undefined)
12
19
  return {}
13
- const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, compliance: _c, ...runtime } = config
14
- return runtime
20
+ const runtime: Record<string, unknown> = {}
21
+ for (const [key, value] of Object.entries(config)) {
22
+ if (!BUILD_KEY_SET.has(key))
23
+ runtime[key] = value
24
+ }
25
+ return runtime as ServerRuntimeConfig
15
26
  }
16
27
 
17
- // Typed as records so that a key added to the config types without being listed here fails the typecheck.
18
- const RUNTIME_KEYS: Record<keyof ServerRuntimeConfig, true> = { site: true, lang: true, assetPrefix: true, security: true, trustedOrigins: true, trustProxy: true, maxRequestBodySize: true, navigation: true, streamTimeout: true, consent: true, compress: true, onError: true, plugins: true }
19
- const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true }
20
- const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
21
- const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
22
-
23
28
  // Edit distance, two neighbours swapped counting as one edit.
24
29
  function editDistance(a: string, b: string): number {
25
30
  let before: number[] = []
@@ -38,13 +43,14 @@ function editDistance(a: string, b: string): number {
38
43
  return previous[b.length]!
39
44
  }
40
45
 
41
- /** The name of `names` within two edits of `name` (one for a name under four letters), the nearest first: the one a typo meant. */
46
+ /** The name of `names` within two edits of `name` (one when either name is under four letters), the nearest first: the one a typo meant. */
42
47
  export function closestName(name: string, names: readonly string[]): string | undefined {
43
48
  let best: string | undefined
44
- let bestDistance = name.length < 4 ? 2 : 3
49
+ let bestDistance = 3
45
50
  for (const known of names) {
51
+ const maxDistance = Math.min(name.length, known.length) < 4 ? 1 : 2
46
52
  const far = editDistance(name, known)
47
- if (far < bestDistance) {
53
+ if (far <= maxDistance && far < bestDistance) {
48
54
  best = known
49
55
  bestDistance = far
50
56
  }
@@ -61,6 +61,49 @@ export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
61
61
  return appStorage.run(ctx, fn)
62
62
  }
63
63
 
64
+ // Bun does not carry an AsyncLocalStorage store into the top level of a module imported inside `run()` (1.4.5), so the context of a config being imported is also kept here.
65
+ // Shared on `globalThis` alongside `appStorage` so dual module instances coordinate, and serialized across non-nested calls so out-of-order imports cannot leak `current`.
66
+ interface ImportFallbackState {
67
+ current: AppRuntimeContext | undefined
68
+ tail: Promise<void>
69
+ inImport: AsyncLocalStorage<boolean>
70
+ }
71
+
72
+ const IMPORT_STATE_KEY = Symbol.for('pru.app.importState')
73
+ const importState: ImportFallbackState = (
74
+ (globalThis as Record<symbol, ImportFallbackState | undefined>)[IMPORT_STATE_KEY]
75
+ ??= { current: undefined, tail: Promise.resolve(), inImport: new AsyncLocalStorage<boolean>() }
76
+ )
77
+
78
+ async function runImporting<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
79
+ const outer = importState.current
80
+ importState.current = ctx
81
+ try {
82
+ return await importState.inImport.run(true, () => runWithAppContext(ctx, load))
83
+ }
84
+ finally {
85
+ importState.current = outer
86
+ }
87
+ }
88
+
89
+ /** Imports with `ctx` as the app context, the imported modules' top-level code included. */
90
+ export async function importWithAppContext<T>(ctx: AppRuntimeContext, load: () => Promise<T>): Promise<T> {
91
+ if (importState.inImport.getStore() === true)
92
+ return runImporting(ctx, load)
93
+ const prev = importState.tail
94
+ let release!: () => void
95
+ importState.tail = new Promise<void>((resolve) => {
96
+ release = resolve
97
+ })
98
+ await prev
99
+ try {
100
+ return await runImporting(ctx, load)
101
+ }
102
+ finally {
103
+ release()
104
+ }
105
+ }
106
+
64
107
  export function getAppContext(): AppRuntimeContext | undefined {
65
- return appStorage.getStore()
108
+ return appStorage.getStore() ?? importState.current
66
109
  }
@@ -7,8 +7,8 @@ export { createAppContext, getAppContext, runWithAppContext } from './context'
7
7
  export type { AppRuntimeContext, CreateAppContextOptions } from './context'
8
8
  export { loadConfig } from './load'
9
9
  export { resolvePlugins } from './order'
10
- export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
11
- export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
10
+ export { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, WEB_MANIFEST_SERVICE, serviceKey } from './services'
11
+ export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey, WebManifestIcon, WebManifestInfo } from './services'
12
12
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
13
13
  export type { ConsentConfig } from '../server/consent'
14
14
  export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -2,20 +2,37 @@
2
2
 
3
3
  import type { AppRuntimeContext } from './context'
4
4
  import type { PrunelleConfig } from './types'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
5
6
  import { existsSync, readFileSync } from 'node:fs'
6
- import { join, relative, resolve } from 'node:path'
7
+ import { join, relative, resolve, sep } from 'node:path'
7
8
  import { assertKnownConfigKeys } from './config'
8
- import { createAppContext, getAppContext, runWithAppContext } from './context'
9
+ import { devFromEnv } from '../server/env'
10
+ import { createAppContext, getAppContext, importWithAppContext } from './context'
9
11
 
10
12
  let configReloadSeq = 0
13
+ const PRUNELLE_SRC_DIR = resolve(import.meta.dir, '..')
14
+ const freshConfigStorage = new AsyncLocalStorage<boolean>()
11
15
 
12
- // In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
13
- function configSpecifier(configPath: string, fresh: boolean, isDev: boolean): string {
16
+ /** Runs `fn` with every nested `loadConfig()` bypassing Bun's module cache (used by long-lived processes such as `prunelle mcp`). */
17
+ export function runWithFreshConfig<T>(fn: () => T): T {
18
+ return freshConfigStorage.run(true, fn)
19
+ }
20
+
21
+ function evictLocalConfigImports(absRoot: string): void {
22
+ const rootPrefix = absRoot.endsWith(sep) ? absRoot : `${absRoot}${sep}`
23
+ const pruPrefix = PRUNELLE_SRC_DIR.endsWith(sep) ? PRUNELLE_SRC_DIR : `${PRUNELLE_SRC_DIR}${sep}`
24
+ const nmSegment = `${sep}node_modules${sep}`
25
+ for (const cached of Object.keys(require.cache)) {
26
+ if (cached.startsWith(rootPrefix) && !cached.includes(nmSegment) && !cached.startsWith(pruPrefix))
27
+ delete require.cache[cached]
28
+ }
29
+ }
30
+
31
+ // Query follows file content so unchanged configs reuse loaded plugin instances while edits reload immediately; `fresh` forces a new evaluation.
32
+ function configSpecifier(configPath: string, fresh: boolean): string {
14
33
  if (fresh)
15
34
  return `${configPath}?v=fresh-${++configReloadSeq}`
16
- if (isDev)
17
- return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
18
- return configPath
35
+ return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
19
36
  }
20
37
 
21
38
  export async function loadConfig(
@@ -27,9 +44,12 @@ export async function loadConfig(
27
44
  if (!existsSync(configPath))
28
45
  return {}
29
46
  const active = options?.appContext ?? getAppContext()
30
- const isDev = options?.dev ?? active?.dev ?? (process.env.PRUNELLE_DEV === '1')
47
+ const isDev = options?.dev ?? active?.dev ?? devFromEnv()
31
48
  const resolvedNodeEnv = options?.nodeEnv ?? active?.nodeEnv
32
- const spec = configSpecifier(configPath, options?.fresh === true, isDev)
49
+ const isFresh = options?.fresh ?? (freshConfigStorage.getStore() === true)
50
+ if (isFresh)
51
+ evictLocalConfigImports(absRoot)
52
+ const spec = configSpecifier(configPath, isFresh)
33
53
  const ctx = active !== undefined && active.root === absRoot
34
54
  ? active
35
55
  : createAppContext({
@@ -42,7 +62,7 @@ export async function loadConfig(
42
62
  })
43
63
  let mod: { default?: PrunelleConfig }
44
64
  try {
45
- mod = await runWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
65
+ mod = await importWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
46
66
  }
47
67
  catch (error) {
48
68
  // Several syntax errors arrive together; the first one names the line to fix.
@@ -7,6 +7,43 @@ function enforceRank(plugin: PrunellePlugin): number {
7
7
  return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
8
8
  }
9
9
 
10
+ function splitScope(name: string): { scope: string | undefined, pkg: string } {
11
+ if (name.startsWith('@')) {
12
+ const slash = name.indexOf('/')
13
+ if (slash > 1 && slash < name.length - 1)
14
+ return { scope: name.slice(0, slash), pkg: name.slice(slash + 1) }
15
+ }
16
+ return { scope: undefined, pkg: name }
17
+ }
18
+
19
+ // Compares scoped plugin names without their shared `@scope/` prefix so short official plugins (`@prunellejs/cms` vs `@prunellejs/mcp`, `@prunellejs/seo` vs `@prunellejs/spa`) never false-positive as typos.
20
+ function closestPluginName(depName: string, names: readonly string[]): string | undefined {
21
+ const dep = splitScope(depName)
22
+ if (dep.scope === undefined)
23
+ return closestName(depName, names.filter(n => splitScope(n).scope === undefined))
24
+
25
+ const sameScopePkgs: string[] = []
26
+ const byPkg = new Map<string, string>()
27
+ const samePkgScopes: string[] = []
28
+ const byScope = new Map<string, string>()
29
+ for (const known of names) {
30
+ const parts = splitScope(known)
31
+ if (parts.scope === dep.scope) {
32
+ sameScopePkgs.push(parts.pkg)
33
+ byPkg.set(parts.pkg, known)
34
+ }
35
+ else if (parts.scope !== undefined && parts.pkg === dep.pkg) {
36
+ samePkgScopes.push(parts.scope)
37
+ byScope.set(parts.scope, known)
38
+ }
39
+ }
40
+ const nearPkg = closestName(dep.pkg, sameScopePkgs)
41
+ if (nearPkg !== undefined)
42
+ return byPkg.get(nearPkg)
43
+ const nearScope = closestName(dep.scope, samePkgScopes)
44
+ return nearScope !== undefined ? byScope.get(nearScope) : undefined
45
+ }
46
+
10
47
  /**
11
48
  * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
12
49
  * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
@@ -44,7 +81,7 @@ export function resolvePlugins(plugins: readonly PrunellePlugin[] | undefined):
44
81
  const depIdx = indexByName.get(depName)
45
82
  // A name no plugin has is an optional dependency that is not installed, unless it is one typo away from one that is.
46
83
  if (depIdx === undefined) {
47
- const near = closestName(depName, names)
84
+ const near = closestPluginName(depName, names)
48
85
  if (near !== undefined)
49
86
  throw new Error(`prunelle: plugin "${base[i]!.name}" runs \`after\` "${depName}", which no plugin is named: did you mean "${near}"?`)
50
87
  continue