prunelle 0.7.1 → 0.7.3

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 (45) hide show
  1. package/llms.txt +5 -5
  2. package/package.json +1 -1
  3. package/src/a11y/declaration.ts +4 -0
  4. package/src/a11y/index.ts +11 -0
  5. package/src/build/bundle.ts +2 -2
  6. package/src/build/files.ts +9 -0
  7. package/src/build/first-load.ts +2 -3
  8. package/src/build/index.ts +6 -12
  9. package/src/build/island-promote.ts +69 -8
  10. package/src/build/output.ts +3 -6
  11. package/src/build/plugin-host.ts +4 -2
  12. package/src/build/precompress.ts +1 -1
  13. package/src/build/prerender.ts +7 -4
  14. package/src/build/reach.ts +92 -28
  15. package/src/build/static-headers.ts +27 -8
  16. package/src/cli/check-forms.ts +60 -34
  17. package/src/cli/check-imports.ts +9 -3
  18. package/src/cli/check.ts +5 -15
  19. package/src/cli/new.ts +1 -1
  20. package/src/cli/upgrade.ts +4 -8
  21. package/src/compiler/analyze.ts +19 -41
  22. package/src/compiler/cacheability-private.ts +566 -0
  23. package/src/compiler/cacheability.ts +21 -322
  24. package/src/compiler/compliance-eco.ts +4 -4
  25. package/src/compiler/compliance-urls.ts +5 -3
  26. package/src/compiler/compliance.ts +68 -17
  27. package/src/compiler/expr-context.ts +113 -44
  28. package/src/compiler/spread-handlers.ts +295 -0
  29. package/src/dom/extras.ts +28 -26
  30. package/src/dom/island.ts +49 -34
  31. package/src/eco/declaration.ts +87 -16
  32. package/src/eco/index.ts +7 -3
  33. package/src/plugins/config.ts +13 -8
  34. package/src/reactivity/store.ts +19 -7
  35. package/src/server/action.ts +137 -40
  36. package/src/server/errors.ts +3 -0
  37. package/src/server/form-schema.ts +6 -12
  38. package/src/server/index.ts +6 -6
  39. package/src/server/page.ts +15 -0
  40. package/src/server/route-cache.ts +99 -3
  41. package/src/server/route-table.ts +23 -13
  42. package/src/server/standard-schema.ts +17 -0
  43. package/src/ssr/context.ts +1 -1
  44. package/src/ssr/index.ts +4 -2
  45. package/src/ssr/region.ts +18 -9
@@ -3,23 +3,27 @@
3
3
  import type { ArrowFunctionExpression, Function as OxcFunction, Node, Program } from 'oxc-parser'
4
4
  import type { RouteCacheSpec } from '../server/route-cache'
5
5
  import type { ModuleAnalysis } from './analyze'
6
- import { visitorKeys } from 'oxc-parser'
6
+ import type { PrivateGraphView, PrivateReadHit } from './cacheability-private'
7
7
  import { buildRouteCacheSpec, parseCacheDuration } from '../server/route-cache'
8
8
  import { walk } from './ast'
9
- import { collectPatternNames, EVENT_ATTR, jsxTagName, resolvePrunelleTag, staticLiteral, unwrapTsExpr } from './shared'
9
+ import {
10
+ checkHeaderCall,
11
+ findExportedFunction,
12
+ findModulePrivateHits,
13
+ memberPropName,
14
+ PRIVATE_SERVER_IMPORTS,
15
+ propKeyName,
16
+ staticStringOrNumber,
17
+ walkTrackedFunction,
18
+ } from './cacheability-private'
19
+ import { EVENT_ATTR, jsxTagName, resolvePrunelleTag, unwrapTsExpr } from './shared'
10
20
 
11
21
  const CACHE_HELP = 'write a duration such as \'30s\', \'5m\', \'1h\', \'1d\', a positive number of seconds, or { maxAge: \'1h\', staleWhileRevalidate?: \'1d\' }'
12
22
  const DYNAMIC_PROPS = new Set(['params', 'url', 'locals', 'cookies', 'headers', 'request', 'consent', 'ip'])
13
- const PRIVATE_CTX_PROPS = new Set(['cookies', 'locals', 'consent', 'ip'])
14
- const PRIVATE_PAGE_PROPS = new Set(['locals', 'cookies', 'consent', 'ip'])
15
- const PRIVATE_SERVER_IMPORTS = new Set(['getActionError', 'currentRequest'])
16
- const PRIVATE_HEADERS = new Set(['cookie', 'authorization'])
17
23
  const DYNAMIC_IMPORTS = new Set(['bun:sqlite', 'node:sqlite', 'sqlite', 'bun:sql'])
18
24
  const SYNC_IO_CALLEES = new Set(['readFileSync', 'readdirSync', 'statSync', 'lstatSync', 'existsSync', 'accessSync'])
19
25
  const DYNAMIC_TAGS = new Set(['ConsentGate', 'ConsentBanner', 'ConsentPreferences', 'Suspense'])
20
- const PRIVATE_TAGS = new Set(['ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
21
26
  const CLIENT_CALLBACK_CALLEES = new Set(['onMount', 'effect', 'onCleanup'])
22
- const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', 'TSInstantiationExpression'])
23
27
 
24
28
  export interface CacheExportResult {
25
29
  hasExport: boolean
@@ -34,46 +38,10 @@ export interface PrivateReadProblem {
34
38
  message: string
35
39
  }
36
40
 
37
- interface PrivateReadHit {
38
- what: string
39
- offset: number
40
- }
41
-
42
- interface GraphView {
43
- readonly analyses: ReadonlyMap<string, ModuleAnalysis>
44
- localDeps(file: string): readonly string[]
45
- }
46
-
47
41
  interface IslandView {
48
42
  readonly targets: ReadonlyMap<string, unknown>
49
43
  }
50
44
 
51
- function staticStringOrNumber(node: Node): { ok: true, value: string | number } | { ok: false, isLiteral: boolean } {
52
- const inner = unwrapTsExpr(node)
53
- if (inner.type === 'TemplateLiteral' && inner.expressions.length === 0 && inner.quasis.length === 1)
54
- return { ok: true, value: inner.quasis[0]!.value.cooked ?? inner.quasis[0]!.value.raw }
55
- const lit = staticLiteral(inner)
56
- if (!lit.ok)
57
- return { ok: false, isLiteral: false }
58
- return typeof lit.value === 'string' || typeof lit.value === 'number'
59
- ? { ok: true, value: lit.value }
60
- : { ok: false, isLiteral: true }
61
- }
62
-
63
- function propKeyName(prop: Node): string | undefined {
64
- if (prop.type !== 'Property')
65
- return undefined
66
- if (!prop.computed && prop.key.type === 'Identifier')
67
- return prop.key.name
68
- return prop.key.type === 'Literal' && typeof prop.key.value === 'string' ? prop.key.value : undefined
69
- }
70
-
71
- function memberPropName(node: Extract<Node, { type: 'MemberExpression' }>): string | undefined {
72
- if (!node.computed && node.property.type === 'Identifier')
73
- return node.property.name
74
- return node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string' ? node.property.value : undefined
75
- }
76
-
77
45
  function parseCacheObjectNode(node: Extract<Node, { type: 'ObjectExpression' }>): { spec: RouteCacheSpec } | { problem: string } {
78
46
  let maxAgeMs: number | undefined
79
47
  let swrMs: number | undefined
@@ -168,278 +136,9 @@ export function parseCacheExport(program: Program): CacheExportResult {
168
136
  return { hasExport: true, offset, spec: buildRouteCacheSpec(ms) }
169
137
  }
170
138
 
171
- function collectTopLevelFns(program: Program): { fns: Map<string, OxcFunction>, inits: Map<string, Node> } {
172
- const fns = new Map<string, OxcFunction>()
173
- const inits = new Map<string, Node>()
174
- const add = (node: Node): void => {
175
- if (node.type === 'FunctionDeclaration' && node.id !== null)
176
- fns.set(node.id.name, node)
177
- else if (node.type === 'VariableDeclaration')
178
- for (const d of node.declarations) if (d.id.type === 'Identifier' && d.init !== null) inits.set(d.id.name, d.init)
179
- }
180
- for (const stmt of program.body)
181
- add(stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null ? stmt.declaration : stmt)
182
- return { fns, inits }
183
- }
184
-
185
- function unwrapFn(node: Node | undefined, fns: ReadonlyMap<string, OxcFunction>, inits: ReadonlyMap<string, Node>, depth = 0): OxcFunction | ArrowFunctionExpression | undefined {
186
- if (node === undefined || depth > 4)
187
- return undefined
188
- const inner = unwrapTsExpr(node)
189
- if (inner.type === 'FunctionDeclaration' || inner.type === 'FunctionExpression' || inner.type === 'ArrowFunctionExpression')
190
- return inner
191
- return inner.type === 'Identifier' ? fns.get(inner.name) ?? unwrapFn(inits.get(inner.name), fns, inits, depth + 1) : undefined
192
- }
193
-
194
- function findExportedFunction(program: Program, exportName: 'default' | 'load'): OxcFunction | ArrowFunctionExpression | undefined {
195
- const { fns, inits } = collectTopLevelFns(program)
196
- for (const stmt of program.body) {
197
- if (exportName === 'default' && stmt.type === 'ExportDefaultDeclaration')
198
- return unwrapFn(stmt.declaration, fns, inits)
199
- if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type')
200
- continue
201
- if (stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id?.name === exportName)
202
- return stmt.declaration
203
- if (stmt.declaration?.type === 'VariableDeclaration') {
204
- for (const d of stmt.declaration.declarations) {
205
- if (d.id.type === 'Identifier' && d.id.name === exportName)
206
- return unwrapFn(d.init ?? undefined, fns, inits)
207
- }
208
- }
209
- for (const spec of stmt.specifiers) {
210
- const exp = spec.exported.type === 'Identifier' ? spec.exported.name : spec.exported.value
211
- if (exp === exportName && stmt.source === null && spec.local.type === 'Identifier')
212
- return fns.get(spec.local.name) ?? unwrapFn(inits.get(spec.local.name), fns, inits)
213
- }
214
- }
215
- return undefined
216
- }
217
-
218
139
  const unwrapParam = (param: Node): Node => (param.type === 'AssignmentPattern' ? param.left : param)
219
140
 
220
- function isPrivateHeaderCall(node: Extract<Node, { type: 'CallExpression' }>, headersAliases?: ReadonlySet<string>): string | undefined {
221
- const callee = unwrapTsExpr(node.callee)
222
- if (callee.type !== 'MemberExpression')
223
- return undefined
224
- const method = memberPropName(callee)
225
- const firstArg = node.arguments[0]
226
- if ((method !== 'get' && method !== 'has') || firstArg === undefined || firstArg.type === 'SpreadElement')
227
- return undefined
228
- const arg = staticStringOrNumber(firstArg)
229
- const header = arg.ok && typeof arg.value === 'string' ? arg.value.toLowerCase() : undefined
230
- if (header === undefined || !PRIVATE_HEADERS.has(header))
231
- return undefined
232
- const obj = unwrapTsExpr(callee.object)
233
- const isHeadersObj = (obj.type === 'MemberExpression' && memberPropName(obj) === 'headers')
234
- || (obj.type === 'Identifier' && (obj.name === 'headers' || headersAliases?.has(obj.name) === true))
235
- if (!isHeadersObj)
236
- return undefined
237
- const owner = obj.type === 'MemberExpression' && obj.object.type === 'Identifier' && obj.object.name === 'ctx' ? 'ctx' : 'request'
238
- return `${owner}.headers.${method}('${header}')`
239
- }
240
-
241
- interface TrackedContext {
242
- paramName: string | undefined
243
- trackedProps: ReadonlySet<string>
244
- prefix: string
245
- checkHeaders: boolean
246
- requestAliases: Set<string>
247
- headersAliases: Set<string>
248
- onHit: (hit: PrivateReadHit) => void
249
- }
250
-
251
- function collectHeaderAlias(pattern: Extract<Node, { type: 'ObjectPattern' }>, headersAliases: Set<string>): void {
252
- for (const prop of pattern.properties) {
253
- if (prop.type === 'Property' && propKeyName(prop) === 'headers') {
254
- const hv = unwrapParam(prop.value)
255
- if (hv.type === 'Identifier')
256
- headersAliases.add(hv.name)
257
- }
258
- }
259
- }
260
-
261
- function scanObjectPattern(pattern: Extract<Node, { type: 'ObjectPattern' }>, ctx: TrackedContext, prefix: string): void {
262
- for (const prop of pattern.properties) {
263
- if (prop.type !== 'Property')
264
- continue
265
- const key = propKeyName(prop)
266
- if (key !== undefined && ctx.trackedProps.has(key))
267
- ctx.onHit({ what: `${prefix}${key}`, offset: prop.start })
268
- if (!ctx.checkHeaders || key !== 'request')
269
- continue
270
- const val = unwrapParam(prop.value)
271
- if (val.type === 'Identifier')
272
- ctx.requestAliases.add(val.name)
273
- else if (val.type === 'ObjectPattern')
274
- collectHeaderAlias(val, ctx.headersAliases)
275
- }
276
- }
277
-
278
- function trackDeclarator(ast: Extract<Node, { type: 'VariableDeclarator' }>, ctx: TrackedContext, paramActive: boolean): void {
279
- if (ast.init === null)
280
- return
281
- const init = unwrapTsExpr(ast.init)
282
- if (paramActive && init.type === 'Identifier' && init.name === ctx.paramName && ast.id.type === 'ObjectPattern')
283
- scanObjectPattern(ast.id, ctx, ctx.prefix)
284
- if (!ctx.checkHeaders)
285
- return
286
- if (init.type === 'MemberExpression' && ast.id.type === 'Identifier') {
287
- const key = memberPropName(init)
288
- const obj = unwrapTsExpr(init.object)
289
- if (key === 'request' && paramActive && obj.type === 'Identifier' && obj.name === ctx.paramName)
290
- ctx.requestAliases.add(ast.id.name)
291
- if (key === 'headers')
292
- ctx.headersAliases.add(ast.id.name)
293
- }
294
- else if (init.type === 'Identifier' && ctx.requestAliases.has(init.name) && ast.id.type === 'ObjectPattern') {
295
- collectHeaderAlias(ast.id, ctx.headersAliases)
296
- }
297
- }
298
-
299
- function blockScopeNames(block: Extract<Node, { type: 'BlockStatement' }>): Set<string> {
300
- const scope = new Set<string>()
301
- for (const stmt of block.body) {
302
- if (stmt.type === 'VariableDeclaration')
303
- for (const d of stmt.declarations) collectPatternNames(d.id, scope)
304
- else if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
305
- scope.add(stmt.id.name)
306
- }
307
- return scope
308
- }
309
-
310
- function walkTrackedFunction(
311
- fn: OxcFunction | ArrowFunctionExpression,
312
- trackedProps: ReadonlySet<string>,
313
- prefix: string,
314
- checkHeaders: boolean,
315
- onHit: (hit: PrivateReadHit) => void,
316
- ): void {
317
- if (fn.body === null || fn.params.length === 0)
318
- return
319
- const first = unwrapParam(fn.params[0]!)
320
- const ctx: TrackedContext = {
321
- paramName: first.type === 'Identifier' ? first.name : undefined,
322
- trackedProps,
323
- prefix,
324
- checkHeaders,
325
- requestAliases: new Set(),
326
- headersAliases: new Set(),
327
- onHit,
328
- }
329
- if (first.type === 'ObjectPattern')
330
- scanObjectPattern(first, ctx, '')
331
-
332
- const scopes: Set<string>[] = [new Set()]
333
- const isParamActive = (): boolean => ctx.paramName !== undefined && !scopes.some(s => s.has(ctx.paramName!))
334
-
335
- const visit = (node: unknown): void => {
336
- if (node === null || typeof node !== 'object')
337
- return
338
- if (Array.isArray(node)) {
339
- for (let i = 0; i < node.length; i++) visit(node[i])
340
- return
341
- }
342
- const ast = node as Node
343
- if (typeof ast.type !== 'string')
344
- return
345
- if (ast.type.startsWith('TS')) {
346
- if (TS_EXPR_WRAPPERS.has(ast.type)) visit((ast as { expression?: unknown }).expression)
347
- return
348
- }
349
- if (ast !== fn && (ast.type === 'FunctionDeclaration' || ast.type === 'FunctionExpression' || ast.type === 'ArrowFunctionExpression')) {
350
- const inner = ast as OxcFunction | ArrowFunctionExpression
351
- const scope = new Set<string>()
352
- if (inner.type !== 'ArrowFunctionExpression' && inner.id !== null) scope.add(inner.id.name)
353
- for (const p of inner.params) collectPatternNames(p, scope)
354
- scopes.push(scope)
355
- if (inner.body !== null) visit(inner.body)
356
- scopes.pop()
357
- return
358
- }
359
- if (ast.type === 'BlockStatement' && ast !== fn.body) {
360
- scopes.push(blockScopeNames(ast))
361
- for (const stmt of ast.body) visit(stmt)
362
- scopes.pop()
363
- return
364
- }
365
-
366
- const active = isParamActive()
367
- if (ast.type === 'VariableDeclarator') {
368
- trackDeclarator(ast, ctx, active)
369
- }
370
- else if (ast.type === 'MemberExpression' && active) {
371
- const obj = unwrapTsExpr(ast.object)
372
- const key = obj.type === 'Identifier' && obj.name === ctx.paramName ? memberPropName(ast) : undefined
373
- if (key !== undefined && ctx.trackedProps.has(key))
374
- ctx.onHit({ what: `${ctx.prefix}${key}`, offset: ast.start })
375
- }
376
- else if (ast.type === 'CallExpression' && ctx.checkHeaders) {
377
- const headerCall = isPrivateHeaderCall(ast, ctx.headersAliases)
378
- if (headerCall !== undefined)
379
- ctx.onHit({ what: headerCall, offset: ast.start })
380
- }
381
-
382
- const keys = visitorKeys[ast.type]
383
- if (keys === undefined)
384
- return
385
- const rec = ast as unknown as Record<string, unknown>
386
- for (let i = 0; i < keys.length; i++) {
387
- const val = rec[keys[i]!]
388
- if (val !== null && typeof val === 'object') visit(val)
389
- }
390
- }
391
-
392
- visit(fn.body)
393
- }
394
-
395
- function findModulePrivateHits(analysis: ModuleAnalysis, includeLoad: boolean, isPageOrLayout = true): PrivateReadHit[] {
396
- const hits: PrivateReadHit[] = []
397
- const seenOffsets = new Set<number>()
398
- const push = (hit: PrivateReadHit): void => {
399
- if (!seenOffsets.has(hit.offset)) {
400
- seenOffsets.add(hit.offset)
401
- hits.push(hit)
402
- }
403
- }
404
- for (const imp of analysis.imports) {
405
- if (imp.source === 'prunelle/server') {
406
- for (const spec of imp.specifiers) {
407
- if (PRIVATE_SERVER_IMPORTS.has(spec.imported))
408
- push({ what: `${spec.imported}()`, offset: imp.start })
409
- }
410
- }
411
- }
412
- walk(analysis.program, (node) => {
413
- if (!isPageOrLayout && node.type === 'JSXAttribute' && node.name.type === 'JSXIdentifier' && EVENT_ATTR.test(node.name.name))
414
- return false
415
- if (!isPageOrLayout && node.type === 'CallExpression' && node.callee.type === 'Identifier' && CLIENT_CALLBACK_CALLEES.has(node.callee.name))
416
- return false
417
- if (node.type === 'JSXOpeningElement') {
418
- const tag = resolvePrunelleTag(jsxTagName(node.name), analysis.imports)
419
- if (tag !== undefined && PRIVATE_TAGS.has(tag))
420
- push({ what: `<${tag}>`, offset: node.start })
421
- }
422
- else if (!isPageOrLayout && node.type === 'CallExpression') {
423
- const headerCall = isPrivateHeaderCall(node)
424
- if (headerCall !== undefined)
425
- push({ what: headerCall, offset: node.start })
426
- }
427
- return undefined
428
- })
429
- if (includeLoad) {
430
- const loadFn = findExportedFunction(analysis.program, 'load')
431
- if (loadFn !== undefined)
432
- walkTrackedFunction(loadFn, PRIVATE_CTX_PROPS, 'ctx.', true, push)
433
- }
434
- if (isPageOrLayout) {
435
- const defaultFn = findExportedFunction(analysis.program, 'default')
436
- if (defaultFn !== undefined)
437
- walkTrackedFunction(defaultFn, PRIVATE_PAGE_PROPS, '', true, push)
438
- }
439
- return hits
440
- }
441
-
442
- function collectTransitiveDeps(graph: GraphView, rootFile: string): string[] {
141
+ function collectTransitiveDeps(graph: PrivateGraphView, rootFile: string): string[] {
443
142
  const visited = new Set<string>([rootFile])
444
143
  const queue = [...graph.localDeps(rootFile)]
445
144
  const deps: string[] = []
@@ -456,7 +155,7 @@ function collectTransitiveDeps(graph: GraphView, rootFile: string): string[] {
456
155
 
457
156
  /** Validates every route exporting `export const cache = ...` against private per-visitor reads in `load()`, the page, ancestor `_layout.tsx` files, and their transitive local dependencies. */
458
157
  export function findCachedRoutePrivateReads(options: {
459
- graph: GraphView
158
+ graph: PrivateGraphView
460
159
  pageFiles: readonly string[]
461
160
  layoutsFor: (pageFile: string) => readonly string[]
462
161
  toRel: (file: string) => string
@@ -475,22 +174,22 @@ export function findCachedRoutePrivateReads(options: {
475
174
  continue
476
175
  const pageRel = toRel(pageFile)
477
176
  const sharedTail = 'cached responses are shared across visitors, so per-visitor data would leak.'
478
- pushHits(pageFile, findModulePrivateHits(analysis, true, true), w => `${tool}: cached route reads ${w}: ${sharedTail} Remove \`export const cache\` or stop reading ${w}.`)
177
+ pushHits(pageFile, findModulePrivateHits(analysis, true, true, pageFile, graph), w => `${tool}: cached route reads ${w}: ${sharedTail} Remove \`export const cache\` or stop reading ${w}.`)
479
178
  for (const depFile of collectTransitiveDeps(graph, pageFile)) {
480
179
  const dep = graph.analyses.get(depFile)
481
180
  if (dep !== undefined)
482
- pushHits(depFile, findModulePrivateHits(dep, false, false), w => `${tool}: cached route "${pageRel}" imports module reading ${w}: ${sharedTail} Remove \`export const cache\` from ${pageRel} or stop reading ${w}.`)
181
+ pushHits(depFile, findModulePrivateHits(dep, false, false, depFile, graph), w => `${tool}: cached route "${pageRel}" imports module reading ${w}: ${sharedTail} Remove \`export const cache\` from ${pageRel} or stop reading ${w}.`)
483
182
  }
484
183
  const layoutMsg = (w: string) => `${tool}: cached route "${pageRel}" inherits layout reading ${w}: ${sharedTail} Remove \`export const cache\` from ${pageRel}, move it into a route group with a public layout, or stop reading ${w}.`
485
184
  for (const layoutFile of layoutsFor(pageFile)) {
486
185
  const layoutAnalysis = graph.analyses.get(layoutFile)
487
186
  if (layoutAnalysis === undefined)
488
187
  continue
489
- pushHits(layoutFile, findModulePrivateHits(layoutAnalysis, true, true), layoutMsg)
188
+ pushHits(layoutFile, findModulePrivateHits(layoutAnalysis, true, true, layoutFile, graph), layoutMsg)
490
189
  for (const depFile of collectTransitiveDeps(graph, layoutFile)) {
491
190
  const dep = graph.analyses.get(depFile)
492
191
  if (dep !== undefined)
493
- pushHits(depFile, findModulePrivateHits(dep, false, false), layoutMsg)
192
+ pushHits(depFile, findModulePrivateHits(dep, false, false, depFile, graph), layoutMsg)
494
193
  }
495
194
  }
496
195
  }
@@ -540,7 +239,7 @@ function defaultReadsDynamicProps(fn: OxcFunction | ArrowFunctionExpression): bo
540
239
  if (first.type !== 'Identifier')
541
240
  return true
542
241
  let readsDynamic = false
543
- walkTrackedFunction(fn, DYNAMIC_PROPS, '', true, () => { readsDynamic = true })
242
+ walkTrackedFunction({ fn, trackedProps: DYNAMIC_PROPS, prefix: '', checkHeaders: true, onHit: () => { readsDynamic = true } })
544
243
  if (readsDynamic)
545
244
  return true
546
245
  walk(fn.body, (node) => {
@@ -573,7 +272,7 @@ function moduleReadsDynamicData(analysis: ModuleAnalysis, isRouteOrLayout: boole
573
272
  return false
574
273
  }
575
274
  }
576
- if (isNonDeterministicOrSyncIo(node) || (node.type === 'CallExpression' && isPrivateHeaderCall(node) !== undefined)) {
275
+ if (isNonDeterministicOrSyncIo(node) || (node.type === 'CallExpression' && checkHeaderCall(node) !== undefined)) {
577
276
  dynamic = true
578
277
  return false
579
278
  }
@@ -602,7 +301,7 @@ function isPureIslandFile(file: string, analysis: ModuleAnalysis, islands: Islan
602
301
  * and no request/clock reads across the page, its `_layout.tsx` chain, or local non-island modules they import.
603
302
  */
604
303
  export function isRouteCacheable(options: {
605
- graph: GraphView
304
+ graph: PrivateGraphView
606
305
  islands: IslandView
607
306
  file: string
608
307
  layoutSrcs: readonly string[]
@@ -49,18 +49,18 @@ export function checkEcoElement(element: JSXElement, tag: string, ctx: EcoElemen
49
49
  return
50
50
  const srcset = findAttr(attrs, 'srcset') ?? findAttr(attrs, 'srcSet')
51
51
  const candidates = srcset === undefined ? undefined : staticStringValueOf(srcset.value)
52
- if (srcset !== undefined && candidates !== undefined && WIDTH_DESCRIPTOR_RE.test(candidates) && findAttr(attrs, 'sizes') === undefined)
52
+ if (srcset !== undefined && candidates !== undefined && WIDTH_DESCRIPTOR_RE.test(candidates) && !hasSpread(attrs) && findAttr(attrs, 'sizes') === undefined)
53
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
54
  if (tag === 'img' && !hasSpread(attrs) && (findAttr(attrs, 'width') === undefined || findAttr(attrs, 'height') === undefined))
55
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
56
  }
57
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[] {
58
+ /** Warns on each file in `publicDir` past 1 MB, which every visitor showing it downloads as is. */
59
+ export function largePublicFileWarnings(root: string, isIgnored: boolean, publicDir = join(root, 'public')): string[] {
60
60
  if (isIgnored)
61
61
  return []
62
62
  const warnings: string[] = []
63
- for (const file of walkFiles(join(root, 'public'), { keep: entry => entry.isFile() }).sort()) {
63
+ for (const file of walkFiles(publicDir, { keep: entry => entry.isFile() }).sort()) {
64
64
  const size = statSync(file).size
65
65
  if (size > LARGE_PUBLIC_FILE_BYTES) {
66
66
  const rel = relPosix(root, file)
@@ -6,6 +6,7 @@ import { unwrapTsExpr } from './shared'
6
6
 
7
7
  // Hosts that only ever mean this machine, never a third party.
8
8
  const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'])
9
+ const EXPR_PLACEHOLDER = '__prunelle_expr__'
9
10
  const LOADING_LINK_RELS = new Set(['stylesheet', 'preload', 'preconnect', 'dns-prefetch', 'modulepreload', 'prefetch', 'prerender', 'icon', 'apple-touch-icon', 'manifest'])
10
11
  const SRC_TAGS = new Set(['script', 'iframe', 'img', 'video', 'audio', 'source', 'embed', 'track'])
11
12
  const SRCSET_TAGS = new Set(['img', 'source'])
@@ -51,13 +52,13 @@ export function thirdPartyOrigin(rawUrl: string): string | undefined {
51
52
  }
52
53
  }
53
54
 
54
- // Every string an expression can evaluate to, as far as the source shows it: a template literal gives its leading text, which holds the origin.
55
+ // Every string an expression can evaluate to, as far as the source shows it: template quasis are joined with a placeholder so CSS url(...) and multi-URL attributes stay intact across interpolations.
55
56
  function expressionStrings(expr: Expression): string[] {
56
57
  const node = unwrapTsExpr(expr)
57
58
  if (node.type === 'Literal')
58
59
  return typeof node.value === 'string' ? [node.value] : []
59
60
  if (node.type === 'TemplateLiteral')
60
- return [node.quasis[0]?.value.cooked ?? '']
61
+ return [node.quasis.map(q => q.value.cooked ?? '').join(EXPR_PLACEHOLDER)]
61
62
  if (node.type === 'ConditionalExpression')
62
63
  return [...expressionStrings(node.consequent), ...expressionStrings(node.alternate)]
63
64
  if (node.type === 'LogicalExpression')
@@ -134,7 +135,8 @@ export function thirdPartyLoads(element: JSXElement, tag: string): ThirdPartyLoa
134
135
  if (attr === undefined)
135
136
  continue
136
137
  const seen = new Set<string>()
137
- for (const url of attrStrings(attr).flatMap(urlsOf)) {
138
+ for (const rawUrl of attrStrings(attr).flatMap(urlsOf)) {
139
+ const url = rawUrl.split(EXPR_PLACEHOLDER, 1)[0]!
138
140
  const origin = thirdPartyOrigin(url)
139
141
  if (origin !== undefined && !seen.has(origin)) {
140
142
  seen.add(origin)
@@ -7,9 +7,10 @@ import type { RgaaJsxRule, RgaaScope } from './compliance-rgaa'
7
7
  import type { CompilerWarning } from './mistakes'
8
8
  import { existsSync, readFileSync } from 'node:fs'
9
9
  import { basename, join } from 'node:path'
10
- import { visitorKeys } from 'oxc-parser'
10
+ import { parseSync, visitorKeys } from 'oxc-parser'
11
11
  import { relPosix, walkFiles } from '../build/files'
12
12
  import { fileToRoutePath } from '../build/routes'
13
+ import { walk } from './ast'
13
14
  import {
14
15
  attrTargetKey,
15
16
  checkRgaaComponent,
@@ -81,8 +82,9 @@ const DEFAULT_LEGAL_PATHS = new Set(['/mentions-legales', '/legal', '/legal-noti
81
82
  const DEFAULT_PRIVACY_PATHS = new Set(['/privacy', '/privacy-policy', '/confidentialite', '/politique-de-confidentialite', '/donnees-personnelles', '/datenschutz'])
82
83
  // A component named Label (or ui.Label) wraps its control like <label>.
83
84
  const LABEL_COMPONENT_RE = /(?:^|\.)Label$/
84
- // An <input> collecting an email or a phone number, by its type or its name.
85
- const PERSONAL_DATA_INPUT_RE = /<input\b[^>]*?\b(?:type=["'](?:email|tel)["']|name=["'](?:email|phone|tel)["'])/
85
+ // `<input>` type/name values that collect an email address or a phone number.
86
+ const PERSONAL_DATA_TYPES = new Set(['email', 'tel'])
87
+ const PERSONAL_DATA_NAMES = new Set(['email', 'phone', 'tel'])
86
88
  const ACCESSIBILITY_PATHS = new Set(['/accessibilite', '/accessibility', '/declaration-accessibilite', '/accessibility-statement'])
87
89
  const ECO_DECLARATION_PATHS = new Set(['/ecoconception', '/declaration-ecoconception', '/eco-design'])
88
90
  // The marker the `prunelle new` legal and privacy notices put in front of every detail the publisher must supply.
@@ -514,6 +516,7 @@ export interface ProjectComplianceInput {
514
516
  root: string
515
517
  srcDir: string
516
518
  routesDir: string
519
+ publicDir?: string | undefined
517
520
  routeFiles: readonly string[]
518
521
  analyses: ReadonlyMap<string, ModuleAnalysis>
519
522
  compliance?: ComplianceConfig | undefined
@@ -534,6 +537,7 @@ export function pluginSetsLang(plugins: readonly { name: string }[]): boolean {
534
537
  /** Collects project-level CSS third-party URL warnings and the LCEN, RGPD and RGAA notice warnings for `prunelle check` and production `prunelle build`. */
535
538
  export function collectProjectComplianceWarnings(input: ProjectComplianceInput): string[] {
536
539
  const { root, srcDir, routesDir, routeFiles, analyses, compliance, consentMaxAge, site, lang, langFromPlugin } = input
540
+ const publicDir = input.publicDir ?? join(root, 'public')
537
541
  const warnings: string[] = []
538
542
  if (consentMaxAge !== undefined && consentMaxAge > CNIL_CHOICE_MAX_AGE && !isRuleIgnored('rgpd/consent-retention', compliance))
539
543
  warnings.push(formatDiagnostic('prunelle.config.ts:1:1', `[rgpd/consent-retention] consent.maxAge keeps the visitor's choice ${Math.round(consentMaxAge / 86_400)} days, past the 6 months the CNIL recommends before asking again: lower it to 15552000 (180 days) or remove it.`, 'warning'))
@@ -544,8 +548,8 @@ export function collectProjectComplianceWarnings(input: ProjectComplianceInput):
544
548
  keep: entry => entry.name.endsWith('.css') || entry.name.endsWith('.tsx'),
545
549
  }).sort()
546
550
  : []
547
- // public/ is served as is, so its stylesheets load whatever they point at too.
548
- const publicCss = walkFiles(join(root, 'public'), { keep: entry => entry.name.endsWith('.css') }).sort()
551
+ // publicDir is served as is, so its stylesheets load whatever they point at too.
552
+ const publicCss = walkFiles(publicDir, { keep: entry => entry.isFile() && entry.name.endsWith('.css') }).sort()
549
553
  for (const cssFile of [...srcFiles.filter(file => file.endsWith('.css')), ...publicCss]) {
550
554
  const code = readFileSync(cssFile, 'utf8')
551
555
  warnings.push(...checkCssCompliance(relPosix(root, cssFile), code, compliance, site))
@@ -573,30 +577,77 @@ export function collectProjectComplianceWarnings(input: ProjectComplianceInput):
573
577
  warnings.push(...checkRouteCompliance(pagePaths, compliance))
574
578
  if (pagePaths.length > 0 && lang === undefined && langFromPlugin !== true && !isRuleIgnored('rgaa/document-lang', compliance))
575
579
  warnings.push(formatDiagnostic('prunelle.config.ts:1:1', '[rgaa/document-lang] No lang in prunelle.config.ts, so every page says <html lang="en"> and @prunellejs/ui speaks English: set lang: \'fr\' (or the language your pages are written in).', 'warning'))
576
- warnings.push(...largePublicFileWarnings(root, isRuleIgnored('rgesn/large-public-file', compliance)))
577
- if (!isRuleIgnored('rgpd/privacy-notice', compliance) && !pagePaths.some(p => matchesNoticePath(p, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS)))
578
- warnings.push(...privacyNoticeWarnings(root, srcFiles.filter(file => file.endsWith('.tsx')), compliance?.privacyNotice))
580
+ warnings.push(...largePublicFileWarnings(root, isRuleIgnored('rgesn/large-public-file', compliance), publicDir))
581
+ if (!isRuleIgnored('rgpd/privacy-notice', compliance) && !pagePaths.some(p => matchesNoticePath(p, compliance?.privacyNotice, DEFAULT_PRIVACY_PATHS))) {
582
+ const tsxFiles = [...new Set([...srcFiles.filter(file => file.endsWith('.tsx')), ...routeFiles.filter(file => file.endsWith('.tsx'))])].sort()
583
+ warnings.push(...privacyNoticeWarnings(root, tsxFiles, analyses, compliance?.privacyNotice))
584
+ }
579
585
  return warnings
580
586
  }
581
587
 
582
- // One warning, at the first form field collecting an email or a phone number: a single privacy page covers every form.
583
- function privacyNoticeWarnings(root: string, tsxFiles: readonly string[], custom: string | false | undefined): string[] {
588
+ function isPersonalDataInput(el: JSXElement): boolean {
589
+ if (jsxTagName(el.openingElement.name) !== 'input')
590
+ return false
591
+ const attrs = el.openingElement.attributes
592
+ const typeAttr = findAttr(attrs, 'type')
593
+ const typeVal = typeAttr === undefined ? undefined : staticStringValueOf(typeAttr.value)?.toLowerCase()
594
+ if (typeVal !== undefined && PERSONAL_DATA_TYPES.has(typeVal))
595
+ return true
596
+ const nameAttr = findAttr(attrs, 'name')
597
+ const nameVal = nameAttr === undefined ? undefined : staticStringValueOf(nameAttr.value)?.toLowerCase()
598
+ return nameVal !== undefined && PERSONAL_DATA_NAMES.has(nameVal)
599
+ }
600
+
601
+ function findPersonalDataInputOffset(program: Program, ignores: IgnoreMap): number | undefined {
602
+ let found: number | undefined
603
+ walk(program, (node): boolean | undefined => {
604
+ if (found !== undefined)
605
+ return false
606
+ if (node.type === 'JSXElement' && isPersonalDataInput(node) && !isIgnoredAt(ignores, 'rgpd/privacy-notice', node.start)) {
607
+ found = node.start
608
+ return false
609
+ }
610
+ return undefined
611
+ })
612
+ return found
613
+ }
614
+
615
+ // One warning, at the first un-ignored form field collecting an email or a phone number: a single privacy page covers every form.
616
+ function privacyNoticeWarnings(root: string, tsxFiles: readonly string[], analyses: ReadonlyMap<string, ModuleAnalysis>, custom: string | false | undefined): string[] {
584
617
  for (const file of tsxFiles) {
618
+ const analysis = analyses.get(file)
619
+ if (analysis !== undefined && !analysis.hasJsx)
620
+ continue
585
621
  const code = readFileSync(file, 'utf8')
586
- const match = PERSONAL_DATA_INPUT_RE.exec(code)
587
- if (match === null)
622
+ const ignores = parsePrunelleIgnores(code)
623
+ if (ignores.fileRules.has('rgpd/privacy-notice'))
624
+ continue
625
+ const program = analysis?.program ?? parseSync(file, code, { lang: 'tsx' }).program
626
+ const offset = findPersonalDataInputOffset(program, ignores)
627
+ if (offset === undefined)
588
628
  continue
589
629
  const relFile = relPosix(root, file)
590
630
  const expected = typeof custom === 'string' ? normalizePath(custom) : '/privacy (or /confidentialite)'
591
- return [formatDiagnostic(formatLoc(relFile, code, match.index), `[rgpd/privacy-notice] ${relFile} collects an email or a phone number but the app has no privacy notice route: RGPD art. 13 requires telling people, as their data is collected, who processes it, why, for how long and what their rights are; add ${expected} and link it beside the form, set compliance.privacyNotice, or silence with compliance: { privacyNotice: false }.`, 'warning')]
631
+ return [formatDiagnostic(formatLoc(relFile, code, offset), `[rgpd/privacy-notice] ${relFile} collects an email or a phone number but the app has no privacy notice route: RGPD art. 13 requires telling people, as their data is collected, who processes it, why, for how long and what their rights are; add ${expected} and link it beside the form, set compliance.privacyNotice, or silence with compliance: { privacyNotice: false }.`, 'warning')]
592
632
  }
593
633
  return []
594
634
  }
595
635
 
596
- // One warning for the first unfilled detail: the publisher fills them all in one pass.
636
+ // One warning for the first unfilled detail outside comments and ignores: the publisher fills them all in one pass.
597
637
  function placeholderWarnings(relFile: string, code: string, notice: NoticeDetails): string[] {
598
- const offset = code.indexOf(notice.marker)
599
- if (offset === -1)
638
+ if (!code.includes(notice.marker))
639
+ return []
640
+ const ignores = parsePrunelleIgnores(code)
641
+ if (ignores.fileRules.has(notice.rule))
600
642
  return []
601
- return [formatDiagnostic(formatLoc(relFile, code, offset), `[${notice.rule}] The ${notice.page} still holds "${notice.marker} ...]" placeholders: ${notice.law}; replace every placeholder in ${relFile}.`, 'warning')]
643
+ const comments = parseSync(relFile, code, { lang: relFile.endsWith('.tsx') ? 'tsx' : 'ts' }).comments
644
+ const inComment = (offset: number): boolean => comments.some(c => offset >= c.start && offset < c.end)
645
+ for (let from = 0; ;) {
646
+ const offset = code.indexOf(notice.marker, from)
647
+ if (offset === -1)
648
+ return []
649
+ if (!inComment(offset) && !isIgnoredAt(ignores, notice.rule, offset))
650
+ return [formatDiagnostic(formatLoc(relFile, code, offset), `[${notice.rule}] The ${notice.page} still holds "${notice.marker} ...]" placeholders: ${notice.law}; replace every placeholder in ${relFile}.`, 'warning')]
651
+ from = offset + notice.marker.length
652
+ }
602
653
  }