prunelle 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +48 -43
  3. package/package.json +4 -1
  4. package/src/a11y/declaration.ts +106 -72
  5. package/src/a11y/index.ts +59 -39
  6. package/src/a11y/rgaa-map.ts +95 -49
  7. package/src/build/bundle.ts +8 -4
  8. package/src/build/byte-size.ts +11 -0
  9. package/src/build/client-plugin.ts +3 -1
  10. package/src/build/compile.ts +2 -1
  11. package/src/build/ecoindex.ts +15 -14
  12. package/src/build/files.ts +6 -0
  13. package/src/build/first-load.ts +83 -11
  14. package/src/build/graph.ts +29 -39
  15. package/src/build/index.ts +57 -18
  16. package/src/build/island-promote.ts +229 -0
  17. package/src/build/islands.ts +9 -201
  18. package/src/build/manifest.ts +4 -125
  19. package/src/build/plugin-host.ts +21 -8
  20. package/src/build/precompress.ts +1 -1
  21. package/src/build/prerender.ts +97 -44
  22. package/src/build/reach.ts +136 -0
  23. package/src/build/render-rules.ts +2 -2
  24. package/src/build/report.ts +19 -3
  25. package/src/build/static-headers.ts +93 -0
  26. package/src/build/static.ts +2 -0
  27. package/src/cli/check-forms.ts +97 -48
  28. package/src/cli/check-imports.ts +25 -0
  29. package/src/cli/check-links.ts +2 -2
  30. package/src/cli/check-security.ts +64 -0
  31. package/src/cli/check.ts +33 -7
  32. package/src/cli/commands.ts +35 -7
  33. package/src/cli/docs.ts +4 -3
  34. package/src/cli/inspect.ts +2 -1
  35. package/src/cli/mcp-tools.ts +7 -5
  36. package/src/cli/mcp.ts +1 -1
  37. package/src/cli/new.ts +14 -3
  38. package/src/cli/render.ts +14 -19
  39. package/src/cli/upgrade.ts +22 -5
  40. package/src/compiler/analyze.ts +26 -5
  41. package/src/compiler/cacheability.ts +2 -2
  42. package/src/compiler/compliance-eco.ts +71 -0
  43. package/src/compiler/compliance-rgaa.ts +110 -4
  44. package/src/compiler/compliance-urls.ts +145 -0
  45. package/src/compiler/compliance.ts +168 -116
  46. package/src/compiler/foreign-imports.ts +88 -0
  47. package/src/compiler/mistakes.ts +19 -1
  48. package/src/compiler/props-body.ts +52 -0
  49. package/src/compiler/shared.ts +2 -2
  50. package/src/compiler/ssr.ts +2 -2
  51. package/src/context.ts +34 -0
  52. package/src/dev/error-log.ts +90 -64
  53. package/src/dev/host-check.ts +26 -0
  54. package/src/dev/index.ts +12 -5
  55. package/src/dev/open-editor.ts +15 -11
  56. package/src/dev/protocol.ts +2 -0
  57. package/src/dev/supervisor.ts +8 -0
  58. package/src/dev/watchers.ts +27 -2
  59. package/src/dom/action.ts +4 -1
  60. package/src/dom/extras.ts +1 -2
  61. package/src/dom/index.ts +13 -2
  62. package/src/dom/island.ts +22 -10
  63. package/src/dom/loop.ts +25 -16
  64. package/src/eco/declaration.ts +257 -0
  65. package/src/eco/index.ts +65 -0
  66. package/src/index.ts +2 -2
  67. package/src/jsx-runtime.ts +2 -2
  68. package/src/plugins/config.ts +1 -1
  69. package/src/plugins/context.ts +16 -1
  70. package/src/plugins/load.ts +4 -3
  71. package/src/plugins/public.ts +2 -2
  72. package/src/plugins/services.ts +3 -0
  73. package/src/plugins/types.ts +17 -2
  74. package/src/server/action-flash.ts +158 -0
  75. package/src/server/action-protect.ts +38 -37
  76. package/src/server/action.ts +11 -127
  77. package/src/server/app-secret.ts +63 -0
  78. package/src/server/compress.ts +5 -1
  79. package/src/server/consent.ts +59 -22
  80. package/src/server/cookies.ts +16 -2
  81. package/src/server/env.ts +14 -0
  82. package/src/server/errors.ts +3 -1
  83. package/src/server/form-schema.ts +1 -1
  84. package/src/server/health.ts +46 -15
  85. package/src/server/http.ts +47 -7
  86. package/src/server/index.ts +52 -30
  87. package/src/server/loader.ts +6 -2
  88. package/src/server/plugin-host.ts +3 -1
  89. package/src/server/public.ts +4 -3
  90. package/src/server/rate-limit.ts +52 -9
  91. package/src/server/route-cache.ts +26 -4
  92. package/src/server/route-table.ts +7 -3
  93. package/src/server/routing.ts +3 -87
  94. package/src/server/sanitize-html.ts +309 -0
  95. package/src/server/security.ts +71 -20
  96. package/src/server/serve-handlers.ts +14 -4
  97. package/src/server/start.ts +1 -1
  98. package/src/server/static-dir.ts +27 -4
  99. package/src/server/stream.ts +28 -6
  100. package/src/ssr/consent-banner.ts +58 -0
  101. package/src/ssr/context.ts +20 -4
  102. package/src/ssr/index.ts +18 -0
  103. package/src/ssr/navigation.ts +2 -2
  104. package/src/style.ts +32 -1
  105. package/templates/_shared/gitignore +5 -0
  106. package/templates/_shared/src/routes/legal.tsx +10 -1
  107. package/templates/app/.env.example +4 -0
  108. package/templates/app/package.json +2 -1
  109. package/templates/app/prunelle.config.ts +2 -0
  110. package/templates/app/src/auth.ts +4 -6
  111. package/templates/app/src/mail.ts +4 -0
  112. package/templates/app/src/routes/_layout.tsx +9 -1
  113. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  114. package/templates/app/src/routes/login.tsx +49 -30
  115. package/templates/app/src/routes/privacy.tsx +25 -0
  116. package/templates/app/src/styles/app.css +8 -1
  117. package/templates/app/tests/app.test.ts +44 -3
  118. package/templates/blog/package.json +1 -1
  119. package/templates/blog/src/routes/_layout.tsx +6 -1
  120. package/templates/blog/src/routes/index.tsx +1 -1
  121. package/templates/blog/src/styles/app.css +6 -1
  122. package/templates/fullstack/package.json +1 -1
  123. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  124. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  125. package/templates/fullstack/src/styles/app.css +11 -1
  126. package/templates/minimal/package.json +1 -1
  127. package/templates/minimal/src/routes/_layout.tsx +4 -0
  128. package/templates/minimal/src/styles/app.css +11 -1
@@ -110,6 +110,7 @@ async function discoverPluginRoutes(
110
110
  assetPrefix,
111
111
  site,
112
112
  dev: false,
113
+ devExposed: false,
113
114
  trustProxy: config.trustProxy ?? false,
114
115
  trustedOrigins: config.trustedOrigins ?? [],
115
116
  config: runtimeConfig,
@@ -122,7 +123,7 @@ async function discoverPluginRoutes(
122
123
  else if (!methods.includes(upper))
123
124
  methods.push(upper)
124
125
  },
125
- rateLimiter: () => ({ hit: () => 0 }),
126
+ rateLimiter: () => ({ hit: () => 0, peek: () => 0 }),
126
127
  rewrite: () => {},
127
128
  provide: appCtx.provide,
128
129
  inject: appCtx.inject,
@@ -12,7 +12,7 @@ import { loadConfig, runWithFreshConfig } from '../plugins/load'
12
12
  import { checkProject, diagnosticData } from './check'
13
13
  import { discoverLlmsDocs, searchLlmsDocs } from './docs'
14
14
  import { inspectProject } from './inspect'
15
- import { renderUrl } from './render'
15
+ import { isReadOnlyRenderMethod, renderMethod, renderUrl } from './render'
16
16
 
17
17
  export interface McpToolAnnotations {
18
18
  title?: string | undefined
@@ -221,12 +221,12 @@ export function listPrunelleTools(): McpToolDefinition[] {
221
221
  },
222
222
  {
223
223
  name: 'render',
224
- description: 'Render a route or API endpoint in-process without binding a port or touching `dist/`.',
224
+ description: 'Render a route or API endpoint in-process without binding a port or touching `dist/`. A method other than GET, HEAD or OPTIONS runs real actions and requires `--allow-write`.',
225
225
  inputSchema: {
226
226
  type: 'object',
227
227
  properties: {
228
228
  url: { type: 'string', description: 'URL path (e.g. "/" or "/api/items?page=2") or full URL to render.' },
229
- method: { type: 'string', description: 'HTTP method (defaults to GET, or POST when body is set).' },
229
+ method: { type: 'string', description: 'HTTP method (defaults to GET, or POST when body is set; anything but GET, HEAD and OPTIONS requires `--allow-write`).' },
230
230
  body: { type: 'string', description: 'Request body string.' },
231
231
  headers: { description: 'Request headers as an object ({ name: value }) or array of "Name: Value" strings.' },
232
232
  cookies: { type: 'array', items: { type: 'string' }, description: 'Cookie entries ("name=value").' },
@@ -334,7 +334,7 @@ async function runBuildAnalyzeTool(ctx: PrunelleMcpContext, args: Record<string,
334
334
  rmSync(tempOutDir, { recursive: true, force: true })
335
335
  if (!cacheExisted && existsSync(cacheDir)) {
336
336
  const remaining = readdirSync(cacheDir)
337
- if (remaining.every(name => name === '.gitignore' || name.startsWith('brotli-')))
337
+ if (remaining.every(name => name === '.gitignore' || name === 'entries' || name.startsWith('brotli-')))
338
338
  rmSync(cacheDir, { recursive: true, force: true })
339
339
  }
340
340
  }
@@ -377,8 +377,10 @@ async function runRenderTool(ctx: PrunelleMcpContext, args: Record<string, unkno
377
377
  if (url === undefined || url.trim().length === 0)
378
378
  throw new Error('prunelle mcp: "url" is required and must be a non-empty string')
379
379
  const targetDir = resolveProjectPath(ctx.root, args.dir, 'dir')
380
- const method = optionalString(args, 'method')
381
380
  const body = optionalString(args, 'body')
381
+ const method = renderMethod(optionalString(args, 'method'), body)
382
+ if (!ctx.allowWrite && !isReadOnlyRenderMethod(method))
383
+ return errorResult(`Rendering a ${method} runs the app's actions and handlers, which may write: start \`prunelle mcp --allow-write\`, or render with GET.`)
382
384
  const headers = normalizeRenderHeaders(args.headers)
383
385
  const cookies = normalizeStringArray(args.cookies, 'cookies')
384
386
  const fresh = optionalBoolean(args, 'fresh') === true
package/src/cli/mcp.ts CHANGED
@@ -47,7 +47,7 @@ const SERVER_INSTRUCTIONS = [
47
47
  'Prunelle development MCP server.',
48
48
  'Read `prunelle://llms/*` resources or call `docs` for framework and plugin APIs.',
49
49
  'Use `check`, `inspect`, `build_analyze`, `render`, and `dev_errors` to verify and debug the app.',
50
- 'Tools that write build output (`build`, or `build_analyze` with `write: true` / `outDir`) require `--allow-write`.',
50
+ 'Tools that write build output (`build`, or `build_analyze` with `write: true` / `outDir`) and `render` with a method other than GET, HEAD or OPTIONS require `--allow-write`.',
51
51
  ].join(' ')
52
52
 
53
53
  function rpcError(id: string | number | null, code: number, message: string): JsonRpcResponse {
package/src/cli/new.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
4
4
  import { basename, dirname, join, resolve } from 'node:path'
5
5
  import pkg from '../../package.json' with { type: 'json' }
6
+ import { DEFAULT_DECLARATION_PATH, draftAccessibilityStatement } from '../a11y/declaration'
6
7
  import { isNotSourceDir, relPosix, walkFiles } from '../build/files'
7
8
 
8
9
  export type ScaffoldTemplate = 'minimal' | 'fullstack' | 'blog' | 'app'
@@ -18,24 +19,34 @@ const TEMPLATES_DIR = join(import.meta.dir, '../../templates')
18
19
  // npm leaves dotfiles like `.gitignore` out of a package, so the template stores them without the leading dot.
19
20
  const RENAMED: Record<string, string> = { 'gitignore': '.gitignore', 'mcp.json': '.mcp.json' }
20
21
 
21
- export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}): { root: string, files: string[] } {
22
+ // What a fresh `git init` leaves in a folder: it does not make the folder one with work in it.
23
+ const FRESH_REPO_ENTRIES = new Set(['.git'])
24
+
25
+ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}): { root: string, files: string[], overwritten: string[] } {
22
26
  const root = resolve(targetDir)
23
27
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'prunelle-app'
24
28
  const template: ScaffoldTemplate = options.template ?? 'minimal'
25
29
  const prunelleVersion = options.prunelleVersion ?? `^${pkg.version}`
26
30
 
27
- if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
31
+ if (existsSync(root) && readdirSync(root).some(entry => !FRESH_REPO_ENTRIES.has(entry)) && !options.force)
28
32
  throw new Error(`prunelle new: directory "${root}" is not empty (pass --force to overwrite)`)
29
33
 
30
34
  const written: string[] = []
35
+ const overwritten: string[] = []
31
36
  for (const dir of [join(TEMPLATES_DIR, '_shared'), join(TEMPLATES_DIR, template)]) {
32
37
  for (const abs of walkFiles(dir, { skipDir: isNotSourceDir, keep: entry => entry.isFile() })) {
33
38
  const rel = RENAMED[relPosix(dir, abs)] ?? relPosix(dir, abs)
34
39
  const text = readFileSync(abs, 'utf8').replaceAll('__APP_NAME__', name).replaceAll('__PRUNELLE_VERSION__', prunelleVersion)
40
+ if (existsSync(join(root, rel)))
41
+ overwritten.push(rel)
35
42
  mkdirSync(dirname(join(root, rel)), { recursive: true })
36
43
  writeFileSync(join(root, rel), text)
37
44
  written.push(rel)
38
45
  }
39
46
  }
40
- return { root, files: written }
47
+ // Drafted rather than copied, so it is dated on the day the app is made and never drifts from what `prunelle a11y --draft` writes.
48
+ if (existsSync(join(root, DEFAULT_DECLARATION_PATH)))
49
+ overwritten.push(DEFAULT_DECLARATION_PATH)
50
+ written.push(draftAccessibilityStatement({ root }).relativePath)
51
+ return { root, files: written, overwritten }
41
52
  }
package/src/cli/render.ts CHANGED
@@ -12,8 +12,6 @@ import { testApp } from '../test/index'
12
12
 
13
13
  const ABSOLUTE_URL_RE = /^https?:\/\//i
14
14
  const CONFIG_FILES = ['prunelle.config.ts', 'prunelle.config.js', 'prunelle.config.mjs'] as const
15
- const CUSTOM_ROUTES_DIR_RE = /\broutesDir\s*:\s*['"]([^'"]+)['"]/
16
- const CUSTOM_PUBLIC_DIR_RE = /\bpublicDir\s*:\s*['"]([^'"]+)['"]/
17
15
  const SAFE_ORIGIN_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
18
16
  const RENDER_LOCK_STALE_MS = 120_000
19
17
  const RENDER_LOCK_TIMEOUT_MS = 60_000
@@ -161,19 +159,6 @@ async function collectSourceInputs(root: string): Promise<{ dirs: string[], file
161
159
  resolve(root, 'messages'),
162
160
  ])
163
161
  const files = new Set<string>()
164
- for (const file of CONFIG_FILES) {
165
- const full = join(root, file)
166
- if (!existsSync(full))
167
- continue
168
- const text = readFileSync(full, 'utf8')
169
- const routesMatch = CUSTOM_ROUTES_DIR_RE.exec(text)
170
- if (routesMatch?.[1] !== undefined)
171
- dirs.add(resolve(root, routesMatch[1]))
172
- const publicMatch = CUSTOM_PUBLIC_DIR_RE.exec(text)
173
- if (publicMatch?.[1] !== undefined)
174
- dirs.add(resolve(root, publicMatch[1]))
175
- }
176
-
177
162
  try {
178
163
  const config = await loadConfig(root)
179
164
  if (config.routesDir !== undefined)
@@ -192,7 +177,7 @@ async function collectSourceInputs(root: string): Promise<{ dirs: string[], file
192
177
  }
193
178
  }
194
179
  catch {
195
- // Broken configs will be surfaced cleanly by build(); fall back to static directory scan for the stamp.
180
+ // Broken configs will be surfaced cleanly by build(); fall back to the default directories for the stamp.
196
181
  return { dirs: [...dirs], files: [...files] }
197
182
  }
198
183
 
@@ -302,13 +287,23 @@ function extractResponseHeaders(res: Response): { headers: Record<string, string
302
287
  return { headers, setCookies }
303
288
  }
304
289
 
290
+ /** The method `renderUrl` sends: `method` upper-cased, else POST with a body and GET without. */
291
+ export function renderMethod(method: string | undefined, body: string | undefined): string {
292
+ if (method !== undefined && method.trim().length > 0)
293
+ return method.trim().toUpperCase()
294
+ return body !== undefined ? 'POST' : 'GET'
295
+ }
296
+
297
+ /** Whether a render with `method` only reads: GET, HEAD or OPTIONS. */
298
+ export function isReadOnlyRenderMethod(method: string): boolean {
299
+ return SAFE_ORIGIN_METHODS.has(method)
300
+ }
301
+
305
302
  /** Renders a URL against the Prunelle app under `options.root` in-process, reusing a cached build under `.prunelle-cache/render-build` when sources are unchanged. */
306
303
  export async function renderUrl(options: RenderUrlOptions): Promise<RenderUrlResult> {
307
304
  const root = resolve(options.root)
308
305
  const targetUrl = normalizeTargetUrl(options.url)
309
- const method = options.method !== undefined && options.method.trim().length > 0
310
- ? options.method.trim().toUpperCase()
311
- : (options.body !== undefined ? 'POST' : 'GET')
306
+ const method = renderMethod(options.method, options.body)
312
307
  const headers = buildRequestHeaders(options.headers, options.cookies, method, targetUrl)
313
308
 
314
309
  const cacheRoot = join(root, '.prunelle-cache')
@@ -36,8 +36,14 @@ const WIRE_RULES: [RegExp, string][] = [
36
36
  [/\bkay:(consent|navigate|region)\b/g, 'pru:$1'],
37
37
  [/\bkay_(session|consent)\b/g, 'pru_$1'],
38
38
  ]
39
- // The kay CLI run as a command; the PATH_RULES run first, so `kay.config` and `.kay-cache` are gone by then.
39
+ // The kay CLI in a script or the agent instructions, which name nothing else kay; the PATH_RULES run first, so `kay.config` and `.kay-cache` are gone by then.
40
40
  const CLI_RULE: [RegExp, string] = [/(?<![\w.@/-])kay(?![\w.:/-])/g, 'prunelle']
41
+ // The kay CLI where a build or CI file runs it, after a runner or before one of its commands, so a user or a runner label named kay stays (#142).
42
+ const KAY_COMMAND = String.raw`(?:new|check|inspect|docs|render|mcp|dev|build|eco|start|upgrade|test|[a-z]+-[a-z-]+)(?![\w:-])`
43
+ const RUN_CLI_RULES: [RegExp, string][] = [
44
+ [/(?<=\b(?:bunx|npx|bun(?:\s+(?:x|run))?)\s+|"bunx",\s*")kay(?![\w.:/-])/g, 'prunelle'],
45
+ [new RegExp(String.raw`(?<![\w.@/-])kay(?=(?:\s+|",\s*")${KAY_COMMAND})`, 'g'), 'prunelle'],
46
+ ]
41
47
 
42
48
  const SOURCE_FILE_RE = /\.(?:tsx?|mts)$/
43
49
  const STYLE_OR_SCRIPT_RE = /\.(?:css|js|mjs)$/
@@ -55,6 +61,14 @@ const GITIGNORE_CACHE_RE = /(?:^|\/)\.prunelle-cache(?:\/|$|\s)/m
55
61
 
56
62
  const apply = (text: string, rules: readonly [RegExp, string][]): string => rules.reduce((out, [re, to]) => out.replace(re, to), text)
57
63
 
64
+ /** Why `root` is no app to upgrade: neither on kay nor prunelle, nor a workspace holding one; undefined when it is one. */
65
+ export function notAnApp(root: string): string | undefined {
66
+ if (hasKayOrPrunelle(root) || existsSync(join(root, 'kay.config.ts')) || existsSync(join(root, 'prunelle.config.ts')) || workspaceMembers(root).some(m => hasKayOrPrunelle(join(root, m))))
67
+ return undefined
68
+ const manifest = existsSync(join(root, 'package.json')) ? 'its package.json names neither @kayjs/kay nor prunelle' : 'it has no package.json'
69
+ return `${root} is not a kay v2 app: ${manifest}, and it has no kay.config.ts`
70
+ }
71
+
58
72
  /** Rewrites the app at `root` in place, and each package its bun workspace lists; installing the renamed dependencies is the caller's job. */
59
73
  export function upgradeProject(root: string): UpgradeResult {
60
74
  return upgradeDir(root)
@@ -85,16 +99,18 @@ function upgradeDir(root: string, inheritedAliases?: ReadonlyMap<string, string>
85
99
  write(file, text, upgradeGitignore(text, isApp))
86
100
  else if (CONFIG_FILE_RE.test(file))
87
101
  write(file, text, apply(text, PATH_RULES))
88
- else if (BUILD_FILE_RE.test(file) || AGENT_FILE_RE.test(file))
102
+ else if (BUILD_FILE_RE.test(file))
103
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
104
+ else if (AGENT_FILE_RE.test(file))
89
105
  write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
90
106
  }
91
107
  for (const dir of CI_DIRS) {
92
108
  if (!existsSync(join(root, dir)))
93
109
  continue
94
- for (const name of readdirSync(join(root, dir)).sort()) {
110
+ for (const name of readdirSync(join(root, dir), { withFileTypes: true }).filter(e => e.isFile()).map(e => e.name).sort()) {
95
111
  const file = `${dir}/${name}`
96
112
  const text = readFileSync(join(root, file), 'utf8')
97
- write(file, text, apply(apply(text, PATH_RULES), [CLI_RULE]))
113
+ write(file, text, apply(apply(text, PATH_RULES), RUN_CLI_RULES))
98
114
  }
99
115
  }
100
116
  const publicDir = configuredPublicDir(root)
@@ -272,7 +288,8 @@ function sourceFiles(root: string, publicDir: string, dir = root, out: string[]
272
288
  if (resolve(path) !== publicDir)
273
289
  sourceFiles(root, publicDir, path, out)
274
290
  }
275
- else if (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name)) {
291
+ // A link is skipped: its target may lie outside the app, or be a file the app reaches twice.
292
+ else if (entry.isFile() && (SOURCE_FILE_RE.test(entry.name) || STYLE_OR_SCRIPT_RE.test(entry.name))) {
276
293
  out.push(relPosix(root, path))
277
294
  }
278
295
  }
@@ -11,11 +11,13 @@ import { checkBrowserGlobals } from './browser-globals'
11
11
  import { parseCacheExport } from './cacheability'
12
12
  import { analyzeDefaultDataKeys } from './data-keys'
13
13
  import { checkCompliance } from './compliance'
14
+ import { assertNoForeignImport } from './foreign-imports'
14
15
  import { resolveInteractivity } from './interactivity'
15
16
  import { findNodeEnvReads } from './node-env'
16
- import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
17
+ import { assertNoKayImport, checkExportHydrate, checkHabits, checkHydrateMode, checkMistakes, frontmatterMistake, guarded, islandRemoved, PrunelleMistake, mistake, serverOnlyTagError, staticStringValue } from './mistakes'
17
18
  import { walkScoped } from './scope'
18
19
  import { calleeName, createExprContext, decodeHtmlEntities, EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
20
+ import { checkBodyPropsDestructure } from './props-body'
19
21
  import { checkBareSignals } from './signal-reads'
20
22
 
21
23
  const REACTIVE_IMPORTS = new Set(['signal', 'computed', 'effect', 'onMount', 'onCleanup', 'selector', 'store', 'useAction'])
@@ -24,8 +26,8 @@ const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
24
26
  const PRUNELLE_SOURCES = new Set(['prunelle'])
25
27
  const PRUNELLE_SSR_SOURCES = new Set(['prunelle', 'prunelle/internal/ssr'])
26
28
  const PRUNELLE_SERVER_SOURCES = new Set(['prunelle/server'])
27
- const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'createContext', 'provideContext', 'useContext', 'useId'])
28
- const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate'])
29
+ const RENDER_CONTEXT_IMPORTS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'createContext', 'provideContext', 'useContext', 'useId'])
30
+ const SERVER_ONLY_TAGS = new Set(['Head', 'Region', 'Suspense', 'ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
29
31
 
30
32
  export interface ImportInfo {
31
33
  source: string
@@ -142,10 +144,15 @@ function decodeAttributeEntities(program: Program): void {
142
144
  })
143
145
  }
144
146
 
147
+ const FRONTMATTER_RE = /^\s*---[ \t]*\r?\n/
148
+
145
149
  export function parseTsx(filename: string, code: string): Program {
146
150
  const lang = /\.[cm]?ts$/i.test(filename) ? 'ts' : 'tsx'
147
151
  const result = parseSync(filename, code, { lang, sourceType: 'module' })
148
152
  if (result.errors.length > 0) {
153
+ const frontmatter = FRONTMATTER_RE.exec(code)
154
+ if (frontmatter !== null)
155
+ throw frontmatterMistake(filename, frontmatter[0].indexOf('---'))
149
156
  const first = result.errors[0]!
150
157
  const label = first.labels?.[0]
151
158
  const offset = label?.start ?? 0
@@ -250,6 +257,7 @@ function scanImports(program: Program, filename: string): ImportScan {
250
257
  }
251
258
 
252
259
  function scanPrunelleImport(scan: ImportScan, source: string, imported: string, local: string, filename: string, start: number): void {
260
+ guarded(start, () => assertNoForeignImport(source, imported, filename))
253
261
  if (PRUNELLE_SOURCES.has(source)) {
254
262
  if (REACTIVE_IMPORTS.has(imported))
255
263
  scan.reactiveLocals.set(local, `uses ${imported}`)
@@ -589,6 +597,14 @@ export function getExprContext(analysis: ModuleAnalysis): ExprContext {
589
597
  return ctx
590
598
  }
591
599
 
600
+ // An island page whose reads of `data` the compiler cannot follow ships the whole `load()` result, personal data it never shows included.
601
+ function wholeLoadShippedWarning(filename: string, start: number): CompilerWarning {
602
+ return {
603
+ start,
604
+ message: `prunelle compiler: the island page in ${filename} uses \`data\` in a way the compiler cannot follow, so the whole load() result is sent to the browser: export \`clientData\` listing the keys the page reads (\`export const clientData = ['title']\`), or \`(data) => data\` to send all of it on purpose.`,
605
+ }
606
+ }
607
+
592
608
  export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
593
609
  const imports = scanImports(program, filename)
594
610
  const decls = scanDeclarations(program, filename, imports)
@@ -596,6 +612,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
596
612
  const loadNodes = loadDeclarations(program)
597
613
  const body = scanBody(program, filename, code, imports, decls, warnings, new Set(loadNodes))
598
614
  checkBareSignals(program, imports.signalCallees, filename)
615
+ checkBodyPropsDestructure(program, code, body.bindings, filename, warnings)
599
616
  const jsxNodes = body.hasJsx ? computeJsxNodes(program) : new WeakSet<Node>()
600
617
  if (body.hasJsx) {
601
618
  checkCompliance(program, filename, code, warnings, tag => resolvePrunelleTag(tag, imports.imports))
@@ -615,13 +632,17 @@ export function analyzeModule(filename: string, code: string, program: Program =
615
632
  guarded(interactivity.serverOnly.offset, () => { throw serverOnlyTagError(filename, interactivity.serverOnly!) })
616
633
 
617
634
  const cacheExport = parseCacheExport(program)
635
+ const hasLoadExport = decls.hasLoadExport || loadNodes.length > 0
636
+ const defaultDataKeys = page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined
637
+ if (page?.interactive === true && hasLoadExport && defaultDataKeys === undefined && !decls.exportedNames.includes('clientData'))
638
+ warnings.push(wholeLoadShippedWarning(filename, decls.localInits.get(decls.defaultLocal ?? '')?.start ?? page.offset ?? 0))
618
639
  return {
619
640
  filename,
620
641
  program,
621
642
  warnings,
622
643
  ...interactivity,
623
644
  hasAsyncDefault,
624
- hasLoadExport: decls.hasLoadExport || loadNodes.length > 0,
645
+ hasLoadExport,
625
646
  hasJsx: body.hasJsx,
626
647
  jsxNodes,
627
648
  hasPrerender: decls.hasPrerender,
@@ -636,7 +657,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
636
657
  asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get('default') ?? 'default']) : decls.asyncLocals,
637
658
  stateExports: stateExportsOf(decls, imports.stateCallees, true),
638
659
  signalExports: stateExportsOf(decls, imports.signalCallees, false),
639
- defaultDataKeys: page?.interactive === true ? analyzeDefaultDataKeys(program, decls.defaultLocal, decls.localInits) : undefined,
660
+ defaultDataKeys,
640
661
  exportedActions: decls.exportedActions,
641
662
  imports: imports.imports,
642
663
  dynamicImports: body.dynamicImports,
@@ -16,8 +16,8 @@ const PRIVATE_SERVER_IMPORTS = new Set(['getActionError', 'currentRequest'])
16
16
  const PRIVATE_HEADERS = new Set(['cookie', 'authorization'])
17
17
  const DYNAMIC_IMPORTS = new Set(['bun:sqlite', 'node:sqlite', 'sqlite', 'bun:sql'])
18
18
  const SYNC_IO_CALLEES = new Set(['readFileSync', 'readdirSync', 'statSync', 'lstatSync', 'existsSync', 'accessSync'])
19
- const DYNAMIC_TAGS = new Set(['ConsentGate', 'Suspense'])
20
- const PRIVATE_TAGS = new Set(['ConsentGate'])
19
+ const DYNAMIC_TAGS = new Set(['ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Suspense'])
20
+ const PRIVATE_TAGS = new Set(['ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
21
21
  const CLIENT_CALLBACK_CALLEES = new Set(['onMount', 'effect', 'onCleanup'])
22
22
  const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', 'TSInstantiationExpression'])
23
23
 
@@ -0,0 +1,71 @@
1
+ // Static RGESN (eco-design) checks: media that plays on its own, images the browser cannot size, and heavy files in public/.
2
+
3
+ import type { JSXAttribute, JSXElement } from 'oxc-parser'
4
+ import type { CompilerWarning } from './mistakes'
5
+ import { statSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { relPosix, walkFiles } from '../build/files'
8
+ import { findAttr, hasSpread, staticStringValueOf } from './compliance-rgaa'
9
+ import { formatDiagnostic, unwrapTsExpr } from './shared'
10
+
11
+ export const ECO_JSX_RULES = ['rgesn/autoplay', 'rgesn/img-size', 'rgesn/img-sizes'] as const
12
+
13
+ export type EcoJsxRule = (typeof ECO_JSX_RULES)[number]
14
+
15
+ export interface EcoElementContext {
16
+ filename: string
17
+ isIgnored: (rule: EcoJsxRule, elementStart: number, attrStart?: number) => boolean
18
+ warnings: CompilerWarning[]
19
+ }
20
+
21
+ // Past this size a file in public/ is worth a second look: a photo straight from a camera, a video, an uncompressed export.
22
+ export const LARGE_PUBLIC_FILE_BYTES = 1_000_000
23
+ const WIDTH_DESCRIPTOR_RE = /\s\d+w\s*(?:,|$)/
24
+
25
+ // `autoplay`, `autoplay={true}` and `autoplay="..."` turn it on; `autoplay={false}` and a dynamic value are left to the app.
26
+ function isOn(attr: JSXAttribute): boolean {
27
+ if (attr.value === null || attr.value.type === 'Literal')
28
+ return true
29
+ if (attr.value.type !== 'JSXExpressionContainer' || attr.value.expression.type === 'JSXEmptyExpression')
30
+ return false
31
+ const expr = unwrapTsExpr(attr.value.expression)
32
+ return expr.type === 'Literal' && expr.value === true
33
+ }
34
+
35
+ function emit(ctx: EcoElementContext, rule: EcoJsxRule, start: number, message: string, attrStart?: number): void {
36
+ if (!ctx.isIgnored(rule, start, attrStart))
37
+ ctx.warnings.push({ rule, start: attrStart ?? start, message })
38
+ }
39
+
40
+ export function checkEcoElement(element: JSXElement, tag: string, ctx: EcoElementContext): void {
41
+ const attrs = element.openingElement.attributes
42
+ if (tag === 'video' || tag === 'audio') {
43
+ const autoplay = findAttr(attrs, 'autoplay') ?? findAttr(attrs, 'autoPlay')
44
+ if (autoplay !== undefined && isOn(autoplay))
45
+ emit(ctx, 'rgesn/autoplay', element.start, `[rgesn/autoplay] <${tag} autoplay> in ${ctx.filename} downloads and plays its media before anyone asks for it: drop autoplay, let the visitor press play, and set preload="none" (or "metadata").`, autoplay.start)
46
+ return
47
+ }
48
+ if (tag !== 'img' && tag !== 'source')
49
+ return
50
+ const srcset = findAttr(attrs, 'srcset') ?? findAttr(attrs, 'srcSet')
51
+ const candidates = srcset === undefined ? undefined : staticStringValueOf(srcset.value)
52
+ if (srcset !== undefined && candidates !== undefined && WIDTH_DESCRIPTOR_RE.test(candidates) && findAttr(attrs, 'sizes') === undefined)
53
+ emit(ctx, 'rgesn/img-sizes', element.start, `[rgesn/img-sizes] <${tag} srcset> in ${ctx.filename} lists widths but no sizes, so the browser assumes the image fills the viewport and fetches the widest file: add sizes="..." with the width it is shown at (e.g. sizes="(min-width: 60rem) 40rem, 100vw").`, srcset.start)
54
+ if (tag === 'img' && !hasSpread(attrs) && (findAttr(attrs, 'width') === undefined || findAttr(attrs, 'height') === undefined))
55
+ emit(ctx, 'rgesn/img-size', element.start, `[rgesn/img-size] <img> in ${ctx.filename} has no width and height, so the browser cannot reserve its box and the page shifts as it loads: give its intrinsic width and height, or use <Img> from @prunellejs/images, which sets them.`)
56
+ }
57
+
58
+ /** Warns on each file in `public/` past 1 MB, which every visitor showing it downloads as is. */
59
+ export function largePublicFileWarnings(root: string, isIgnored: boolean): string[] {
60
+ if (isIgnored)
61
+ return []
62
+ const warnings: string[] = []
63
+ for (const file of walkFiles(join(root, 'public'), { keep: entry => entry.isFile() }).sort()) {
64
+ const size = statSync(file).size
65
+ if (size > LARGE_PUBLIC_FILE_BYTES) {
66
+ const rel = relPosix(root, file)
67
+ warnings.push(formatDiagnostic(`${rel}:1:1`, `[rgesn/large-public-file] ${rel} weighs ${(size / 1_000_000).toFixed(1)} MB and is served as is: compress it, resize an image with @prunellejs/images, or host a video on a streaming service behind <ConsentGate>.`, 'warning'))
68
+ }
69
+ }
70
+ return warnings
71
+ }
@@ -21,6 +21,11 @@ export const RGAA_JSX_RULES = [
21
21
  'rgaa/click-without-key',
22
22
  'rgaa/autofocus',
23
23
  'rgaa/meta-refresh',
24
+ 'rgaa/role-without-focus',
25
+ 'rgaa/mouse-only',
26
+ 'rgaa/frame-title',
27
+ 'rgaa/empty-heading',
28
+ 'rgaa/autocomplete',
24
29
  ] as const
25
30
 
26
31
  export type RgaaJsxRule = (typeof RGAA_JSX_RULES)[number]
@@ -32,6 +37,18 @@ const NATIVE_CLICKABLE_TAGS = new Set(['a', 'button', 'input', 'select', 'textar
32
37
  const TABLE_STRUCTURAL_TAGS = new Set(['thead', 'tbody', 'tfoot', 'tr'])
33
38
  const HEADING_LEVELS: Record<string, number> = { h1: 1, h2: 2, h3: 3, h4: 4, h5: 5, h6: 6 }
34
39
  const PRESENTATIONAL_ROLES = new Set(['presentation', 'none'])
40
+ // Roles a user operates directly, so the element needs a tabindex to be reached from the keyboard.
41
+ const FOCUSABLE_ROLES = new Set(['button', 'link', 'checkbox', 'switch', 'radio', 'slider', 'spinbutton', 'textbox', 'searchbox', 'combobox', 'tab'])
42
+ // Items of a composite widget, moved through with arrow keys: hovering them to highlight is not hover-only behaviour.
43
+ const COMPOSITE_ITEM_ROLES = new Set(['option', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'treeitem', 'gridcell', 'row', 'tab'])
44
+ // Field names that collect personal data, normalized (lowercase, no `-` or `_`), with the autocomplete token they need (RGAA 11.13).
45
+ const AUTOCOMPLETE_BY_NAME = new Map(Object.entries({
46
+ email: 'email', tel: 'tel', phone: 'tel', name: 'name', fullname: 'name',
47
+ givenname: 'given-name', firstname: 'given-name', familyname: 'family-name', lastname: 'family-name', surname: 'family-name',
48
+ address: 'street-address', streetaddress: 'street-address', postalcode: 'postal-code', zip: 'postal-code', zipcode: 'postal-code', postcode: 'postal-code',
49
+ city: 'address-level2', country: 'country-name', username: 'username', organization: 'organization',
50
+ }))
51
+ const NAME_SEPARATORS_RE = /[-_]/g
35
52
  const INT_RE = /^-?\d+$/
36
53
  const NUM_RE = /^-?(?:\d+\.?\d*|\.\d+)$/
37
54
  const TABINDEX_NUM_RE = /^[+-]?\d+(?:\.\d+)?$/
@@ -155,13 +172,27 @@ export function attrTargetKey(attr: JSXAttribute | undefined): string | undefine
155
172
  if (str !== undefined && str.trim() !== '')
156
173
  return `s:${str}`
157
174
  if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
158
- const expr = unwrapTsExpr(attr.value.expression)
159
- if (expr.type === 'Identifier')
160
- return `i:${expr.name}`
175
+ const path = staticPath(attr.value.expression)
176
+ if (path !== undefined)
177
+ return `i:${path}`
161
178
  }
162
179
  return undefined
163
180
  }
164
181
 
182
+ // `ids`, `ids.name` and `ids['name']` as one dotted path, so `for` and `id` holding the same expression match.
183
+ function staticPath(node: Node): string | undefined {
184
+ const expr = unwrapTsExpr(node)
185
+ if (expr.type === 'Identifier')
186
+ return expr.name
187
+ if (expr.type !== 'MemberExpression')
188
+ return undefined
189
+ const object = staticPath(expr.object)
190
+ const property = !expr.computed && expr.property.type === 'Identifier'
191
+ ? expr.property.name
192
+ : expr.property.type === 'Literal' && typeof expr.property.value === 'string' ? expr.property.value : undefined
193
+ return object !== undefined && property !== undefined ? `${object}.${property}` : undefined
194
+ }
195
+
165
196
  export function hasNonEmptyAttr(attributes: readonly JSXAttributeItem[], name: string): boolean {
166
197
  const attr = findAttr(attributes, name)
167
198
  if (attr === undefined || attr.value === null)
@@ -480,12 +511,82 @@ function checkStructureAndIdentity(element: JSXElement, tag: string, spread: boo
480
511
  }
481
512
  }
482
513
 
514
+ function hasHandler(attributes: readonly JSXAttributeItem[], names: readonly string[]): boolean {
515
+ return names.some((name) => {
516
+ const attr = findAttr(attributes, name)
517
+ return attr !== undefined && !isExplicitlyFalsyExpr(attr.value)
518
+ })
519
+ }
520
+
521
+ // Keyboard reach: an operable role without tabindex, hover-only handlers, and a link that goes nowhere.
522
+ function checkKeyboardReach(element: JSXElement, tag: string, ctx: RgaaElementContext): void {
523
+ const attrs = element.openingElement.attributes
524
+ const role = staticStringValueOf(findAttr(attrs, 'role')?.value ?? null)?.trim().split(/\s+/)[0]
525
+ if (role !== undefined && FOCUSABLE_ROLES.has(role) && !NATIVE_CLICKABLE_TAGS.has(tag) && findAttrLower(attrs, 'tabindex') === undefined)
526
+ emitWarning(ctx, 'rgaa/role-without-focus', element.start, `[rgaa/role-without-focus] <${tag} role="${role}"> in ${ctx.filename} cannot be reached from the keyboard: add tabIndex={0}, or use the native element (<button>, <a href>, <input>).`)
527
+
528
+ if (role === undefined || !COMPOSITE_ITEM_ROLES.has(role)) {
529
+ const enterOnly = hasHandler(attrs, ['onMouseEnter', 'onMouseOver']) && !hasHandler(attrs, ['onFocus', 'onFocusIn'])
530
+ const leaveOnly = hasHandler(attrs, ['onMouseLeave', 'onMouseOut']) && !hasHandler(attrs, ['onBlur', 'onFocusOut'])
531
+ if (enterOnly || leaveOnly) {
532
+ const pair = enterOnly ? 'onMouseEnter or onMouseOver with onFocus or onFocusIn' : 'onMouseLeave or onMouseOut with onBlur or onFocusOut'
533
+ emitWarning(ctx, 'rgaa/mouse-only', element.start, `[rgaa/mouse-only] <${tag}> in ${ctx.filename} reacts to the mouse only: pair ${pair}, so keyboard users get the same behaviour.`)
534
+ }
535
+ }
536
+
537
+ const href = tag === 'a' ? staticStringValueOf(findAttr(attrs, 'href')?.value ?? null)?.trim() : undefined
538
+ if (href === '#' || href?.toLowerCase().startsWith('javascript:') === true)
539
+ emitWarning(ctx, 'rgaa/link-as-button', element.start, `[rgaa/link-as-button] <a href="${href}"> in ${ctx.filename} goes nowhere: use <button type="button"> for an action, or link to a page or an #id.`)
540
+ }
541
+
542
+ // Elements whose name or content assistive tools read out: a frame, a heading, an SVG drawn as an image.
543
+ function checkMissingNames(element: JSXElement, tag: string, ctx: RgaaElementContext): void {
544
+ const attrs = element.openingElement.attributes
545
+ if (tag === 'iframe' && !isAriaHidden(attrs) && !hasLabelAttr(attrs))
546
+ emitWarning(ctx, 'rgaa/frame-title', element.start, `[rgaa/frame-title] <iframe> in ${ctx.filename} has no title: add title="..." naming what the frame holds.`)
547
+
548
+ if (HEADING_LEVELS[tag] !== undefined && !hasLabelAttr(attrs) && !hasAccessibleName(element.children))
549
+ emitWarning(ctx, 'rgaa/empty-heading', element.start, `[rgaa/empty-heading] <${tag}> in ${ctx.filename} is empty: give it text, or remove it.`)
550
+
551
+ const role = staticStringValueOf(findAttr(attrs, 'role')?.value ?? null)?.trim()
552
+ if (tag === 'svg' && role === 'img' && !isAriaHidden(attrs) && !hasAccessibleName([element]))
553
+ emitWarning(ctx, 'rgaa/accessible-name', element.start, `[rgaa/accessible-name] <svg role="img"> in ${ctx.filename} has no accessible name: add aria-label="..." or a <title> child.`)
554
+ }
555
+
556
+ // A field collecting personal data names its purpose, so browsers and assistive tools can fill it (RGAA 11.13).
557
+ function checkAutocomplete(element: JSXElement, tag: string, ctx: RgaaElementContext): void {
558
+ const attrs = element.openingElement.attributes
559
+ if ((tag !== 'input' && tag !== 'select') || findAttrLower(attrs, 'autocomplete') !== undefined)
560
+ return
561
+ const type = tag === 'input' ? (staticStringValueOf(findAttr(attrs, 'type')?.value ?? null)?.toLowerCase() ?? 'text') : 'text'
562
+ const name = staticStringValueOf(findAttr(attrs, 'name')?.value ?? null)
563
+ const token = type === 'email' || type === 'tel'
564
+ ? type
565
+ : type === 'text' && name !== undefined ? AUTOCOMPLETE_BY_NAME.get(name.toLowerCase().replace(NAME_SEPARATORS_RE, '')) : undefined
566
+ if (token !== undefined)
567
+ emitWarning(ctx, 'rgaa/autocomplete', element.start, `[rgaa/autocomplete] <${tag}${name !== undefined ? ` name="${name}"` : ''}> in ${ctx.filename} collects personal data without autocomplete: add autocomplete="${token}".`)
568
+ }
569
+
570
+ // The ui Select draws its own combobox, so it needs a name as a native <select> does.
571
+ const SELECT_COMPONENT_RE = /(?:^|\.)Select$/
572
+
573
+ /** Runs the RGAA checks that apply to a component: a `Select` with no label, id link or `ariaLabel`. */
574
+ export function checkRgaaComponent(element: JSXElement, tag: string, ctx: RgaaElementContext): void {
575
+ const attrs = element.openingElement.attributes
576
+ if (!SELECT_COMPONENT_RE.test(tag) || hasSpread(attrs) || ctx.inLabel || hasLabelAttr(attrs) || hasNonEmptyAttr(attrs, 'ariaLabel'))
577
+ return
578
+ const idKey = attrTargetKey(findAttr(attrs, 'id'))
579
+ if (idKey === undefined || !ctx.labelTargets.has(idKey))
580
+ emitWarning(ctx, 'rgaa/form-label', element.start, `[rgaa/form-label] <${tag}> in ${ctx.filename} has no accessible name: put it in <Field label="...">, link <label for="id">, or pass ariaLabel="...".`)
581
+ }
582
+
483
583
  /** Runs all static RGAA JSX compliance checks on an intrinsic HTML element. */
484
584
  export function checkRgaaElement(element: JSXElement, tag: string, ctx: RgaaElementContext): void {
485
585
  const attrs = element.openingElement.attributes
486
586
  const spread = hasSpread(attrs)
487
587
 
488
- if (tag === 'img' && !spread) {
588
+ // RGAA 1.2 accepts role="presentation" or aria-hidden as well as alt="" for a decorative image.
589
+ if (tag === 'img' && !spread && !isPresentational(attrs) && !isAriaHidden(attrs)) {
489
590
  const altAttr = findAttr(attrs, 'alt')
490
591
  if (altAttr === undefined || isExplicitlyFalsyExpr(altAttr.value))
491
592
  emitWarning(ctx, 'rgaa/img-alt', element.start, `[rgaa/img-alt] <img> in ${ctx.filename} is missing an alt attribute: add alt="description" or alt="" for decorative images.`, altAttr?.start)
@@ -505,4 +606,9 @@ export function checkRgaaElement(element: JSXElement, tag: string, ctx: RgaaElem
505
606
  checkRoleAndAria(element, tag, ctx)
506
607
  checkFocusAndInteraction(element, tag, spread, ctx)
507
608
  checkStructureAndIdentity(element, tag, spread, ctx)
609
+ if (!spread) {
610
+ checkKeyboardReach(element, tag, ctx)
611
+ checkMissingNames(element, tag, ctx)
612
+ checkAutocomplete(element, tag, ctx)
613
+ }
508
614
  }