prunelle 0.7.7 → 0.9.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 (189) hide show
  1. package/llms.txt +63 -46
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +6 -10
  4. package/src/a11y/index.ts +69 -125
  5. package/src/animate.ts +127 -0
  6. package/src/build/asides.ts +51 -0
  7. package/src/build/bundle.ts +88 -134
  8. package/src/build/client-entries.ts +6 -6
  9. package/src/build/client-outputs.ts +75 -0
  10. package/src/build/client-plugin.ts +9 -4
  11. package/src/build/ecoindex.ts +4 -2
  12. package/src/build/files.ts +18 -0
  13. package/src/build/graph.ts +15 -7
  14. package/src/build/index.ts +20 -10
  15. package/src/build/island-promote.ts +1 -1
  16. package/src/build/islands.ts +4 -1
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +19 -1
  19. package/src/build/plugin-host.ts +2 -0
  20. package/src/build/prerender.ts +2 -2
  21. package/src/build/reach.ts +14 -1
  22. package/src/build/report.ts +1 -1
  23. package/src/build/route-types.ts +16 -0
  24. package/src/build/routes.ts +24 -15
  25. package/src/build/seed-ids.ts +65 -0
  26. package/src/build/seed-writes.ts +111 -0
  27. package/src/build/static-headers.ts +2 -2
  28. package/src/build/static.ts +1 -1
  29. package/src/cli/check-cache.ts +51 -0
  30. package/src/cli/check-consent.ts +95 -0
  31. package/src/cli/check-forms.ts +2 -2
  32. package/src/cli/check-links-patterns.ts +101 -0
  33. package/src/cli/check-links.ts +16 -100
  34. package/src/cli/check-regions.ts +185 -0
  35. package/src/cli/check-security.ts +57 -6
  36. package/src/cli/check.ts +40 -17
  37. package/src/cli/commands.ts +134 -14
  38. package/src/cli/docs.ts +21 -2
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/inspect.ts +2 -0
  41. package/src/cli/mcp-tools.ts +2 -2
  42. package/src/cli/new.ts +9 -5
  43. package/src/cli/upgrade-names.ts +14 -2
  44. package/src/cli/upgrade.ts +3 -0
  45. package/src/compiler/analyze.ts +18 -4
  46. package/src/compiler/cacheability.ts +24 -2
  47. package/src/compiler/compliance-contrast.ts +284 -0
  48. package/src/compiler/compliance-empty.ts +24 -0
  49. package/src/compiler/compliance-rgaa-content.ts +95 -0
  50. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  51. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  52. package/src/compiler/compliance-rgaa.ts +19 -0
  53. package/src/compiler/compliance-third-party.ts +59 -0
  54. package/src/compiler/compliance-urls.ts +52 -0
  55. package/src/compiler/compliance.ts +72 -42
  56. package/src/compiler/cookie-inventory.ts +119 -0
  57. package/src/compiler/dom-attrs.ts +4 -1
  58. package/src/compiler/emit.ts +1 -1
  59. package/src/compiler/foreign-imports.ts +5 -3
  60. package/src/compiler/mistakes.ts +18 -9
  61. package/src/compiler/props-pattern.ts +211 -0
  62. package/src/compiler/props.ts +177 -346
  63. package/src/compiler/shared.ts +9 -16
  64. package/src/compiler/ssr-emit.ts +510 -0
  65. package/src/compiler/ssr-helpers.ts +170 -121
  66. package/src/compiler/ssr.ts +25 -440
  67. package/src/context.ts +14 -1
  68. package/src/dev/child.ts +1 -1
  69. package/src/dev/hot-islands.ts +71 -0
  70. package/src/dev/index.ts +31 -18
  71. package/src/dev/protocol.ts +1 -1
  72. package/src/dev/queue.ts +3 -2
  73. package/src/dev/reload.ts +1 -1
  74. package/src/dev/supervisor.ts +3 -1
  75. package/src/dev/watchers.ts +6 -2
  76. package/src/dom/action.ts +97 -14
  77. package/src/dom/attrs.ts +8 -0
  78. package/src/dom/extras.ts +2 -1
  79. package/src/dom/field-marks.ts +24 -0
  80. package/src/dom/hot.ts +9 -0
  81. package/src/dom/index.ts +25 -5
  82. package/src/dom/island-hot.ts +29 -0
  83. package/src/dom/island.ts +13 -2
  84. package/src/dom/prefetch.ts +132 -0
  85. package/src/dom/regions.ts +498 -0
  86. package/src/dom/swap.ts +245 -0
  87. package/src/dom/trusted.ts +22 -0
  88. package/src/dom/upload.ts +44 -0
  89. package/src/eco/declaration.ts +39 -40
  90. package/src/eco/index.ts +5 -5
  91. package/src/href.ts +31 -0
  92. package/src/index.ts +9 -3
  93. package/src/plugins/config.ts +1 -1
  94. package/src/plugins/context.ts +7 -1
  95. package/src/plugins/daily.ts +27 -0
  96. package/src/plugins/index.ts +3 -3
  97. package/src/plugins/order.ts +1 -1
  98. package/src/plugins/public.ts +8 -5
  99. package/src/plugins/services.ts +88 -14
  100. package/src/plugins/types.ts +121 -10
  101. package/src/reactivity/hmr.ts +90 -0
  102. package/src/reactivity/index.ts +38 -18
  103. package/src/reactivity/resource.ts +115 -0
  104. package/src/reactivity/seed.ts +39 -0
  105. package/src/reactivity/server-seed.ts +194 -0
  106. package/src/reactivity/store.ts +55 -1
  107. package/src/rgpd/draft.ts +171 -0
  108. package/src/rgpd/forms.ts +85 -0
  109. package/src/rgpd/index.ts +57 -0
  110. package/src/server/action-flash.ts +1 -0
  111. package/src/server/action-registry.ts +6 -8
  112. package/src/server/action.ts +51 -19
  113. package/src/server/app-secret.ts +22 -17
  114. package/src/server/cache-invalidation.ts +96 -0
  115. package/src/server/compress.ts +3 -1
  116. package/src/server/consent.ts +16 -2
  117. package/src/server/cookie-inventory.ts +78 -0
  118. package/src/server/cookies.ts +50 -0
  119. package/src/server/csp-report.ts +86 -0
  120. package/src/server/discard.ts +13 -0
  121. package/src/server/document.ts +7 -4
  122. package/src/server/env.ts +1 -1
  123. package/src/server/errors.ts +9 -2
  124. package/src/server/field-errors.ts +91 -0
  125. package/src/server/form-schema.ts +16 -11
  126. package/src/server/health.ts +35 -14
  127. package/src/server/http.ts +25 -10
  128. package/src/server/index.ts +102 -299
  129. package/src/server/loader.ts +1 -0
  130. package/src/server/page.ts +11 -24
  131. package/src/server/plugin-host.ts +26 -8
  132. package/src/server/public.ts +14 -3
  133. package/src/server/rate-limit.ts +39 -10
  134. package/src/server/region.ts +3 -0
  135. package/src/server/request-handler.ts +370 -0
  136. package/src/server/request-log.ts +94 -0
  137. package/src/server/route-cache.ts +41 -6
  138. package/src/server/route-input.ts +54 -0
  139. package/src/server/route-table.ts +35 -19
  140. package/src/server/routing.ts +12 -11
  141. package/src/server/sanitize-html.ts +1 -1
  142. package/src/server/security.ts +81 -20
  143. package/src/server/serve-handlers.ts +9 -5
  144. package/src/server/shared-store.ts +314 -0
  145. package/src/server/start.ts +12 -5
  146. package/src/server/static-dir.ts +14 -10
  147. package/src/server/stream.ts +2 -1
  148. package/src/server/surface.ts +39 -0
  149. package/src/server/webhook.ts +48 -0
  150. package/src/server/workers.ts +168 -0
  151. package/src/ssr/consent-banner.ts +20 -16
  152. package/src/ssr/consent-texts.ts +40 -0
  153. package/src/ssr/context.ts +26 -3
  154. package/src/ssr/cookie-table.ts +75 -0
  155. package/src/ssr/index.ts +23 -13
  156. package/src/ssr/navigation.ts +161 -14
  157. package/src/test/browser.ts +50 -22
  158. package/src/test/build-reuse.ts +70 -0
  159. package/src/test/index.ts +45 -6
  160. package/src/test/mount.ts +53 -0
  161. package/src/test/outside.ts +94 -0
  162. package/templates/_shared/AGENTS.md +1 -1
  163. package/templates/_shared/Dockerfile +22 -0
  164. package/templates/_shared/dockerignore +9 -0
  165. package/templates/_shared/gitignore +2 -0
  166. package/templates/app/.env.example +3 -1
  167. package/templates/app/compose.yaml +32 -0
  168. package/templates/app/db/migrations/001_notes.sql +7 -0
  169. package/templates/app/db/schema.ts +11 -0
  170. package/templates/app/package.json +1 -0
  171. package/templates/app/prunelle.config.ts +6 -0
  172. package/templates/app/src/actions/notes.ts +26 -0
  173. package/templates/app/src/auth.ts +4 -2
  174. package/templates/app/src/db.ts +5 -0
  175. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  176. package/templates/app/src/routes/privacy.tsx +6 -2
  177. package/templates/app/tests/app.test.ts +14 -3
  178. package/templates/plugin/AGENTS.md +11 -0
  179. package/templates/plugin/CLAUDE.md +1 -0
  180. package/templates/plugin/README.md +27 -0
  181. package/templates/plugin/gitignore +2 -0
  182. package/templates/plugin/llms.txt +19 -0
  183. package/templates/plugin/package.json +33 -0
  184. package/templates/plugin/src/index.ts +40 -0
  185. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  186. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  187. package/templates/plugin/tests/plugin.test.ts +42 -0
  188. package/templates/plugin/tsconfig.json +19 -0
  189. package/ts-plugin.cjs +3674 -2196
@@ -6,8 +6,13 @@ import { walk } from '../compiler/ast'
6
6
  import { SourceEditor } from '../compiler/patch'
7
7
 
8
8
  const KAY_SOURCE_RE = /^@kayjs\//
9
+ const PRUNELLE_SOURCE_RE = /^(?:prunelle(?:\/|$)|@prunellejs\/)/
9
10
  const REF_TYPES_RE = /^(\s*\/\/\/\s*<reference\s+types=)(["'])([^"']+)\2(\s*\/>)/gm
10
11
 
12
+ const RENAMED_EXPORTS: Readonly<Record<string, string>> = {
13
+ UI_KUI_LAYER_SERVICE: 'UI_LAYER_SERVICE',
14
+ }
15
+
11
16
  type Import = Extract<AstNode, { type: 'ImportDeclaration' }>
12
17
  type Specifier = Extract<AstNode, { type: 'ImportSpecifier' }>
13
18
 
@@ -19,8 +24,11 @@ interface Binding {
19
24
  pinned: boolean
20
25
  }
21
26
 
22
- /** What a name kay exported is called in prunelle, or undefined when it kept its name. */
27
+ /** What a name kay or an older prunelle exported is called now, or undefined when it kept its name. */
23
28
  export function prunelleName(name: string): string | undefined {
29
+ const renamed = RENAMED_EXPORTS[name]
30
+ if (renamed !== undefined)
31
+ return renamed
24
32
  const next = name.replace(/KAY/g, 'PRUNELLE').replace(/Kay/g, 'Prunelle').replace(/kay/g, 'prunelle')
25
33
  return next === name ? undefined : next
26
34
  }
@@ -42,6 +50,10 @@ function resolveAlias(spec: string, aliases?: ReadonlyMap<string, string>): stri
42
50
  function hasKaySourceHint(code: string, aliases?: ReadonlyMap<string, string>): boolean {
43
51
  if (code.includes('@kayjs/'))
44
52
  return true
53
+ for (const name of Object.keys(RENAMED_EXPORTS)) {
54
+ if (code.includes(name))
55
+ return true
56
+ }
45
57
  if (aliases === undefined || aliases.size === 0)
46
58
  return false
47
59
  for (const alias of aliases.keys()) {
@@ -71,7 +83,7 @@ export function renameKayNames(file: string, code: string, aliases?: ReadonlyMap
71
83
  const skipped = new Set<number>()
72
84
  const patchedSources = new Set<number>()
73
85
  const fromKay = (source: { value?: unknown } | null | undefined): boolean =>
74
- typeof source?.value === 'string' && (KAY_SOURCE_RE.test(source.value) || resolveAlias(source.value, aliases) !== undefined)
86
+ typeof source?.value === 'string' && (KAY_SOURCE_RE.test(source.value) || PRUNELLE_SOURCE_RE.test(source.value) || resolveAlias(source.value, aliases) !== undefined)
75
87
  const rewriteSource = (source: { start: number, end: number, value?: unknown } | null | undefined): void => {
76
88
  if (source === null || source === undefined || typeof source.value !== 'string' || patchedSources.has(source.start))
77
89
  return
@@ -30,11 +30,14 @@ const PATH_RULES: [RegExp, string][] = [
30
30
  // The names kay sent the browser, as app code and styles may spell them.
31
31
  const WIRE_RULES: [RegExp, string][] = [
32
32
  [/\bdata-kay-/g, 'data-pru-'],
33
+ [/\bdata-kui-fallback\b/g, 'data-pru-fallback'],
33
34
  [/\bx-kay-/gi, 'x-pru-'],
34
35
  [/\/_kay\//g, '/_pru/'],
35
36
  [/\bkay-(island|slot|s)\b/g, 'pru-$1'],
36
37
  [/\bkay:(consent|navigate|region)\b/g, 'pru:$1'],
37
38
  [/\bkay_(session|consent)\b/g, 'pru_$1'],
39
+ [/@layer\b([^{;]*)\bkui\b/g, '@layer$1pru-ui'],
40
+ [/\bkui-sr-only\b/g, 'pru-sr-only'],
38
41
  ]
39
42
  // The kay CLI where a script, build, CI or agent file runs it, after a runner or before one of its commands, so a user, label or prose named kay stays (#142, #165).
40
43
  const KAY_COMMAND = String.raw`(?:new|check|inspect|docs|render|mcp|dev|build|eco|a11y|start|upgrade|test|[a-z]+-[a-z-]+)(?![\w:-])`
@@ -22,14 +22,14 @@ import { checkBareSignals } from './signal-reads'
22
22
  import type { BindingUnit } from './spread-handlers'
23
23
  import { bindingUnits, checkStaticSpreadHandlers, collectUnitInits, findSpreadInteractiveAttr } from './spread-handlers'
24
24
 
25
- const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction'])
25
+ const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction', 'resource'])
26
26
  // Primitives whose result is reactive state another module can import and read.
27
27
  const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
28
28
  const PRUNELLE_SOURCES = new Set(['prunelle'])
29
29
  const PRUNELLE_SSR_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
30
30
  const PRUNELLE_SERVER_SOURCES = new Set(['prunelle/server'])
31
31
  const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'createContext', 'provideContext', 'useContext', 'useId'])
32
- const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
32
+ const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'CookieTable'])
33
33
 
34
34
  export interface ImportInfo {
35
35
  source: string
@@ -308,6 +308,16 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
308
308
  scan.localInits.set(d.id.name, d.init)
309
309
  }
310
310
  }
311
+ // `import X from './x'; export default X` (or `export { X }`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`.
312
+ const reexportImported = (exported: string, local: string, start: number): void => {
313
+ for (const imp of imports.imports) {
314
+ const spec = imp.specifiers.find(s => s.local === local && s.imported !== '*')
315
+ if (spec !== undefined) {
316
+ scan.reexports.push({ exported, local: spec.imported, source: imp.source, start })
317
+ return
318
+ }
319
+ }
320
+ }
311
321
  const addExport = (exported: string, local: string | undefined): void => {
312
322
  scan.exportedNames.push(exported)
313
323
  if (local !== undefined)
@@ -335,8 +345,10 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
335
345
  addExport('default', decl.type === 'Identifier' ? decl.name : named ?? 'default')
336
346
  if (isAsyncFunction(decl))
337
347
  scan.hasAsyncDefault = true
338
- else if (decl.type === 'Identifier')
348
+ else if (decl.type === 'Identifier') {
339
349
  scan.defaultLocal = decl.name
350
+ reexportImported('default', decl.name, stmt.start)
351
+ }
340
352
  else
341
353
  scan.localInits.set('default', decl)
342
354
  }
@@ -349,7 +361,9 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
349
361
  addExport(exported, stmt.source === null ? local : undefined)
350
362
  if (stmt.source !== null)
351
363
  scan.reexports.push({ exported, local, source: stmt.source.value, start: stmt.start })
352
- else if (exported === 'default')
364
+ else
365
+ reexportImported(exported, local, stmt.start)
366
+ if (stmt.source === null && exported === 'default')
353
367
  scan.defaultLocal = local
354
368
  }
355
369
  if (stmt.declaration !== null)
@@ -18,7 +18,7 @@ import {
18
18
  } from './cacheability-private'
19
19
  import { EVENT_ATTR, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
20
20
 
21
- const CACHE_HELP = 'write a duration such as \'30s\', \'5m\', \'1h\', \'1d\', a positive number of seconds, or { maxAge: \'1h\', staleWhileRevalidate?: \'1d\' }'
21
+ const CACHE_HELP = 'write a duration such as \'30s\', \'5m\', \'1h\', \'1d\', a positive number of seconds, or { maxAge: \'1h\', staleWhileRevalidate?: \'1d\', tags?: [\'posts\'] }'
22
22
  const DYNAMIC_PROPS = new Set(['params', 'url', 'locals', 'cookies', 'headers', 'request', 'consent', 'ip'])
23
23
  const DYNAMIC_IMPORTS = new Set(['bun:sqlite', 'node:sqlite', 'sqlite', 'bun:sql'])
24
24
  const SYNC_IO_CALLEES = new Set(['readFileSync', 'readdirSync', 'statSync', 'lstatSync', 'existsSync', 'accessSync'])
@@ -46,12 +46,20 @@ function parseCacheObjectNode(node: Extract<Node, { type: 'ObjectExpression' }>)
46
46
  let maxAgeMs: number | undefined
47
47
  let swrMs: number | undefined
48
48
  let swrKeyCount = 0
49
+ let tags: string[] = []
49
50
  for (const prop of node.properties) {
50
51
  if (prop.type !== 'Property' || prop.kind !== 'init')
51
52
  return { problem: `cache object must use static properties: ${CACHE_HELP}` }
52
53
  const key = propKeyName(prop)
53
54
  if (key === undefined)
54
55
  return { problem: `cache object has a dynamic key: ${CACHE_HELP}` }
56
+ if (key === 'tags') {
57
+ const names = staticTagNames(prop.value)
58
+ if (names === undefined)
59
+ return { problem: 'cache.tags must be a list of tag names written in the route, such as tags: [\'posts\']: invalidateCache({ tag }) and prunelle check read them from the source' }
60
+ tags = names
61
+ continue
62
+ }
55
63
  if (key !== 'maxAge' && key !== 'staleWhileRevalidate' && key !== 'swr')
56
64
  return { problem: `unknown cache option "${key}": ${CACHE_HELP}` }
57
65
  const parsed = staticStringOrNumber(prop.value)
@@ -72,7 +80,21 @@ function parseCacheObjectNode(node: Extract<Node, { type: 'ObjectExpression' }>)
72
80
  return { problem: `cache object is missing "maxAge": ${CACHE_HELP}` }
73
81
  if (swrKeyCount > 1)
74
82
  return { problem: `specify either "staleWhileRevalidate" or "swr", not both: ${CACHE_HELP}` }
75
- return { spec: buildRouteCacheSpec(maxAgeMs, swrMs ?? maxAgeMs) }
83
+ return { spec: buildRouteCacheSpec(maxAgeMs, swrMs ?? maxAgeMs, tags) }
84
+ }
85
+
86
+ function staticTagNames(node: Node): string[] | undefined {
87
+ const list = unwrapTsExpr(node)
88
+ if (list.type !== 'ArrayExpression')
89
+ return undefined
90
+ const names: string[] = []
91
+ for (const item of list.elements) {
92
+ const name = item === null || item.type === 'SpreadElement' ? undefined : staticStringOrNumber(item)
93
+ if (name?.ok !== true || typeof name.value !== 'string' || name.value === '')
94
+ return undefined
95
+ names.push(name.value)
96
+ }
97
+ return names
76
98
  }
77
99
 
78
100
  /** Parses and validates `export const cache = ...` (or `const cache = ...; export { cache }`) from a module AST. */
@@ -0,0 +1,284 @@
1
+ // RGAA 3.2 read from the app's own stylesheets: a rule that sets both its text colour and its background, in the light and the dark scheme, with the custom properties its stylesheet declares on :root.
2
+
3
+ export type ContrastRule = 'rgaa/contrast'
4
+
5
+ export interface ContrastFinding {
6
+ offset: number
7
+ message: string
8
+ }
9
+
10
+ type Scheme = 'light' | 'dark'
11
+ type Rgb = readonly [number, number, number]
12
+
13
+ interface StyleRule {
14
+ selector: string
15
+ /** Set by `@media (prefers-color-scheme)` or a `[data-theme]`, `.dark` or `.light` selector; undefined in both schemes. */
16
+ scheme: Scheme | undefined
17
+ decls: Map<string, string>
18
+ offset: number
19
+ }
20
+
21
+ interface Tokens {
22
+ base: Map<string, string>
23
+ light: Map<string, string>
24
+ dark: Map<string, string>
25
+ }
26
+
27
+ const COMMENT_RE = /\/\*[\s\S]*?\*\//g
28
+ const MEDIA_SCHEME_RE = /prefers-color-scheme\s*:\s*(light|dark)/
29
+ const SELECTOR_SCHEME_RE = /\[data-theme\s*=\s*["']?(light|dark)["']?\s*\]|\.(light|dark)\b/
30
+ // At-rules whose blocks hold no style rule.
31
+ const OPAQUE_AT_RULE_RE = /^@(?:keyframes|-webkit-keyframes|font-face|property|page|counter-style|font-feature-values)\b/
32
+ const HEX_RE = /^#([\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})$/i
33
+ const FUNCTION_COLOR_RE = /^(rgba?|hsla?)\(([^()]*)\)$/i
34
+ const FONT_SIZE_RE = /^([\d.]+)(px|rem|pt)$/
35
+ // The 17 colours of CSS 2.1 and their common aliases; a name outside them is not resolved, so its rule is skipped.
36
+ const NAMED: Record<string, Rgb> = {
37
+ black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
38
+ red: [255, 0, 0], maroon: [128, 0, 0], yellow: [255, 255, 0], olive: [128, 128, 0], lime: [0, 255, 0], green: [0, 128, 0],
39
+ aqua: [0, 255, 255], cyan: [0, 255, 255], teal: [0, 128, 128], blue: [0, 0, 255], navy: [0, 0, 128],
40
+ fuchsia: [255, 0, 255], magenta: [255, 0, 255], purple: [128, 0, 128], orange: [255, 165, 0],
41
+ }
42
+ const MAX_VAR_DEPTH = 10
43
+
44
+ function schemeOfSelector(selector: string): Scheme | undefined {
45
+ const match = SELECTOR_SCHEME_RE.exec(selector)
46
+ return match === null ? undefined : (match[1] ?? match[2]) as Scheme
47
+ }
48
+
49
+ // The index of the parenthesis or brace closing the one at `open`, strings skipped.
50
+ function closing(css: string, open: number): number {
51
+ const [opener, closer] = css[open] === '(' ? ['(', ')'] : ['{', '}']
52
+ let depth = 0
53
+ for (let i = open; i < css.length; i++) {
54
+ const ch = css[i]
55
+ if (ch === '"' || ch === '\'') {
56
+ i = css.indexOf(ch, i + 1)
57
+ if (i === -1)
58
+ return css.length
59
+ }
60
+ else if (ch === opener) {
61
+ depth++
62
+ }
63
+ else if (ch === closer && --depth === 0) {
64
+ return i
65
+ }
66
+ }
67
+ return css.length
68
+ }
69
+
70
+ // The declarations at the top of a rule's body; nested rules are left out.
71
+ function declarationsOf(body: string): Map<string, string> {
72
+ const decls = new Map<string, string>()
73
+ let start = 0
74
+ for (let i = 0; i <= body.length; i++) {
75
+ const ch = body[i]
76
+ if (ch === '(' || ch === '{') {
77
+ const end = closing(body, i)
78
+ if (ch === '{')
79
+ start = end + 1
80
+ i = end
81
+ continue
82
+ }
83
+ if (ch !== ';' && i !== body.length)
84
+ continue
85
+ const decl = body.slice(start, i)
86
+ const colon = decl.indexOf(':')
87
+ if (colon > 0)
88
+ decls.set(decl.slice(0, colon).trim().toLowerCase(), decl.slice(colon + 1).replace(/!important\s*$/i, '').trim())
89
+ start = i + 1
90
+ }
91
+ return decls
92
+ }
93
+
94
+ function styleRules(source: string): StyleRule[] {
95
+ const css = source.replace(COMMENT_RE, match => ' '.repeat(match.length))
96
+ const rules: StyleRule[] = []
97
+ const walk = (from: number, to: number, scheme: Scheme | undefined): void => {
98
+ let start = from
99
+ for (let i = from; i < to; i++) {
100
+ const ch = css[i]
101
+ if (ch === ';') {
102
+ start = i + 1
103
+ continue
104
+ }
105
+ if (ch !== '{')
106
+ continue
107
+ const end = closing(css, i)
108
+ const prelude = css.slice(start, i)
109
+ const selector = prelude.trim()
110
+ if (selector.startsWith('@')) {
111
+ if (!OPAQUE_AT_RULE_RE.test(selector))
112
+ walk(i + 1, end, (MEDIA_SCHEME_RE.exec(selector)?.[1] as Scheme | undefined) ?? scheme)
113
+ }
114
+ else {
115
+ rules.push({ selector, scheme: schemeOfSelector(selector) ?? scheme, decls: declarationsOf(css.slice(i + 1, end)), offset: start + prelude.length - prelude.trimStart().length })
116
+ }
117
+ i = end
118
+ start = end + 1
119
+ }
120
+ }
121
+ walk(0, css.length, undefined)
122
+ return rules
123
+ }
124
+
125
+ // `:root`, `html` or `:host`, alone or with a theme qualifier: the places a stylesheet declares its tokens.
126
+ function isRootSelector(selector: string): boolean {
127
+ return selector.split(',').every((part) => {
128
+ const bare = part.replace(SELECTOR_SCHEME_RE, '').trim()
129
+ return bare === '' || bare === ':root' || bare === 'html' || bare === ':host'
130
+ })
131
+ }
132
+
133
+ function tokensOf(rules: readonly StyleRule[]): Tokens {
134
+ const tokens: Tokens = { base: new Map(), light: new Map(), dark: new Map() }
135
+ for (const rule of rules) {
136
+ if (!isRootSelector(rule.selector))
137
+ continue
138
+ const into = rule.scheme === undefined ? tokens.base : tokens[rule.scheme]
139
+ for (const [name, value] of rule.decls) {
140
+ if (name.startsWith('--'))
141
+ into.set(name, value)
142
+ }
143
+ }
144
+ return tokens
145
+ }
146
+
147
+ // The arguments of a function call, split at its top-level commas.
148
+ function argsOf(inner: string): string[] {
149
+ const args: string[] = []
150
+ let start = 0
151
+ for (let i = 0; i < inner.length; i++) {
152
+ if (inner[i] === '(') {
153
+ i = closing(inner, i)
154
+ }
155
+ else if (inner[i] === ',') {
156
+ args.push(inner.slice(start, i).trim())
157
+ start = i + 1
158
+ }
159
+ }
160
+ args.push(inner.slice(start).trim())
161
+ return args
162
+ }
163
+
164
+ // `value` with its `var()` and `light-dark()` replaced for `scheme`; undefined when a variable is not declared and has no fallback.
165
+ function substitute(value: string, scheme: Scheme, tokens: Tokens, depth = 0): string | undefined {
166
+ if (depth > MAX_VAR_DEPTH)
167
+ return undefined
168
+ const match = /\b(var|light-dark)\(/i.exec(value)
169
+ if (match === null)
170
+ return value
171
+ const open = match.index + match[0].length - 1
172
+ const end = closing(value, open)
173
+ const args = argsOf(value.slice(open + 1, end))
174
+ let replacement: string | undefined
175
+ if (match[1]!.toLowerCase() === 'var') {
176
+ const declared = tokens[scheme].get(args[0]!) ?? tokens.base.get(args[0]!)
177
+ replacement = declared ?? (args.length > 1 ? args.slice(1).join(',') : undefined)
178
+ }
179
+ else {
180
+ replacement = scheme === 'light' ? args[0] : args[1]
181
+ }
182
+ if (replacement === undefined)
183
+ return undefined
184
+ return substitute(value.slice(0, match.index) + replacement + value.slice(end + 1), scheme, tokens, depth + 1)
185
+ }
186
+
187
+ function channel(raw: string, max: number): number | undefined {
188
+ const n = Number.parseFloat(raw)
189
+ if (Number.isNaN(n))
190
+ return undefined
191
+ return raw.endsWith('%') ? (n / 100) * max : n
192
+ }
193
+
194
+ function hslToRgb(h: number, s: number, l: number): Rgb {
195
+ const k = (n: number): number => (n + h / 30) % 12
196
+ const a = s * Math.min(l, 1 - l)
197
+ const f = (n: number): number => Math.round(255 * (l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))))
198
+ return [f(0), f(8), f(4)]
199
+ }
200
+
201
+ /** An opaque colour as sRGB channels; undefined for a translucent one, which shows what lies under it, and for any syntax not read here. */
202
+ export function parseColor(raw: string): Rgb | undefined {
203
+ const value = raw.trim().toLowerCase()
204
+ if (value in NAMED)
205
+ return NAMED[value]
206
+ const hex = HEX_RE.exec(value)?.[1]
207
+ if (hex !== undefined) {
208
+ const full = hex.length <= 4 ? [...hex].map(c => c + c).join('') : hex
209
+ if (full.length === 8 && full.slice(6) !== 'ff')
210
+ return undefined
211
+ return [Number.parseInt(full.slice(0, 2), 16), Number.parseInt(full.slice(2, 4), 16), Number.parseInt(full.slice(4, 6), 16)]
212
+ }
213
+ const fn = FUNCTION_COLOR_RE.exec(value)
214
+ if (fn === null)
215
+ return undefined
216
+ const parts = fn[2]!.split(/[\s,/]+/).filter(Boolean)
217
+ if (parts.length < 3 || parts.length > 4 || (parts.length === 4 && channel(parts[3]!, 1) !== 1))
218
+ return undefined
219
+ if (fn[1]!.startsWith('rgb')) {
220
+ const [r, g, b] = [channel(parts[0]!, 255), channel(parts[1]!, 255), channel(parts[2]!, 255)]
221
+ return r === undefined || g === undefined || b === undefined ? undefined : [Math.round(r), Math.round(g), Math.round(b)]
222
+ }
223
+ const [h, s, l] = [Number.parseFloat(parts[0]!), channel(parts[1]!, 1), channel(parts[2]!, 1)]
224
+ return Number.isNaN(h) || s === undefined || l === undefined ? undefined : hslToRgb(((h % 360) + 360) % 360, s, l)
225
+ }
226
+
227
+ function luminance(rgb: Rgb): number {
228
+ const [r, g, b] = rgb.map((c) => {
229
+ const s = c / 255
230
+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
231
+ })
232
+ return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!
233
+ }
234
+
235
+ /** The WCAG contrast ratio of two opaque colours, from 1 to 21. */
236
+ export function contrastRatio(a: Rgb, b: Rgb): number {
237
+ const [la, lb] = [luminance(a), luminance(b)]
238
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
239
+ }
240
+
241
+ // Text from 24px, or from 18.66px when bold, needs 3:1 instead of 4.5:1.
242
+ function isLargeText(decls: ReadonlyMap<string, string>): boolean {
243
+ const size = FONT_SIZE_RE.exec(decls.get('font-size') ?? '')
244
+ if (size === null)
245
+ return false
246
+ const px = Number.parseFloat(size[1]!) * (size[2] === 'rem' ? 16 : size[2] === 'pt' ? 4 / 3 : 1)
247
+ const weight = decls.get('font-weight') ?? ''
248
+ const bold = weight === 'bold' || weight === 'bolder' || Number.parseInt(weight, 10) >= 700
249
+ return px >= 24 || (bold && px >= 18.66)
250
+ }
251
+
252
+ const hexOf = (rgb: Rgb): string => `#${rgb.map(c => c.toString(16).padStart(2, '0')).join('')}`
253
+
254
+ /** Each rule of a stylesheet whose text colour and background, both set in the rule and both resolved, fall under the contrast RGAA 3.2 asks: 4.5:1, or 3:1 for large text. */
255
+ export function contrastFindings(code: string): ContrastFinding[] {
256
+ const rules = styleRules(code)
257
+ const tokens = tokensOf(rules)
258
+ const findings: ContrastFinding[] = []
259
+ for (const rule of rules) {
260
+ const color = rule.decls.get('color')
261
+ const background = rule.decls.get('background-color') ?? rule.decls.get('background')
262
+ if (color === undefined || background === undefined)
263
+ continue
264
+ const min = isLargeText(rule.decls) ? 3 : 4.5
265
+ const failing = new Map<string, Scheme[]>()
266
+ for (const scheme of rule.scheme === undefined ? ['light', 'dark'] as const : [rule.scheme]) {
267
+ const fg = parseColor(substitute(color, scheme, tokens) ?? '')
268
+ const bg = parseColor(substitute(background, scheme, tokens) ?? '')
269
+ if (fg === undefined || bg === undefined)
270
+ continue
271
+ const ratio = contrastRatio(fg, bg)
272
+ if (ratio >= min)
273
+ continue
274
+ // Floored, so a ratio just under the minimum never prints as the minimum.
275
+ const key = `${hexOf(fg)} on ${hexOf(bg)}, ${Math.floor(ratio * 100) / 100}:1`
276
+ failing.set(key, [...failing.get(key) ?? [], scheme])
277
+ }
278
+ for (const [key, schemes] of failing) {
279
+ const where = schemes.length === 2 || rule.scheme !== undefined ? '' : ` in the ${schemes[0]} scheme`
280
+ findings.push({ offset: rule.offset, message: `[rgaa/contrast] "${rule.selector}" sets ${key}${where}, under the ${min}:1 RGAA 3.2 asks of ${min === 3 ? 'large ' : ''}text: darken one or lighten the other until they reach ${min}:1.` })
281
+ }
282
+ }
283
+ return findings
284
+ }
@@ -0,0 +1,24 @@
1
+ // Whether a page's JSX can render anything to read, for the notice pages `prunelle check` expects someone to have written.
2
+
3
+ import type { Program } from 'oxc-parser'
4
+ import { walk } from './ast'
5
+ import { isComponentTag, jsxTagName } from './shared'
6
+
7
+ /** True when the module has JSX but none of it holds text, an expression or a component, so the page renders nothing to read. A module with no JSX at all is not judged. */
8
+ export function rendersNoText(program: Program): boolean {
9
+ let hasJsx = false
10
+ let hasContent = false
11
+ walk(program, (node): undefined => {
12
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
13
+ hasJsx = true
14
+ if (node.type === 'JSXElement' && isComponentTag(jsxTagName(node.openingElement.name)))
15
+ hasContent = true
16
+ for (const child of node.children) {
17
+ if (child.type === 'JSXText' ? child.value.trim() !== '' : child.type === 'JSXSpreadChild' || (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression'))
18
+ hasContent = true
19
+ }
20
+ }
21
+ return undefined
22
+ })
23
+ return hasJsx && !hasContent
24
+ }
@@ -0,0 +1,95 @@
1
+ // What an element says or carries, read from its children: a link's whole text (RGAA 6.1), a video's caption track (4.3), a table's caption (5.4).
2
+
3
+ import type { JSXChild, JSXElement } from 'oxc-parser'
4
+ import { isComponentTag, jsxTagName, staticLiteral, unwrapTsExpr } from './shared'
5
+
6
+ // Link texts that say nothing of where the link goes once read alone, as a screen reader's list of links reads them.
7
+ const GENERIC_LINK_TEXTS = new Set([
8
+ 'ici', 'cliquez ici', 'cliquer ici', 'en savoir plus', 'savoir plus', 'lire la suite', 'la suite', 'suite', 'voir plus', 'voir', 'plus', 'plus de détails', 'détails', 'lien', 'ce lien',
9
+ 'here', 'click here', 'read more', 'more', 'learn more', 'see more', 'more details', 'details', 'link', 'this link',
10
+ ])
11
+ // Punctuation and arrows a generic text is often dressed in: "Lire la suite…", "En savoir plus →".
12
+ // Pieces join as the browser renders them, so `<span>Lire</span>la suite` reads "Lirela suite".
13
+ const DRESSING_RE = /[\s.,;:!?…»«›‹→←>()[\]-]+/g
14
+ const CAPTION_KINDS = new Set(['captions', 'subtitles'])
15
+
16
+ function textOf(children: readonly JSXChild[]): string | undefined {
17
+ let text = ''
18
+ for (const child of children) {
19
+ if (child.type === 'JSXText') {
20
+ text += child.value
21
+ }
22
+ else if (child.type === 'JSXFragment') {
23
+ const inner = textOf(child.children)
24
+ if (inner === undefined)
25
+ return undefined
26
+ text += inner
27
+ }
28
+ else if (child.type === 'JSXElement') {
29
+ const tag = jsxTagName(child.openingElement.name)
30
+ // A component may render anything, and an image or a drawing adds its own name.
31
+ const inner = isComponentTag(tag) || tag === 'img' || tag === 'svg' ? undefined : textOf(child.children)
32
+ if (inner === undefined)
33
+ return undefined
34
+ text += inner
35
+ }
36
+ else if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
37
+ const literal = staticLiteral(unwrapTsExpr(child.expression))
38
+ if (!literal.ok || typeof literal.value !== 'string')
39
+ return undefined
40
+ text += literal.value
41
+ }
42
+ }
43
+ return text
44
+ }
45
+
46
+ /** The text of a link when the whole of it is generic ("Lire la suite", "click here"); undefined when it names its target or is not known before render. */
47
+ export function genericLinkText(element: JSXElement): string | undefined {
48
+ const text = textOf(element.children)
49
+ if (text === undefined)
50
+ return undefined
51
+ return GENERIC_LINK_TEXTS.has(text.toLowerCase().replace(DRESSING_RE, ' ').trim()) ? text.replace(/\s+/g, ' ').trim() : undefined
52
+ }
53
+
54
+ /** Whether `children` may hold an element `matches` accepts: a component or an expression might render one. */
55
+ function mayHold(children: readonly JSXChild[], matches: (el: JSXElement, tag: string) => boolean): boolean {
56
+ for (const child of children) {
57
+ if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression')
58
+ return true
59
+ if (child.type === 'JSXFragment' && mayHold(child.children, matches))
60
+ return true
61
+ if (child.type === 'JSXElement') {
62
+ const tag = jsxTagName(child.openingElement.name)
63
+ if (isComponentTag(tag) || matches(child, tag))
64
+ return true
65
+ }
66
+ }
67
+ return false
68
+ }
69
+
70
+ // A track whose kind is captions or subtitles, or is set by a spread or an expression known only at render.
71
+ function mayCaption(track: JSXElement): boolean {
72
+ for (const attr of track.openingElement.attributes) {
73
+ if (attr.type === 'JSXSpreadAttribute')
74
+ return true
75
+ if (attr.name.type !== 'JSXIdentifier' || attr.name.name !== 'kind' || attr.value === null)
76
+ continue
77
+ if (attr.value.type === 'Literal')
78
+ return CAPTION_KINDS.has(String(attr.value.value).toLowerCase())
79
+ if (attr.value.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
80
+ return false
81
+ const literal = staticLiteral(unwrapTsExpr(attr.value.expression))
82
+ return !literal.ok || CAPTION_KINDS.has(String(literal.value).toLowerCase())
83
+ }
84
+ return false
85
+ }
86
+
87
+ /** A `<video>` none of whose children is, or may render, a `<track kind="captions">` or `kind="subtitles"`. */
88
+ export function videoWithoutCaptions(element: JSXElement): boolean {
89
+ return !mayHold(element.children, (el, tag) => tag === 'track' && mayCaption(el))
90
+ }
91
+
92
+ /** A `<table>` none of whose children is, or may render, a `<caption>`. */
93
+ export function tableWithoutCaption(element: JSXElement): boolean {
94
+ return !mayHold(element.children, (_el, tag) => tag === 'caption')
95
+ }
@@ -0,0 +1,45 @@
1
+ // The RGAA 4.1 criteria each static rule partly covers, so `prunelle check` can say how little a clean run proves.
2
+
3
+ import type { ContrastRule } from './compliance-contrast'
4
+ import type { RgaaJsxRule } from './compliance-rgaa'
5
+ import type { RgaaPageRule } from './compliance-rgaa-pages'
6
+
7
+ /** The criteria of the RGAA 4.1. */
8
+ export const RGAA_CRITERIA_TOTAL = 106
9
+
10
+ // Every rule has an entry, so a new rule cannot ship without saying which criteria it touches. `rgaa/autofocus` maps to none: no criterion names it.
11
+ const CRITERIA_BY_RULE: Record<RgaaJsxRule | RgaaPageRule | ContrastRule | 'rgaa/document-lang', readonly string[]> = {
12
+ 'rgaa/img-alt': ['1.1', '1.2'],
13
+ 'rgaa/form-label': ['11.1'],
14
+ 'rgaa/accessible-name': ['1.1', '6.2', '11.9'],
15
+ 'rgaa/duplicate-id': ['8.2'],
16
+ 'rgaa/positive-tabindex': ['12.8'],
17
+ 'rgaa/nested-control': ['8.2'],
18
+ 'rgaa/link-as-button': ['7.1'],
19
+ 'rgaa/unknown-role': ['7.1'],
20
+ 'rgaa/unknown-aria': ['7.1'],
21
+ 'rgaa/invalid-aria-value': ['7.1'],
22
+ 'rgaa/skipped-heading': ['9.1'],
23
+ 'rgaa/table-without-header': ['5.6'],
24
+ 'rgaa/fieldset-without-legend': ['11.5', '11.6'],
25
+ 'rgaa/click-without-key': ['7.3'],
26
+ 'rgaa/autofocus': [],
27
+ 'rgaa/meta-refresh': ['13.1'],
28
+ 'rgaa/role-without-focus': ['7.3'],
29
+ 'rgaa/mouse-only': ['7.3'],
30
+ 'rgaa/frame-title': ['2.1'],
31
+ 'rgaa/empty-heading': ['9.1'],
32
+ 'rgaa/autocomplete': ['11.13'],
33
+ 'rgaa/generic-link-text': ['6.1'],
34
+ 'rgaa/video-captions': ['4.3'],
35
+ 'rgaa/table-caption': ['5.4'],
36
+ 'rgaa/document-lang': ['8.3'],
37
+ 'rgaa/skip-link': ['12.7'],
38
+ 'rgaa/page-title': ['8.5'],
39
+ 'rgaa/contrast': ['3.2'],
40
+ }
41
+
42
+ /** How many distinct RGAA criteria at least one rule of `prunelle check` partly covers. */
43
+ export function rgaaCriteriaCovered(): number {
44
+ return new Set(Object.values(CRITERIA_BY_RULE).flat()).size
45
+ }