prunelle 0.1.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +369 -0
  5. package/src/a11y/index.ts +466 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +88 -40
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +230 -0
  15. package/src/build/files.ts +6 -0
  16. package/src/build/first-load.ts +83 -11
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +218 -113
  19. package/src/build/island-promote.ts +229 -0
  20. package/src/build/islands.ts +11 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +2 -2
  23. package/src/build/plugin-host.ts +113 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +173 -38
  26. package/src/build/reach.ts +136 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +42 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +93 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +610 -0
  36. package/src/cli/check-imports.ts +25 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +107 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -18
  49. package/src/compiler/analyze.ts +68 -14
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability.ts +636 -0
  52. package/src/compiler/compliance-eco.ts +71 -0
  53. package/src/compiler/compliance-rgaa.ts +614 -0
  54. package/src/compiler/compliance-urls.ts +145 -0
  55. package/src/compiler/compliance.ts +355 -351
  56. package/src/compiler/data-keys.ts +199 -192
  57. package/src/compiler/dev-source.ts +87 -0
  58. package/src/compiler/dom-attrs.ts +138 -65
  59. package/src/compiler/dom.ts +517 -442
  60. package/src/compiler/expr-context.ts +167 -57
  61. package/src/compiler/foreign-imports.ts +88 -0
  62. package/src/compiler/mistakes.ts +23 -2
  63. package/src/compiler/props-body.ts +52 -0
  64. package/src/compiler/props.ts +87 -36
  65. package/src/compiler/scope.ts +400 -333
  66. package/src/compiler/server-only.ts +190 -151
  67. package/src/compiler/shared.ts +42 -14
  68. package/src/compiler/signal-reads.ts +6 -2
  69. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  70. package/src/compiler/ssr.ts +220 -89
  71. package/src/context.ts +34 -0
  72. package/src/dev/error-log.ts +177 -0
  73. package/src/dev/host-check.ts +26 -0
  74. package/src/dev/index.ts +91 -34
  75. package/src/dev/open-editor.ts +208 -0
  76. package/src/dev/protocol.ts +3 -0
  77. package/src/dev/reload.ts +5 -3
  78. package/src/dev/supervisor.ts +50 -25
  79. package/src/dev/watchers.ts +74 -13
  80. package/src/dom/action.ts +47 -21
  81. package/src/dom/attrs.ts +15 -3
  82. package/src/dom/extras.ts +29 -14
  83. package/src/dom/index.ts +39 -10
  84. package/src/dom/island.ts +54 -35
  85. package/src/dom/loop.ts +33 -23
  86. package/src/eco/declaration.ts +257 -0
  87. package/src/eco/index.ts +65 -0
  88. package/src/index.ts +2 -2
  89. package/src/jsx-runtime.ts +2 -2
  90. package/src/plugins/config.ts +8 -7
  91. package/src/plugins/context.ts +16 -1
  92. package/src/plugins/index.ts +2 -2
  93. package/src/plugins/load.ts +30 -10
  94. package/src/plugins/order.ts +38 -1
  95. package/src/plugins/public.ts +6 -3
  96. package/src/plugins/services.ts +84 -0
  97. package/src/plugins/types.ts +51 -2
  98. package/src/reactivity/graph.ts +10 -0
  99. package/src/reactivity/index.ts +24 -16
  100. package/src/reactivity/selector.ts +31 -4
  101. package/src/reactivity/store.ts +45 -13
  102. package/src/server/action-flash.ts +158 -0
  103. package/src/server/action-protect.ts +199 -0
  104. package/src/server/action-registry.ts +1 -1
  105. package/src/server/action.ts +56 -117
  106. package/src/server/app-secret.ts +63 -0
  107. package/src/server/assets.ts +34 -2
  108. package/src/server/compress.ts +96 -10
  109. package/src/server/consent.ts +59 -22
  110. package/src/server/cookies.ts +16 -2
  111. package/src/server/document.ts +25 -10
  112. package/src/server/env.ts +14 -0
  113. package/src/server/errors.ts +305 -65
  114. package/src/server/form-schema.ts +343 -0
  115. package/src/server/health.ts +275 -0
  116. package/src/server/http.ts +177 -38
  117. package/src/server/index.ts +264 -272
  118. package/src/server/loader.ts +11 -2
  119. package/src/server/param-matchers.ts +112 -0
  120. package/src/server/plugin-host.ts +125 -88
  121. package/src/server/public.ts +6 -5
  122. package/src/server/rate-limit.ts +102 -36
  123. package/src/server/request-body.ts +1 -1
  124. package/src/server/route-cache.ts +445 -0
  125. package/src/server/route-table.ts +344 -9
  126. package/src/server/router.ts +125 -40
  127. package/src/server/routing.ts +112 -63
  128. package/src/server/sanitize-html.ts +309 -0
  129. package/src/server/security.ts +277 -50
  130. package/src/server/serve-handlers.ts +31 -7
  131. package/src/server/start.ts +60 -16
  132. package/src/server/static-dir.ts +87 -11
  133. package/src/server/stream.ts +68 -27
  134. package/src/ssr/consent-banner.ts +58 -0
  135. package/src/ssr/context.ts +105 -7
  136. package/src/ssr/index.ts +148 -3
  137. package/src/ssr/navigation.ts +2 -2
  138. package/src/ssr/region.ts +31 -19
  139. package/src/style.ts +32 -1
  140. package/src/test/browser.ts +28 -13
  141. package/src/test/index.ts +97 -12
  142. package/src/ts-plugin/diagnostics.ts +505 -0
  143. package/src/ts-plugin/fixes.ts +364 -0
  144. package/src/ts-plugin/index.ts +194 -0
  145. package/templates/_shared/AGENTS.md +2 -2
  146. package/templates/_shared/gitignore +5 -0
  147. package/templates/_shared/mcp.json +11 -0
  148. package/templates/_shared/src/routes/legal.tsx +15 -1
  149. package/templates/_shared/tsconfig.json +5 -0
  150. package/templates/app/.env.example +4 -0
  151. package/templates/app/package.json +2 -1
  152. package/templates/app/prunelle.config.ts +2 -0
  153. package/templates/app/src/auth.ts +4 -6
  154. package/templates/app/src/mail.ts +4 -0
  155. package/templates/app/src/routes/_layout.tsx +9 -1
  156. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  157. package/templates/app/src/routes/login.tsx +49 -30
  158. package/templates/app/src/routes/privacy.tsx +25 -0
  159. package/templates/app/src/styles/app.css +8 -1
  160. package/templates/app/tests/app.test.ts +44 -3
  161. package/templates/blog/package.json +1 -1
  162. package/templates/blog/prunelle.config.ts +1 -1
  163. package/templates/blog/src/routes/_layout.tsx +6 -1
  164. package/templates/blog/src/routes/index.tsx +5 -1
  165. package/templates/blog/src/styles/app.css +6 -1
  166. package/templates/fullstack/package.json +1 -1
  167. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  168. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  169. package/templates/fullstack/src/styles/app.css +11 -1
  170. package/templates/minimal/package.json +1 -1
  171. package/templates/minimal/src/routes/_layout.tsx +4 -0
  172. package/templates/minimal/src/styles/app.css +11 -1
  173. package/ts-plugin.cjs +4277 -0
@@ -1,22 +1,49 @@
1
1
  // French web law compliance checks (RGAA, RGPD, LCEN): static TSX/CSS warnings and route-level checks with explicit silencing.
2
2
 
3
- import type { JSXAttribute, JSXAttributeItem, JSXChild, JSXElement, Node, Program } from 'oxc-parser'
3
+ import type { JSXElement, Node, Program } from 'oxc-parser'
4
4
  import type { ModuleAnalysis } from './analyze'
5
+ import type { EcoJsxRule } from './compliance-eco'
6
+ import type { RgaaJsxRule, RgaaScope } from './compliance-rgaa'
5
7
  import type { CompilerWarning } from './mistakes'
6
8
  import { existsSync, readFileSync } from 'node:fs'
7
- import { basename } from 'node:path'
9
+ import { basename, join } from 'node:path'
8
10
  import { visitorKeys } from 'oxc-parser'
9
11
  import { relPosix, walkFiles } from '../build/files'
10
12
  import { fileToRoutePath } from '../build/routes'
11
- import { cleanJsxText, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, unwrapParens, unwrapTsExpr } from './shared'
13
+ import {
14
+ attrTargetKey,
15
+ checkRgaaComponent,
16
+ checkRgaaElement,
17
+ cloneRgaaScope,
18
+ createRgaaScope,
19
+ findAttr,
20
+ hasNonEmptyAttr,
21
+ INTERACTIVE_ANCESTORS,
22
+ mergeRgaaScope,
23
+ RGAA_JSX_RULES,
24
+ staticStringValueOf,
25
+ } from './compliance-rgaa'
26
+ import { STATEMENT_PLACEHOLDER } from '../a11y/declaration'
27
+ import { checkEcoElement, ECO_JSX_RULES, largePublicFileWarnings } from './compliance-eco'
28
+ import { CSS_IMPORT_RE, CSS_URL_RE, parseOrigin, thirdPartyLoads, thirdPartyOrigin } from './compliance-urls'
29
+ import { formatDiagnostic, formatLoc, getLineStarts, isComponentTag, jsxTagName, lineIndexAtOffset, unwrapTsExpr } from './shared'
12
30
 
13
31
  export type ComplianceRule =
14
- | 'rgaa/img-alt'
15
- | 'rgaa/form-label'
16
- | 'rgaa/accessible-name'
32
+ | RgaaJsxRule
33
+ | EcoJsxRule
34
+ | 'rgesn/large-public-file'
35
+ | 'rgesn/declaration'
36
+ | 'rgesn/island-by-value'
17
37
  | 'rgpd/third-party-url'
38
+ | 'rgpd/consent-retention'
39
+ | 'rgpd/privacy-notice'
18
40
  | 'lcen/legal-notice'
41
+ | 'rgaa/document-lang'
19
42
  | 'rgaa/accessibility-statement'
43
+ | FormWarningRule
44
+
45
+ /** The warnings of the form-vs-action check (`cli/check-forms.ts`), silenced like the compliance rules. */
46
+ export type FormWarningRule = 'action/unguarded-public-form' | 'form/invalid-option' | 'form/schema-unsupported' | 'form/unchecked'
20
47
 
21
48
  export interface ComplianceConfig {
22
49
  /** Compliance rules to silence across the app. */
@@ -25,57 +52,59 @@ export interface ComplianceConfig {
25
52
  publicBody?: boolean | undefined
26
53
  /** Custom route path for the legal notice page, or `false` to silence `lcen/legal-notice`. */
27
54
  legalNotice?: string | false | undefined
55
+ /** Custom route path for the privacy notice page, or `false` to silence `rgpd/privacy-notice`. */
56
+ privacyNotice?: string | false | undefined
28
57
  }
29
58
 
30
59
  const COMPLIANCE_RULES = new Set<ComplianceRule>([
31
- 'rgaa/img-alt',
32
- 'rgaa/form-label',
33
- 'rgaa/accessible-name',
60
+ ...RGAA_JSX_RULES,
61
+ ...ECO_JSX_RULES,
62
+ 'rgesn/large-public-file',
63
+ 'rgesn/declaration',
64
+ 'rgesn/island-by-value',
34
65
  'rgpd/third-party-url',
66
+ 'rgpd/consent-retention',
67
+ 'rgpd/privacy-notice',
35
68
  'lcen/legal-notice',
69
+ 'rgaa/document-lang',
36
70
  'rgaa/accessibility-statement',
71
+ 'action/unguarded-public-form',
72
+ 'form/invalid-option',
73
+ 'form/schema-unsupported',
74
+ 'form/unchecked',
37
75
  ])
38
76
 
39
- const NON_LABELLED_INPUT_TYPES = new Set(['hidden', 'submit', 'reset', 'button', 'image'])
40
- const THIRD_PARTY_LINK_RELS = new Set(['stylesheet', 'preload', 'preconnect', 'dns-prefetch'])
41
- const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'])
42
- const DEFAULT_LEGAL_PATHS = new Set(['/mentions-legales', '/legal', '/legal-notice', '/imprint', '/impressum', '/cgu', '/cgv'])
77
+ // The CNIL recommends keeping a cookie choice, consent or refusal, 6 months before asking again.
78
+ const CNIL_CHOICE_MAX_AGE = 15_552_000
79
+ const INLINE_MAP_METHODS = new Set(['map', 'flatMap'])
80
+ const DEFAULT_LEGAL_PATHS = new Set(['/mentions-legales', '/legal', '/legal-notice', '/imprint', '/impressum'])
81
+ const DEFAULT_PRIVACY_PATHS = new Set(['/privacy', '/privacy-policy', '/confidentialite', '/politique-de-confidentialite', '/donnees-personnelles', '/datenschutz'])
82
+ // A component named Label (or ui.Label) wraps its control like <label>.
83
+ const LABEL_COMPONENT_RE = /(?:^|\.)Label$/
84
+ // An <input> collecting an email or a phone number, by its type or its name.
85
+ const PERSONAL_DATA_INPUT_RE = /<input\b[^>]*?\b(?:type=["'](?:email|tel)["']|name=["'](?:email|phone|tel)["'])/
43
86
  const ACCESSIBILITY_PATHS = new Set(['/accessibilite', '/accessibility', '/declaration-accessibilite', '/accessibility-statement'])
87
+ const ECO_DECLARATION_PATHS = new Set(['/ecoconception', '/declaration-ecoconception', '/eco-design'])
88
+ // The marker the `prunelle new` legal and privacy notices put in front of every detail the publisher must supply.
89
+ const TEMPLATE_PLACEHOLDER = '[to fill in'
90
+
91
+ interface NoticeDetails { rule: ComplianceRule, page: string, law: string, marker: string }
92
+ const LEGAL_NOTICE_DETAILS: NoticeDetails = { rule: 'lcen/legal-notice', page: 'legal notice', law: 'French law (LCEN art. 1-1) requires the publisher\'s identity, address and phone, the publication director and the host\'s name, address and phone', marker: TEMPLATE_PLACEHOLDER }
93
+ const PRIVACY_NOTICE_DETAILS: NoticeDetails = { rule: 'rgpd/privacy-notice', page: 'privacy notice', law: 'the RGPD (art. 13) requires the controller\'s identity and contact, the purposes and legal basis, the retention periods, the recipients and the rights of the people concerned', marker: TEMPLATE_PLACEHOLDER }
94
+ const ECO_DECLARATION_DETAILS: NoticeDetails = { rule: 'rgesn/declaration', page: 'eco-design declaration', law: 'the RGESN 2024 asks it to name the service, the evaluating entity and a contact, the minimum hardware profile and the planned actions, and to justify each criterion', marker: STATEMENT_PLACEHOLDER }
95
+ const STATEMENT_DETAILS: NoticeDetails = { rule: 'rgaa/accessibility-statement', page: 'accessibility statement', law: 'the RGAA requires it to name the publisher, the site it covers and the pages audited, and to give a contact for accessibility feedback', marker: STATEMENT_PLACEHOLDER }
96
+ const LOCALE_PREFIX_RE = /^\/(?:[a-z]{2}(?:-[a-z]{2})?|:[a-z_]\w*(?:=[^/]+)?\??|\[\[?[^\]]+\]\]?)(\/.+)$/i
44
97
 
45
98
  const LINE_IGNORE_RE = /(?:^|[\s{;(,])\/\/\s*prunelle-ignore(-file)?[ \t]+([^\r\n]+)/g
46
99
  const BLOCK_IGNORE_RE = /\/\*\s*prunelle-ignore(-file)?\s+([\s\S]*?)\*\//g
47
100
  const CSS_COMMENT_RE = /\/\*[\s\S]*?\*\//g
48
- const CSS_IMPORT_RE = /@import\s+(?:url\(\s*)?(?:'([^']+)'|"([^"]+)"|([^'"\s);]+))/gi
49
- const CSS_URL_RE = /url\(\s*(?:'([^']+)'|"([^"]+)"|([^'"\s)]+))\s*\)/gi
50
101
 
51
102
  interface IgnoreMap {
52
- lineStarts: number[]
103
+ lineStarts: readonly number[]
53
104
  fileRules: Set<ComplianceRule>
54
105
  lineRules: Map<number, Set<ComplianceRule>>
55
106
  }
56
107
 
57
- function buildLineStarts(code: string): number[] {
58
- const starts = [0]
59
- for (let i = 0; i < code.length; i++) {
60
- if (code.charCodeAt(i) === 10)
61
- starts.push(i + 1)
62
- }
63
- return starts
64
- }
65
-
66
- function offsetToLine(lineStarts: readonly number[], offset: number): number {
67
- let lo = 0
68
- let hi = lineStarts.length - 1
69
- while (lo < hi) {
70
- const mid = (lo + hi + 1) >> 1
71
- if (lineStarts[mid]! <= offset)
72
- lo = mid
73
- else
74
- hi = mid - 1
75
- }
76
- return lo + 1
77
- }
78
-
79
108
  function extractRules(text: string): ComplianceRule[] {
80
109
  const out: ComplianceRule[] = []
81
110
  for (const token of text.trim().split(/[\s,]+/)) {
@@ -86,7 +115,7 @@ function extractRules(text: string): ComplianceRule[] {
86
115
  }
87
116
 
88
117
  export function parsePrunelleIgnores(code: string): IgnoreMap {
89
- const lineStarts = buildLineStarts(code)
118
+ const lineStarts = getLineStarts(code)
90
119
  const fileRules = new Set<ComplianceRule>()
91
120
  const lineRules = new Map<number, Set<ComplianceRule>>()
92
121
 
@@ -99,8 +128,8 @@ export function parsePrunelleIgnores(code: string): IgnoreMap {
99
128
  fileRules.add(r)
100
129
  return
101
130
  }
102
- const startLine = offsetToLine(lineStarts, start)
103
- const endLine = offsetToLine(lineStarts, end)
131
+ const startLine = lineIndexAtOffset(lineStarts, start) + 1
132
+ const endLine = lineIndexAtOffset(lineStarts, end) + 1
104
133
  for (const line of [startLine, endLine, endLine + 1]) {
105
134
  let set = lineRules.get(line)
106
135
  if (set === undefined) {
@@ -120,49 +149,21 @@ export function parsePrunelleIgnores(code: string): IgnoreMap {
120
149
  return { lineStarts, fileRules, lineRules }
121
150
  }
122
151
 
123
- function isIgnoredAt(ignores: IgnoreMap, rule: ComplianceRule, offset: number): boolean {
152
+ export function isIgnoredAt(ignores: IgnoreMap, rule: ComplianceRule, offset: number): boolean {
124
153
  if (ignores.fileRules.has(rule))
125
154
  return true
126
- const line = offsetToLine(ignores.lineStarts, offset)
155
+ const line = lineIndexAtOffset(ignores.lineStarts, offset) + 1
127
156
  return ignores.lineRules.get(line)?.has(rule) === true
128
157
  }
129
158
 
130
159
  export function isRuleIgnored(rule: ComplianceRule, compliance?: ComplianceConfig | undefined): boolean {
131
160
  if (rule === 'lcen/legal-notice' && compliance?.legalNotice === false)
132
161
  return true
162
+ if (rule === 'rgpd/privacy-notice' && compliance?.privacyNotice === false)
163
+ return true
133
164
  return compliance?.ignore?.includes(rule) === true
134
165
  }
135
166
 
136
- export function parseOrigin(url: string | undefined): string | undefined {
137
- if (url === undefined || url.trim() === '')
138
- return undefined
139
- try {
140
- return new URL(url.trim()).origin
141
- }
142
- catch {
143
- return undefined
144
- }
145
- }
146
-
147
- /** Returns the external origin when `rawUrl` points to a non-localhost third-party URL, or `undefined` otherwise. */
148
- export function thirdPartyOrigin(rawUrl: string): string | undefined {
149
- const trimmed = rawUrl.trim()
150
- if (!/^(?:https?:)?\/\//i.test(trimmed))
151
- return undefined
152
- try {
153
- const parsed = new URL(trimmed.startsWith('//') ? `https:${trimmed}` : trimmed)
154
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
155
- return undefined
156
- const host = parsed.hostname.toLowerCase()
157
- if (LOCAL_HOSTS.has(host) || host.endsWith('.localhost'))
158
- return undefined
159
- return parsed.origin
160
- }
161
- catch {
162
- return undefined
163
- }
164
- }
165
-
166
167
  /** Whether a compiler warning should be surfaced given `compliance` and `site` config. */
167
168
  export function shouldEmitWarning(warning: CompilerWarning, compliance?: ComplianceConfig | undefined, site?: string | undefined): boolean {
168
169
  if (warning.rule !== undefined && isRuleIgnored(warning.rule, compliance))
@@ -175,174 +176,69 @@ export function shouldEmitWarning(warning: CompilerWarning, compliance?: Complia
175
176
  return true
176
177
  }
177
178
 
178
- function findAttr(attributes: readonly JSXAttributeItem[], name: string): JSXAttribute | undefined {
179
- for (const attr of attributes) {
180
- if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier' && attr.name.name === name)
181
- return attr
182
- }
183
- return undefined
184
- }
185
-
186
- function hasSpread(attributes: readonly JSXAttributeItem[]): boolean {
187
- return attributes.some(a => a.type === 'JSXSpreadAttribute')
188
- }
189
-
190
- function staticStringValueOf(value: JSXAttribute['value']): string | undefined {
191
- if (value === null)
192
- return undefined
193
- if (value.type === 'Literal' && typeof value.value === 'string')
194
- return value.value
195
- if (value.type === 'JSXExpressionContainer' && value.expression.type !== 'JSXEmptyExpression') {
196
- const expr = unwrapTsExpr(value.expression)
197
- if (expr.type === 'Literal' && typeof expr.value === 'string')
198
- return expr.value
199
- if (expr.type === 'TemplateLiteral' && expr.expressions.length === 0)
200
- return expr.quasis[0]?.value.cooked ?? undefined
201
- }
202
- return undefined
203
- }
204
-
205
- function attrTargetKey(attr: JSXAttribute | undefined): string | undefined {
206
- if (attr === undefined || attr.value === null)
207
- return undefined
208
- const str = staticStringValueOf(attr.value)
209
- if (str !== undefined && str.trim() !== '')
210
- return `s:${str}`
211
- if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
212
- const expr = unwrapTsExpr(attr.value.expression)
213
- if (expr.type === 'Identifier')
214
- return `i:${expr.name}`
215
- }
216
- return undefined
179
+ interface AncestorState {
180
+ labelDepth: number
181
+ consentGateDepth: number
182
+ interactiveAncestor: string | undefined
183
+ inLoop: boolean
217
184
  }
218
185
 
219
- function hasNonEmptyAttr(attributes: readonly JSXAttributeItem[], name: string): boolean {
220
- const attr = findAttr(attributes, name)
221
- if (attr === undefined || attr.value === null)
186
+ function isInlineMapCall(node: Node): node is Extract<Node, { type: 'CallExpression' }> {
187
+ if (node.type !== 'CallExpression' || node.arguments.length === 0)
222
188
  return false
223
- const str = staticStringValueOf(attr.value)
224
- if (str !== undefined)
225
- return str.trim() !== ''
226
- if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
227
- const expr = unwrapParens(attr.value.expression)
228
- if (expr.type === 'Literal' && (expr.value === null || expr.value === false || expr.value === ''))
229
- return false
230
- if (expr.type === 'Identifier' && expr.name === 'undefined')
231
- return false
232
- return true
233
- }
234
- return false
235
- }
236
-
237
- function hasLabelAttr(attributes: readonly JSXAttributeItem[]): boolean {
238
- return hasNonEmptyAttr(attributes, 'aria-label')
239
- || hasNonEmptyAttr(attributes, 'aria-labelledby')
240
- || hasNonEmptyAttr(attributes, 'title')
241
- }
242
-
243
- function isAriaHidden(attributes: readonly JSXAttributeItem[]): boolean {
244
- const attr = findAttr(attributes, 'aria-hidden')
245
- if (attr === undefined)
189
+ const callee = unwrapTsExpr(node.callee)
190
+ if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier' || !INLINE_MAP_METHODS.has(callee.property.name))
246
191
  return false
247
- if (attr.value === null)
248
- return true
249
- if (attr.value.type === 'Literal')
250
- return attr.value.value === 'true'
251
- if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
252
- const expr = unwrapParens(attr.value.expression)
253
- return expr.type === 'Literal' && (expr.value === true || expr.value === 'true')
254
- }
255
- return false
192
+ const first = node.arguments[0]!
193
+ if (first.type === 'SpreadElement')
194
+ return false
195
+ const cb = unwrapTsExpr(first)
196
+ return cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression'
256
197
  }
257
198
 
258
- function hasMeaningfulExpression(expr: Node): boolean {
259
- const inner = unwrapParens(expr)
260
- if (inner.type === 'Literal')
261
- return typeof inner.value === 'string' ? inner.value.trim() !== '' : typeof inner.value === 'number'
262
- if (inner.type === 'Identifier' && inner.name === 'undefined')
263
- return false
264
- return true
199
+ function isFunctionNode(node: Node): boolean {
200
+ return node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression'
265
201
  }
266
202
 
267
- function hasAccessibleName(children: readonly JSXChild[]): boolean {
268
- for (const child of children) {
269
- if (child.type === 'JSXText') {
270
- if (cleanJsxText(child.value).trim() !== '')
271
- return true
203
+ // Collects `<label for / htmlFor>` targets owned by the current component/function (including inline `.map()` callbacks, excluding nested functions).
204
+ function collectDirectLabelTargets(root: Node | null | undefined): Set<string> {
205
+ const targets = new Set<string>()
206
+ const walkScope = (value: unknown, isRoot: boolean): void => {
207
+ if (value === null || typeof value !== 'object')
208
+ return
209
+ if (Array.isArray(value)) {
210
+ for (let i = 0; i < value.length; i++)
211
+ walkScope(value[i], false)
212
+ return
272
213
  }
273
- else if (child.type === 'JSXExpressionContainer') {
274
- if (child.expression.type !== 'JSXEmptyExpression' && hasMeaningfulExpression(child.expression))
275
- return true
214
+ const node = value as Node
215
+ if (typeof node.type !== 'string')
216
+ return
217
+ if (!isRoot && isFunctionNode(node))
218
+ return
219
+ if (isInlineMapCall(node)) {
220
+ walkScope(node.callee, false)
221
+ const cb = unwrapTsExpr(node.arguments[0]!)
222
+ if (cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
223
+ walkScope(cb.body, false)
224
+ for (let i = 1; i < node.arguments.length; i++)
225
+ walkScope(node.arguments[i], false)
226
+ return
276
227
  }
277
- else if (child.type === 'JSXFragment') {
278
- if (hasAccessibleName(child.children))
279
- return true
228
+ if (node.type === 'JSXElement' && jsxTagName(node.openingElement.name) === 'label') {
229
+ const attrs = node.openingElement.attributes
230
+ const key = attrTargetKey(findAttr(attrs, 'for') ?? findAttr(attrs, 'htmlFor'))
231
+ if (key !== undefined)
232
+ targets.add(key)
280
233
  }
281
- else if (child.type === 'JSXElement') {
282
- const attrs = child.openingElement.attributes
283
- if (isAriaHidden(attrs))
284
- continue
285
- const tag = jsxTagName(child.openingElement.name)
286
- if (hasSpread(attrs) || hasLabelAttr(attrs))
287
- return true
288
- if (tag === 'img') {
289
- if (hasNonEmptyAttr(attrs, 'alt'))
290
- return true
291
- continue
292
- }
293
- if (tag === 'svg') {
294
- const hasTitle = child.children.some(c =>
295
- c.type === 'JSXElement' && jsxTagName(c.openingElement.name) === 'title' && hasAccessibleName(c.children),
296
- )
297
- if (hasTitle)
298
- return true
299
- continue
300
- }
301
- if (isComponentTag(tag)) {
302
- if (hasNonEmptyAttr(attrs, 'label') || hasAccessibleName(child.children))
303
- return true
304
- continue
305
- }
306
- if (hasAccessibleName(child.children))
307
- return true
234
+ const keys = visitorKeys[node.type]
235
+ if (keys !== undefined) {
236
+ const rec = node as unknown as Record<string, unknown>
237
+ for (let i = 0; i < keys.length; i++)
238
+ walkScope(rec[keys[i]!], false)
308
239
  }
309
240
  }
310
- return false
311
- }
312
-
313
- function walkAst(value: unknown, enter: (node: Node) => void, exit?: (node: Node) => void): void {
314
- if (value === null || typeof value !== 'object')
315
- return
316
- if (Array.isArray(value)) {
317
- for (let i = 0; i < value.length; i++)
318
- walkAst(value[i], enter, exit)
319
- return
320
- }
321
- const node = value as Node
322
- if (typeof node.type !== 'string')
323
- return
324
- enter(node)
325
- const keys = visitorKeys[node.type]
326
- if (keys !== undefined) {
327
- for (let i = 0; i < keys.length; i++)
328
- walkAst((node as unknown as Record<string, unknown>)[keys[i]!], enter, exit)
329
- }
330
- exit?.(node)
331
- }
332
-
333
- function collectLabelTargets(program: Program): Set<string> {
334
- const targets = new Set<string>()
335
- walkAst(program, (node) => {
336
- if (node.type !== 'JSXElement')
337
- return
338
- const tag = jsxTagName(node.openingElement.name)
339
- if (tag !== 'label')
340
- return
341
- const attrs = node.openingElement.attributes
342
- const key = attrTargetKey(findAttr(attrs, 'for') ?? findAttr(attrs, 'htmlFor'))
343
- if (key !== undefined)
344
- targets.add(key)
345
- })
241
+ walkScope(root, true)
346
242
  return targets
347
243
  }
348
244
 
@@ -353,85 +249,31 @@ function checkThirdPartyElement(
353
249
  ignores: IgnoreMap,
354
250
  warnings: CompilerWarning[],
355
251
  ): void {
356
- const attrs = element.openingElement.attributes
357
- let attr: JSXAttribute | undefined
358
- let attrName = ''
359
- if (tag === 'script' || tag === 'iframe') {
360
- attr = findAttr(attrs, 'src')
361
- attrName = 'src'
362
- }
363
- else if (tag === 'link') {
364
- const relVal = staticStringValueOf(findAttr(attrs, 'rel')?.value ?? null)
365
- if (relVal === undefined)
366
- return
367
- const rels = relVal.toLowerCase().split(/\s+/)
368
- if (!rels.some(r => THIRD_PARTY_LINK_RELS.has(r)))
369
- return
370
- attr = findAttr(attrs, 'href')
371
- attrName = 'href'
372
- }
373
- if (attr === undefined)
374
- return
375
- const url = staticStringValueOf(attr.value)
376
- if (url === undefined)
377
- return
378
- const origin = thirdPartyOrigin(url)
379
- if (origin === undefined || isIgnoredAt(ignores, 'rgpd/third-party-url', attr.start))
380
- return
381
- warnings.push({
382
- rule: 'rgpd/third-party-url',
383
- urlOrigin: origin,
384
- start: attr.start,
385
- message: `[rgpd/third-party-url] <${tag} ${attrName}="${url}"> in ${filename} loads a third-party resource without consent: self-host it (e.g. @prunellejs/seo fonts or public/) or wrap it in <ConsentGate category="...">.`,
386
- })
387
- }
388
-
389
- function checkJsxElementCompliance(
390
- element: JSXElement,
391
- filename: string,
392
- inLabel: boolean,
393
- inConsentGate: boolean,
394
- labelTargets: ReadonlySet<string>,
395
- ignores: IgnoreMap,
396
- warnings: CompilerWarning[],
397
- ): void {
398
- const tag = jsxTagName(element.openingElement.name)
399
- if (tag === '' || isComponentTag(tag))
400
- return
401
- const attrs = element.openingElement.attributes
402
- const spread = hasSpread(attrs)
403
-
404
- if (tag === 'img' && !spread && findAttr(attrs, 'alt') === undefined && !isIgnoredAt(ignores, 'rgaa/img-alt', element.start)) {
252
+ for (const load of thirdPartyLoads(element, tag)) {
253
+ if (isIgnoredAt(ignores, 'rgpd/third-party-url', load.start))
254
+ continue
405
255
  warnings.push({
406
- rule: 'rgaa/img-alt',
407
- start: element.start,
408
- message: `[rgaa/img-alt] <img> in ${filename} is missing an alt attribute: add alt="description" or alt="" for decorative images.`,
256
+ rule: 'rgpd/third-party-url',
257
+ urlOrigin: load.origin,
258
+ start: load.start,
259
+ message: `[rgpd/third-party-url] <${tag} ${load.attr}="${load.url}"> in ${filename} loads a third-party resource without consent: self-host it (e.g. @prunellejs/seo fonts or public/) or wrap it in <ConsentGate category="...">.`,
409
260
  })
410
261
  }
262
+ }
411
263
 
412
- if ((tag === 'input' || tag === 'select' || tag === 'textarea') && !spread && !inLabel && !hasLabelAttr(attrs)) {
413
- const inputType = tag === 'input' ? staticStringValueOf(findAttr(attrs, 'type')?.value ?? null)?.toLowerCase() : undefined
414
- const idKey = attrTargetKey(findAttr(attrs, 'id'))
415
- const linked = idKey !== undefined && labelTargets.has(idKey)
416
- if ((inputType === undefined || !NON_LABELLED_INPUT_TYPES.has(inputType)) && !linked && !isIgnoredAt(ignores, 'rgaa/form-label', element.start)) {
417
- warnings.push({
418
- rule: 'rgaa/form-label',
419
- start: element.start,
420
- message: `[rgaa/form-label] <${tag}> in ${filename} has no associated label: wrap it in <label>, link <label for="id">, or add aria-label="..." / aria-labelledby="...".`,
421
- })
422
- }
423
- }
424
-
425
- if ((tag === 'button' || tag === 'a') && !spread && !hasLabelAttr(attrs) && !hasAccessibleName(element.children) && !isIgnoredAt(ignores, 'rgaa/accessible-name', element.start)) {
426
- warnings.push({
427
- rule: 'rgaa/accessible-name',
428
- start: element.start,
429
- message: `[rgaa/accessible-name] <${tag}> in ${filename} has no accessible name: add visible text or aria-label="...".`,
430
- })
431
- }
264
+ // A gate on the essential category always renders its children, so it holds nothing back until consent.
265
+ function opensConsentGate(element: JSXElement, resolvedTag: string | undefined): boolean {
266
+ return resolvedTag === 'ConsentGate' && staticStringValueOf(findAttr(element.openingElement.attributes, 'category')?.value ?? null) !== 'essential'
267
+ }
432
268
 
433
- if (!inConsentGate)
434
- checkThirdPartyElement(element, tag, filename, ignores, warnings)
269
+ function definitelyExits(stmt: Node): boolean {
270
+ if (stmt.type === 'ReturnStatement' || stmt.type === 'ThrowStatement')
271
+ return true
272
+ if (stmt.type === 'BlockStatement')
273
+ return stmt.body.length > 0 && definitelyExits(stmt.body[stmt.body.length - 1]!)
274
+ if (stmt.type === 'IfStatement')
275
+ return stmt.alternate !== null && definitelyExits(stmt.consequent) && definitelyExits(stmt.alternate)
276
+ return false
435
277
  }
436
278
 
437
279
  /** Runs RGAA & RGPD static JSX compliance checks on `program`, appending warnings (never throwing). */
@@ -443,36 +285,126 @@ export function checkCompliance(
443
285
  resolveTag: (tag: string) => string | undefined,
444
286
  ): void {
445
287
  const ignores = parsePrunelleIgnores(code)
446
- const labelTargets = collectLabelTargets(program)
447
- let labelDepth = 0
448
- let consentGateDepth = 0
449
- const labelFlags: boolean[] = []
450
- const consentFlags: boolean[] = []
288
+ const isIgnored = (rule: RgaaJsxRule | EcoJsxRule, elementStart: number, attrStart?: number): boolean =>
289
+ isIgnoredAt(ignores, rule, elementStart) || (attrStart !== undefined && isIgnoredAt(ignores, rule, attrStart))
451
290
 
452
- walkAst(
453
- program,
454
- (node) => {
455
- if (node.type !== 'JSXElement')
456
- return
291
+ const visitChildren = (node: Node, ancestors: AncestorState, scope: RgaaScope, labelTargets: ReadonlySet<string>): void => {
292
+ const keys = visitorKeys[node.type]
293
+ if (keys === undefined)
294
+ return
295
+ const rec = node as unknown as Record<string, unknown>
296
+ for (let i = 0; i < keys.length; i++)
297
+ visit(rec[keys[i]!], ancestors, scope, labelTargets)
298
+ }
299
+
300
+ const visit = (value: unknown, ancestors: AncestorState, scope: RgaaScope, labelTargets: ReadonlySet<string>): void => {
301
+ if (value === null || typeof value !== 'object')
302
+ return
303
+ if (Array.isArray(value)) {
304
+ for (let i = 0; i < value.length; i++)
305
+ visit(value[i], ancestors, scope, labelTargets)
306
+ return
307
+ }
308
+ const node = value as Node
309
+ if (typeof node.type !== 'string')
310
+ return
311
+
312
+ if (isInlineMapCall(node)) {
313
+ visit(node.callee, ancestors, scope, labelTargets)
314
+ const cb = unwrapTsExpr(node.arguments[0]!)
315
+ if (cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression') {
316
+ const loopAncestors: AncestorState = ancestors.inLoop ? ancestors : { ...ancestors, inLoop: true }
317
+ visitChildren(cb, loopAncestors, createRgaaScope(), labelTargets)
318
+ }
319
+ for (let i = 1; i < node.arguments.length; i++)
320
+ visit(node.arguments[i], ancestors, scope, labelTargets)
321
+ return
322
+ }
323
+
324
+ if (isFunctionNode(node)) {
325
+ const resetAncestors: AncestorState = {
326
+ labelDepth: 0,
327
+ consentGateDepth: ancestors.consentGateDepth,
328
+ interactiveAncestor: undefined,
329
+ inLoop: false,
330
+ }
331
+ visitChildren(node, resetAncestors, createRgaaScope(), collectDirectLabelTargets(node))
332
+ return
333
+ }
334
+
335
+ if (node.type === 'ConditionalExpression') {
336
+ visit(node.test, ancestors, scope, labelTargets)
337
+ const branchA = cloneRgaaScope(scope)
338
+ const branchB = cloneRgaaScope(scope)
339
+ visit(node.consequent, ancestors, branchA, labelTargets)
340
+ visit(node.alternate, ancestors, branchB, labelTargets)
341
+ mergeRgaaScope(scope, branchA)
342
+ mergeRgaaScope(scope, branchB)
343
+ return
344
+ }
345
+
346
+ if (node.type === 'IfStatement') {
347
+ visit(node.test, ancestors, scope, labelTargets)
348
+ const branchA = cloneRgaaScope(scope)
349
+ visit(node.consequent, ancestors, branchA, labelTargets)
350
+ const branchB = cloneRgaaScope(scope)
351
+ if (node.alternate !== null)
352
+ visit(node.alternate, ancestors, branchB, labelTargets)
353
+ if (!definitelyExits(node.consequent))
354
+ mergeRgaaScope(scope, branchA)
355
+ if (node.alternate !== null && !definitelyExits(node.alternate))
356
+ mergeRgaaScope(scope, branchB)
357
+ return
358
+ }
359
+
360
+ if (node.type === 'JSXElement') {
457
361
  const tag = jsxTagName(node.openingElement.name)
458
- checkJsxElementCompliance(node, filename, labelDepth > 0, consentGateDepth > 0, labelTargets, ignores, warnings)
459
- const opensLabel = tag === 'label' || (isComponentTag(tag) && hasNonEmptyAttr(node.openingElement.attributes, 'label'))
460
- const opensConsentGate = resolveTag(tag) === 'ConsentGate'
461
- labelFlags.push(opensLabel)
462
- consentFlags.push(opensConsentGate)
463
- if (opensLabel)
464
- labelDepth++
465
- if (opensConsentGate)
466
- consentGateDepth++
467
- },
468
- (node) => {
469
- if (node.type !== 'JSXElement')
470
- return
471
- if (labelFlags.pop() === true)
472
- labelDepth--
473
- if (consentFlags.pop() === true)
474
- consentGateDepth--
475
- },
362
+ const attrs = node.openingElement.attributes
363
+ if (tag !== '') {
364
+ const ctx = {
365
+ filename,
366
+ inLabel: ancestors.labelDepth > 0,
367
+ inLoop: ancestors.inLoop,
368
+ interactiveAncestor: ancestors.interactiveAncestor,
369
+ labelTargets,
370
+ scope,
371
+ isIgnored,
372
+ warnings,
373
+ }
374
+ if (isComponentTag(tag)) {
375
+ checkRgaaComponent(node, tag, ctx)
376
+ }
377
+ else {
378
+ checkRgaaElement(node, tag, ctx)
379
+ checkEcoElement(node, tag, ctx)
380
+ if (ancestors.consentGateDepth === 0)
381
+ checkThirdPartyElement(node, tag, filename, ignores, warnings)
382
+ }
383
+ }
384
+ visit(attrs, ancestors, scope, labelTargets)
385
+ const opensLabel = tag === 'label' || (isComponentTag(tag) && (LABEL_COMPONENT_RE.test(tag) || hasNonEmptyAttr(attrs, 'label')))
386
+ const opensGate = opensConsentGate(node, resolveTag(tag))
387
+ const nextInteractive = INTERACTIVE_ANCESTORS.has(tag) ? tag : ancestors.interactiveAncestor
388
+ const childAncestors = opensLabel || opensGate || nextInteractive !== ancestors.interactiveAncestor
389
+ ? {
390
+ labelDepth: ancestors.labelDepth + (opensLabel ? 1 : 0),
391
+ consentGateDepth: ancestors.consentGateDepth + (opensGate ? 1 : 0),
392
+ interactiveAncestor: nextInteractive,
393
+ inLoop: ancestors.inLoop,
394
+ }
395
+ : ancestors
396
+ visit(node.children, childAncestors, scope, labelTargets)
397
+ return
398
+ }
399
+
400
+ visitChildren(node, ancestors, scope, labelTargets)
401
+ }
402
+
403
+ visit(
404
+ program,
405
+ { labelDepth: 0, consentGateDepth: 0, interactiveAncestor: undefined, inLoop: false },
406
+ createRgaaScope(),
407
+ collectDirectLabelTargets(program),
476
408
  )
477
409
  }
478
410
 
@@ -531,18 +463,38 @@ function normalizePath(path: string): string {
531
463
  return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1).toLowerCase() : withSlash.toLowerCase()
532
464
  }
533
465
 
466
+ function stripLocalePrefix(normalizedPath: string): string {
467
+ const m = LOCALE_PREFIX_RE.exec(normalizedPath)
468
+ return m !== null ? m[1]! : normalizedPath
469
+ }
470
+
471
+ function matchesNoticePath(routePath: string, custom: string | false | undefined, defaults: ReadonlySet<string>): boolean {
472
+ const path = normalizePath(routePath)
473
+ const bare = stripLocalePrefix(path)
474
+ if (typeof custom === 'string') {
475
+ const wanted = normalizePath(custom)
476
+ return path === wanted || bare === wanted
477
+ }
478
+ return defaults.has(path) || defaults.has(bare)
479
+ }
480
+
481
+ function isLegalNoticePath(routePath: string, compliance: ComplianceConfig | undefined): boolean {
482
+ return matchesNoticePath(routePath, compliance?.legalNotice, DEFAULT_LEGAL_PATHS)
483
+ }
484
+
485
+ function isStatementPath(routePath: string): boolean {
486
+ return matchesNoticePath(routePath, undefined, ACCESSIBILITY_PATHS)
487
+ }
488
+
534
489
  /** Checks project-level LCEN legal notice and RGAA accessibility statement routes. */
535
490
  export function checkRouteCompliance(pageRoutePaths: readonly string[], compliance?: ComplianceConfig | undefined): string[] {
536
491
  if (pageRoutePaths.length === 0)
537
492
  return []
538
- const normalized = new Set(pageRoutePaths.map(normalizePath))
539
493
  const out: string[] = []
540
494
 
541
495
  if (!isRuleIgnored('lcen/legal-notice', compliance)) {
542
496
  const custom = typeof compliance?.legalNotice === 'string' ? normalizePath(compliance.legalNotice) : undefined
543
- const hasLegal = custom !== undefined
544
- ? normalized.has(custom)
545
- : [...normalized].some(p => DEFAULT_LEGAL_PATHS.has(p))
497
+ const hasLegal = pageRoutePaths.some(p => isLegalNoticePath(p, compliance))
546
498
  if (!hasLegal) {
547
499
  const expected = custom ?? '/mentions-legales (or /legal)'
548
500
  out.push(formatDiagnostic('prunelle.config.ts:1:1', `[lcen/legal-notice] App has no legal notice route: add ${expected}, set compliance.legalNotice, or silence with compliance: { legalNotice: false }.`, 'warning'))
@@ -550,9 +502,8 @@ export function checkRouteCompliance(pageRoutePaths: readonly string[], complian
550
502
  }
551
503
 
552
504
  if (compliance?.publicBody === true && !isRuleIgnored('rgaa/accessibility-statement', compliance)) {
553
- const hasA11y = [...normalized].some(p => ACCESSIBILITY_PATHS.has(p))
554
- if (!hasA11y) {
555
- out.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/accessibility-statement] Public-body site (compliance.publicBody: true) has no accessibility statement route: add /accessibilite (or /accessibility).', 'warning'))
505
+ if (!pageRoutePaths.some(isStatementPath)) {
506
+ out.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/accessibility-statement] Public-body site (compliance.publicBody: true) has no accessibility statement route: add /accessibilite (or /accessibility), or draft one with `prunelle a11y --draft`.', 'warning'))
556
507
  }
557
508
  }
558
509
 
@@ -566,23 +517,38 @@ export interface ProjectComplianceInput {
566
517
  routeFiles: readonly string[]
567
518
  analyses: ReadonlyMap<string, ModuleAnalysis>
568
519
  compliance?: ComplianceConfig | undefined
520
+ /** `consent.maxAge` from the config, in seconds. */
521
+ consentMaxAge?: number | undefined
569
522
  site?: string | undefined
523
+ /** `lang` from the config. */
524
+ lang?: string | undefined
525
+ /** A plugin sets `<html lang>` per request, so a missing `lang` is not a mistake. */
526
+ langFromPlugin?: boolean | undefined
570
527
  }
571
528
 
572
- /** Collects project-level CSS third-party URL warnings and LCEN/RGAA route warnings for `prunelle check` and production `prunelle build`. */
529
+ /** True when a plugin sets `<html lang>` from the request's locale (`@prunellejs/i18n`). */
530
+ export function pluginSetsLang(plugins: readonly { name: string }[]): boolean {
531
+ return plugins.some(p => p.name === '@prunellejs/i18n')
532
+ }
533
+
534
+ /** Collects project-level CSS third-party URL warnings and the LCEN, RGPD and RGAA notice warnings for `prunelle check` and production `prunelle build`. */
573
535
  export function collectProjectComplianceWarnings(input: ProjectComplianceInput): string[] {
574
- const { root, srcDir, routesDir, routeFiles, analyses, compliance, site } = input
536
+ const { root, srcDir, routesDir, routeFiles, analyses, compliance, consentMaxAge, site, lang, langFromPlugin } = input
575
537
  const warnings: string[] = []
576
-
577
- if (existsSync(srcDir)) {
578
- const cssFiles = walkFiles(srcDir, {
579
- skipDir: name => name === 'node_modules' || name === 'dist' || name.startsWith('.'),
580
- keep: entry => entry.name.endsWith('.css'),
581
- }).sort()
582
- for (const cssFile of cssFiles) {
583
- const code = readFileSync(cssFile, 'utf8')
584
- warnings.push(...checkCssCompliance(relPosix(root, cssFile), code, compliance, site))
585
- }
538
+ if (consentMaxAge !== undefined && consentMaxAge > CNIL_CHOICE_MAX_AGE && !isRuleIgnored('rgpd/consent-retention', compliance))
539
+ warnings.push(formatDiagnostic('prunelle.config.ts:1:1', `[rgpd/consent-retention] consent.maxAge keeps the visitor's choice ${Math.round(consentMaxAge / 86_400)} days, past the 6 months the CNIL recommends before asking again: lower it to 15552000 (180 days) or remove it.`, 'warning'))
540
+
541
+ const srcFiles = existsSync(srcDir)
542
+ ? walkFiles(srcDir, {
543
+ skipDir: name => name === 'node_modules' || name === 'dist' || name.startsWith('.'),
544
+ keep: entry => entry.name.endsWith('.css') || entry.name.endsWith('.tsx'),
545
+ }).sort()
546
+ : []
547
+ // public/ is served as is, so its stylesheets load whatever they point at too.
548
+ const publicCss = walkFiles(join(root, 'public'), { keep: entry => entry.name.endsWith('.css') }).sort()
549
+ for (const cssFile of [...srcFiles.filter(file => file.endsWith('.css')), ...publicCss]) {
550
+ const code = readFileSync(cssFile, 'utf8')
551
+ warnings.push(...checkCssCompliance(relPosix(root, cssFile), code, compliance, site))
586
552
  }
587
553
 
588
554
  const pagePaths: string[] = []
@@ -590,9 +556,47 @@ export function collectProjectComplianceWarnings(input: ProjectComplianceInput):
590
556
  if (basename(file).startsWith('_'))
591
557
  continue
592
558
  const analysis = analyses.get(file)
593
- if (analysis !== undefined && analysis.exportedNames.includes('default'))
594
- pagePaths.push(fileToRoutePath(routesDir, file))
559
+ if (analysis === undefined || !analysis.exportedNames.includes('default'))
560
+ continue
561
+ const routePath = fileToRoutePath(routesDir, file)
562
+ pagePaths.push(routePath)
563
+ if (isLegalNoticePath(routePath, compliance) && !isRuleIgnored('lcen/legal-notice', compliance))
564
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), LEGAL_NOTICE_DETAILS))
565
+ if (matchesNoticePath(routePath, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS) && !isRuleIgnored('rgpd/privacy-notice', compliance))
566
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), PRIVACY_NOTICE_DETAILS))
567
+ // Any site that publishes a statement, public body or not, publishes what it says.
568
+ if (isStatementPath(routePath) && !isRuleIgnored('rgaa/accessibility-statement', compliance))
569
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), STATEMENT_DETAILS))
570
+ if (matchesNoticePath(routePath, undefined, ECO_DECLARATION_PATHS) && !isRuleIgnored('rgesn/declaration', compliance))
571
+ warnings.push(...placeholderWarnings(relPosix(root, file), readFileSync(file, 'utf8'), ECO_DECLARATION_DETAILS))
595
572
  }
596
573
  warnings.push(...checkRouteCompliance(pagePaths, compliance))
574
+ if (pagePaths.length > 0 && lang === undefined && langFromPlugin !== true && !isRuleIgnored('rgaa/document-lang', compliance))
575
+ warnings.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/document-lang] No lang in prunelle.config.ts, so every page says <html lang="en"> and @prunellejs/ui speaks English: set lang: \'fr\' (or the language your pages are written in).', 'warning'))
576
+ warnings.push(...largePublicFileWarnings(root, isRuleIgnored('rgesn/large-public-file', compliance)))
577
+ if (!isRuleIgnored('rgpd/privacy-notice', compliance) && !pagePaths.some(p => matchesNoticePath(p, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS)))
578
+ warnings.push(...privacyNoticeWarnings(root, srcFiles.filter(file => file.endsWith('.tsx')), compliance?.privacyNotice))
597
579
  return warnings
598
580
  }
581
+
582
+ // One warning, at the first form field collecting an email or a phone number: a single privacy page covers every form.
583
+ function privacyNoticeWarnings(root: string, tsxFiles: readonly string[], custom: string | false | undefined): string[] {
584
+ for (const file of tsxFiles) {
585
+ const code = readFileSync(file, 'utf8')
586
+ const match = PERSONAL_DATA_INPUT_RE.exec(code)
587
+ if (match === null)
588
+ continue
589
+ const relFile = relPosix(root, file)
590
+ const expected = typeof custom === 'string' ? normalizePath(custom) : '/privacy (or /confidentialite)'
591
+ return [formatDiagnostic(formatLoc(relFile, code, match.index), `[rgpd/privacy-notice] ${relFile} collects an email or a phone number but the app has no privacy notice route: RGPD art. 13 requires telling people, as their data is collected, who processes it, why, for how long and what their rights are; add ${expected} and link it beside the form, set compliance.privacyNotice, or silence with compliance: { privacyNotice: false }.`, 'warning')]
592
+ }
593
+ return []
594
+ }
595
+
596
+ // One warning for the first unfilled detail: the publisher fills them all in one pass.
597
+ function placeholderWarnings(relFile: string, code: string, notice: NoticeDetails): string[] {
598
+ const offset = code.indexOf(notice.marker)
599
+ if (offset === -1)
600
+ return []
601
+ return [formatDiagnostic(formatLoc(relFile, code, offset), `[${notice.rule}] The ${notice.page} still holds "${notice.marker} ...]" placeholders: ${notice.law}; replace every placeholder in ${relFile}.`, 'warning')]
602
+ }