prunelle 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +25 -16
  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 +61 -18
  16. package/src/build/island-promote.ts +250 -0
  17. package/src/build/islands.ts +12 -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 +25 -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 +37 -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 +27 -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 +146 -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 +60 -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 +32 -0
  54. package/src/dev/index.ts +17 -7
  55. package/src/dev/open-editor.ts +36 -12
  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 +28 -6
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +60 -27
  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 +44 -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 +56 -8
  86. package/src/server/index.ts +59 -30
  87. package/src/server/loader.ts +10 -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 +73 -22
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +31 -5
  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 +64 -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
@@ -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,
@@ -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
@@ -16,7 +16,7 @@ export function pickRuntimeConfig(config: PrunelleConfig | undefined): ServerRun
16
16
 
17
17
  // Typed as records so that a key added to the config types without being listed here fails the typecheck.
18
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, routeCache: true, healthCheck: 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, autoPrerender: true }
19
+ const BUILD_KEYS: Record<Exclude<keyof PrunelleConfig, keyof ServerRuntimeConfig>, true> = { port: true, routesDir: true, outDir: true, publicDir: true, compliance: true, autoPrerender: true, budget: true }
20
20
  const RUNTIME_CONFIG_KEYS = Object.keys(RUNTIME_KEYS) as (keyof ServerRuntimeConfig)[]
21
21
  const CONFIG_KEYS = [...RUNTIME_CONFIG_KEYS, ...Object.keys(BUILD_KEYS)]
22
22
 
@@ -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
  }
@@ -6,7 +6,8 @@ import { AsyncLocalStorage } from 'node:async_hooks'
6
6
  import { existsSync, readFileSync } from 'node:fs'
7
7
  import { join, relative, resolve, sep } from 'node:path'
8
8
  import { assertKnownConfigKeys } from './config'
9
- import { createAppContext, getAppContext, runWithAppContext } from './context'
9
+ import { devFromEnv } from '../server/env'
10
+ import { createAppContext, getAppContext, importWithAppContext } from './context'
10
11
 
11
12
  let configReloadSeq = 0
12
13
  const PRUNELLE_SRC_DIR = resolve(import.meta.dir, '..')
@@ -43,7 +44,7 @@ export async function loadConfig(
43
44
  if (!existsSync(configPath))
44
45
  return {}
45
46
  const active = options?.appContext ?? getAppContext()
46
- const isDev = options?.dev ?? active?.dev ?? (process.env.PRUNELLE_DEV === '1')
47
+ const isDev = options?.dev ?? active?.dev ?? devFromEnv()
47
48
  const resolvedNodeEnv = options?.nodeEnv ?? active?.nodeEnv
48
49
  const isFresh = options?.fresh ?? (freshConfigStorage.getStore() === true)
49
50
  if (isFresh)
@@ -61,7 +62,7 @@ export async function loadConfig(
61
62
  })
62
63
  let mod: { default?: PrunelleConfig }
63
64
  try {
64
- mod = await runWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
65
+ mod = await importWithAppContext(ctx, () => import(spec)) as { default?: PrunelleConfig }
65
66
  }
66
67
  catch (error) {
67
68
  // Several syntax errors arrive together; the first one names the line to fix.
@@ -8,8 +8,8 @@ export type { FirstLoad, Locate } from '../build/first-load'
8
8
  export { brotliSize } from '../build/precompress'
9
9
  export { minifyCss } from '../build/style-bundles'
10
10
  export { defineConfig, definePlugin } from './config'
11
- 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 { CMS_INLINE_ENABLED_SERVICE, CONTENT_COLLECTIONS_SERVICE, CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, JOBS_SERVICE, serviceKey, UI_KUI_LAYER_SERVICE, WEB_MANIFEST_SERVICE } from './services'
12
12
  export type { AccessedContentEntry, ActiveI18nConfig, ContentCollectionDescriptor, ContentCollectionEntrySummary, ContentCollectionsService, ContentImageResolver, ContentImageResult, JobsEnqueueOptions, JobsQueueOptions, JobsService, ServiceKey, WebManifestIcon, WebManifestInfo } from './services'
13
13
  export type { ComplianceConfig, ComplianceRule } from '../compiler/compliance'
14
14
  export type { ConsentConfig } from '../server/consent'
15
- export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
15
+ export type { BudgetConfig, BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, PrunelleConfig, PrunellePlugin, MiddlewareOptions, PluginRouteOptions, RequiresPluginContext, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -23,6 +23,9 @@ export interface ActiveI18nConfig {
23
23
 
24
24
  export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('prunelle.i18n.config')
25
25
 
26
+ /** Set by `@prunellejs/ui` when it emits its grammar layer, so `@prunellejs/tailwind` places the `kui` layer between its base and utilities layers. */
27
+ export const UI_KUI_LAYER_SERVICE = serviceKey<boolean>('prunelle.ui.kuiLayer')
28
+
26
29
  export interface ContentImageResult {
27
30
  src: string
28
31
  srcset?: string | undefined
@@ -84,6 +84,8 @@ export interface FinalizeBuildContext {
84
84
  export interface CheckPluginContext {
85
85
  readonly root: string
86
86
  readonly routesDir: string
87
+ /** The app's own static folder (`publicDir`, `public/` by default), as `prunelle check` resolved it. */
88
+ readonly publicDir?: string | undefined
87
89
  /** Report a validation error from `prunelle check`. */
88
90
  error(message: string): void
89
91
  /** Report what may be intended but usually is not; `prunelle check --strict` fails on it. */
@@ -98,6 +100,8 @@ export interface RequiresPluginContext {
98
100
  readonly root: string
99
101
  /** `PrunelleConfig.site`, when the app sets it. */
100
102
  readonly site: string | undefined
103
+ /** The categories `consent.categories` declares, `essential` left out; empty when the app declares none. */
104
+ readonly consentCategories: readonly string[]
101
105
  }
102
106
 
103
107
  export interface PluginRouteOptions {
@@ -132,6 +136,8 @@ export interface ServerPluginAPI {
132
136
  readonly assetPrefix: string
133
137
  readonly site?: string | undefined
134
138
  readonly dev: boolean
139
+ /** True when `prunelle dev --host` binds an address other machines reach (`0.0.0.0`, a LAN address): a dev-only route that writes or reveals data then needs a guard. */
140
+ readonly devExposed: boolean
135
141
  /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
136
142
  readonly trustProxy: TrustProxy
137
143
  readonly trustedOrigins: readonly string[]
@@ -141,7 +147,7 @@ export interface ServerPluginAPI {
141
147
  use(middleware: Middleware, options?: MiddlewareOptions): void
142
148
  /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
143
149
  route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
144
- /** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait. */
150
+ /** A limiter counting in this server's store, for limits a route option cannot express (per account, per email): `hit(key)` returns 0, or the seconds to wait, and `peek(key)` answers the same without counting. */
145
151
  rateLimiter(limit: Pick<RateLimit, 'max' | 'windowMs'>): RateLimiter
146
152
  /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
147
153
  rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
@@ -198,7 +204,7 @@ export interface PrunellePlugin {
198
204
  /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
199
205
  transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
200
206
  /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
201
- bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
207
+ bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget, lang?: string | undefined }) => BunPlugin[]) | undefined
202
208
  /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
203
209
  css?: string[] | undefined
204
210
  /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
@@ -260,4 +266,13 @@ export interface PrunelleConfig extends ServerRuntimeConfig {
260
266
  compliance?: ComplianceConfig | undefined
261
267
  /** Automatically prerender static pages that read nothing from the request or clock (and have no middleware or `cache` export). */
262
268
  autoPrerender?: boolean | undefined
269
+ /** Page weight caps `prunelle build` fails on: bytes, or a size like `'40kb'`. */
270
+ budget?: BudgetConfig | undefined
271
+ }
272
+
273
+ export interface BudgetConfig {
274
+ /** Eager JS per route, gzipped (`--max-js` overrides it for one run). */
275
+ js?: number | string | undefined
276
+ /** What a first visit downloads, brotli: the stylesheets, scripts and fonts, and on a prerendered page its HTML and every image. */
277
+ firstLoad?: number | string | undefined
263
278
  }