prunelle 0.8.0 → 0.10.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 (209) hide show
  1. package/llms.txt +68 -51
  2. package/package.json +7 -2
  3. package/src/a11y/declaration.ts +10 -17
  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 +94 -136
  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 +14 -6
  14. package/src/build/index.ts +23 -11
  15. package/src/build/island-promote.ts +42 -2
  16. package/src/build/islands.ts +63 -9
  17. package/src/build/key-types.ts +31 -0
  18. package/src/build/manifest.ts +117 -1
  19. package/src/build/plugin-host.ts +13 -1
  20. package/src/build/prerender.ts +8 -3
  21. package/src/build/reach.ts +18 -4
  22. package/src/build/report.ts +1 -1
  23. package/src/build/resolve.ts +5 -1
  24. package/src/build/route-types.ts +16 -0
  25. package/src/build/routes.ts +42 -15
  26. package/src/build/seed-ids.ts +65 -0
  27. package/src/build/seed-writes.ts +111 -0
  28. package/src/build/static-headers.ts +2 -2
  29. package/src/build/static.ts +1 -1
  30. package/src/cli/check-cache.ts +51 -0
  31. package/src/cli/check-consent.ts +95 -0
  32. package/src/cli/check-forms.ts +10 -2
  33. package/src/cli/check-links-patterns.ts +101 -0
  34. package/src/cli/check-links.ts +30 -105
  35. package/src/cli/check-regions.ts +185 -0
  36. package/src/cli/check-security.ts +50 -6
  37. package/src/cli/check.ts +49 -21
  38. package/src/cli/commands.ts +138 -16
  39. package/src/cli/docs.ts +21 -2
  40. package/src/cli/form-opaque-children.ts +40 -0
  41. package/src/cli/index.ts +1 -1
  42. package/src/cli/inspect.ts +2 -0
  43. package/src/cli/mcp-tools.ts +2 -2
  44. package/src/cli/new.ts +9 -5
  45. package/src/cli/upgrade-names.ts +14 -2
  46. package/src/cli/upgrade.ts +3 -0
  47. package/src/compiler/analyze.ts +22 -16
  48. package/src/compiler/cacheability-private.ts +13 -3
  49. package/src/compiler/cacheability.ts +24 -2
  50. package/src/compiler/compliance-contrast.ts +322 -0
  51. package/src/compiler/compliance-empty.ts +24 -0
  52. package/src/compiler/compliance-rgaa-content.ts +95 -0
  53. package/src/compiler/compliance-rgaa-criteria.ts +45 -0
  54. package/src/compiler/compliance-rgaa-pages.ts +140 -0
  55. package/src/compiler/compliance-rgaa.ts +19 -0
  56. package/src/compiler/compliance-rules.ts +72 -0
  57. package/src/compiler/compliance-third-party.ts +59 -0
  58. package/src/compiler/compliance-urls.ts +52 -0
  59. package/src/compiler/compliance.ts +61 -93
  60. package/src/compiler/cookie-inventory.ts +119 -0
  61. package/src/compiler/dom-attrs.ts +178 -22
  62. package/src/compiler/dom.ts +31 -44
  63. package/src/compiler/emit.ts +17 -6
  64. package/src/compiler/expr-context.ts +260 -207
  65. package/src/compiler/foreign-imports.ts +5 -3
  66. package/src/compiler/mistakes.ts +18 -9
  67. package/src/compiler/props-body.ts +263 -21
  68. package/src/compiler/props-pattern.ts +211 -0
  69. package/src/compiler/props.ts +324 -343
  70. package/src/compiler/signal-reads.ts +142 -29
  71. package/src/compiler/spread-handlers.ts +25 -13
  72. package/src/compiler/ssr-emit.ts +510 -0
  73. package/src/compiler/ssr-helpers.ts +165 -121
  74. package/src/compiler/ssr.ts +28 -441
  75. package/src/context.ts +14 -1
  76. package/src/dev/child.ts +1 -1
  77. package/src/dev/host-check.ts +2 -1
  78. package/src/dev/hot-islands.ts +71 -0
  79. package/src/dev/index.ts +31 -18
  80. package/src/dev/protocol.ts +1 -1
  81. package/src/dev/queue.ts +3 -2
  82. package/src/dev/reload.ts +5 -2
  83. package/src/dev/supervisor.ts +3 -1
  84. package/src/dev/watchers.ts +6 -2
  85. package/src/dom/action.ts +97 -14
  86. package/src/dom/attrs.ts +93 -25
  87. package/src/dom/extras.ts +91 -50
  88. package/src/dom/field-marks.ts +32 -0
  89. package/src/dom/hot.ts +9 -0
  90. package/src/dom/index.ts +44 -18
  91. package/src/dom/island-hot.ts +29 -0
  92. package/src/dom/island.ts +13 -2
  93. package/src/dom/loop.ts +259 -188
  94. package/src/dom/prefetch.ts +135 -0
  95. package/src/dom/regions.ts +515 -0
  96. package/src/dom/swap.ts +246 -0
  97. package/src/dom/trusted.ts +22 -0
  98. package/src/dom/upload.ts +44 -0
  99. package/src/eco/declaration.ts +44 -41
  100. package/src/eco/index.ts +8 -5
  101. package/src/href.ts +31 -0
  102. package/src/index.ts +12 -5
  103. package/src/plugins/config.ts +1 -1
  104. package/src/plugins/context.ts +7 -1
  105. package/src/plugins/daily.ts +27 -0
  106. package/src/plugins/index.ts +3 -3
  107. package/src/plugins/order.ts +1 -1
  108. package/src/plugins/public.ts +12 -5
  109. package/src/plugins/services.ts +88 -14
  110. package/src/plugins/types.ts +128 -10
  111. package/src/reactivity/graph.ts +244 -41
  112. package/src/reactivity/hmr.ts +101 -0
  113. package/src/reactivity/index.ts +243 -239
  114. package/src/reactivity/resource.ts +129 -0
  115. package/src/reactivity/seed.ts +141 -0
  116. package/src/reactivity/selector.ts +85 -47
  117. package/src/reactivity/server-seed.ts +202 -0
  118. package/src/reactivity/store.ts +331 -97
  119. package/src/rgpd/draft.ts +171 -0
  120. package/src/rgpd/forms.ts +85 -0
  121. package/src/rgpd/index.ts +57 -0
  122. package/src/server/action-flash.ts +1 -0
  123. package/src/server/action-protect.ts +3 -0
  124. package/src/server/action-registry.ts +11 -9
  125. package/src/server/action.ts +51 -19
  126. package/src/server/app-secret.ts +14 -8
  127. package/src/server/cache-invalidation.ts +97 -0
  128. package/src/server/compress.ts +55 -18
  129. package/src/server/consent.ts +21 -5
  130. package/src/server/cookie-inventory.ts +78 -0
  131. package/src/server/cookies.ts +77 -8
  132. package/src/server/cors.ts +98 -0
  133. package/src/server/csp-report.ts +90 -0
  134. package/src/server/discard.ts +13 -0
  135. package/src/server/document.ts +2 -2
  136. package/src/server/env.ts +1 -1
  137. package/src/server/errors.ts +9 -2
  138. package/src/server/field-errors.ts +91 -0
  139. package/src/server/form-schema.ts +16 -11
  140. package/src/server/health.ts +41 -11
  141. package/src/server/http.ts +28 -11
  142. package/src/server/index.ts +122 -307
  143. package/src/server/loader.ts +2 -0
  144. package/src/server/page.ts +3 -9
  145. package/src/server/plugin-host.ts +66 -16
  146. package/src/server/plugin-route-shadow.ts +24 -0
  147. package/src/server/public.ts +14 -3
  148. package/src/server/rate-limit.ts +49 -10
  149. package/src/server/region.ts +22 -2
  150. package/src/server/request-handler.ts +406 -0
  151. package/src/server/request-log.ts +94 -0
  152. package/src/server/route-cache.ts +55 -8
  153. package/src/server/route-input.ts +54 -0
  154. package/src/server/route-table.ts +53 -27
  155. package/src/server/router.ts +2 -1
  156. package/src/server/routing.ts +104 -45
  157. package/src/server/sanitize-html.ts +4 -2
  158. package/src/server/security.ts +38 -8
  159. package/src/server/serve-handlers.ts +16 -6
  160. package/src/server/served-file.ts +19 -14
  161. package/src/server/shared-store.ts +323 -0
  162. package/src/server/start.ts +12 -5
  163. package/src/server/static-dir.ts +34 -12
  164. package/src/server/stream.ts +2 -1
  165. package/src/server/surface.ts +39 -0
  166. package/src/server/webhook.ts +50 -0
  167. package/src/server/workers.ts +168 -0
  168. package/src/ssr/consent-banner.ts +20 -16
  169. package/src/ssr/consent-texts.ts +40 -0
  170. package/src/ssr/context.ts +174 -53
  171. package/src/ssr/cookie-table.ts +75 -0
  172. package/src/ssr/index.ts +63 -58
  173. package/src/ssr/navigation.ts +161 -14
  174. package/src/ssr/region.ts +9 -3
  175. package/src/style.ts +12 -5
  176. package/src/test/browser.ts +53 -23
  177. package/src/test/build-reuse.ts +85 -0
  178. package/src/test/index.ts +51 -8
  179. package/src/test/mount.ts +53 -0
  180. package/src/test/outside.ts +94 -0
  181. package/src/ts-plugin/diagnostics.ts +56 -18
  182. package/templates/_shared/AGENTS.md +1 -1
  183. package/templates/_shared/Dockerfile +22 -0
  184. package/templates/_shared/dockerignore +9 -0
  185. package/templates/_shared/gitignore +2 -0
  186. package/templates/app/.env.example +3 -1
  187. package/templates/app/compose.yaml +32 -0
  188. package/templates/app/db/migrations/001_notes.sql +7 -0
  189. package/templates/app/db/schema.ts +11 -0
  190. package/templates/app/package.json +1 -0
  191. package/templates/app/prunelle.config.ts +6 -0
  192. package/templates/app/src/actions/notes.ts +26 -0
  193. package/templates/app/src/auth.ts +4 -2
  194. package/templates/app/src/db.ts +5 -0
  195. package/templates/app/src/routes/dashboard/index.tsx +26 -1
  196. package/templates/app/src/routes/privacy.tsx +6 -2
  197. package/templates/app/tests/app.test.ts +14 -3
  198. package/templates/plugin/AGENTS.md +11 -0
  199. package/templates/plugin/CLAUDE.md +1 -0
  200. package/templates/plugin/README.md +27 -0
  201. package/templates/plugin/gitignore +2 -0
  202. package/templates/plugin/llms.txt +19 -0
  203. package/templates/plugin/package.json +33 -0
  204. package/templates/plugin/src/index.ts +40 -0
  205. package/templates/plugin/tests/fixture/prunelle.config.ts +4 -0
  206. package/templates/plugin/tests/fixture/src/routes/index.tsx +11 -0
  207. package/templates/plugin/tests/plugin.test.ts +42 -0
  208. package/templates/plugin/tsconfig.json +19 -0
  209. package/ts-plugin.cjs +4058 -2246
@@ -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
- const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store'])
27
+ const STATE_PRIMITIVES = new Set(['signal', 'computed', 'selector', 'store', 'resource'])
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
@@ -63,7 +63,8 @@ export interface ModuleAnalysis extends Interactivity {
63
63
  hasPaths: boolean
64
64
  usesRenderContext: boolean
65
65
  defaultHydrate: string | undefined
66
- deferredIslandTags: Set<string>
66
+ /** Per component tag, the `$hydrate` modes of its uses (`''` for a use with none, which takes the island file's own mode). */
67
+ hydrateUses: Map<string, Set<string>>
67
68
  /** `$hydrate` modes the module writes; `*` stands for one computed at runtime. */
68
69
  hydrateModes: Set<string>
69
70
  /** Component tags the module renders, `NS.Tag` included. */
@@ -267,7 +268,7 @@ function scanPrunelleImport(scan: ImportScan, source: string, imported: string,
267
268
  guarded(start, () => { throw islandRemoved(filename, start) })
268
269
  if (STATE_PRIMITIVES.has(imported))
269
270
  scan.stateCallees.add(local)
270
- if (imported === 'signal' || imported === 'computed')
271
+ if (imported === 'signal' || imported === 'computed' || imported === 'resource')
271
272
  scan.signalCallees.add(local)
272
273
  if (imported === 'effect')
273
274
  scan.effectCallees.add(local)
@@ -308,10 +309,10 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
308
309
  scan.localInits.set(d.id.name, d.init)
309
310
  }
310
311
  }
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
+ // `import X from './x'; export default X` (or `export { X }`, or `export const Y = X`) re-exports './x', so islands and state behind it are followed like `export { default } from './x'`; a namespace import follows like `export * as X from './x'`.
312
313
  const reexportImported = (exported: string, local: string, start: number): void => {
313
314
  for (const imp of imports.imports) {
314
- const spec = imp.specifiers.find(s => s.local === local && s.imported !== '*')
315
+ const spec = imp.specifiers.find(s => s.local === local)
315
316
  if (spec !== undefined) {
316
317
  scan.reexports.push({ exported, local: spec.imported, source: imp.source, start })
317
318
  return
@@ -337,7 +338,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
337
338
  }
338
339
  else if (stmt.type === 'ExportAllDeclaration') {
339
340
  if (stmt.exportKind !== 'type')
340
- scan.reexports.push({ exported: '*', local: '*', source: stmt.source.value, start: stmt.start })
341
+ scan.reexports.push({ exported: (stmt.exported === null ? undefined : exportedName(stmt.exported)) ?? '*', local: '*', source: stmt.source.value, start: stmt.start })
341
342
  }
342
343
  else if (stmt.type === 'ExportDefaultDeclaration') {
343
344
  const decl = unwrapTsExpr(stmt.declaration)
@@ -367,7 +368,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
367
368
  scan.defaultLocal = local
368
369
  }
369
370
  if (stmt.declaration !== null)
370
- scanExportedDeclaration(scan, stmt.declaration, filename, imports, collectInits, addExport)
371
+ scanExportedDeclaration(scan, stmt.declaration, filename, imports, collectInits, addExport, reexportImported)
371
372
  }
372
373
  }
373
374
  const hydrateLocal = scan.defaultHydrate === undefined ? scan.exportLocals.get('hydrate') : undefined
@@ -376,7 +377,7 @@ function scanDeclarations(program: Program, filename: string, imports: ImportSca
376
377
  return scan
377
378
  }
378
379
 
379
- function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<ExportNamedDeclaration['declaration']>, filename: string, imports: ImportScan, collectInits: (decl: VariableDeclaration) => void, addExport: (exported: string, local: string) => void): void {
380
+ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<ExportNamedDeclaration['declaration']>, filename: string, imports: ImportScan, collectInits: (decl: VariableDeclaration) => void, addExport: (exported: string, local: string) => void, reexportImported: (exported: string, local: string, start: number) => void): void {
380
381
  if (decl.type === 'FunctionDeclaration' && decl.id !== null) {
381
382
  if (decl.async === true)
382
383
  scan.asyncLocals.add(decl.id.name)
@@ -392,6 +393,8 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
392
393
  continue
393
394
  const name = d.id.name
394
395
  addExport(name, name)
396
+ if (d.init?.type === 'Identifier')
397
+ reexportImported(name, d.init.name, d.start)
395
398
  if (name === 'prerender' && d.init?.type === 'Literal') {
396
399
  if (d.init.value === true)
397
400
  scan.hasPrerender = true
@@ -412,7 +415,8 @@ function scanExportedDeclaration(scan: DeclarationScan, decl: NonNullable<Export
412
415
  interface BodyScan {
413
416
  hasJsx: boolean
414
417
  usesRenderContext: boolean
415
- deferredIslandTags: Set<string>
418
+ /** Per component tag, the `$hydrate` modes of its uses (`''` for a use with none, which takes the island file's own mode). */
419
+ hydrateUses: Map<string, Set<string>>
416
420
  hydrateModes: Set<string>
417
421
  jsxTags: Set<string>
418
422
  dynamicImports: { source: string, start: number }[]
@@ -425,7 +429,7 @@ const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSa
425
429
  // Walks each top-level binding for JSX, mistakes, action() placement and what makes it run in the browser.
426
430
  function scanBody(program: Program, filename: string, code: string, imports: ImportScan, decls: DeclarationScan, warnings: CompilerWarning[], loadCode: ReadonlySet<Node>): BodyScan {
427
431
  const units = bindingUnits(program)
428
- const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext, deferredIslandTags: new Set(), hydrateModes: new Set(), jsxTags: new Set(), dynamicImports: [], bindings: [], units }
432
+ const body: BodyScan = { hasJsx: false, usesRenderContext: imports.usesRenderContext, hydrateUses: new Map(), hydrateModes: new Set(), jsxTags: new Set(), dynamicImports: [], bindings: [], units }
429
433
  const tracked = new Set(units.map(u => u.name))
430
434
  for (const imp of imports.imports) {
431
435
  for (const spec of imp.specifiers)
@@ -512,6 +516,7 @@ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>,
512
516
  binding.serverOnlyTag ??= member
513
517
  }
514
518
  }
519
+ let useMode = ''
515
520
  for (const attr of node.attributes) {
516
521
  if (attr.type === 'JSXSpreadAttribute') {
517
522
  if (!isComponent && tag !== '') {
@@ -528,13 +533,14 @@ function scanOpeningElement(node: Extract<Node, { type: 'JSXOpeningElement' }>,
528
533
  const mode = hydrateMode(attr.value)
529
534
  guarded(attr.start, () => checkHydrateMode(mode, `$hydrate="${mode}"`, filename))
530
535
  body.hydrateModes.add(mode)
531
- if (mode !== 'load')
532
- body.deferredIslandTags.add(tag)
536
+ useMode = mode
533
537
  }
534
538
  // A handler or ref on a component tag is a prop for that component; only a DOM element binds it in the browser.
535
539
  if (!isComponent && tag !== '' && (EVENT_ATTR.test(attrName) || attrName === 'ref'))
536
540
  binding.fact ??= { reason: `uses ${attrName}`, offset: attr.start }
537
541
  }
542
+ if (isComponent)
543
+ body.hydrateUses.set(tag, (body.hydrateUses.get(tag) ?? new Set()).add(useMode))
538
544
  }
539
545
 
540
546
  // `prunelle.signal(...)`, `prunelle.Head` and the like, through a namespace import of prunelle.
@@ -549,7 +555,7 @@ function scanPrunelleMember(node: Extract<Node, { type: 'MemberExpression' }>, b
549
555
  binding.fact ??= { reason: `calls ${callee}`, offset: node.start }
550
556
  if (STATE_PRIMITIVES.has(member))
551
557
  imports.stateCallees.add(callee)
552
- if (member === 'signal' || member === 'computed')
558
+ if (member === 'signal' || member === 'computed' || member === 'resource')
553
559
  imports.signalCallees.add(callee)
554
560
  if (RENDER_CONTEXT_IMPORTS.has(member))
555
561
  body.usesRenderContext = true
@@ -644,7 +650,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
644
650
  hasPaths: decls.hasPaths,
645
651
  usesRenderContext: body.usesRenderContext,
646
652
  defaultHydrate: decls.defaultHydrate,
647
- deferredIslandTags: body.deferredIslandTags,
653
+ hydrateUses: body.hydrateUses,
648
654
  hydrateModes: body.hydrateModes,
649
655
  jsxTags: body.jsxTags,
650
656
  asyncLocals: decls.hasAsyncDefault ? new Set([...decls.asyncLocals, decls.exportLocals.get('default') ?? 'default']) : decls.asyncLocals,
@@ -110,19 +110,29 @@ function headerOwner(obj: Node): string {
110
110
  return inner.type === 'MemberExpression' && inner.object.type === 'Identifier' && inner.object.name === 'ctx' ? 'ctx' : 'request'
111
111
  }
112
112
 
113
+ // `request`, `req`, `ctx`, `ctx.request` or an alias the walk tracked: a `.headers` of anything else (a fetch `Response`, a local record) is not the visitor's.
114
+ function isRequestExpr(node: Node, lookupAlias: (name: string) => AliasKind | undefined): boolean {
115
+ const inner = unwrapTsExpr(node)
116
+ if (inner.type === 'Identifier') {
117
+ const kind = lookupAlias(inner.name)
118
+ return kind === 'request' || kind === 'param' || (kind === undefined && (inner.name === 'request' || inner.name === 'req' || inner.name === 'ctx'))
119
+ }
120
+ return inner.type === 'MemberExpression' && memberPropName(inner) === 'request'
121
+ }
122
+
113
123
  function isHeadersExpr(node: Node, lookupAlias: (name: string) => AliasKind | undefined, allowBareHeaders: boolean): boolean {
114
124
  const inner = unwrapTsExpr(node)
115
125
  if (inner.type === 'Identifier') {
116
126
  const kind = lookupAlias(inner.name)
117
127
  return kind === 'headers' || (allowBareHeaders && kind === undefined && inner.name === 'headers')
118
128
  }
119
- return inner.type === 'MemberExpression' && memberPropName(inner) === 'headers'
129
+ return inner.type === 'MemberExpression' && memberPropName(inner) === 'headers' && isRequestExpr(inner.object, lookupAlias)
120
130
  }
121
131
 
122
132
  export function checkHeaderCall(
123
133
  node: Extract<Node, { type: 'CallExpression' }>,
124
134
  lookupAlias: (name: string) => AliasKind | undefined = () => undefined,
125
- allowBareHeaders = true,
135
+ allowBareHeaders = false,
126
136
  ): string | undefined {
127
137
  const callee = unwrapTsExpr(node.callee)
128
138
  if (callee.type !== 'MemberExpression' || !isHeadersExpr(callee.object, lookupAlias, allowBareHeaders))
@@ -297,7 +307,7 @@ function exprAliasKind(node: Node, lookup: (name: string) => AliasKind | undefin
297
307
  const obj = unwrapTsExpr(inner.object)
298
308
  if (key === 'request' && obj.type === 'Identifier' && lookup(obj.name) === 'param')
299
309
  return 'request'
300
- if (key === 'headers')
310
+ if (key === 'headers' && isRequestExpr(obj, lookup))
301
311
  return 'headers'
302
312
  }
303
313
  return undefined
@@ -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,322 @@
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|em|pt)$/
35
+ const BOLD_RE = /^(?:bold|bolder|\d{3,4})$/
36
+ const SIZE_KEYWORDS: Record<string, number> = {
37
+ 'xx-small': 9, 'x-small': 10, 'small': 13, 'medium': 16, 'large': 18, 'x-large': 24, 'xx-large': 32, 'xxx-large': 48,
38
+ }
39
+ // The 17 colours of CSS 2.1 and their common aliases; a name outside them is not resolved, so its rule is skipped.
40
+ const NAMED: Record<string, Rgb> = {
41
+ black: [0, 0, 0], white: [255, 255, 255], gray: [128, 128, 128], grey: [128, 128, 128], silver: [192, 192, 192],
42
+ red: [255, 0, 0], maroon: [128, 0, 0], yellow: [255, 255, 0], olive: [128, 128, 0], lime: [0, 255, 0], green: [0, 128, 0],
43
+ aqua: [0, 255, 255], cyan: [0, 255, 255], teal: [0, 128, 128], blue: [0, 0, 255], navy: [0, 0, 128],
44
+ fuchsia: [255, 0, 255], magenta: [255, 0, 255], purple: [128, 0, 128], orange: [255, 165, 0],
45
+ }
46
+ const MAX_VAR_DEPTH = 10
47
+
48
+ function schemeOfSelector(selector: string): Scheme | undefined {
49
+ const match = SELECTOR_SCHEME_RE.exec(selector)
50
+ return match === null ? undefined : (match[1] ?? match[2]) as Scheme
51
+ }
52
+
53
+ // The index of the parenthesis or brace closing the one at `open`, strings skipped.
54
+ function closing(css: string, open: number): number {
55
+ const [opener, closer] = css[open] === '(' ? ['(', ')'] : ['{', '}']
56
+ let depth = 0
57
+ for (let i = open; i < css.length; i++) {
58
+ const ch = css[i]
59
+ if (ch === '"' || ch === '\'') {
60
+ i = css.indexOf(ch, i + 1)
61
+ if (i === -1)
62
+ return css.length
63
+ }
64
+ else if (ch === opener) {
65
+ depth++
66
+ }
67
+ else if (ch === closer && --depth === 0) {
68
+ return i
69
+ }
70
+ }
71
+ return css.length
72
+ }
73
+
74
+ // The declarations at the top of a rule's body; nested rules are left out.
75
+ function declarationsOf(body: string): Map<string, string> {
76
+ const decls = new Map<string, string>()
77
+ let start = 0
78
+ for (let i = 0; i <= body.length; i++) {
79
+ const ch = body[i]
80
+ if (ch === '(' || ch === '{') {
81
+ const end = closing(body, i)
82
+ if (ch === '{')
83
+ start = end + 1
84
+ i = end
85
+ continue
86
+ }
87
+ if (ch !== ';' && i !== body.length)
88
+ continue
89
+ const decl = body.slice(start, i)
90
+ const colon = decl.indexOf(':')
91
+ if (colon > 0)
92
+ decls.set(decl.slice(0, colon).trim().toLowerCase(), decl.slice(colon + 1).replace(/!important\s*$/i, '').trim())
93
+ start = i + 1
94
+ }
95
+ return decls
96
+ }
97
+
98
+ function styleRules(source: string): StyleRule[] {
99
+ const css = source.replace(COMMENT_RE, match => ' '.repeat(match.length))
100
+ const rules: StyleRule[] = []
101
+ const walk = (from: number, to: number, scheme: Scheme | undefined): void => {
102
+ let start = from
103
+ for (let i = from; i < to; i++) {
104
+ const ch = css[i]
105
+ if (ch === ';') {
106
+ start = i + 1
107
+ continue
108
+ }
109
+ if (ch !== '{')
110
+ continue
111
+ const end = closing(css, i)
112
+ const prelude = css.slice(start, i)
113
+ const selector = prelude.trim()
114
+ if (selector.startsWith('@')) {
115
+ if (!OPAQUE_AT_RULE_RE.test(selector))
116
+ walk(i + 1, end, (MEDIA_SCHEME_RE.exec(selector)?.[1] as Scheme | undefined) ?? scheme)
117
+ }
118
+ else {
119
+ rules.push({ selector, scheme: schemeOfSelector(selector) ?? scheme, decls: declarationsOf(css.slice(i + 1, end)), offset: start + prelude.length - prelude.trimStart().length })
120
+ }
121
+ i = end
122
+ start = end + 1
123
+ }
124
+ }
125
+ walk(0, css.length, undefined)
126
+ return rules
127
+ }
128
+
129
+ // `:root`, `html` or `:host`, alone or with a theme qualifier: the places a stylesheet declares its tokens.
130
+ function isRootSelector(selector: string): boolean {
131
+ return selector.split(',').every((part) => {
132
+ const bare = part.replace(SELECTOR_SCHEME_RE, '').trim()
133
+ return bare === '' || bare === ':root' || bare === 'html' || bare === ':host'
134
+ })
135
+ }
136
+
137
+ function tokensOf(rules: readonly StyleRule[]): Tokens {
138
+ const tokens: Tokens = { base: new Map(), light: new Map(), dark: new Map() }
139
+ for (const rule of rules) {
140
+ if (!isRootSelector(rule.selector))
141
+ continue
142
+ const into = rule.scheme === undefined ? tokens.base : tokens[rule.scheme]
143
+ for (const [name, value] of rule.decls) {
144
+ if (name.startsWith('--'))
145
+ into.set(name, value)
146
+ }
147
+ }
148
+ return tokens
149
+ }
150
+
151
+ // The arguments of a function call, split at its top-level commas.
152
+ function argsOf(inner: string): string[] {
153
+ const args: string[] = []
154
+ let start = 0
155
+ for (let i = 0; i < inner.length; i++) {
156
+ if (inner[i] === '(') {
157
+ i = closing(inner, i)
158
+ }
159
+ else if (inner[i] === ',') {
160
+ args.push(inner.slice(start, i).trim())
161
+ start = i + 1
162
+ }
163
+ }
164
+ args.push(inner.slice(start).trim())
165
+ return args
166
+ }
167
+
168
+ // `value` with its `var()` and `light-dark()` replaced for `scheme`; undefined when a variable is not declared and has no fallback.
169
+ function substitute(value: string, scheme: Scheme, tokens: Tokens, depth = 0): string | undefined {
170
+ if (depth > MAX_VAR_DEPTH)
171
+ return undefined
172
+ const match = /\b(var|light-dark)\(/i.exec(value)
173
+ if (match === null)
174
+ return value
175
+ const open = match.index + match[0].length - 1
176
+ const end = closing(value, open)
177
+ const args = argsOf(value.slice(open + 1, end))
178
+ let replacement: string | undefined
179
+ if (match[1]!.toLowerCase() === 'var') {
180
+ const declared = tokens[scheme].get(args[0]!) ?? tokens.base.get(args[0]!)
181
+ replacement = declared ?? (args.length > 1 ? args.slice(1).join(',') : undefined)
182
+ }
183
+ else {
184
+ replacement = scheme === 'light' ? args[0] : args[1]
185
+ }
186
+ if (replacement === undefined)
187
+ return undefined
188
+ return substitute(value.slice(0, match.index) + replacement + value.slice(end + 1), scheme, tokens, depth + 1)
189
+ }
190
+
191
+ function channel(raw: string, max: number): number | undefined {
192
+ const n = Number.parseFloat(raw)
193
+ if (Number.isNaN(n))
194
+ return undefined
195
+ return raw.endsWith('%') ? (n / 100) * max : n
196
+ }
197
+
198
+ function hslToRgb(h: number, s: number, l: number): Rgb {
199
+ const k = (n: number): number => (n + h / 30) % 12
200
+ const a = s * Math.min(l, 1 - l)
201
+ const f = (n: number): number => Math.round(255 * (l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))))
202
+ return [f(0), f(8), f(4)]
203
+ }
204
+
205
+ /** An opaque colour as sRGB channels; undefined for a translucent one, which shows what lies under it, and for any syntax not read here. */
206
+ export function parseColor(raw: string): Rgb | undefined {
207
+ const value = raw.trim().toLowerCase()
208
+ if (value in NAMED)
209
+ return NAMED[value]
210
+ const hex = HEX_RE.exec(value)?.[1]
211
+ if (hex !== undefined) {
212
+ const full = hex.length <= 4 ? [...hex].map(c => c + c).join('') : hex
213
+ if (full.length === 8 && full.slice(6) !== 'ff')
214
+ return undefined
215
+ return [Number.parseInt(full.slice(0, 2), 16), Number.parseInt(full.slice(2, 4), 16), Number.parseInt(full.slice(4, 6), 16)]
216
+ }
217
+ const fn = FUNCTION_COLOR_RE.exec(value)
218
+ if (fn === null)
219
+ return undefined
220
+ const parts = fn[2]!.split(/[\s,/]+/).filter(Boolean)
221
+ if (parts.length < 3 || parts.length > 4 || (parts.length === 4 && channel(parts[3]!, 1) !== 1))
222
+ return undefined
223
+ if (fn[1]!.startsWith('rgb')) {
224
+ const [r, g, b] = [channel(parts[0]!, 255), channel(parts[1]!, 255), channel(parts[2]!, 255)]
225
+ return r === undefined || g === undefined || b === undefined ? undefined : [clamp255(r), clamp255(g), clamp255(b)]
226
+ }
227
+ const [h, s, l] = [hueDegrees(parts[0]!), channel(parts[1]!, 1), channel(parts[2]!, 1)]
228
+ return h === undefined || s === undefined || l === undefined ? undefined : hslToRgb(((h % 360) + 360) % 360, clamp01(s), clamp01(l))
229
+ }
230
+
231
+ const clamp255 = (n: number): number => Math.max(0, Math.min(255, Math.round(n)))
232
+ const clamp01 = (n: number): number => Math.max(0, Math.min(1, n))
233
+
234
+ // A hue in degrees: a bare number or `deg`, or `grad`, `rad` and `turn`; any other unit is not read.
235
+ function hueDegrees(raw: string): number | undefined {
236
+ const match = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/.exec(raw)
237
+ if (match === null)
238
+ return undefined
239
+ const n = Number.parseFloat(match[1]!)
240
+ switch (match[2]) {
241
+ case 'grad': return n * 0.9
242
+ case 'rad': return n * 180 / Math.PI
243
+ case 'turn': return n * 360
244
+ default: return n
245
+ }
246
+ }
247
+
248
+ function luminance(rgb: Rgb): number {
249
+ const [r, g, b] = rgb.map((c) => {
250
+ const s = c / 255
251
+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4
252
+ })
253
+ return 0.2126 * r! + 0.7152 * g! + 0.0722 * b!
254
+ }
255
+
256
+ /** The WCAG contrast ratio of two opaque colours, from 1 to 21. */
257
+ export function contrastRatio(a: Rgb, b: Rgb): number {
258
+ const [la, lb] = [luminance(a), luminance(b)]
259
+ return (Math.max(la, lb) + 0.05) / (Math.min(la, lb) + 0.05)
260
+ }
261
+
262
+ // A font size in px: a length (`em` read against the 16px default) or a keyword.
263
+ function pxOfSize(token: string): number | undefined {
264
+ if (Object.hasOwn(SIZE_KEYWORDS, token))
265
+ return SIZE_KEYWORDS[token]
266
+ const size = FONT_SIZE_RE.exec(token)
267
+ if (size === null)
268
+ return undefined
269
+ return Number.parseFloat(size[1]!) * (size[2] === 'rem' || size[2] === 'em' ? 16 : size[2] === 'pt' ? 4 / 3 : 1)
270
+ }
271
+
272
+ // Text from 24px, or from 18.66px when bold, needs 3:1 instead of 4.5:1; the size and weight come from `font-size` and `font-weight`, else from the `font` shorthand.
273
+ function isLargeText(decls: ReadonlyMap<string, string>): boolean {
274
+ const shorthand = (decls.get('font') ?? '').toLowerCase().split(/\s+/)
275
+ let px = pxOfSize((decls.get('font-size') ?? '').toLowerCase())
276
+ if (px === undefined) {
277
+ for (const token of shorthand) {
278
+ px = pxOfSize(token.split('/')[0]!)
279
+ if (px !== undefined)
280
+ break
281
+ }
282
+ }
283
+ if (px === undefined)
284
+ return false
285
+ const weight = (decls.get('font-weight') ?? shorthand.find(token => BOLD_RE.test(token)) ?? '').toLowerCase()
286
+ const bold = BOLD_RE.test(weight) && (weight === 'bold' || weight === 'bolder' || Number.parseInt(weight, 10) >= 700)
287
+ return px >= 24 || (bold && px >= 18.66)
288
+ }
289
+
290
+ const hexOf = (rgb: Rgb): string => `#${rgb.map(c => c.toString(16).padStart(2, '0')).join('')}`
291
+
292
+ /** 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. */
293
+ export function contrastFindings(code: string): ContrastFinding[] {
294
+ const rules = styleRules(code)
295
+ const tokens = tokensOf(rules)
296
+ const findings: ContrastFinding[] = []
297
+ for (const rule of rules) {
298
+ const color = rule.decls.get('color')
299
+ const background = rule.decls.get('background-color') ?? rule.decls.get('background')
300
+ if (color === undefined || background === undefined)
301
+ continue
302
+ const min = isLargeText(rule.decls) ? 3 : 4.5
303
+ const failing = new Map<string, Scheme[]>()
304
+ for (const scheme of rule.scheme === undefined ? ['light', 'dark'] as const : [rule.scheme]) {
305
+ const fg = parseColor(substitute(color, scheme, tokens) ?? '')
306
+ const bg = parseColor(substitute(background, scheme, tokens) ?? '')
307
+ if (fg === undefined || bg === undefined)
308
+ continue
309
+ const ratio = contrastRatio(fg, bg)
310
+ if (ratio >= min)
311
+ continue
312
+ // Floored, so a ratio just under the minimum never prints as the minimum.
313
+ const key = `${hexOf(fg)} on ${hexOf(bg)}, ${Math.floor(ratio * 100) / 100}:1`
314
+ failing.set(key, [...failing.get(key) ?? [], scheme])
315
+ }
316
+ for (const [key, schemes] of failing) {
317
+ const where = schemes.length === 2 || rule.scheme !== undefined ? '' : ` in the ${schemes[0]} scheme`
318
+ 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.` })
319
+ }
320
+ }
321
+ return findings
322
+ }
@@ -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
+ }