prunelle 0.1.1 → 0.7.2

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 (177) hide show
  1. package/LICENSE +21 -0
  2. package/llms.txt +137 -40
  3. package/package.json +11 -2
  4. package/src/a11y/declaration.ts +373 -0
  5. package/src/a11y/index.ts +477 -0
  6. package/src/a11y/rgaa-map.ts +230 -0
  7. package/src/attrs.ts +11 -3
  8. package/src/build/bundle.ts +89 -41
  9. package/src/build/byte-size.ts +11 -0
  10. package/src/build/client-entries.ts +3 -2
  11. package/src/build/client-plugin.ts +11 -5
  12. package/src/build/client-prune.ts +56 -6
  13. package/src/build/compile.ts +13 -10
  14. package/src/build/ecoindex.ts +238 -0
  15. package/src/build/files.ts +15 -0
  16. package/src/build/first-load.ts +85 -14
  17. package/src/build/graph.ts +29 -39
  18. package/src/build/index.ts +225 -122
  19. package/src/build/island-promote.ts +311 -0
  20. package/src/build/islands.ts +14 -203
  21. package/src/build/manifest.ts +56 -116
  22. package/src/build/output.ts +3 -6
  23. package/src/build/plugin-host.ts +115 -41
  24. package/src/build/precompress.ts +16 -3
  25. package/src/build/prerender.ts +177 -39
  26. package/src/build/reach.ts +200 -0
  27. package/src/build/render-rules.ts +2 -2
  28. package/src/build/report.ts +48 -5
  29. package/src/build/resolve.ts +8 -6
  30. package/src/build/routes.ts +175 -10
  31. package/src/build/static-headers.ts +112 -0
  32. package/src/build/static.ts +139 -39
  33. package/src/build/status-pages.ts +127 -0
  34. package/src/build/style-bundles.ts +526 -0
  35. package/src/cli/check-forms.ts +636 -0
  36. package/src/cli/check-imports.ts +31 -0
  37. package/src/cli/check-links.ts +632 -0
  38. package/src/cli/check-security.ts +64 -0
  39. package/src/cli/check.ts +101 -26
  40. package/src/cli/commands.ts +120 -11
  41. package/src/cli/docs.ts +403 -0
  42. package/src/cli/inspect.ts +105 -15
  43. package/src/cli/mcp-tools.ts +492 -0
  44. package/src/cli/mcp.ts +205 -0
  45. package/src/cli/new.ts +16 -5
  46. package/src/cli/render.ts +416 -0
  47. package/src/cli/upgrade-names.ts +73 -13
  48. package/src/cli/upgrade.ts +156 -22
  49. package/src/compiler/analyze.ts +87 -54
  50. package/src/compiler/browser-globals.ts +140 -17
  51. package/src/compiler/cacheability-private.ts +566 -0
  52. package/src/compiler/cacheability.ts +335 -0
  53. package/src/compiler/compliance-eco.ts +71 -0
  54. package/src/compiler/compliance-rgaa.ts +614 -0
  55. package/src/compiler/compliance-urls.ts +148 -0
  56. package/src/compiler/compliance.ts +407 -352
  57. package/src/compiler/data-keys.ts +199 -192
  58. package/src/compiler/dev-source.ts +87 -0
  59. package/src/compiler/dom-attrs.ts +138 -65
  60. package/src/compiler/dom.ts +517 -442
  61. package/src/compiler/expr-context.ts +260 -81
  62. package/src/compiler/foreign-imports.ts +88 -0
  63. package/src/compiler/mistakes.ts +23 -2
  64. package/src/compiler/props-body.ts +60 -0
  65. package/src/compiler/props.ts +87 -36
  66. package/src/compiler/scope.ts +400 -333
  67. package/src/compiler/server-only.ts +190 -151
  68. package/src/compiler/shared.ts +42 -14
  69. package/src/compiler/signal-reads.ts +6 -2
  70. package/src/compiler/spread-handlers.ts +295 -0
  71. package/src/compiler/ssr-prunelle-tags.ts +27 -14
  72. package/src/compiler/ssr.ts +220 -89
  73. package/src/context.ts +34 -0
  74. package/src/dev/error-log.ts +177 -0
  75. package/src/dev/host-check.ts +32 -0
  76. package/src/dev/index.ts +94 -34
  77. package/src/dev/open-editor.ts +228 -0
  78. package/src/dev/protocol.ts +3 -0
  79. package/src/dev/reload.ts +5 -3
  80. package/src/dev/supervisor.ts +50 -25
  81. package/src/dev/watchers.ts +74 -13
  82. package/src/dom/action.ts +47 -21
  83. package/src/dom/attrs.ts +15 -3
  84. package/src/dom/extras.ts +57 -40
  85. package/src/dom/index.ts +54 -14
  86. package/src/dom/island.ts +102 -68
  87. package/src/dom/loop.ts +66 -32
  88. package/src/eco/declaration.ts +328 -0
  89. package/src/eco/index.ts +69 -0
  90. package/src/index.ts +2 -2
  91. package/src/jsx-runtime.ts +2 -2
  92. package/src/plugins/config.ts +18 -12
  93. package/src/plugins/context.ts +44 -1
  94. package/src/plugins/index.ts +2 -2
  95. package/src/plugins/load.ts +30 -10
  96. package/src/plugins/order.ts +38 -1
  97. package/src/plugins/public.ts +6 -3
  98. package/src/plugins/services.ts +84 -0
  99. package/src/plugins/types.ts +51 -2
  100. package/src/reactivity/graph.ts +10 -0
  101. package/src/reactivity/index.ts +24 -16
  102. package/src/reactivity/selector.ts +31 -4
  103. package/src/reactivity/store.ts +64 -20
  104. package/src/server/action-flash.ts +158 -0
  105. package/src/server/action-protect.ts +199 -0
  106. package/src/server/action-registry.ts +1 -1
  107. package/src/server/action.ts +188 -152
  108. package/src/server/app-secret.ts +63 -0
  109. package/src/server/assets.ts +34 -2
  110. package/src/server/compress.ts +96 -10
  111. package/src/server/consent.ts +59 -22
  112. package/src/server/cookies.ts +16 -2
  113. package/src/server/document.ts +25 -10
  114. package/src/server/env.ts +14 -0
  115. package/src/server/errors.ts +308 -65
  116. package/src/server/form-schema.ts +337 -0
  117. package/src/server/health.ts +275 -0
  118. package/src/server/http.ts +186 -39
  119. package/src/server/index.ts +272 -273
  120. package/src/server/loader.ts +15 -2
  121. package/src/server/page.ts +15 -0
  122. package/src/server/param-matchers.ts +112 -0
  123. package/src/server/plugin-host.ts +125 -88
  124. package/src/server/public.ts +6 -5
  125. package/src/server/rate-limit.ts +102 -36
  126. package/src/server/request-body.ts +1 -1
  127. package/src/server/route-cache.ts +541 -0
  128. package/src/server/route-table.ts +356 -11
  129. package/src/server/router.ts +125 -40
  130. package/src/server/routing.ts +112 -63
  131. package/src/server/sanitize-html.ts +309 -0
  132. package/src/server/security.ts +279 -52
  133. package/src/server/serve-handlers.ts +31 -7
  134. package/src/server/standard-schema.ts +17 -0
  135. package/src/server/start.ts +60 -16
  136. package/src/server/static-dir.ts +91 -12
  137. package/src/server/stream.ts +68 -27
  138. package/src/ssr/consent-banner.ts +58 -0
  139. package/src/ssr/context.ts +106 -8
  140. package/src/ssr/index.ts +151 -4
  141. package/src/ssr/navigation.ts +2 -2
  142. package/src/ssr/region.ts +40 -19
  143. package/src/style.ts +64 -1
  144. package/src/test/browser.ts +28 -13
  145. package/src/test/index.ts +97 -12
  146. package/src/ts-plugin/diagnostics.ts +505 -0
  147. package/src/ts-plugin/fixes.ts +364 -0
  148. package/src/ts-plugin/index.ts +194 -0
  149. package/templates/_shared/AGENTS.md +2 -2
  150. package/templates/_shared/gitignore +5 -0
  151. package/templates/_shared/mcp.json +11 -0
  152. package/templates/_shared/src/routes/legal.tsx +15 -1
  153. package/templates/_shared/tsconfig.json +5 -0
  154. package/templates/app/.env.example +4 -0
  155. package/templates/app/package.json +2 -1
  156. package/templates/app/prunelle.config.ts +2 -0
  157. package/templates/app/src/auth.ts +4 -6
  158. package/templates/app/src/mail.ts +4 -0
  159. package/templates/app/src/routes/_layout.tsx +9 -1
  160. package/templates/app/src/routes/dashboard/index.tsx +42 -8
  161. package/templates/app/src/routes/login.tsx +49 -30
  162. package/templates/app/src/routes/privacy.tsx +25 -0
  163. package/templates/app/src/styles/app.css +8 -1
  164. package/templates/app/tests/app.test.ts +44 -3
  165. package/templates/blog/package.json +1 -1
  166. package/templates/blog/prunelle.config.ts +1 -1
  167. package/templates/blog/src/routes/_layout.tsx +6 -1
  168. package/templates/blog/src/routes/index.tsx +5 -1
  169. package/templates/blog/src/styles/app.css +6 -1
  170. package/templates/fullstack/package.json +1 -1
  171. package/templates/fullstack/src/components/GreetForm.tsx +2 -1
  172. package/templates/fullstack/src/routes/_layout.tsx +4 -0
  173. package/templates/fullstack/src/styles/app.css +11 -1
  174. package/templates/minimal/package.json +1 -1
  175. package/templates/minimal/src/routes/_layout.tsx +4 -0
  176. package/templates/minimal/src/styles/app.css +11 -1
  177. package/ts-plugin.cjs +4277 -0
@@ -0,0 +1,566 @@
1
+ // Private-read analysis for cached routes: tracks `ctx`/`props`/`request`/`headers` aliases,
2
+ // header inspections, and helper calls across same-file and local-module boundaries.
3
+
4
+ import type { ArrowFunctionExpression, Function as OxcFunction, Node, Program } from 'oxc-parser'
5
+ import type { ModuleAnalysis } from './analyze'
6
+ import { visitorKeys } from 'oxc-parser'
7
+ import { walk } from './ast'
8
+ import { collectPatternNames, EVENT_ATTR, jsxTagName, resolvePrunelleTag, staticLiteral, unwrapTsExpr } from './shared'
9
+
10
+ export const PRIVATE_CTX_PROPS = new Set(['cookies', 'locals', 'consent', 'ip'])
11
+ export const PRIVATE_PAGE_PROPS = new Set(['locals', 'cookies', 'consent', 'ip'])
12
+ export const PRIVATE_SERVER_IMPORTS = new Set(['getActionError', 'currentRequest'])
13
+ const PRIVATE_HEADERS = new Set(['cookie', 'authorization'])
14
+ const BULK_HEADER_METHODS = new Set(['entries', 'values', 'keys', 'forEach', 'toJSON', 'getSetCookie'])
15
+ const PRIVATE_TAGS = new Set(['ConsentGate', 'ConsentBanner', 'ConsentPreferences'])
16
+ const CLIENT_CALLBACK_CALLEES = new Set(['onMount', 'effect', 'onCleanup'])
17
+ const TS_EXPR_WRAPPERS = new Set(['TSAsExpression', 'TSNonNullExpression', 'TSSatisfiesExpression', 'TSTypeAssertion', 'TSInstantiationExpression'])
18
+
19
+ export interface PrivateReadHit {
20
+ what: string
21
+ offset: number
22
+ }
23
+
24
+ export interface PrivateGraphView {
25
+ readonly analyses: ReadonlyMap<string, ModuleAnalysis>
26
+ localDeps(file: string): readonly string[]
27
+ resolve?(from: string, specifier: string): string | undefined
28
+ }
29
+
30
+ type AliasKind = 'param' | 'request' | 'headers' | 'shadowed'
31
+ type ScopeMap = Map<string, AliasKind>
32
+
33
+ export function staticStringOrNumber(node: Node): { ok: true, value: string | number } | { ok: false, isLiteral: boolean } {
34
+ const inner = unwrapTsExpr(node)
35
+ if (inner.type === 'TemplateLiteral' && inner.expressions.length === 0 && inner.quasis.length === 1)
36
+ return { ok: true, value: inner.quasis[0]!.value.cooked ?? inner.quasis[0]!.value.raw }
37
+ const lit = staticLiteral(inner)
38
+ if (!lit.ok)
39
+ return { ok: false, isLiteral: false }
40
+ return typeof lit.value === 'string' || typeof lit.value === 'number'
41
+ ? { ok: true, value: lit.value }
42
+ : { ok: false, isLiteral: true }
43
+ }
44
+
45
+ export function propKeyName(prop: Node): string | undefined {
46
+ if (prop.type !== 'Property')
47
+ return undefined
48
+ if (!prop.computed && prop.key.type === 'Identifier')
49
+ return prop.key.name
50
+ return prop.key.type === 'Literal' && typeof prop.key.value === 'string' ? prop.key.value : undefined
51
+ }
52
+
53
+ export function memberPropName(node: Extract<Node, { type: 'MemberExpression' }>): string | undefined {
54
+ if (!node.computed && node.property.type === 'Identifier')
55
+ return node.property.name
56
+ return node.computed && node.property.type === 'Literal' && typeof node.property.value === 'string' ? node.property.value : undefined
57
+ }
58
+
59
+ function collectTopLevelFns(program: Program): { fns: Map<string, OxcFunction>, inits: Map<string, Node> } {
60
+ const fns = new Map<string, OxcFunction>()
61
+ const inits = new Map<string, Node>()
62
+ const add = (node: Node): void => {
63
+ if (node.type === 'FunctionDeclaration' && node.id !== null)
64
+ fns.set(node.id.name, node)
65
+ else if (node.type === 'VariableDeclaration')
66
+ for (const d of node.declarations) if (d.id.type === 'Identifier' && d.init !== null) inits.set(d.id.name, d.init)
67
+ }
68
+ for (const stmt of program.body)
69
+ add(stmt.type === 'ExportNamedDeclaration' && stmt.declaration !== null ? stmt.declaration : stmt)
70
+ return { fns, inits }
71
+ }
72
+
73
+ function unwrapFn(node: Node | undefined, fns: ReadonlyMap<string, OxcFunction>, inits: ReadonlyMap<string, Node>, depth = 0): OxcFunction | ArrowFunctionExpression | undefined {
74
+ if (node === undefined || depth > 4)
75
+ return undefined
76
+ const inner = unwrapTsExpr(node)
77
+ if (inner.type === 'FunctionDeclaration' || inner.type === 'FunctionExpression' || inner.type === 'ArrowFunctionExpression')
78
+ return inner
79
+ return inner.type === 'Identifier' ? fns.get(inner.name) ?? unwrapFn(inits.get(inner.name), fns, inits, depth + 1) : undefined
80
+ }
81
+
82
+ export function findExportedFunction(program: Program, exportName: string): OxcFunction | ArrowFunctionExpression | undefined {
83
+ const { fns, inits } = collectTopLevelFns(program)
84
+ for (const stmt of program.body) {
85
+ if (exportName === 'default' && stmt.type === 'ExportDefaultDeclaration')
86
+ return unwrapFn(stmt.declaration, fns, inits)
87
+ if (stmt.type !== 'ExportNamedDeclaration' || stmt.exportKind === 'type')
88
+ continue
89
+ if (stmt.declaration?.type === 'FunctionDeclaration' && stmt.declaration.id?.name === exportName)
90
+ return stmt.declaration
91
+ if (stmt.declaration?.type === 'VariableDeclaration') {
92
+ for (const d of stmt.declaration.declarations) {
93
+ if (d.id.type === 'Identifier' && d.id.name === exportName)
94
+ return unwrapFn(d.init ?? undefined, fns, inits)
95
+ }
96
+ }
97
+ for (const spec of stmt.specifiers) {
98
+ const exp = spec.exported.type === 'Identifier' ? spec.exported.name : spec.exported.value
99
+ if (exp === exportName && stmt.source === null && spec.local.type === 'Identifier')
100
+ return fns.get(spec.local.name) ?? unwrapFn(inits.get(spec.local.name), fns, inits)
101
+ }
102
+ }
103
+ return undefined
104
+ }
105
+
106
+ const unwrapParam = (param: Node): Node => (param.type === 'AssignmentPattern' ? param.left : param)
107
+
108
+ function headerOwner(obj: Node): string {
109
+ const inner = unwrapTsExpr(obj)
110
+ return inner.type === 'MemberExpression' && inner.object.type === 'Identifier' && inner.object.name === 'ctx' ? 'ctx' : 'request'
111
+ }
112
+
113
+ function isHeadersExpr(node: Node, lookupAlias: (name: string) => AliasKind | undefined, allowBareHeaders: boolean): boolean {
114
+ const inner = unwrapTsExpr(node)
115
+ if (inner.type === 'Identifier') {
116
+ const kind = lookupAlias(inner.name)
117
+ return kind === 'headers' || (allowBareHeaders && kind === undefined && inner.name === 'headers')
118
+ }
119
+ return inner.type === 'MemberExpression' && memberPropName(inner) === 'headers'
120
+ }
121
+
122
+ export function checkHeaderCall(
123
+ node: Extract<Node, { type: 'CallExpression' }>,
124
+ lookupAlias: (name: string) => AliasKind | undefined = () => undefined,
125
+ allowBareHeaders = true,
126
+ ): string | undefined {
127
+ const callee = unwrapTsExpr(node.callee)
128
+ if (callee.type !== 'MemberExpression' || !isHeadersExpr(callee.object, lookupAlias, allowBareHeaders))
129
+ return undefined
130
+ const method = memberPropName(callee)
131
+ const owner = headerOwner(callee.object)
132
+ if (method === 'get' || method === 'has') {
133
+ const firstArg = node.arguments[0]
134
+ if (firstArg === undefined || firstArg.type === 'SpreadElement')
135
+ return `${owner}.headers.${method}(...)`
136
+ const arg = staticStringOrNumber(firstArg)
137
+ if (!arg.ok || typeof arg.value !== 'string')
138
+ return `${owner}.headers.${method}(...)`
139
+ const header = arg.value.toLowerCase()
140
+ return PRIVATE_HEADERS.has(header) ? `${owner}.headers.${method}('${header}')` : undefined
141
+ }
142
+ return method !== undefined && BULK_HEADER_METHODS.has(method) ? `${owner}.headers.${method}()` : undefined
143
+ }
144
+
145
+ function calleeLabel(node: Node): string {
146
+ const inner = unwrapTsExpr(node)
147
+ if (inner.type === 'Identifier')
148
+ return inner.name
149
+ if (inner.type === 'MemberExpression') {
150
+ const prop = memberPropName(inner)
151
+ if (prop !== undefined)
152
+ return `${calleeLabel(inner.object)}.${prop}`
153
+ }
154
+ return 'helper'
155
+ }
156
+
157
+ function blockScopeNames(block: Extract<Node, { type: 'BlockStatement' }>): Set<string> {
158
+ const scope = new Set<string>()
159
+ for (const stmt of block.body) {
160
+ if (stmt.type === 'VariableDeclaration')
161
+ for (const d of stmt.declarations) collectPatternNames(d.id, scope)
162
+ else if (stmt.type === 'FunctionDeclaration' && stmt.id !== null)
163
+ scope.add(stmt.id.name)
164
+ }
165
+ return scope
166
+ }
167
+
168
+ export interface WalkTrackedOptions {
169
+ fn: OxcFunction | ArrowFunctionExpression
170
+ paramIndex?: number | undefined
171
+ initialKind?: 'param' | 'request' | undefined
172
+ trackedProps: ReadonlySet<string>
173
+ prefix: string
174
+ checkHeaders: boolean
175
+ checkEscapes?: boolean | undefined
176
+ file?: string | undefined
177
+ analysis?: ModuleAnalysis | undefined
178
+ graph?: PrivateGraphView | undefined
179
+ visitedCalls?: Set<string> | undefined
180
+ onHit: (hit: PrivateReadHit) => void
181
+ }
182
+
183
+ interface ResolvedCallee {
184
+ file: string | undefined
185
+ analysis: ModuleAnalysis | undefined
186
+ fn: OxcFunction | ArrowFunctionExpression
187
+ name: string
188
+ }
189
+
190
+ interface WalkState {
191
+ opts: WalkTrackedOptions
192
+ checkEscapes: boolean
193
+ visitedCalls: Set<string>
194
+ scopes: ScopeMap[]
195
+ topFns: { fns: Map<string, OxcFunction>, inits: Map<string, Node> }
196
+ checkedHeaderMembers: WeakSet<Node>
197
+ }
198
+
199
+ function lookupAlias(scopes: readonly ScopeMap[], name: string): AliasKind | undefined {
200
+ for (let i = scopes.length - 1; i >= 0; i--) {
201
+ const kind = scopes[i]!.get(name)
202
+ if (kind !== undefined)
203
+ return kind === 'shadowed' ? undefined : kind
204
+ }
205
+ return undefined
206
+ }
207
+
208
+ function resolveImportedFn(
209
+ file: string | undefined,
210
+ analysis: ModuleAnalysis | undefined,
211
+ graph: PrivateGraphView | undefined,
212
+ source: string,
213
+ exportName: string,
214
+ displayName: string,
215
+ ): ResolvedCallee | undefined {
216
+ if (file === undefined || analysis === undefined || graph?.resolve === undefined)
217
+ return undefined
218
+ const targetFile = graph.resolve(file, source)
219
+ const targetAnalysis = targetFile === undefined ? undefined : graph.analyses.get(targetFile)
220
+ if (targetAnalysis === undefined)
221
+ return undefined
222
+ const targetFn = findExportedFunction(targetAnalysis.program, exportName)
223
+ return targetFn === undefined ? undefined : { file: targetFile, analysis: targetAnalysis, fn: targetFn, name: displayName }
224
+ }
225
+
226
+ function resolveLocalCallee(calleeNode: Node, state: WalkState): ResolvedCallee | undefined {
227
+ const { file, analysis, graph } = state.opts
228
+ const isShadowed = (name: string): boolean => state.scopes.some(s => s.has(name))
229
+ const callee = unwrapTsExpr(calleeNode)
230
+ if (callee.type === 'Identifier' && !isShadowed(callee.name)) {
231
+ const sameFile = unwrapFn(callee, state.topFns.fns, state.topFns.inits)
232
+ if (sameFile !== undefined)
233
+ return { file, analysis, fn: sameFile, name: callee.name }
234
+ for (const imp of analysis?.imports ?? []) {
235
+ const spec = imp.specifiers.find(s => s.local === callee.name && s.imported !== '*')
236
+ if (spec !== undefined)
237
+ return resolveImportedFn(file, analysis, graph, imp.source, spec.imported, callee.name)
238
+ }
239
+ return undefined
240
+ }
241
+ if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && !isShadowed(callee.object.name)) {
242
+ const nsName = callee.object.name
243
+ const prop = memberPropName(callee)
244
+ if (prop === undefined)
245
+ return undefined
246
+ for (const imp of analysis?.imports ?? []) {
247
+ if (imp.specifiers.some(s => s.local === nsName && s.imported === '*'))
248
+ return resolveImportedFn(file, analysis, graph, imp.source, prop, `${nsName}.${prop}`)
249
+ }
250
+ }
251
+ return undefined
252
+ }
253
+
254
+ function bindHeadersFromPattern(pattern: Extract<Node, { type: 'ObjectPattern' }>, scope: ScopeMap): void {
255
+ for (const prop of pattern.properties) {
256
+ if (prop.type === 'Property' && propKeyName(prop) === 'headers') {
257
+ const hv = unwrapParam(prop.value)
258
+ if (hv.type === 'Identifier')
259
+ scope.set(hv.name, 'headers')
260
+ }
261
+ }
262
+ }
263
+
264
+ function bindObjectPattern(
265
+ pattern: Extract<Node, { type: 'ObjectPattern' }>,
266
+ trackedProps: ReadonlySet<string>,
267
+ prefix: string,
268
+ checkHeaders: boolean,
269
+ scope: ScopeMap,
270
+ onHit: (hit: PrivateReadHit) => void,
271
+ ): void {
272
+ for (const prop of pattern.properties) {
273
+ if (prop.type === 'RestElement') {
274
+ if (prop.argument.type === 'Identifier')
275
+ scope.set(prop.argument.name, 'param')
276
+ continue
277
+ }
278
+ const key = propKeyName(prop)
279
+ if (key !== undefined && trackedProps.has(key))
280
+ onHit({ what: `${prefix}${key}`, offset: prop.start })
281
+ if (!checkHeaders || key !== 'request')
282
+ continue
283
+ const val = unwrapParam(prop.value)
284
+ if (val.type === 'Identifier')
285
+ scope.set(val.name, 'request')
286
+ else if (val.type === 'ObjectPattern')
287
+ bindHeadersFromPattern(val, scope)
288
+ }
289
+ }
290
+
291
+ function exprAliasKind(node: Node, lookup: (name: string) => AliasKind | undefined, checkHeaders: boolean): AliasKind | undefined {
292
+ const inner = unwrapTsExpr(node)
293
+ if (inner.type === 'Identifier')
294
+ return lookup(inner.name)
295
+ if (inner.type === 'MemberExpression' && checkHeaders) {
296
+ const key = memberPropName(inner)
297
+ const obj = unwrapTsExpr(inner.object)
298
+ if (key === 'request' && obj.type === 'Identifier' && lookup(obj.name) === 'param')
299
+ return 'request'
300
+ if (key === 'headers')
301
+ return 'headers'
302
+ }
303
+ return undefined
304
+ }
305
+
306
+ function followOrFlagCall(state: WalkState, calleeNode: Node, argIdx: number, argKind: 'param' | 'request', callOffset: number): void {
307
+ const { opts, visitedCalls } = state
308
+ const targetLabel = argKind === 'request' ? 'request' : (opts.prefix === 'ctx.' ? 'ctx' : 'props')
309
+ const resolved = resolveLocalCallee(calleeNode, state)
310
+ if (resolved === undefined) {
311
+ opts.onHit({ what: `${targetLabel} via ${calleeLabel(calleeNode)}()`, offset: callOffset })
312
+ return
313
+ }
314
+ if (resolved.fn.params.length <= argIdx)
315
+ return
316
+ if (resolved.fn.params.slice(0, argIdx + 1).some(p => p.type === 'RestElement')) {
317
+ opts.onHit({ what: `${targetLabel} via ${calleeLabel(calleeNode)}()`, offset: callOffset })
318
+ return
319
+ }
320
+ const callKey = `${resolved.file ?? ''}:${resolved.fn.start}:${argIdx}:${argKind}`
321
+ if (visitedCalls.has(callKey))
322
+ return
323
+ visitedCalls.add(callKey)
324
+ walkTrackedFunction({
325
+ fn: resolved.fn,
326
+ paramIndex: argIdx,
327
+ initialKind: argKind,
328
+ trackedProps: opts.trackedProps,
329
+ prefix: argKind === 'param' ? opts.prefix : '',
330
+ checkHeaders: true,
331
+ checkEscapes: true,
332
+ file: resolved.file,
333
+ analysis: resolved.analysis,
334
+ graph: opts.graph,
335
+ visitedCalls,
336
+ onHit: hit => opts.onHit({ what: `${hit.what} (via ${resolved.name}())`, offset: callOffset }),
337
+ })
338
+ }
339
+
340
+ function inspectCallArgs(state: WalkState, calleeNode: Node, args: readonly Node[], callOffset: number): void {
341
+ const lookup = (name: string): AliasKind | undefined => lookupAlias(state.scopes, name)
342
+ for (let i = 0; i < args.length; i++) {
343
+ const arg = args[i]!
344
+ const expr = arg.type === 'SpreadElement' ? unwrapTsExpr(arg.argument) : unwrapTsExpr(arg)
345
+ if (state.opts.checkHeaders && isHeadersExpr(expr, lookup, true)) {
346
+ state.opts.onHit({ what: `${headerOwner(expr)}.headers`, offset: arg.start })
347
+ continue
348
+ }
349
+ if (!state.checkEscapes)
350
+ continue
351
+ const kind = exprAliasKind(expr, lookup, state.opts.checkHeaders)
352
+ if (kind === 'param' || kind === 'request')
353
+ followOrFlagCall(state, calleeNode, i, kind, callOffset)
354
+ }
355
+ }
356
+
357
+ function inspectDeclarator(ast: Extract<Node, { type: 'VariableDeclarator' }>, state: WalkState): void {
358
+ if (ast.init === null)
359
+ return
360
+ const { opts, scopes } = state
361
+ const kind = exprAliasKind(ast.init, name => lookupAlias(scopes, name), opts.checkHeaders)
362
+ if (kind === undefined || kind === 'shadowed')
363
+ return
364
+ const top = scopes[scopes.length - 1]!
365
+ if (ast.id.type === 'Identifier')
366
+ top.set(ast.id.name, kind)
367
+ else if (ast.id.type === 'ObjectPattern' && kind === 'param')
368
+ bindObjectPattern(ast.id, opts.trackedProps, opts.prefix, opts.checkHeaders, top, opts.onHit)
369
+ else if (ast.id.type === 'ObjectPattern' && kind === 'request' && opts.checkHeaders)
370
+ bindHeadersFromPattern(ast.id, top)
371
+ }
372
+
373
+ function inspectMemberAccess(ast: Extract<Node, { type: 'MemberExpression' }>, state: WalkState): void {
374
+ const { opts, scopes, checkEscapes, checkedHeaderMembers } = state
375
+ const lookup = (name: string): AliasKind | undefined => lookupAlias(scopes, name)
376
+ const obj = unwrapTsExpr(ast.object)
377
+ const objKind = obj.type === 'Identifier' ? lookup(obj.name) : undefined
378
+ if (objKind === 'param') {
379
+ const key = memberPropName(ast)
380
+ if (key !== undefined && opts.trackedProps.has(key))
381
+ opts.onHit({ what: `${opts.prefix}${key}`, offset: ast.start })
382
+ else if (checkEscapes && ast.computed && key === undefined)
383
+ opts.onHit({ what: `${opts.prefix}[...]`, offset: ast.start })
384
+ return
385
+ }
386
+ if (!opts.checkHeaders || checkedHeaderMembers.has(ast) || !isHeadersExpr(obj, lookup, true))
387
+ return
388
+ const key = memberPropName(ast)
389
+ if (key !== undefined && PRIVATE_HEADERS.has(key.toLowerCase()))
390
+ opts.onHit({ what: `${headerOwner(obj)}.headers['${key.toLowerCase()}']`, offset: ast.start })
391
+ else if (ast.computed && key === undefined)
392
+ opts.onHit({ what: `${headerOwner(obj)}.headers[...]`, offset: ast.start })
393
+ }
394
+
395
+ function inspectCallNode(ast: Extract<Node, { type: 'CallExpression' }>, state: WalkState): void {
396
+ const { opts, scopes, checkedHeaderMembers } = state
397
+ if (opts.checkHeaders) {
398
+ const lookup = (name: string): AliasKind | undefined => lookupAlias(scopes, name)
399
+ const callee = unwrapTsExpr(ast.callee)
400
+ if (callee.type === 'MemberExpression' && isHeadersExpr(callee.object, lookup, true)) {
401
+ checkedHeaderMembers.add(callee)
402
+ const headerHit = checkHeaderCall(ast, lookup, true)
403
+ if (headerHit !== undefined)
404
+ opts.onHit({ what: headerHit, offset: ast.start })
405
+ }
406
+ }
407
+ inspectCallArgs(state, ast.callee, ast.arguments, ast.start)
408
+ }
409
+
410
+ function inspectTrackedNode(ast: Node, state: WalkState): void {
411
+ const { opts, scopes, checkEscapes } = state
412
+ const lookup = (name: string): AliasKind | undefined => lookupAlias(scopes, name)
413
+ if (ast.type === 'VariableDeclarator')
414
+ return inspectDeclarator(ast, state)
415
+ if (ast.type === 'AssignmentExpression' && ast.left.type === 'Identifier') {
416
+ const kind = exprAliasKind(ast.right, lookup, opts.checkHeaders)
417
+ if (kind !== undefined && kind !== 'shadowed')
418
+ scopes[scopes.length - 1]!.set(ast.left.name, kind)
419
+ return
420
+ }
421
+ if (ast.type === 'CallExpression')
422
+ return inspectCallNode(ast, state)
423
+ if (ast.type === 'NewExpression')
424
+ return inspectCallArgs(state, ast.callee, ast.arguments, ast.start)
425
+ if (ast.type === 'MemberExpression')
426
+ return inspectMemberAccess(ast, state)
427
+ if (ast.type === 'SpreadElement') {
428
+ if (opts.checkHeaders && isHeadersExpr(ast.argument, lookup, true))
429
+ opts.onHit({ what: `${headerOwner(ast.argument)}.headers`, offset: ast.start })
430
+ else if (checkEscapes && exprAliasKind(ast.argument, lookup, opts.checkHeaders) === 'param')
431
+ opts.onHit({ what: `${opts.prefix === 'ctx.' ? 'ctx' : 'props'} spread`, offset: ast.start })
432
+ }
433
+ else if (ast.type === 'JSXSpreadAttribute' && checkEscapes && exprAliasKind(ast.argument, lookup, opts.checkHeaders) === 'param') {
434
+ opts.onHit({ what: `${opts.prefix === 'ctx.' ? 'ctx' : 'props'} spread`, offset: ast.start })
435
+ }
436
+ else if (ast.type === 'ForOfStatement' && opts.checkHeaders && isHeadersExpr(ast.right, lookup, true)) {
437
+ opts.onHit({ what: `${headerOwner(ast.right)}.headers`, offset: ast.right.start })
438
+ }
439
+ }
440
+
441
+ export function walkTrackedFunction(options: WalkTrackedOptions): void {
442
+ const { fn, trackedProps, checkHeaders, analysis, onHit } = options
443
+ const paramIndex = options.paramIndex ?? 0
444
+ const initialKind = options.initialKind ?? 'param'
445
+ if (fn.body === null || fn.params.length <= paramIndex)
446
+ return
447
+ const rawParam = fn.params[paramIndex]!
448
+ if (rawParam.type === 'RestElement')
449
+ return
450
+ const param = unwrapParam(rawParam)
451
+ const rootScope: ScopeMap = new Map()
452
+ if (param.type === 'Identifier')
453
+ rootScope.set(param.name, initialKind)
454
+ else if (param.type === 'ObjectPattern' && initialKind === 'param')
455
+ bindObjectPattern(param, trackedProps, '', checkHeaders, rootScope, onHit)
456
+ else if (param.type === 'ObjectPattern')
457
+ bindHeadersFromPattern(param, rootScope)
458
+
459
+ const state: WalkState = {
460
+ opts: options,
461
+ checkEscapes: options.checkEscapes === true,
462
+ visitedCalls: options.visitedCalls ?? new Set(),
463
+ scopes: [rootScope],
464
+ topFns: analysis !== undefined ? collectTopLevelFns(analysis.program) : { fns: new Map(), inits: new Map() },
465
+ checkedHeaderMembers: new WeakSet(),
466
+ }
467
+
468
+ const visit = (node: unknown): void => {
469
+ if (node === null || typeof node !== 'object')
470
+ return
471
+ if (Array.isArray(node)) {
472
+ for (let i = 0; i < node.length; i++) visit(node[i])
473
+ return
474
+ }
475
+ const ast = node as Node
476
+ if (typeof ast.type !== 'string')
477
+ return
478
+ if (ast.type.startsWith('TS')) {
479
+ if (TS_EXPR_WRAPPERS.has(ast.type)) visit((ast as { expression?: unknown }).expression)
480
+ return
481
+ }
482
+ if (ast !== fn && (ast.type === 'FunctionDeclaration' || ast.type === 'FunctionExpression' || ast.type === 'ArrowFunctionExpression')) {
483
+ const inner = ast as OxcFunction | ArrowFunctionExpression
484
+ const scope: ScopeMap = new Map()
485
+ if (inner.type !== 'ArrowFunctionExpression' && inner.id !== null) scope.set(inner.id.name, 'shadowed')
486
+ const names = new Set<string>()
487
+ for (const p of inner.params) collectPatternNames(p, names)
488
+ for (const name of names) scope.set(name, 'shadowed')
489
+ state.scopes.push(scope)
490
+ if (inner.body !== null) visit(inner.body)
491
+ state.scopes.pop()
492
+ return
493
+ }
494
+ if (ast.type === 'BlockStatement' && ast !== fn.body) {
495
+ const scope: ScopeMap = new Map()
496
+ for (const name of blockScopeNames(ast)) scope.set(name, 'shadowed')
497
+ state.scopes.push(scope)
498
+ for (const stmt of ast.body) visit(stmt)
499
+ state.scopes.pop()
500
+ return
501
+ }
502
+ inspectTrackedNode(ast, state)
503
+ const keys = visitorKeys[ast.type]
504
+ if (keys === undefined)
505
+ return
506
+ const rec = ast as unknown as Record<string, unknown>
507
+ for (let i = 0; i < keys.length; i++) {
508
+ const val = rec[keys[i]!]
509
+ if (val !== null && typeof val === 'object') visit(val)
510
+ }
511
+ }
512
+ visit(fn.body)
513
+ }
514
+
515
+ export function findModulePrivateHits(
516
+ analysis: ModuleAnalysis,
517
+ includeLoad: boolean,
518
+ isPageOrLayout = true,
519
+ file?: string,
520
+ graph?: PrivateGraphView,
521
+ ): PrivateReadHit[] {
522
+ const hits: PrivateReadHit[] = []
523
+ const seenOffsets = new Set<number>()
524
+ const push = (hit: PrivateReadHit): void => {
525
+ if (!seenOffsets.has(hit.offset)) {
526
+ seenOffsets.add(hit.offset)
527
+ hits.push(hit)
528
+ }
529
+ }
530
+ for (const imp of analysis.imports) {
531
+ if (imp.source === 'prunelle/server') {
532
+ for (const spec of imp.specifiers) {
533
+ if (PRIVATE_SERVER_IMPORTS.has(spec.imported))
534
+ push({ what: `${spec.imported}()`, offset: imp.start })
535
+ }
536
+ }
537
+ }
538
+ walk(analysis.program, (node) => {
539
+ if (!isPageOrLayout && node.type === 'JSXAttribute' && node.name.type === 'JSXIdentifier' && EVENT_ATTR.test(node.name.name))
540
+ return false
541
+ if (!isPageOrLayout && node.type === 'CallExpression' && node.callee.type === 'Identifier' && CLIENT_CALLBACK_CALLEES.has(node.callee.name))
542
+ return false
543
+ if (node.type === 'JSXOpeningElement') {
544
+ const tag = resolvePrunelleTag(jsxTagName(node.name), analysis.imports)
545
+ if (tag !== undefined && PRIVATE_TAGS.has(tag))
546
+ push({ what: `<${tag}>`, offset: node.start })
547
+ }
548
+ else if (!isPageOrLayout && node.type === 'CallExpression') {
549
+ const headerCall = checkHeaderCall(node)
550
+ if (headerCall !== undefined)
551
+ push({ what: headerCall, offset: node.start })
552
+ }
553
+ return undefined
554
+ })
555
+ if (includeLoad) {
556
+ const loadFn = findExportedFunction(analysis.program, 'load')
557
+ if (loadFn !== undefined)
558
+ walkTrackedFunction({ fn: loadFn, trackedProps: PRIVATE_CTX_PROPS, prefix: 'ctx.', checkHeaders: true, checkEscapes: true, file, analysis, graph, onHit: push })
559
+ }
560
+ if (isPageOrLayout) {
561
+ const defaultFn = findExportedFunction(analysis.program, 'default')
562
+ if (defaultFn !== undefined)
563
+ walkTrackedFunction({ fn: defaultFn, trackedProps: PRIVATE_PAGE_PROPS, prefix: '', checkHeaders: true, checkEscapes: true, file, analysis, graph, onHit: push })
564
+ }
565
+ return hits
566
+ }