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
@@ -0,0 +1,95 @@
1
+ // `prunelle check` warnings about the cookies an app sets: a banner nobody can reopen, a cookie set before the visitor chose, and one `<CookieTable>` cannot describe.
2
+
3
+ import type { Argument, ObjectExpression } from 'oxc-parser'
4
+ import type { ComplianceConfig } from '../compiler/compliance'
5
+ import { parseSync } from 'oxc-parser'
6
+ import { walk } from '../compiler/ast'
7
+ import { isIgnoredAt, isRuleIgnored, parsePrunelleIgnores } from '../compiler/compliance'
8
+ import { isCookieSet, mergeCookies, scanCookieSets, unreadableFields } from '../compiler/cookie-inventory'
9
+ import { formatDiagnostic } from '../compiler/shared'
10
+
11
+ type Read = (file: string) => string
12
+ type Locate = (file: string, offset: number) => string
13
+
14
+ const BANNER_RE = /<ConsentBanner\b/g
15
+ const PREFERENCES_RE = /<ConsentPreferences\b/
16
+
17
+
18
+ /** The warnings about the app's cookies: those about its `consent` config only when it has one. */
19
+ export function cookieWarnings(consentConfigured: boolean, files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
20
+ const consent = consentConfigured ? [...consentPreferencesWarnings(files, read, locate, compliance), ...cookieCategoryWarnings(files, read, locate, compliance)] : []
21
+ return [...consent, ...cookiePurposeWarnings(files, read, locate, compliance)]
22
+ }
23
+
24
+ /** One warning at the first `<ConsentBanner>` when no file renders `<ConsentPreferences>`: the banner is gone once the visitor chose, so nothing lets them change it. */
25
+ export function consentPreferencesWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
26
+ if (isRuleIgnored('rgpd/consent-preferences', compliance))
27
+ return []
28
+ const sources = files.map(file => ({ file, code: read(file) }))
29
+ if (sources.some(({ code }) => PREFERENCES_RE.test(code)))
30
+ return []
31
+ for (const { file, code } of sources) {
32
+ const ignores = parsePrunelleIgnores(code)
33
+ for (const match of code.matchAll(BANNER_RE)) {
34
+ if (!isIgnoredAt(ignores, 'rgpd/consent-preferences', match.index))
35
+ return [formatDiagnostic(locate(file, match.index), '[rgpd/consent-preferences] <ConsentBanner> asks for consent but no page renders <ConsentPreferences>, so a visitor cannot change or withdraw their choice afterwards, and the CNIL asks withdrawing to be as easy as consenting: add <ConsentPreferences /> to the cookie policy page and link it from the footer.', 'warning')]
36
+ }
37
+ }
38
+ return []
39
+ }
40
+
41
+
42
+ function hasCategory(options: ObjectExpression): boolean {
43
+ return options.properties.some((prop) => {
44
+ if (prop.type !== 'Property' || prop.computed)
45
+ return false
46
+ return (prop.key.type === 'Identifier' ? prop.key.name : prop.key.type === 'Literal' ? prop.key.value : undefined) === 'category'
47
+ })
48
+ }
49
+
50
+ // Options held in a variable or spread into the object cannot be read, so they may hold the category.
51
+ function lacksCategory(options: Argument | undefined): boolean {
52
+ if (options === undefined)
53
+ return true
54
+ return options.type === 'ObjectExpression' && options.properties.every(prop => prop.type === 'Property') && !hasCategory(options)
55
+ }
56
+
57
+ /** A warning at each cookie set with no `category` while `consent` is configured: it counts as essential, so it is set before the visitor chose. */
58
+ export function cookieCategoryWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
59
+ if (isRuleIgnored('rgpd/cookie-category', compliance))
60
+ return []
61
+ const warnings: string[] = []
62
+ for (const file of files) {
63
+ const code = read(file)
64
+ if (!code.includes('cookies'))
65
+ continue
66
+ const ignores = parsePrunelleIgnores(code)
67
+ if (ignores.fileRules.has('rgpd/cookie-category'))
68
+ continue
69
+ walk(parseSync(file, code, { lang: file.endsWith('x') ? 'tsx' : 'ts' }).program, (node): undefined => {
70
+ if (node.type !== 'CallExpression' || !isCookieSet(node.callee) || !lacksCategory(node.arguments[2]) || isIgnoredAt(ignores, 'rgpd/cookie-category', node.start))
71
+ return undefined
72
+ const name = node.arguments[0]
73
+ const literal = name?.type === 'Literal' && typeof name.value === 'string' ? name.value : undefined
74
+ warnings.push(formatDiagnostic(locate(file, node.start), `[rgpd/cookie-category] ${literal === undefined ? 'a cookie' : `cookie "${literal}"`} is set without a category while consent is configured, so it is set before the visitor chose anything: pass { category: 'essential' } when the site cannot work without it, or its consent category (such as 'analytics') so it waits for the visitor's consent.`, 'warning'))
75
+ return undefined
76
+ })
77
+ }
78
+ return warnings
79
+ }
80
+
81
+ /** A warning at each cookie whose name, purpose, category or lifetime cannot be read from the source, so `<CookieTable>` cannot list it whole. */
82
+ export function cookiePurposeWarnings(files: readonly string[], read: Read, locate: Locate, compliance?: ComplianceConfig | undefined): string[] {
83
+ if (isRuleIgnored('rgpd/cookie-purpose', compliance))
84
+ return []
85
+ const sources = files.map(file => ({ file, code: read(file) }))
86
+ const ignoresOf = new Map(sources.map(({ file, code }) => [file, parsePrunelleIgnores(code)]))
87
+ const warnings: string[] = []
88
+ for (const cookie of mergeCookies(sources.flatMap(({ file, code }) => scanCookieSets(file, code)))) {
89
+ const missing = unreadableFields(cookie)
90
+ if (missing.length === 0 || isIgnoredAt(ignoresOf.get(cookie.file)!, 'rgpd/cookie-purpose', cookie.start))
91
+ continue
92
+ warnings.push(formatDiagnostic(locate(cookie.file, cookie.start), `[rgpd/cookie-purpose] prunelle cannot read the ${missing.join(' and ')} of ${cookie.name === undefined ? 'a cookie' : `cookie "${cookie.name}"`}, which a cookie policy must give, so <CookieTable> shows [to fill in] in its place: write it as a literal in the options of cookies.set, such as { purpose: 'Keeps the chosen theme.', maxAge: 31536000 }.`, 'warning'))
93
+ }
94
+ return warnings
95
+ }
@@ -20,7 +20,7 @@ import { calleeName, formatDiagnostic, formatLoc, isComponentTag, jsxTagName, re
20
20
  import { staticLiteralOrTemplate, staticOptionText } from '../compiler/ssr-helpers'
21
21
  import { closestName } from '../plugins/config'
22
22
  import { isServerAction } from '../server/action'
23
- import { FORM_TIMESTAMP_FIELD, honeypotFieldName } from '../server/action-protect'
23
+ import { FORM_TIMESTAMP_FIELD, honeypotFieldName, MAX_FORM_AGE_MS } from '../server/action-protect'
24
24
  import { extractFormSchema, isRecord, lookupFieldConstraint } from '../server/form-schema'
25
25
 
26
26
  export interface FormCheckInput {
@@ -589,7 +589,7 @@ function frozenTimestampErrors(form: CollectedForm, pages: readonly string[], gr
589
589
  const analysis = graph.analyses.get(page)
590
590
  const frozenBy = analysis?.hasPrerender === true ? 'prerender = true' : analysis?.cache !== undefined ? 'cache' : undefined
591
591
  if (frozenBy === undefined) continue
592
- errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused 24 h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
592
+ errors.push(formatDiagnostic(loc, `[action/min-time-frozen] Form bound to action "${form.action.exportName}" uses protect.minTime on ${relOf(page)}, which exports ${frozenBy}: its signed timestamp is rendered once for every visitor, so bots pass minTime at once and every submit is refused ${MAX_FORM_AGE_MS / 3_600_000} h after the render. Remove ${frozenBy === 'cache' ? 'the cache export' : 'prerender = true'} from ${relOf(page)}, or drop minTime and keep honeypot and rateLimit.`, 'error'))
593
593
  }
594
594
  return errors
595
595
  }
@@ -0,0 +1,101 @@
1
+ // The route patterns `prunelle check` matches internal links against: optional segments expanded, param matchers applied, and templated links (`/posts/${id}`) matched segment by segment.
2
+
3
+ import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../server/param-matchers'
4
+ import { parsePatternSegment } from '../server/param-matchers'
5
+
6
+ export interface DynamicSegment { kind: 'static' | 'param' | 'catchall', value: string, matcherName?: string | undefined, matcher?: ParamMatcher | undefined }
7
+
8
+ export function normalizePathname(raw: string): string {
9
+ const cut = raw.search(/[?#]/)
10
+ const p = cut === -1 ? raw : raw.slice(0, cut)
11
+ return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
12
+ }
13
+
14
+ export function compileDynamicPatterns(pattern: string, matchers: ParamMatcherMap): DynamicSegment[][] {
15
+ const norm = normalizePathname(pattern)
16
+ const parsed: ParsedPatternSegment[] = norm === '/' ? [] : norm.slice(1).split('/').map(parsePatternSegment)
17
+ const optIdx = parsed.flatMap((s, i) => s.kind === 'optional' ? [i] : [])
18
+ if (optIdx.length > 6) return []
19
+ const toSeg = (s: ParsedPatternSegment): DynamicSegment => ({
20
+ kind: s.kind === 'optional' ? 'param' : s.kind, value: s.value, matcherName: s.matcherName,
21
+ matcher: s.matcherName !== undefined ? matchers[s.matcherName] : undefined,
22
+ })
23
+ const variants: DynamicSegment[][] = []
24
+ const expand = (k: number, omitted: Set<number>): void => {
25
+ if (k === optIdx.length) { variants.push(parsed.filter((_, i) => !omitted.has(i)).map(toSeg)); return }
26
+ expand(k + 1, omitted)
27
+ omitted.add(optIdx[k]!)
28
+ expand(k + 1, omitted)
29
+ omitted.delete(optIdx[k]!)
30
+ }
31
+ expand(0, new Set())
32
+ return variants
33
+ }
34
+
35
+ const paramAccepts = (seg: DynamicSegment, value: string): boolean => seg.matcherName === undefined || (seg.matcher !== undefined && seg.matcher(value))
36
+
37
+ export function patternMatchesPrefix(segs: readonly DynamicSegment[], complete: readonly string[], partial: string | undefined): boolean {
38
+ let catchAll: DynamicSegment | undefined
39
+ for (let i = 0; i < complete.length; i++) {
40
+ const part = complete[i]!
41
+ if (catchAll !== undefined) { if (!paramAccepts(catchAll, part)) return false; continue }
42
+ const seg = segs[i]
43
+ if (seg === undefined) return false
44
+ if (seg.kind === 'catchall') { catchAll = seg; if (!paramAccepts(seg, part)) return false }
45
+ else if (seg.kind === 'static' ? seg.value !== part : !paramAccepts(seg, part)) return false
46
+ }
47
+ if (catchAll !== undefined) return true
48
+ const next = segs[complete.length]
49
+ return next !== undefined && (partial === undefined || next.kind !== 'static' || next.value.startsWith(partial))
50
+ }
51
+
52
+ export function staticPrefixOfPattern(pattern: string): string | undefined {
53
+ const norm = normalizePathname(pattern)
54
+ if (norm === '/') return undefined
55
+ const kept: string[] = []
56
+ for (const seg of norm.slice(1).split('/')) {
57
+ if (parsePatternSegment(seg).kind !== 'static') break
58
+ kept.push(seg)
59
+ }
60
+ return kept.length > 0 ? `/${kept.join('/')}` : undefined
61
+ }
62
+
63
+ function segMatchesPattern(tSeg: string, pSeg: DynamicSegment): boolean {
64
+ if (!tSeg.includes('\0')) return pSeg.kind === 'static' ? pSeg.value === tSeg : paramAccepts(pSeg, tSeg)
65
+ if (pSeg.kind !== 'static') return true
66
+ const pieces = tSeg.split('\0')
67
+ let pos = 0
68
+ for (let i = 0; i < pieces.length; i++) {
69
+ const piece = pieces[i]!
70
+ if (piece === '') continue
71
+ if (i === 0 && !pSeg.value.startsWith(piece)) return false
72
+ if (i === pieces.length - 1 && !pSeg.value.endsWith(piece)) return false
73
+ const idx = pSeg.value.indexOf(piece, pos)
74
+ if (idx === -1) return false
75
+ pos = idx + piece.length
76
+ }
77
+ return true
78
+ }
79
+
80
+ export function patternMatchesTemplate(pat: readonly DynamicSegment[], tSegs: readonly string[]): boolean {
81
+ const matchAt = (ti: number, pi: number): boolean => {
82
+ if (ti === tSegs.length && pi === pat.length) return true
83
+ if (pi === pat.length) return false
84
+ const pSeg = pat[pi]!
85
+ if (pSeg.kind === 'catchall') {
86
+ for (let k = ti; k < tSegs.length; k++)
87
+ if (!tSegs[k]!.includes('\0') && !paramAccepts(pSeg, tSegs[k]!)) return false
88
+ return ti < tSegs.length
89
+ }
90
+ if (ti === tSegs.length) return false
91
+ const tSeg = tSegs[ti]!
92
+ if (!tSeg.includes('\0')) return segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)
93
+ if (segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)) return true
94
+ if (tSeg === '\0') {
95
+ for (let nextPi = pi + 2; nextPi <= pat.length; nextPi++)
96
+ if (matchAt(ti + 1, nextPi)) return true
97
+ }
98
+ return false
99
+ }
100
+ return matchAt(0, 0)
101
+ }
@@ -4,7 +4,7 @@ import type { Node, Program } from 'oxc-parser'
4
4
  import type { RouteManifestEntry } from '../build/manifest'
5
5
  import type { ModuleAnalysis } from '../compiler/analyze'
6
6
  import type { ActiveI18nConfig, AppRuntimeContext, BuildPluginContext, PrunelleConfig, PrunellePlugin, ServerPluginAPI } from '../plugins/index'
7
- import type { ParamMatcher, ParamMatcherMap, ParsedPatternSegment } from '../server/param-matchers'
7
+ import type { ParamMatcher, ParamMatcherMap } from '../server/param-matchers'
8
8
  import { existsSync, readFileSync, statSync } from 'node:fs'
9
9
  import { basename, resolve } from 'node:path'
10
10
  import { pathToFileURL } from 'node:url'
@@ -14,7 +14,8 @@ import { discoverRouteMatchers, fileToRoutePath, hasRouteHandlerExport, SPECIAL_
14
14
  import { walk } from '../compiler/ast'
15
15
  import { calleeName, formatDiagnostic, formatLoc, offsetToLineCol, unwrapTsExpr } from '../compiler/shared'
16
16
  import { createAppContext, I18N_CONFIG_SERVICE, pickRuntimeConfig, runWithAppContext } from '../plugins/index'
17
- import { BUILTIN_PARAM_MATCHERS, extractMatcherFn, parsePatternSegment } from '../server/param-matchers'
17
+ import { BUILTIN_PARAM_MATCHERS, extractMatcherFn } from '../server/param-matchers'
18
+ import { compileDynamicPatterns, type DynamicSegment, normalizePathname, patternMatchesPrefix, patternMatchesTemplate, staticPrefixOfPattern } from './check-links-patterns'
18
19
  import { decodeRequestPath } from '../server/request-path'
19
20
  import { Router } from '../server/router'
20
21
 
@@ -25,7 +26,6 @@ export interface LinkCheckInput {
25
26
  }
26
27
 
27
28
  interface RouteEntry { pattern: string, fileRel?: string | undefined, isDynamic: boolean, knownPaths?: ReadonlySet<string> | undefined, knownPathList?: readonly string[] | undefined }
28
- interface DynamicSegment { kind: 'static' | 'param' | 'catchall', value: string, matcherName?: string | undefined, matcher?: ParamMatcher | undefined }
29
29
  interface LinkTarget { kind: 'exact' | 'prefix' | 'template', value: string, parts?: readonly string[] | undefined, offset: number, parentOffset: number }
30
30
  interface LinkResolver { checkExact: (raw: string) => string | undefined, checkPrefix: (raw: string) => string | undefined, checkTemplate: (parts: readonly string[]) => string | undefined }
31
31
  interface PluginProbeResult { pluginRoutes: string[], emittedPublic: string[], locales: string[] }
@@ -40,12 +40,6 @@ const MD_LINK_RE = /\[(?:[^\]\\]|\\.|\[[^\]]*\])*\]\(\s*(?:<([^>\n]+)>|([^)\s]+)
40
40
  const MD_HTML_A_RE = /<a\b[^>]*?\bhref\s*=\s*(?:"([^"]*)"|'([^']*)')/gi
41
41
  const PROBE_ROUTE: RouteManifestEntry = { path: '/__pru_probe__', file: '__pru_probe__.ts', layouts: [], middlewares: [], islandChunks: [] }
42
42
 
43
- function normalizePathname(raw: string): string {
44
- const cut = raw.search(/[?#]/)
45
- const p = cut === -1 ? raw : raw.slice(0, cut)
46
- return p.length > 1 && p.endsWith('/') ? (p.replace(/\/+$/, '') || '/') : p
47
- }
48
-
49
43
  function decodePathname(raw: string): string {
50
44
  const norm = normalizePathname(raw)
51
45
  const decoded = decodeRequestPath(norm)?.staticPath
@@ -180,6 +174,8 @@ async function probeSinglePlugin(
180
174
  rateLimiter: () => ({ hit: () => 0, peek: () => 0 }), rewrite: () => {}, provide: state.provide,
181
175
  inject: key => inject(key) as never, getBuildData: () => undefined, healthCheck: () => {},
182
176
  onShutdown: fn => { state.shutdowns.push(fn) },
177
+ onRequestEnd: () => {},
178
+ surface: () => ({ actions: [], routes: [] }),
183
179
  }
184
180
  await silently(() => plugin.server!(api))
185
181
  }
@@ -247,95 +243,6 @@ function collectPublicPaths(publicDir: string, emittedPublic: readonly string[])
247
243
  return out
248
244
  }
249
245
 
250
- function compileDynamicPatterns(pattern: string, matchers: ParamMatcherMap): DynamicSegment[][] {
251
- const norm = normalizePathname(pattern)
252
- const parsed: ParsedPatternSegment[] = norm === '/' ? [] : norm.slice(1).split('/').map(parsePatternSegment)
253
- const optIdx = parsed.flatMap((s, i) => s.kind === 'optional' ? [i] : [])
254
- if (optIdx.length > 6) return []
255
- const toSeg = (s: ParsedPatternSegment): DynamicSegment => ({
256
- kind: s.kind === 'optional' ? 'param' : s.kind, value: s.value, matcherName: s.matcherName,
257
- matcher: s.matcherName !== undefined ? matchers[s.matcherName] : undefined,
258
- })
259
- const variants: DynamicSegment[][] = []
260
- const expand = (k: number, omitted: Set<number>): void => {
261
- if (k === optIdx.length) { variants.push(parsed.filter((_, i) => !omitted.has(i)).map(toSeg)); return }
262
- expand(k + 1, omitted)
263
- omitted.add(optIdx[k]!)
264
- expand(k + 1, omitted)
265
- omitted.delete(optIdx[k]!)
266
- }
267
- expand(0, new Set())
268
- return variants
269
- }
270
-
271
- const paramAccepts = (seg: DynamicSegment, value: string): boolean => seg.matcherName === undefined || (seg.matcher !== undefined && seg.matcher(value))
272
-
273
- function patternMatchesPrefix(segs: readonly DynamicSegment[], complete: readonly string[], partial: string | undefined): boolean {
274
- let catchAll: DynamicSegment | undefined
275
- for (let i = 0; i < complete.length; i++) {
276
- const part = complete[i]!
277
- if (catchAll !== undefined) { if (!paramAccepts(catchAll, part)) return false; continue }
278
- const seg = segs[i]
279
- if (seg === undefined) return false
280
- if (seg.kind === 'catchall') { catchAll = seg; if (!paramAccepts(seg, part)) return false }
281
- else if (seg.kind === 'static' ? seg.value !== part : !paramAccepts(seg, part)) return false
282
- }
283
- if (catchAll !== undefined) return true
284
- const next = segs[complete.length]
285
- return next !== undefined && (partial === undefined || next.kind !== 'static' || next.value.startsWith(partial))
286
- }
287
-
288
- function staticPrefixOfPattern(pattern: string): string | undefined {
289
- const norm = normalizePathname(pattern)
290
- if (norm === '/') return undefined
291
- const kept: string[] = []
292
- for (const seg of norm.slice(1).split('/')) {
293
- if (parsePatternSegment(seg).kind !== 'static') break
294
- kept.push(seg)
295
- }
296
- return kept.length > 0 ? `/${kept.join('/')}` : undefined
297
- }
298
-
299
- function segMatchesPattern(tSeg: string, pSeg: DynamicSegment): boolean {
300
- if (!tSeg.includes('\0')) return pSeg.kind === 'static' ? pSeg.value === tSeg : paramAccepts(pSeg, tSeg)
301
- if (pSeg.kind !== 'static') return true
302
- const pieces = tSeg.split('\0')
303
- let pos = 0
304
- for (let i = 0; i < pieces.length; i++) {
305
- const piece = pieces[i]!
306
- if (piece === '') continue
307
- if (i === 0 && !pSeg.value.startsWith(piece)) return false
308
- if (i === pieces.length - 1 && !pSeg.value.endsWith(piece)) return false
309
- const idx = pSeg.value.indexOf(piece, pos)
310
- if (idx === -1) return false
311
- pos = idx + piece.length
312
- }
313
- return true
314
- }
315
-
316
- function patternMatchesTemplate(pat: readonly DynamicSegment[], tSegs: readonly string[]): boolean {
317
- const matchAt = (ti: number, pi: number): boolean => {
318
- if (ti === tSegs.length && pi === pat.length) return true
319
- if (pi === pat.length) return false
320
- const pSeg = pat[pi]!
321
- if (pSeg.kind === 'catchall') {
322
- for (let k = ti; k < tSegs.length; k++)
323
- if (!tSegs[k]!.includes('\0') && !paramAccepts(pSeg, tSegs[k]!)) return false
324
- return ti < tSegs.length
325
- }
326
- if (ti === tSegs.length) return false
327
- const tSeg = tSegs[ti]!
328
- if (!tSeg.includes('\0')) return segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)
329
- if (segMatchesPattern(tSeg, pSeg) && matchAt(ti + 1, pi + 1)) return true
330
- if (tSeg === '\0') {
331
- for (let nextPi = pi + 2; nextPi <= pat.length; nextPi++)
332
- if (matchAt(ti + 1, nextPi)) return true
333
- }
334
- return false
335
- }
336
- return matchAt(0, 0)
337
- }
338
-
339
246
  function stripLocale(pathname: string, locales: readonly string[]): string | undefined {
340
247
  const first = locales.length > 0 ? pathname.slice(1).split('/', 1)[0] : undefined
341
248
  return first !== undefined && locales.includes(first) ? (pathname.slice(first.length + 1) || '/') : undefined
@@ -485,6 +392,16 @@ function scanModuleLinks(relFile: string, analysis: ModuleAnalysis, code: string
485
392
  }
486
393
  }
487
394
 
395
+ /** A plugin whose `watchPaths` throws has none to offer: the content check goes on without it. */
396
+ function pluginWatchPaths(plugin: PrunellePlugin, root: string): readonly string[] {
397
+ try {
398
+ return (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths) ?? []
399
+ }
400
+ catch {
401
+ return []
402
+ }
403
+ }
404
+
488
405
  function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[], analyses: ReadonlyMap<string, ModuleAnalysis>): string[] {
489
406
  const dirs = new Set<string>()
490
407
  const addDir = (raw: string): void => {
@@ -493,8 +410,7 @@ function discoverCollectionDirs(root: string, plugins: readonly PrunellePlugin[]
493
410
  }
494
411
  for (const plugin of plugins) {
495
412
  if (plugin.name !== '@prunellejs/content' || plugin.watchPaths === undefined) continue
496
- try { (typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : plugin.watchPaths).forEach(addDir) }
497
- catch (err) { void err }
413
+ pluginWatchPaths(plugin, root).forEach(addDir)
498
414
  }
499
415
  for (const [file, analysis] of analyses) {
500
416
  if (isInNodeModules(file) || !isInside(root, file)) continue
@@ -0,0 +1,185 @@
1
+ // `prunelle check` rule for `<Region>`: reports static `data-pru-target="<name>"` attributes that name no `<Region name="<name>">` in the project, using parsed JSX AST and scoping dynamic `<Region name={expr}>` to the routes reaching them.
2
+
3
+ import type { JSXAttribute, Node } from 'oxc-parser'
4
+ import type { ModuleGraph } from '../build/graph'
5
+ import type { ModuleAnalysis } from '../compiler/analyze'
6
+ import { isInNodeModules } from '../build/files'
7
+ import { ancestorFiles } from '../build/routes'
8
+ import { walk } from '../compiler/ast'
9
+ import { formatDiagnostic, jsxTagName, resolvePrunelleTag, staticLiteral, unwrapTsExpr } from '../compiler/shared'
10
+
11
+ interface TargetRef {
12
+ file: string
13
+ name: string
14
+ offset: number
15
+ }
16
+
17
+ /** A dynamic `<Region name={expr}>`: `pattern` narrows template literals (e.g. `` `tab-${id}` ``), or `undefined` for arbitrary expressions. */
18
+ interface DynamicRegion {
19
+ pattern: RegExp | undefined
20
+ }
21
+
22
+ function jsxAttrName(attr: JSXAttribute): string {
23
+ return attr.name.type === 'JSXIdentifier' ? attr.name.name : `${attr.name.namespace.name}:${attr.name.name.name}`
24
+ }
25
+
26
+ function jsxStaticString(attr: JSXAttribute): string | undefined {
27
+ if (attr.value === null)
28
+ return undefined
29
+ if (attr.value.type === 'Literal')
30
+ return typeof attr.value.value === 'string' ? attr.value.value : undefined
31
+ if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
32
+ const lit = staticLiteral(attr.value.expression as Node)
33
+ return lit.ok && typeof lit.value === 'string' ? lit.value : undefined
34
+ }
35
+ return undefined
36
+ }
37
+
38
+ function templatePattern(expr: Node): RegExp | undefined {
39
+ const inner = unwrapTsExpr(expr)
40
+ if (inner.type !== 'TemplateLiteral' || inner.expressions.length === 0)
41
+ return undefined
42
+ const parts = inner.quasis.map(q => RegExp.escape(q.value.cooked ?? q.value.raw))
43
+ return new RegExp(`^${parts.join('.*')}$`)
44
+ }
45
+
46
+ function collectFileRegions(
47
+ file: string,
48
+ analysis: ModuleAnalysis,
49
+ staticRegions: Set<string>,
50
+ dynamicByFile: Map<string, DynamicRegion[]>,
51
+ targets: TargetRef[],
52
+ ): void {
53
+ walk(analysis.program, (node) => {
54
+ if (node.type !== 'JSXOpeningElement')
55
+ return
56
+ const tag = jsxTagName(node.name)
57
+ if (resolvePrunelleTag(tag, analysis.imports) === 'Region') {
58
+ let nameAttr: JSXAttribute | undefined
59
+ let hasSpread = false
60
+ for (const attr of node.attributes) {
61
+ if (attr.type === 'JSXSpreadAttribute')
62
+ hasSpread = true
63
+ else if (jsxAttrName(attr) === 'name')
64
+ nameAttr = attr
65
+ }
66
+ if (nameAttr !== undefined) {
67
+ const staticName = jsxStaticString(nameAttr)
68
+ if (staticName !== undefined) {
69
+ staticRegions.add(staticName)
70
+ }
71
+ else {
72
+ const expr = nameAttr.value?.type === 'JSXExpressionContainer' && nameAttr.value.expression.type !== 'JSXEmptyExpression'
73
+ ? nameAttr.value.expression as Node
74
+ : undefined
75
+ const list = dynamicByFile.get(file) ?? []
76
+ list.push({ pattern: expr === undefined ? undefined : templatePattern(expr) })
77
+ dynamicByFile.set(file, list)
78
+ }
79
+ }
80
+ else if (hasSpread) {
81
+ const list = dynamicByFile.get(file) ?? []
82
+ list.push({ pattern: undefined })
83
+ dynamicByFile.set(file, list)
84
+ }
85
+ return
86
+ }
87
+ if (tag !== 'a' && tag !== 'form')
88
+ return
89
+ for (const attr of node.attributes) {
90
+ if (attr.type !== 'JSXAttribute' || jsxAttrName(attr) !== 'data-pru-target')
91
+ continue
92
+ const target = jsxStaticString(attr)
93
+ if (target !== undefined && target !== '')
94
+ targets.push({ file, name: target, offset: attr.start })
95
+ }
96
+ })
97
+ }
98
+
99
+ function reachableFiles(roots: readonly string[], graph: ModuleGraph): Set<string> {
100
+ const seen = new Set<string>(roots)
101
+ const stack = [...roots]
102
+ while (stack.length > 0) {
103
+ const cur = stack.pop()!
104
+ for (const dep of graph.localDeps(cur)) {
105
+ if (!seen.has(dep)) {
106
+ seen.add(dep)
107
+ stack.push(dep)
108
+ }
109
+ }
110
+ }
111
+ return seen
112
+ }
113
+
114
+ function matchesDynamic(name: string, dynamics: readonly DynamicRegion[] | undefined): boolean {
115
+ if (dynamics === undefined)
116
+ return false
117
+ for (const dyn of dynamics) {
118
+ if (dyn.pattern === undefined || dyn.pattern.test(name))
119
+ return true
120
+ }
121
+ return false
122
+ }
123
+
124
+ export function checkRegionTargets(options: {
125
+ graph: ModuleGraph
126
+ routesDir: string
127
+ pageFiles: readonly string[]
128
+ locate: (file: string, offset: number) => string
129
+ }): string[] {
130
+ const { graph, routesDir, pageFiles, locate } = options
131
+ const staticRegions = new Set<string>()
132
+ const dynamicByFile = new Map<string, DynamicRegion[]>()
133
+ const targets: TargetRef[] = []
134
+
135
+ for (const [file, analysis] of graph.analyses) {
136
+ if (isInNodeModules(file) || !file.endsWith('.tsx'))
137
+ continue
138
+ collectFileRegions(file, analysis, staticRegions, dynamicByFile, targets)
139
+ }
140
+
141
+ if (targets.length === 0)
142
+ return []
143
+
144
+ const dynamicsForFile = new Map<string, DynamicRegion[]>()
145
+ const addDynamics = (file: string, list: readonly DynamicRegion[]): void => {
146
+ const existing = dynamicsForFile.get(file) ?? []
147
+ existing.push(...list)
148
+ dynamicsForFile.set(file, existing)
149
+ }
150
+ for (const [file, list] of dynamicByFile)
151
+ addDynamics(file, list)
152
+
153
+ if (dynamicByFile.size > 0) {
154
+ for (const pageFile of pageFiles) {
155
+ const layouts = ancestorFiles(routesDir, pageFile, ['_layout.tsx'])
156
+ const files = reachableFiles([...layouts, pageFile], graph)
157
+ const routeDynamics: { file: string, entry: DynamicRegion }[] = []
158
+ for (const f of files) {
159
+ const list = dynamicByFile.get(f)
160
+ if (list !== undefined) {
161
+ for (const entry of list)
162
+ routeDynamics.push({ file: f, entry })
163
+ }
164
+ }
165
+ if (routeDynamics.length === 0)
166
+ continue
167
+ for (const f of files) {
168
+ const extra = routeDynamics.filter(d => d.file !== f).map(d => d.entry)
169
+ if (extra.length > 0)
170
+ addDynamics(f, extra)
171
+ }
172
+ }
173
+ }
174
+
175
+ const errors: string[] = []
176
+ for (const target of targets) {
177
+ if (staticRegions.has(target.name) || matchesDynamic(target.name, dynamicsForFile.get(target.file)))
178
+ continue
179
+ errors.push(formatDiagnostic(
180
+ locate(target.file, target.offset),
181
+ `[regions] data-pru-target="${target.name}" names no <Region name="${target.name}"> in src/: add the region, or fix the name`,
182
+ ))
183
+ }
184
+ return errors
185
+ }