@nifrajs/cli 5.17.0 → 5.18.1

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 (178) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/check-diagnostics.d.ts +7 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +3 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan-sql.d.ts +95 -0
  7. package/dist/check-scan-sql.d.ts.map +1 -0
  8. package/dist/check-scan-sql.js +1190 -0
  9. package/dist/check-scan-sql.js.map +1 -0
  10. package/dist/check-scan.d.ts +5 -93
  11. package/dist/check-scan.d.ts.map +1 -1
  12. package/dist/check-scan.js +20 -1207
  13. package/dist/check-scan.js.map +1 -1
  14. package/dist/check.d.ts.map +1 -1
  15. package/dist/check.js +9 -0
  16. package/dist/check.js.map +1 -1
  17. package/dist/cli.d.ts +2 -6
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +249 -80
  20. package/dist/cli.js.map +1 -1
  21. package/dist/command-catalog.d.ts +3 -0
  22. package/dist/command-catalog.d.ts.map +1 -1
  23. package/dist/command-catalog.js +18 -4
  24. package/dist/command-catalog.js.map +1 -1
  25. package/dist/frontend-guidance.js +1 -1
  26. package/dist/frontend-guidance.js.map +1 -1
  27. package/dist/internal/a11y-element.d.ts +33 -0
  28. package/dist/internal/a11y-element.d.ts.map +1 -0
  29. package/dist/internal/a11y-element.js +124 -0
  30. package/dist/internal/a11y-element.js.map +1 -0
  31. package/dist/internal/a11y-jsx.d.ts +12 -0
  32. package/dist/internal/a11y-jsx.d.ts.map +1 -0
  33. package/dist/internal/a11y-jsx.js +42 -0
  34. package/dist/internal/a11y-jsx.js.map +1 -0
  35. package/dist/internal/a11y-template.d.ts +11 -0
  36. package/dist/internal/a11y-template.d.ts.map +1 -0
  37. package/dist/internal/a11y-template.js +56 -0
  38. package/dist/internal/a11y-template.js.map +1 -0
  39. package/dist/internal/aria-data.d.ts +23 -0
  40. package/dist/internal/aria-data.d.ts.map +1 -0
  41. package/dist/internal/aria-data.js +220 -0
  42. package/dist/internal/aria-data.js.map +1 -0
  43. package/dist/internal/edit-distance.d.ts +3 -0
  44. package/dist/internal/edit-distance.d.ts.map +1 -0
  45. package/dist/internal/edit-distance.js +12 -0
  46. package/dist/internal/edit-distance.js.map +1 -0
  47. package/dist/internal/imported-as.d.ts +10 -0
  48. package/dist/internal/imported-as.d.ts.map +1 -0
  49. package/dist/internal/imported-as.js +23 -0
  50. package/dist/internal/imported-as.js.map +1 -0
  51. package/dist/internal/source-facts.d.ts +3 -0
  52. package/dist/internal/source-facts.d.ts.map +1 -1
  53. package/dist/internal/source-facts.js +2 -0
  54. package/dist/internal/source-facts.js.map +1 -1
  55. package/dist/internal/template-markup.d.ts +58 -0
  56. package/dist/internal/template-markup.d.ts.map +1 -0
  57. package/dist/internal/template-markup.js +221 -0
  58. package/dist/internal/template-markup.js.map +1 -0
  59. package/dist/internal/typescript-import.d.ts.map +1 -1
  60. package/dist/internal/typescript-import.js +11 -0
  61. package/dist/internal/typescript-import.js.map +1 -1
  62. package/dist/mcp-exec.d.ts.map +1 -1
  63. package/dist/mcp-exec.js +37 -23
  64. package/dist/mcp-exec.js.map +1 -1
  65. package/dist/mcp-http.js +1 -1
  66. package/dist/mcp-io.d.ts.map +1 -1
  67. package/dist/mcp-io.js +5 -3
  68. package/dist/mcp-io.js.map +1 -1
  69. package/dist/mcp-root.js +1 -1
  70. package/dist/mcp-root.js.map +1 -1
  71. package/dist/mcp-ws.d.ts.map +1 -1
  72. package/dist/mcp-ws.js +3 -2
  73. package/dist/mcp-ws.js.map +1 -1
  74. package/dist/migrate-layout-config.d.ts +63 -0
  75. package/dist/migrate-layout-config.d.ts.map +1 -0
  76. package/dist/migrate-layout-config.js +507 -0
  77. package/dist/migrate-layout-config.js.map +1 -0
  78. package/dist/migrate-layout-split.d.ts +46 -0
  79. package/dist/migrate-layout-split.d.ts.map +1 -0
  80. package/dist/migrate-layout-split.js +687 -0
  81. package/dist/migrate-layout-split.js.map +1 -0
  82. package/dist/migrate-layout.d.ts +4 -24
  83. package/dist/migrate-layout.d.ts.map +1 -1
  84. package/dist/migrate-layout.js +8 -1183
  85. package/dist/migrate-layout.js.map +1 -1
  86. package/dist/output-schemas.d.ts.map +1 -1
  87. package/dist/output-schemas.js +78 -10
  88. package/dist/output-schemas.js.map +1 -1
  89. package/dist/recipes/5.18.0.d.ts +9 -0
  90. package/dist/recipes/5.18.0.d.ts.map +1 -0
  91. package/dist/recipes/5.18.0.js +56 -0
  92. package/dist/recipes/5.18.0.js.map +1 -0
  93. package/dist/recipes/index.d.ts.map +1 -1
  94. package/dist/recipes/index.js +2 -0
  95. package/dist/recipes/index.js.map +1 -1
  96. package/dist/review.d.ts.map +1 -1
  97. package/dist/review.js +6 -0
  98. package/dist/review.js.map +1 -1
  99. package/dist/rules/a11y.d.ts +5 -0
  100. package/dist/rules/a11y.d.ts.map +1 -0
  101. package/dist/rules/a11y.js +78 -0
  102. package/dist/rules/a11y.js.map +1 -0
  103. package/dist/rules/codes.d.ts +6 -0
  104. package/dist/rules/codes.d.ts.map +1 -1
  105. package/dist/rules/codes.js +6 -0
  106. package/dist/rules/codes.js.map +1 -1
  107. package/dist/rules/comment-markers.js +1 -1
  108. package/dist/rules/comment-markers.js.map +1 -1
  109. package/dist/rules/explanations.d.ts.map +1 -1
  110. package/dist/rules/explanations.js +30 -0
  111. package/dist/rules/explanations.js.map +1 -1
  112. package/dist/rules/host-exposure.d.ts +23 -0
  113. package/dist/rules/host-exposure.d.ts.map +1 -0
  114. package/dist/rules/host-exposure.js +380 -0
  115. package/dist/rules/host-exposure.js.map +1 -0
  116. package/dist/rules/internal-links.d.ts.map +1 -1
  117. package/dist/rules/internal-links.js +16 -141
  118. package/dist/rules/internal-links.js.map +1 -1
  119. package/dist/rules/islands.d.ts +54 -0
  120. package/dist/rules/islands.d.ts.map +1 -1
  121. package/dist/rules/islands.js +577 -80
  122. package/dist/rules/islands.js.map +1 -1
  123. package/dist/rules/security.d.ts +1 -0
  124. package/dist/rules/security.d.ts.map +1 -1
  125. package/dist/rules/security.js +34 -7
  126. package/dist/rules/security.js.map +1 -1
  127. package/dist/runtime-differences.js +3 -3
  128. package/dist/runtime-differences.js.map +1 -1
  129. package/dist/scaffold.d.ts +1 -1
  130. package/dist/scaffold.d.ts.map +1 -1
  131. package/dist/scaffold.js +2 -2
  132. package/dist/scaffold.js.map +1 -1
  133. package/dist/source-rewrites.d.ts.map +1 -1
  134. package/dist/source-rewrites.js +2 -19
  135. package/dist/source-rewrites.js.map +1 -1
  136. package/docs/examples.json +4 -4
  137. package/docs/llms-full.txt +422 -42
  138. package/docs/types.json +466 -56
  139. package/package.json +12 -12
  140. package/src/check-diagnostics.ts +11 -0
  141. package/src/check-scan-sql.ts +1746 -0
  142. package/src/check-scan.ts +34 -1754
  143. package/src/check.ts +10 -1
  144. package/src/cli.ts +258 -98
  145. package/src/command-catalog.ts +21 -4
  146. package/src/frontend-guidance.ts +1 -1
  147. package/src/internal/a11y-element.ts +227 -0
  148. package/src/internal/a11y-jsx.ts +54 -0
  149. package/src/internal/a11y-template.ts +74 -0
  150. package/src/internal/aria-data.ts +242 -0
  151. package/src/internal/edit-distance.ts +16 -0
  152. package/src/internal/imported-as.ts +30 -0
  153. package/src/internal/source-facts.ts +4 -0
  154. package/src/internal/template-markup.ts +270 -0
  155. package/src/internal/typescript-import.ts +15 -0
  156. package/src/mcp-exec.ts +43 -22
  157. package/src/mcp-http.ts +1 -1
  158. package/src/mcp-io.ts +5 -3
  159. package/src/mcp-root.ts +1 -1
  160. package/src/mcp-ws.ts +3 -2
  161. package/src/migrate-layout-config.ts +615 -0
  162. package/src/migrate-layout-split.ts +870 -0
  163. package/src/migrate-layout.ts +37 -1468
  164. package/src/output-schemas.ts +85 -17
  165. package/src/recipes/5.18.0.ts +63 -0
  166. package/src/recipes/index.ts +2 -0
  167. package/src/review.ts +6 -0
  168. package/src/rules/a11y.ts +119 -0
  169. package/src/rules/codes.ts +6 -0
  170. package/src/rules/comment-markers.ts +2 -2
  171. package/src/rules/explanations.ts +30 -0
  172. package/src/rules/host-exposure.ts +531 -0
  173. package/src/rules/internal-links.ts +21 -154
  174. package/src/rules/islands.ts +698 -86
  175. package/src/rules/security.ts +48 -7
  176. package/src/runtime-differences.ts +3 -3
  177. package/src/scaffold.ts +3 -3
  178. package/src/source-rewrites.ts +2 -15
@@ -0,0 +1,1746 @@
1
+ /**
2
+ * AST-based interpolated SQL scanner for `nifra check`.
3
+ */
4
+ import { readFileSync, realpathSync } from "node:fs"
5
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path"
6
+ import type * as TSApi from "typescript"
7
+ import {
8
+ bySite,
9
+ IGNORED_DIR,
10
+ isRelativeSpecifier,
11
+ type SourceFinding,
12
+ type SqlFinding,
13
+ walkSource,
14
+ } from "./check-scan.ts"
15
+ import { realpathOrSelf } from "./internal/realpath-or-self.ts"
16
+ import { scriptKindOf } from "./internal/script-kind.ts"
17
+ import {
18
+ loadProjectTypeScript,
19
+ type TypeScriptApi,
20
+ type TypeScriptSourceIndex,
21
+ } from "./internal/typescript-import.ts"
22
+ import { commentBlockExpectation } from "./rules/comment-markers.ts"
23
+
24
+ /**
25
+ * SQL built by interpolating a value into the statement text. The value is not a parameter, it is
26
+ * STATEMENT, so anything the caller controls can end the literal and continue as SQL.
27
+ *
28
+ * Two things this deliberately does not flag, because both are safe and flagging them would train
29
+ * people to ignore the rule:
30
+ *
31
+ * - A TAGGED template - ``sql`... ${id} ...` `` in postgres.js, drizzle or kysely. The tag receives the
32
+ * substitutions separately and binds them; that is the parameterised form, not a bypass of it.
33
+ * - A literal with no substitution at all. `db.query("SELECT … WHERE id = ?")` is the shape being
34
+ * argued for.
35
+ *
36
+ * A SQL keyword is required in the literal, so `cache.query(`user:${id}`)` stays quiet. The named
37
+ * escape hatches (`$queryRawUnsafe`, `sql.unsafe`) are flagged on the call alone: their whole purpose
38
+ * is to take a statement as text, and a substitution in one is the exact thing the name warns about.
39
+ */
40
+ const SQL_METHODS = new Set([
41
+ "query",
42
+ "queryRaw",
43
+ "prepare",
44
+ "exec",
45
+ "execute",
46
+ "run",
47
+ "unsafe",
48
+ "$queryRawUnsafe",
49
+ "$executeRawUnsafe",
50
+ "raw",
51
+ ])
52
+ const SQL_KEYWORD =
53
+ /\b(select|insert\s+into|update|delete\s+from|drop\s+table|create\s+table|alter\s+table|truncate|from|where|values|set|join|union)\b/i
54
+ const ALWAYS_UNSAFE = new Set(["unsafe", "$queryRawUnsafe", "$executeRawUnsafe", "raw"])
55
+ /** Driver calls that take a statement under names that are everyday words elsewhere (`map.get`,
56
+ * `client.get("/users/update")`): node-sqlite3's `all`/`get`/`each` and pg-promise's result-shaping
57
+ * calls. One of these, and any bare call, is judged by whether its text starts like a statement. */
58
+ const DRIVER_READ_METHODS = new Set([
59
+ "all",
60
+ "get",
61
+ "each",
62
+ "any",
63
+ "one",
64
+ "none",
65
+ "many",
66
+ "oneOrNone",
67
+ "manyOrNone",
68
+ "result",
69
+ "multi",
70
+ "multiResult",
71
+ ])
72
+ const STATEMENT_START =
73
+ /^\s*\(?\s*(?:select|insert|update|delete|with|replace|merge|create|drop|alter|truncate|pragma)\s/i
74
+
75
+ interface SqlExpressionShape {
76
+ readonly staticText: string
77
+ readonly dynamic: boolean
78
+ readonly concatenated: boolean
79
+ readonly literal: boolean
80
+ readonly parameterizedTag: boolean
81
+ }
82
+
83
+ /** Module-scope `const` initializers by name - the one binding form the SQL scanner resolves. */
84
+ type ModuleConsts = ReadonlyMap<string, TSApi.Expression>
85
+
86
+ /** A name some other module exports, named exactly as the edge that reaches it writes it. */
87
+ interface ExportEdge {
88
+ readonly specifier: string
89
+ readonly exported: string
90
+ }
91
+
92
+ /**
93
+ * One module's provable module-scope bindings: its top-level `const` initializers plus the exact
94
+ * import/export edges this scan is allowed to follow.
95
+ *
96
+ * Everything absent from these maps stays unresolved, and an unresolved interpolation keeps flagging.
97
+ * That is the whole safety argument: resolution can only ever make this rule QUIETER, so a form the
98
+ * scan cannot prove must fall out as "unknown" rather than be guessed at. Deliberately absent:
99
+ * `export default`, `export let`/`var`, destructured or computed names, default and namespace imports,
100
+ * `export * as ns`, `require`, and dynamic `import()`.
101
+ */
102
+ interface SqlModuleScope {
103
+ /** The module's identity - an absolute path from the loader, or the entry file's path as given. Keys
104
+ * the parsed-scope cache and the cycle guard, and is the base its own specifiers resolve against. */
105
+ readonly id: string
106
+ readonly consts: ModuleConsts
107
+ /** Local name bound by `import { X as local }` → the edge that provides it. */
108
+ readonly imports: ReadonlyMap<string, ExportEdge>
109
+ /** Exported name → the local name it reads (`export { a as b }` → `b` → `a`). */
110
+ readonly localExports: ReadonlyMap<string, string>
111
+ /** Exported name → another module's export (`export { a as b } from "./m"`). */
112
+ readonly reExports: ReadonlyMap<string, ExportEdge>
113
+ /** `export * from "./m"` specifiers, in source order. */
114
+ readonly starExports: readonly string[]
115
+ }
116
+
117
+ /** Read one module's top-level `const` bindings and its import/export edges. Pure syntax - no checker,
118
+ * no filesystem. Destructured names, `let`, `var`, and anything nested stay out on purpose: a
119
+ * module-scope `const` is the only form that provably cannot carry request data. */
120
+ function sqlModuleScope(ts: TypeScriptApi, id: string, source: TSApi.SourceFile): SqlModuleScope {
121
+ const consts = new Map<string, TSApi.Expression>()
122
+ const imports = new Map<string, ExportEdge>()
123
+ const localExports = new Map<string, string>()
124
+ const reExports = new Map<string, ExportEdge>()
125
+ const starExports: string[] = []
126
+ for (const statement of source.statements) {
127
+ if (ts.isVariableStatement(statement)) {
128
+ if ((statement.declarationList.flags & ts.NodeFlags.Const) === 0) continue
129
+ const exported =
130
+ statement.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) === true
131
+ for (const declaration of statement.declarationList.declarations) {
132
+ if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
133
+ consts.set(declaration.name.text, declaration.initializer)
134
+ if (exported) localExports.set(declaration.name.text, declaration.name.text)
135
+ }
136
+ continue
137
+ }
138
+ if (ts.isImportDeclaration(statement)) {
139
+ const clause = statement.importClause
140
+ if (clause === undefined || clause.isTypeOnly) continue
141
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) continue
142
+ const bindings = clause.namedBindings
143
+ // Only `import { X }` / `import { X as local }`. A default or namespace import binds a value
144
+ // whose contents this scan cannot prove, so it stays unbound and every use of it flags.
145
+ if (bindings === undefined || !ts.isNamedImports(bindings)) continue
146
+ for (const element of bindings.elements) {
147
+ if (element.isTypeOnly) continue
148
+ imports.set(element.name.text, {
149
+ specifier: statement.moduleSpecifier.text,
150
+ exported: element.propertyName?.text ?? element.name.text,
151
+ })
152
+ }
153
+ continue
154
+ }
155
+ if (!ts.isExportDeclaration(statement) || statement.isTypeOnly) continue
156
+ const from = statement.moduleSpecifier
157
+ if (from !== undefined && !ts.isStringLiteral(from)) continue
158
+ const clause = statement.exportClause
159
+ if (clause === undefined) {
160
+ // No clause and a specifier is `export * from "./m"`. `export * as ns from "./m"` carries a
161
+ // NamespaceExport clause instead and falls out below, unresolved, which is what we want.
162
+ if (from !== undefined) starExports.push(from.text)
163
+ continue
164
+ }
165
+ if (!ts.isNamedExports(clause)) continue
166
+ for (const element of clause.elements) {
167
+ if (element.isTypeOnly) continue
168
+ const local = element.propertyName?.text ?? element.name.text
169
+ if (from === undefined) localExports.set(element.name.text, local)
170
+ else reExports.set(element.name.text, { specifier: from.text, exported: local })
171
+ }
172
+ }
173
+ return { id, consts, imports, localExports, reExports, starExports }
174
+ }
175
+
176
+ /** A module's identity + source, as resolved from a specifier. `id` must be stable and absolute: it
177
+ * keys the parsed-scope cache, seeds the cycle guard, and is what the module's own relative specifiers
178
+ * resolve against. */
179
+ export interface SqlModuleSource {
180
+ readonly id: string
181
+ readonly content: string
182
+ }
183
+
184
+ /**
185
+ * Resolves a specifier written in the module `fromModule` to the target's identity + source, or
186
+ * `undefined` when it cannot be resolved, read, or proved to be in-project source.
187
+ *
188
+ * Injected rather than built in: it keeps {@link scanInterpolatedSql} pure and filesystem-free, so
189
+ * the resolution rules can be unit-tested against a virtual module graph.
190
+ * {@link createProjectSqlImports} is the on-disk implementation.
191
+ */
192
+ export type SqlModuleLoader = (fromModule: string, specifier: string) => SqlModuleSource | undefined
193
+
194
+ /** Cross-module resolution state for one run: the loader plus a parsed-scope cache, so a fragments
195
+ * module imported by fifty callers is read and parsed once. A cached `undefined` is a REFUSAL (the
196
+ * module did not parse), cached so it is not re-attempted. Build with {@link createSqlImports}. */
197
+ export interface SqlImports {
198
+ readonly load: SqlModuleLoader
199
+ readonly scopes: Map<string, SqlModuleScope | undefined>
200
+ }
201
+
202
+ export const createSqlImports = (load: SqlModuleLoader): SqlImports => ({
203
+ load,
204
+ scopes: new Map(),
205
+ })
206
+
207
+ /** Where an expression's identifiers are read: the module the expression physically lives in, plus the
208
+ * run's cross-module state. `imports === undefined` is same-file-only resolution - the behavior before
209
+ * imported fragments were followed, and still what an unconfigured `scanInterpolatedSql` call does. */
210
+ interface SqlScope {
211
+ readonly module: SqlModuleScope
212
+ readonly imports: SqlImports | undefined
213
+ }
214
+
215
+ /** Parse a module for the SQL scan, or `undefined` when it does not parse. Malformed source is already
216
+ * a typecheck failure; parser recovery nodes are not evidence of anything, so a file that fails to
217
+ * parse contributes no findings and proves no constant. */
218
+ function parseSqlSource(
219
+ ts: TypeScriptApi,
220
+ file: string,
221
+ content: string,
222
+ ): TSApi.SourceFile | undefined {
223
+ const kind = scriptKindOf(ts, file)
224
+ let source: TSApi.SourceFile
225
+ try {
226
+ source = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true, kind)
227
+ } catch {
228
+ // TypeScript 7 parses only the files its session preloaded; an imported module outside that set
229
+ // proves no constant, like one that does not parse.
230
+ return undefined
231
+ }
232
+ const parseDiagnostics =
233
+ // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: TS internal parseDiagnostics property on SourceFile
234
+ (source as TSApi.SourceFile & { readonly parseDiagnostics?: readonly TSApi.Diagnostic[] })
235
+ .parseDiagnostics
236
+ return parseDiagnostics !== undefined && parseDiagnostics.length > 0 ? undefined : source
237
+ }
238
+
239
+ /** Module-boundary hops one name may cross. Barrels are why it is not 1: `route → index → fragments`
240
+ * already spends two, and the third leaves room for one more layer without letting the scan wander the
241
+ * module graph. Past the cap the name is unresolved, so the interpolation flags. */
242
+ const SQL_IMPORT_HOPS = 3
243
+
244
+ /** Load + parse the module a specifier names, through the run's cache. */
245
+ function loadSqlModuleScope(
246
+ ts: TypeScriptApi,
247
+ imports: SqlImports,
248
+ fromModule: string,
249
+ specifier: string,
250
+ ): SqlModuleScope | undefined {
251
+ const loaded = imports.load(fromModule, specifier)
252
+ if (loaded === undefined) return undefined
253
+ if (imports.scopes.has(loaded.id)) return imports.scopes.get(loaded.id)
254
+ const source = parseSqlSource(ts, loaded.id, loaded.content)
255
+ const scope = source === undefined ? undefined : sqlModuleScope(ts, loaded.id, source)
256
+ imports.scopes.set(loaded.id, scope)
257
+ return scope
258
+ }
259
+
260
+ /** One exported name resolved to the `const` initializer behind it, together with the scope that
261
+ * initializer's OWN identifiers must be read in. */
262
+ interface ResolvedExport {
263
+ readonly expression: TSApi.Expression
264
+ readonly scope: SqlModuleScope
265
+ }
266
+
267
+ /**
268
+ * Follow an exported name to its `const` initializer, across re-export hops.
269
+ *
270
+ * Handles the three forms a fragments module actually uses: `export const NAME = …`, the two-statement
271
+ * `const NAME = …; export { NAME }` (including the pass-through `import { A } …; export { A }`), and
272
+ * barrels - `export { X } from "./m"` and `export * from "./m"`. Bounded by {@link SQL_IMPORT_HOPS} and
273
+ * a per-chain visited set, so a cyclic barrel terminates instead of recursing.
274
+ *
275
+ * Two `export *` sources providing the same name is a conflict, and the scan refuses rather than
276
+ * picking one: guessing here would silence a real finding.
277
+ */
278
+ function resolveExportedConst(
279
+ ts: TypeScriptApi,
280
+ imports: SqlImports,
281
+ scope: SqlModuleScope,
282
+ name: string,
283
+ hops: number,
284
+ seen: ReadonlySet<string>,
285
+ ): ResolvedExport | undefined {
286
+ if (hops > SQL_IMPORT_HOPS) return undefined
287
+ const key = `${scope.id}#${name}`
288
+ if (seen.has(key)) return undefined
289
+ const nextSeen = new Set(seen).add(key)
290
+ const follow = (edge: ExportEdge): ResolvedExport | undefined => {
291
+ const target = loadSqlModuleScope(ts, imports, scope.id, edge.specifier)
292
+ return target === undefined
293
+ ? undefined
294
+ : resolveExportedConst(ts, imports, target, edge.exported, hops + 1, nextSeen)
295
+ }
296
+ const local = scope.localExports.get(name)
297
+ if (local !== undefined) {
298
+ const initializer = scope.consts.get(local)
299
+ if (initializer !== undefined) return { expression: initializer, scope }
300
+ // `import { A } from "./a"; export { A }` - the same pass-through as `export { A } from "./a"`,
301
+ // written in two statements. Anything else the name could be (a `let`, a function, a class) has no
302
+ // initializer in `consts` and no import edge, so it lands on `undefined` and flags.
303
+ const via = scope.imports.get(local)
304
+ return via === undefined ? undefined : follow(via)
305
+ }
306
+ const reExported = scope.reExports.get(name)
307
+ if (reExported !== undefined) return follow(reExported)
308
+ let found: ResolvedExport | undefined
309
+ for (const specifier of scope.starExports) {
310
+ const hit = follow({ specifier, exported: name })
311
+ if (hit === undefined) continue
312
+ if (found !== undefined) return undefined
313
+ found = hit
314
+ }
315
+ return found
316
+ }
317
+
318
+ /** Whether `name`, read at `at`, might be re-declared by anything between the read and module scope.
319
+ * Conservative on purpose: the OUTERMOST enclosing function/block subtree is scanned for ANY binding
320
+ * of the name (parameter, `var`/`let`/`const`, catch, local function, destructuring element) - so a
321
+ * hoisted `var` in a sibling block, or a binding in a branch that never runs, still refuses
322
+ * resolution. Over-refusal flags a safe line (the pre-feature behavior); under-refusal would resolve
323
+ * the wrong binding, which is why the cheap-and-broad scan wins over scope simulation. A use with no
324
+ * enclosing function or block reads module scope directly and cannot be shadowed. */
325
+ function isShadowedAt(ts: TypeScriptApi, at: TSApi.Node, name: string): boolean {
326
+ let scope: TSApi.Node | undefined
327
+ for (let node: TSApi.Node | undefined = at.parent; node !== undefined; node = node.parent) {
328
+ if (ts.isSourceFile(node)) break
329
+ if (ts.isFunctionLike(node) || ts.isBlock(node)) scope = node
330
+ }
331
+ if (scope === undefined) return false
332
+ const bindsName = (binding: TSApi.BindingName): boolean =>
333
+ ts.isIdentifier(binding)
334
+ ? binding.text === name
335
+ : binding.elements.some(
336
+ (element) =>
337
+ !ts.isOmittedExpression(element) &&
338
+ (ts.isIdentifier(element.name) ? element.name.text === name : bindsName(element.name)),
339
+ )
340
+ let found = false
341
+ const scan = (node: TSApi.Node): void => {
342
+ if (found) return
343
+ if ((ts.isVariableDeclaration(node) || ts.isParameter(node)) && bindsName(node.name)) {
344
+ found = true
345
+ return
346
+ }
347
+ if (ts.isFunctionDeclaration(node) && node.name?.text === name) {
348
+ found = true
349
+ return
350
+ }
351
+ ts.forEachChild(node, scan)
352
+ }
353
+ scan(scope)
354
+ return found
355
+ }
356
+
357
+ const CONST_RESOLUTION_DEPTH = 5
358
+
359
+ /**
360
+ * Resolve an interpolated expression to compile-time text, or `undefined` when it can carry runtime
361
+ * data. Pure syntax, no type checker - the same honest limit the rule already documents. What
362
+ * resolves: string/number literals, no-substitution templates, templates whose every span resolves,
363
+ * ternaries with both branches resolvable (BOTH branch texts are returned, so a hostile keyword in
364
+ * either still feeds the keyword scan), `as`/`satisfies` wrappers, a `const` whose initializer
365
+ * resolves (the nearest binding: function or block scope, then module scope; recursively,
366
+ * depth-capped), `.join(sep?)` over an array {@link staticArrayItems} proves, and - when
367
+ * `scope.imports` is configured - a module `const` imported by name from another in-project module.
368
+ * Everything else - `let`, a parameter, any other call, a member access, a shadowed name, a
369
+ * bare-specifier import - stays unresolved and the interpolation is flagged exactly as before.
370
+ */
371
+ function resolveStaticSqlText(
372
+ ts: TypeScriptApi,
373
+ node: TSApi.Expression,
374
+ scope: SqlScope,
375
+ depth: number,
376
+ ): string | undefined {
377
+ if (depth > CONST_RESOLUTION_DEPTH) return undefined
378
+ if (ts.isParenthesizedExpression(node)) {
379
+ return resolveStaticSqlText(ts, node.expression, scope, depth)
380
+ }
381
+ if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) {
382
+ return resolveStaticSqlText(ts, node.expression, scope, depth)
383
+ }
384
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text
385
+ if (ts.isNumericLiteral(node)) return node.text
386
+ if (ts.isTemplateExpression(node)) {
387
+ let text = node.head.text
388
+ for (const span of node.templateSpans) {
389
+ const part =
390
+ placeholderNumber(ts, text, span.expression, depth) ??
391
+ resolveStaticSqlText(ts, span.expression, scope, depth + 1)
392
+ if (part === undefined) return undefined
393
+ text += part + span.literal.text
394
+ }
395
+ return text
396
+ }
397
+ if (ts.isConditionalExpression(node)) {
398
+ const whenTrue = resolveStaticSqlText(ts, node.whenTrue, scope, depth + 1)
399
+ const whenFalse = resolveStaticSqlText(ts, node.whenFalse, scope, depth + 1)
400
+ if (whenTrue === undefined || whenFalse === undefined) return undefined
401
+ return `${whenTrue} ${whenFalse}`
402
+ }
403
+ if (ts.isCallExpression(node)) return resolveStaticJoin(ts, node, scope, depth)
404
+ if (ts.isIdentifier(node)) {
405
+ const local = localConstInitializer(ts, node)
406
+ if (local === "shadow") return undefined
407
+ if (local !== undefined) return resolveStaticSqlText(ts, local, scope, depth + 1)
408
+ const initializer = scope.module.consts.get(node.text)
409
+ const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined
410
+ // Membership first: `isShadowedAt` walks a subtree, and most identifiers in a query are neither a
411
+ // module const nor an import binding.
412
+ if (initializer === undefined && edge === undefined) return undefined
413
+ // Shadowing is a property of where the identifier is WRITTEN, so one check is right on both sides
414
+ // of an import hop: an initializer in the imported module sits at module scope with nothing above
415
+ // it to shadow it, while a use inside a function in this file is still refused.
416
+ if (isShadowedAt(ts, node, node.text)) return undefined
417
+ if (initializer !== undefined) return resolveStaticSqlText(ts, initializer, scope, depth + 1)
418
+ if (edge === undefined || scope.imports === undefined) return undefined
419
+ const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier)
420
+ if (target === undefined) return undefined
421
+ const exported = resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set())
422
+ if (exported === undefined) return undefined
423
+ // The imported initializer's own identifiers read THAT module's consts, never this file's. A
424
+ // caller that happens to have its own `const DIR` must not silently supply the fragment's `DIR`,
425
+ // which is the one way cross-module resolution could resolve to text nobody wrote.
426
+ return resolveStaticSqlText(
427
+ ts,
428
+ exported.expression,
429
+ { module: exported.scope, imports: scope.imports },
430
+ depth + 1,
431
+ )
432
+ }
433
+ return undefined
434
+ }
435
+
436
+ /**
437
+ * The initializer of the `const` a function or block scope binds `node` to, `"shadow"` when the
438
+ * nearest such binding is anything else (a parameter, `let`, `var`, destructuring), or `undefined`
439
+ * when no scope below the module binds it - the module-scope lookup applies then.
440
+ */
441
+ function localConstInitializer(
442
+ ts: TypeScriptApi,
443
+ node: TSApi.Identifier,
444
+ ): TSApi.Expression | "shadow" | undefined {
445
+ const source = node.getSourceFile()
446
+ for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
447
+ if (ts.isSourceFile(scope)) return undefined
448
+ const binding = directBinding(ts, source, scope, node.text)
449
+ if (binding === "shadow") return "shadow"
450
+ if (binding !== undefined) return binding.constant ? binding.initializer : "shadow"
451
+ }
452
+ return undefined
453
+ }
454
+
455
+ const unwrapExpression = (ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression => {
456
+ let current = node
457
+ while (
458
+ ts.isParenthesizedExpression(current) ||
459
+ ts.isAsExpression(current) ||
460
+ ts.isSatisfiesExpression(current)
461
+ ) {
462
+ current = current.expression
463
+ }
464
+ return current
465
+ }
466
+
467
+ /** `Object.freeze([...])` with `Object` unshadowed: the one array form no later code can change. */
468
+ function frozenArrayLiteral(
469
+ ts: TypeScriptApi,
470
+ node: TSApi.Expression,
471
+ ): TSApi.ArrayLiteralExpression | undefined {
472
+ const call = unwrapExpression(ts, node)
473
+ if (!ts.isCallExpression(call) || call.arguments.length !== 1) return undefined
474
+ const callee = call.expression
475
+ if (
476
+ !ts.isPropertyAccessExpression(callee) ||
477
+ callee.name.text !== "freeze" ||
478
+ !ts.isIdentifier(callee.expression) ||
479
+ callee.expression.text !== "Object" ||
480
+ isShadowedAt(ts, callee.expression, "Object")
481
+ ) {
482
+ return undefined
483
+ }
484
+ const array = unwrapExpression(ts, call.arguments[0]!)
485
+ return ts.isArrayLiteralExpression(array) ? array : undefined
486
+ }
487
+
488
+ const ARRAY_READS: ReadonlySet<string> = new Set(["join", "includes", "indexOf"])
489
+
490
+ /**
491
+ * Whether every use of `name` in `source` other than its declaration is a call of `.join(`,
492
+ * `.includes(` or `.indexOf(`, or a `.length` read: then nothing pushes to, sorts, exports or hands
493
+ * away the array, so it still holds its literal elements. A `.push(...)` is accepted too and its
494
+ * arguments collected in `pushed`, for the caller to prove (the `where.push(...)` builder). A
495
+ * same-named binding elsewhere only adds uses, so the answer can only err toward refusing.
496
+ */
497
+ function onlyReadsArray(
498
+ ts: TypeScriptApi,
499
+ source: TSApi.SourceFile,
500
+ name: string,
501
+ declaration: TSApi.Node,
502
+ pushed: TSApi.Expression[],
503
+ ): boolean {
504
+ let ok = true
505
+ const visit = (node: TSApi.Node): void => {
506
+ if (!ok) return
507
+ if (ts.isIdentifier(node) && node.text === name && node !== declaration) {
508
+ const access = node.parent
509
+ const call =
510
+ ts.isPropertyAccessExpression(access) &&
511
+ access.expression === node &&
512
+ ts.isCallExpression(access.parent) &&
513
+ access.parent.expression === access
514
+ ? access.parent
515
+ : undefined
516
+ if (
517
+ call !== undefined &&
518
+ ts.isPropertyAccessExpression(access) &&
519
+ access.name.text === "push"
520
+ ) {
521
+ if (call.arguments.some((argument) => ts.isSpreadElement(argument))) ok = false
522
+ else pushed.push(...call.arguments)
523
+ // An argument can mention the array again; those uses are checked as well.
524
+ for (const argument of call.arguments) visit(argument)
525
+ return
526
+ }
527
+ const read =
528
+ ts.isPropertyAccessExpression(access) &&
529
+ access.expression === node &&
530
+ (access.name.text === "length"
531
+ ? !isWrittenTo(ts, access)
532
+ : ARRAY_READS.has(access.name.text) && call !== undefined)
533
+ if (!read) ok = false
534
+ return
535
+ }
536
+ ts.forEachChild(node, visit)
537
+ }
538
+ visit(source)
539
+ return ok
540
+ }
541
+
542
+ /** `node` as the target of an assignment, `++`/`--`, or `delete`. */
543
+ function isWrittenTo(ts: TypeScriptApi, node: TSApi.Node): boolean {
544
+ const parent = node.parent
545
+ if (
546
+ ts.isBinaryExpression(parent) &&
547
+ parent.left === node &&
548
+ parent.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
549
+ parent.operatorToken.kind <= ts.SyntaxKind.LastAssignment
550
+ ) {
551
+ return true
552
+ }
553
+ if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
554
+ return (
555
+ parent.operator === ts.SyntaxKind.PlusPlusToken ||
556
+ parent.operator === ts.SyntaxKind.MinusMinusToken
557
+ )
558
+ }
559
+ return ts.isDeleteExpression(parent)
560
+ }
561
+
562
+ /**
563
+ * The element texts of an array `receiver` names, when the array provably still holds them: an
564
+ * inline literal, `Object.freeze([...])` anywhere it is bound or imported from, or a `const` array
565
+ * literal bound in this file, not exported, and only ever read ({@link onlyReadsArray}). `as const`
566
+ * is type-only and proves nothing.
567
+ */
568
+ function staticArrayItems(
569
+ ts: TypeScriptApi,
570
+ receiver: TSApi.Expression,
571
+ scope: SqlScope,
572
+ depth: number,
573
+ ): readonly string[] | undefined {
574
+ const node = unwrapExpression(ts, receiver)
575
+ let array = ts.isArrayLiteralExpression(node) ? node : frozenArrayLiteral(ts, node)
576
+ let itemScope = scope
577
+ const pushed: TSApi.Expression[] = []
578
+ if (array === undefined && ts.isIdentifier(node)) {
579
+ const local = localConstInitializer(ts, node)
580
+ if (local === "shadow") return undefined
581
+ let initializer = local
582
+ let exported = false
583
+ if (initializer === undefined && !isShadowedAt(ts, node, node.text)) {
584
+ initializer = scope.module.consts.get(node.text)
585
+ exported = [...scope.module.localExports.values()].includes(node.text)
586
+ const edge = initializer === undefined ? scope.module.imports.get(node.text) : undefined
587
+ if (edge !== undefined && scope.imports !== undefined) {
588
+ const target = loadSqlModuleScope(ts, scope.imports, scope.module.id, edge.specifier)
589
+ const found =
590
+ target === undefined
591
+ ? undefined
592
+ : resolveExportedConst(ts, scope.imports, target, edge.exported, 1, new Set())
593
+ if (found === undefined) return undefined
594
+ // Another module's array is accepted only frozen: its own file may mutate it.
595
+ array = frozenArrayLiteral(ts, found.expression)
596
+ itemScope = { module: found.scope, imports: scope.imports }
597
+ }
598
+ }
599
+ if (array === undefined && initializer !== undefined) {
600
+ array = frozenArrayLiteral(ts, initializer)
601
+ const literal = unwrapExpression(ts, initializer)
602
+ if (
603
+ array === undefined &&
604
+ !exported &&
605
+ ts.isArrayLiteralExpression(literal) &&
606
+ ts.isVariableDeclaration(initializer.parent) &&
607
+ onlyReadsArray(ts, node.getSourceFile(), node.text, initializer.parent.name, pushed)
608
+ ) {
609
+ array = literal
610
+ }
611
+ }
612
+ }
613
+ if (array === undefined) return undefined
614
+ const items: string[] = []
615
+ // What the array may hold: its literal elements, and anything pushed onto it in any order.
616
+ for (const element of [...array.elements, ...pushed]) {
617
+ if (ts.isSpreadElement(element) || ts.isOmittedExpression(element)) return undefined
618
+ const text = resolveStaticSqlText(ts, element, itemScope, depth + 1)
619
+ if (text === undefined) return undefined
620
+ items.push(text)
621
+ }
622
+ return items
623
+ }
624
+
625
+ /** `items.join(sep?)` over a {@link staticArrayItems} array with a literal or absent separator. */
626
+ function resolveStaticJoin(
627
+ ts: TypeScriptApi,
628
+ call: TSApi.CallExpression,
629
+ scope: SqlScope,
630
+ depth: number,
631
+ ): string | undefined {
632
+ const callee = call.expression
633
+ if (
634
+ !ts.isPropertyAccessExpression(callee) ||
635
+ callee.questionDotToken !== undefined ||
636
+ callee.name.text !== "join" ||
637
+ call.arguments.length > 1
638
+ ) {
639
+ return undefined
640
+ }
641
+ const separatorArg = call.arguments[0]
642
+ const separator =
643
+ separatorArg === undefined
644
+ ? ","
645
+ : ts.isStringLiteral(separatorArg) || ts.isNoSubstitutionTemplateLiteral(separatorArg)
646
+ ? separatorArg.text
647
+ : undefined
648
+ if (separator === undefined) return undefined
649
+ const items =
650
+ staticArrayItems(ts, callee.expression, scope, depth + 1) ??
651
+ mappedItem(ts, callee.expression, scope, depth + 1)
652
+ return items?.join(separator)
653
+ }
654
+
655
+ /**
656
+ * `xs.map(fn)`, `xs.flatMap(fn)` or `Array.from(src, fn)` whose callback returns text that resolves
657
+ * for every element - `(_, i) => \`($${i * 2 + 1}, $${i * 2 + 2})\``, the batch `VALUES` idiom. How
658
+ * many items there are is runtime data, what each one says is not, so one item stands for all.
659
+ */
660
+ function mappedItem(
661
+ ts: TypeScriptApi,
662
+ receiver: TSApi.Expression,
663
+ scope: SqlScope,
664
+ depth: number,
665
+ ): readonly string[] | undefined {
666
+ const call = unwrapExpression(ts, receiver)
667
+ if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression))
668
+ return undefined
669
+ // Only these return what the callback returns; `filter` and the rest hand back the elements.
670
+ const method = call.expression.name.text
671
+ const argument = indexCallbackArgument(ts, call)
672
+ if (argument === undefined || !(method === "map" || method === "flatMap" || argument === 1))
673
+ return undefined
674
+ const fn = call.arguments[argument]
675
+ if (fn === undefined || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return undefined
676
+ const only =
677
+ ts.isBlock(fn.body) && fn.body.statements.length === 1 ? fn.body.statements[0] : undefined
678
+ const body = ts.isBlock(fn.body)
679
+ ? only !== undefined && ts.isReturnStatement(only)
680
+ ? only.expression
681
+ : undefined
682
+ : fn.body
683
+ const text = body === undefined ? undefined : resolveStaticSqlText(ts, body, scope, depth + 1)
684
+ return text === undefined ? undefined : [text]
685
+ }
686
+
687
+ /** Array methods whose callback receives the element's index, and where in the callback it is. */
688
+ const INDEX_PARAMETER: ReadonlyMap<string, number> = new Map([
689
+ ["map", 1],
690
+ ["flatMap", 1],
691
+ ["forEach", 1],
692
+ ["filter", 1],
693
+ ["some", 1],
694
+ ["every", 1],
695
+ ["find", 1],
696
+ ["findIndex", 1],
697
+ ["reduce", 2],
698
+ ["reduceRight", 2],
699
+ ])
700
+
701
+ /** Which argument of `call` is a callback handed an array index: the first for `xs.map(fn)` and its
702
+ * kin, the second for an unshadowed `Array.from(src, fn)`. */
703
+ function indexCallbackArgument(ts: TypeScriptApi, call: TSApi.CallExpression): number | undefined {
704
+ const callee = call.expression
705
+ if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
706
+ return undefined
707
+ if (INDEX_PARAMETER.has(callee.name.text)) return 0
708
+ return callee.name.text === "from" &&
709
+ ts.isIdentifier(callee.expression) &&
710
+ callee.expression.text === "Array" &&
711
+ !isShadowedAt(ts, callee.expression, "Array")
712
+ ? 1
713
+ : undefined
714
+ }
715
+
716
+ /**
717
+ * `"1"` for a span written right after a `$` whose expression provably evaluates to a number: a
718
+ * Postgres placeholder index (`$${i + 1}`), which binds a parameter and can carry no SQL. Any string
719
+ * there could, so anything not proved numeric stays unresolved.
720
+ */
721
+ function placeholderNumber(
722
+ ts: TypeScriptApi,
723
+ before: string,
724
+ node: TSApi.Expression,
725
+ depth: number,
726
+ ): string | undefined {
727
+ return before.endsWith("$") && isNumericExpression(ts, node, depth) ? "1" : undefined
728
+ }
729
+
730
+ const NUMERIC_OPERATORS = (ts: TypeScriptApi): ReadonlySet<TSApi.SyntaxKind> =>
731
+ new Set([
732
+ ts.SyntaxKind.MinusToken,
733
+ ts.SyntaxKind.AsteriskToken,
734
+ ts.SyntaxKind.AsteriskAsteriskToken,
735
+ ts.SyntaxKind.SlashToken,
736
+ ts.SyntaxKind.PercentToken,
737
+ ts.SyntaxKind.AmpersandToken,
738
+ ts.SyntaxKind.BarToken,
739
+ ts.SyntaxKind.CaretToken,
740
+ ts.SyntaxKind.LessThanLessThanToken,
741
+ ts.SyntaxKind.GreaterThanGreaterThanToken,
742
+ ts.SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
743
+ ])
744
+ const NUMBER_FUNCTIONS: ReadonlySet<string> = new Set(["Number", "parseInt", "parseFloat"])
745
+
746
+ /**
747
+ * Whether an expression evaluates to a number whatever its inputs hold. Every arithmetic operator but
748
+ * `+` converts its operands, so `i * 2` is a number even if `i` were a string; `+` is one only when
749
+ * both sides are. A name proves it when it is a callback's array index, or a `const`, never-reassigned
750
+ * `let` or `for` counter bound to a number and only ever updated by arithmetic. Also `xs.push(...)`
751
+ * (the new length), `Number`/`parseInt`/`parseFloat`/`Math.*` calls, and `.length` of an array a
752
+ * nearby binding builds from a literal. A type annotation proves nothing: it does not run.
753
+ */
754
+ function isNumericExpression(ts: TypeScriptApi, node: TSApi.Expression, depth: number): boolean {
755
+ if (depth > CONST_RESOLUTION_DEPTH) return false
756
+ const expression = unwrapExpression(ts, node)
757
+ if (ts.isNumericLiteral(expression)) return true
758
+ if (ts.isPrefixUnaryExpression(expression))
759
+ return expression.operator !== ts.SyntaxKind.ExclamationToken
760
+ if (ts.isPostfixUnaryExpression(expression)) return true
761
+ if (ts.isBinaryExpression(expression)) {
762
+ const operator = expression.operatorToken.kind
763
+ if (operator === ts.SyntaxKind.PlusToken) {
764
+ return (
765
+ isNumericExpression(ts, expression.left, depth + 1) &&
766
+ isNumericExpression(ts, expression.right, depth + 1)
767
+ )
768
+ }
769
+ return NUMERIC_OPERATORS(ts).has(operator)
770
+ }
771
+ if (ts.isIdentifier(expression)) return isNumericName(ts, expression, depth)
772
+ if (ts.isCallExpression(expression)) {
773
+ const callee = expression.expression
774
+ if (ts.isIdentifier(callee))
775
+ return NUMBER_FUNCTIONS.has(callee.text) && !isShadowedAt(ts, callee, callee.text)
776
+ if (!ts.isPropertyAccessExpression(callee) || callee.questionDotToken !== undefined)
777
+ return false
778
+ if (callee.name.text === "push") return true
779
+ return (
780
+ ts.isIdentifier(callee.expression) &&
781
+ callee.expression.text === "Math" &&
782
+ !isShadowedAt(ts, callee.expression, "Math")
783
+ )
784
+ }
785
+ if (
786
+ ts.isPropertyAccessExpression(expression) &&
787
+ expression.name.text === "length" &&
788
+ ts.isIdentifier(expression.expression)
789
+ ) {
790
+ const binding = nameBinding(ts, expression.expression)
791
+ return (
792
+ binding.kind === "value" &&
793
+ ts.isArrayLiteralExpression(unwrapExpression(ts, binding.initializer))
794
+ )
795
+ }
796
+ return false
797
+ }
798
+
799
+ /** How the nearest scope binds a name: a readable value ({@link directBinding}), a parameter, a `let`
800
+ * counter a `for` statement declares and updates, or nothing this walk can read. */
801
+ type NameBinding =
802
+ | { readonly kind: "value"; readonly initializer: TSApi.Expression }
803
+ | {
804
+ readonly kind: "parameter"
805
+ readonly fn: TSApi.SignatureDeclaration
806
+ readonly position: number
807
+ }
808
+ | { readonly kind: "counter"; readonly initializer: TSApi.Expression }
809
+ | { readonly kind: "unknown" }
810
+
811
+ function nameBinding(ts: TypeScriptApi, node: TSApi.Identifier): NameBinding {
812
+ const source = node.getSourceFile()
813
+ for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
814
+ if (ts.isFunctionLike(scope)) {
815
+ const position = scope.parameters.findIndex((p) => bindingNameCovers(ts, p.name, node.text))
816
+ if (position !== -1) {
817
+ return ts.isIdentifier(scope.parameters[position]?.name ?? node)
818
+ ? { kind: "parameter", fn: scope, position }
819
+ : { kind: "unknown" }
820
+ }
821
+ }
822
+ const binding = directBinding(ts, source, scope, node.text)
823
+ if (binding === "shadow") {
824
+ // `for (let i = 0; ...; i++)`: the one reassigned `let` worth reading, checked by the caller.
825
+ const list = ts.isForStatement(scope) ? scope.initializer : undefined
826
+ const declaration =
827
+ list !== undefined && ts.isVariableDeclarationList(list)
828
+ ? list.declarations.find((d) => ts.isIdentifier(d.name) && d.name.text === node.text)
829
+ : undefined
830
+ return declaration?.initializer === undefined
831
+ ? { kind: "unknown" }
832
+ : { kind: "counter", initializer: declaration.initializer }
833
+ }
834
+ if (binding !== undefined) return { kind: "value", initializer: binding.initializer }
835
+ if (ts.isSourceFile(scope)) break
836
+ }
837
+ return { kind: "unknown" }
838
+ }
839
+
840
+ function isNumericName(ts: TypeScriptApi, node: TSApi.Identifier, depth: number): boolean {
841
+ const source = node.getSourceFile()
842
+ const binding = nameBinding(ts, node)
843
+ if (binding.kind === "value") return isNumericExpression(ts, binding.initializer, depth + 1)
844
+ if (binding.kind === "counter") {
845
+ return (
846
+ isNumericExpression(ts, binding.initializer, depth + 1) &&
847
+ onlyNumericWrites(ts, source, node.text, depth)
848
+ )
849
+ }
850
+ if (binding.kind !== "parameter") return false
851
+ // An array callback's index parameter, never reassigned.
852
+ const call = binding.fn.parent
853
+ if (!ts.isCallExpression(call) || !ts.isPropertyAccessExpression(call.expression)) return false
854
+ const argument = indexCallbackArgument(ts, call)
855
+ const position = argument === 1 ? 1 : INDEX_PARAMETER.get(call.expression.name.text)
856
+ return (
857
+ argument !== undefined &&
858
+ call.arguments[argument] === binding.fn &&
859
+ binding.position === position &&
860
+ !isReassignedInFile(ts, source, node.text)
861
+ )
862
+ }
863
+
864
+ /** Compound assignments that always store a number. */
865
+ const NUMERIC_ASSIGNMENTS = (ts: TypeScriptApi): ReadonlySet<TSApi.SyntaxKind> =>
866
+ new Set([
867
+ ts.SyntaxKind.MinusEqualsToken,
868
+ ts.SyntaxKind.AsteriskEqualsToken,
869
+ ts.SyntaxKind.AsteriskAsteriskEqualsToken,
870
+ ts.SyntaxKind.SlashEqualsToken,
871
+ ts.SyntaxKind.PercentEqualsToken,
872
+ ts.SyntaxKind.AmpersandEqualsToken,
873
+ ts.SyntaxKind.BarEqualsToken,
874
+ ts.SyntaxKind.CaretEqualsToken,
875
+ ts.SyntaxKind.LessThanLessThanEqualsToken,
876
+ ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
877
+ ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
878
+ ])
879
+
880
+ /** Every write to `name` in the file is `++`/`--`, or an assignment that stores a number. */
881
+ function onlyNumericWrites(
882
+ ts: TypeScriptApi,
883
+ source: TSApi.SourceFile,
884
+ name: string,
885
+ depth: number,
886
+ ): boolean {
887
+ let ok = true
888
+ const visit = (node: TSApi.Node): void => {
889
+ if (!ok) return
890
+ if (ts.isIdentifier(node) && node.text === name && isWrittenTo(ts, node)) {
891
+ const parent = node.parent
892
+ if (ts.isBinaryExpression(parent)) {
893
+ const operator = parent.operatorToken.kind
894
+ ok =
895
+ operator === ts.SyntaxKind.EqualsToken || operator === ts.SyntaxKind.PlusEqualsToken
896
+ ? isNumericExpression(ts, parent.right, depth + 1)
897
+ : NUMERIC_ASSIGNMENTS(ts).has(operator)
898
+ } else ok = !ts.isDeleteExpression(parent)
899
+ return
900
+ }
901
+ ts.forEachChild(node, visit)
902
+ }
903
+ visit(source)
904
+ return ok
905
+ }
906
+
907
+ /** A template's contribution to the shape: resolved span texts fold into `staticText` (so the
908
+ * keyword scan still sees what a `const` carries); any unresolvable span keeps it `dynamic`. */
909
+ function templateShape(
910
+ ts: TypeScriptApi,
911
+ template: TSApi.TemplateExpression,
912
+ scope: SqlScope | undefined,
913
+ ): { staticText: string; dynamic: boolean } {
914
+ let staticText = template.head.text
915
+ let dynamic = false
916
+ for (const span of template.templateSpans) {
917
+ const resolved =
918
+ scope === undefined
919
+ ? undefined
920
+ : (placeholderNumber(ts, staticText, span.expression, 0) ??
921
+ resolveStaticSqlText(ts, span.expression, scope, 0))
922
+ if (resolved === undefined) dynamic = true
923
+ else staticText += resolved
924
+ staticText += span.literal.text
925
+ }
926
+ return { staticText, dynamic }
927
+ }
928
+
929
+ /** A same-file binding the argument resolver proved holds one expression: a `const`, or a `let` the
930
+ * whole file never reassigns. `"shadow"` marks a nearer binding of the name we can NOT read through (a
931
+ * parameter, `var`, destructured, uninitialized, reassigned `let`) - it stops the outward walk so a
932
+ * farther, resolvable const of the same name is never read in its place. */
933
+ type ResolvableBinding =
934
+ | { readonly initializer: TSApi.Expression; readonly constant: boolean }
935
+ | "shadow"
936
+
937
+ /** Whether `name` is written to anywhere in the file - a plain, compound, or `++`/`--` assignment to a
938
+ * bare identifier of that name. A `let` that is is over-cautiously refused (it might be reassigned from
939
+ * request data); a `const` never needs this. Over-refusal only ever leaves an interpolation flagged as
940
+ * before, never the reverse. */
941
+ function isReassignedInFile(ts: TypeScriptApi, source: TSApi.SourceFile, name: string): boolean {
942
+ let found = false
943
+ const visit = (node: TSApi.Node): void => {
944
+ if (found) return
945
+ if (
946
+ ts.isBinaryExpression(node) &&
947
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
948
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment &&
949
+ ts.isIdentifier(node.left) &&
950
+ node.left.text === name
951
+ ) {
952
+ found = true
953
+ return
954
+ }
955
+ if (
956
+ (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
957
+ (node.operator === ts.SyntaxKind.PlusPlusToken ||
958
+ node.operator === ts.SyntaxKind.MinusMinusToken) &&
959
+ ts.isIdentifier(node.operand) &&
960
+ node.operand.text === name
961
+ ) {
962
+ found = true
963
+ return
964
+ }
965
+ ts.forEachChild(node, visit)
966
+ }
967
+ visit(source)
968
+ return found
969
+ }
970
+
971
+ /** Does `binding` bind `name` (as a plain identifier or nested inside a destructuring pattern)? Mirrors
972
+ * the pattern walk in {@link isShadowedAt}. */
973
+ function bindingNameCovers(ts: TypeScriptApi, binding: TSApi.BindingName, name: string): boolean {
974
+ return ts.isIdentifier(binding)
975
+ ? binding.text === name
976
+ : binding.elements.some(
977
+ (element) =>
978
+ !ts.isOmittedExpression(element) &&
979
+ (ts.isIdentifier(element.name)
980
+ ? element.name.text === name
981
+ : bindingNameCovers(ts, element.name, name)),
982
+ )
983
+ }
984
+
985
+ /** Inspect the bindings a single scope node introduces DIRECTLY (not nested) for `name`: parameters and
986
+ * catch variables of a function/catch, `var`/`let`/`const` and function/class declarations of a
987
+ * statement list. Returns the readable initializer, `"shadow"` for a form we cannot read through, or
988
+ * `undefined` when this scope does not bind the name at all. */
989
+ function directBinding(
990
+ ts: TypeScriptApi,
991
+ source: TSApi.SourceFile,
992
+ scope: TSApi.Node,
993
+ name: string,
994
+ ): ResolvableBinding | undefined {
995
+ if (ts.isFunctionLike(scope)) {
996
+ for (const parameter of scope.parameters) {
997
+ if (bindingNameCovers(ts, parameter.name, name)) return "shadow"
998
+ }
999
+ }
1000
+ if (ts.isCatchClause(scope)) {
1001
+ const declared = scope.variableDeclaration
1002
+ if (declared !== undefined && bindingNameCovers(ts, declared.name, name)) return "shadow"
1003
+ }
1004
+ for (const statement of scopeStatements(ts, scope) ?? []) {
1005
+ if (
1006
+ (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) &&
1007
+ statement.name?.text === name
1008
+ ) {
1009
+ return "shadow"
1010
+ }
1011
+ }
1012
+ for (const list of scopeDeclarationLists(ts, scope)) {
1013
+ for (const declaration of list.declarations) {
1014
+ if (!bindingNameCovers(ts, declaration.name, name)) continue
1015
+ // A destructured or uninitialized binding, or a `var` (hoisting + reassignment risk), is not a
1016
+ // value we can read one expression out of.
1017
+ if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined)
1018
+ return "shadow"
1019
+ const isConst = (list.flags & ts.NodeFlags.Const) !== 0
1020
+ const isLet = (list.flags & ts.NodeFlags.Let) !== 0
1021
+ if (isConst) return { initializer: declaration.initializer, constant: true }
1022
+ if (isLet && !isReassignedInFile(ts, source, name))
1023
+ return { initializer: declaration.initializer, constant: false }
1024
+ return "shadow"
1025
+ }
1026
+ }
1027
+ return undefined
1028
+ }
1029
+
1030
+ function scopeStatements(
1031
+ ts: TypeScriptApi,
1032
+ scope: TSApi.Node,
1033
+ ): readonly TSApi.Statement[] | undefined {
1034
+ return ts.isSourceFile(scope) ||
1035
+ ts.isBlock(scope) ||
1036
+ ts.isModuleBlock(scope) ||
1037
+ ts.isCaseClause(scope) ||
1038
+ ts.isDefaultClause(scope)
1039
+ ? scope.statements
1040
+ : undefined
1041
+ }
1042
+
1043
+ /** The `var`/`let`/`const` lists a scope node declares directly: its statements' and a `for` head's. */
1044
+ function scopeDeclarationLists(
1045
+ ts: TypeScriptApi,
1046
+ scope: TSApi.Node,
1047
+ ): TSApi.VariableDeclarationList[] {
1048
+ const lists: TSApi.VariableDeclarationList[] = []
1049
+ for (const statement of scopeStatements(ts, scope) ?? []) {
1050
+ if (ts.isVariableStatement(statement)) lists.push(statement.declarationList)
1051
+ }
1052
+ if (
1053
+ (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) &&
1054
+ scope.initializer !== undefined &&
1055
+ ts.isVariableDeclarationList(scope.initializer)
1056
+ ) {
1057
+ lists.push(scope.initializer)
1058
+ }
1059
+ return lists
1060
+ }
1061
+
1062
+ /** The `var` or `let` a scope declares `name` with by a plain identifier, if any. */
1063
+ function mutableDeclaration(
1064
+ ts: TypeScriptApi,
1065
+ scope: TSApi.Node,
1066
+ name: string,
1067
+ ): TSApi.VariableDeclaration | undefined {
1068
+ for (const list of scopeDeclarationLists(ts, scope)) {
1069
+ if ((list.flags & ts.NodeFlags.Const) !== 0) continue
1070
+ for (const declaration of list.declarations) {
1071
+ if (ts.isIdentifier(declaration.name) && declaration.name.text === name) return declaration
1072
+ }
1073
+ }
1074
+ return undefined
1075
+ }
1076
+
1077
+ interface SqlWrite {
1078
+ readonly value: TSApi.Expression
1079
+ /** `+=`: the value is glued onto what the variable already holds. */
1080
+ readonly appends: boolean
1081
+ }
1082
+
1083
+ /**
1084
+ * Every value a statement variable may hold where the query reads it, so a statement parked in a
1085
+ * variable is scanned as if it had been written inline at the call. This is the counterpart to
1086
+ * {@link resolveStaticSqlText}: that folds a const's text INTO a template's shape; this unfolds the
1087
+ * statement back out of the variable it was lifted into. Without it, ANY interpolated-SQL finding
1088
+ * could be silenced, invisibly, by hoisting the statement to `const q = …` first, or by building it
1089
+ * in steps (`let q = "SELECT …"; q += …`).
1090
+ *
1091
+ * Same-file only. Nearest enclosing declaration wins, so a shadowing local is read and never a
1092
+ * same-named module const. A `const`, or a `let` the file never reassigns, holds its initializer. A
1093
+ * `var` or reassigned `let` holds its initializer and every value assigned to the name anywhere in
1094
+ * the function (or module) that declares it: over-collected rather than scope-simulated, which only
1095
+ * ever adds a value to check. `key` names the binding, so a value that reads the variable it is
1096
+ * assigned to is recognised. A parameter, an imported or destructured binding, or a name with no
1097
+ * same-file declaration returns `undefined` - which leaves the argument scanned as itself.
1098
+ */
1099
+ function variableWrites(
1100
+ ts: TypeScriptApi,
1101
+ node: TSApi.Identifier,
1102
+ ): { readonly key: TSApi.Node; readonly writes: readonly SqlWrite[] } | undefined {
1103
+ const source = node.getSourceFile()
1104
+ const name = node.text
1105
+ for (let scope: TSApi.Node | undefined = node.parent; scope !== undefined; scope = scope.parent) {
1106
+ const binding = directBinding(ts, source, scope, name)
1107
+ if (binding === "shadow") {
1108
+ const declaration = mutableDeclaration(ts, scope, name)
1109
+ if (declaration === undefined) return undefined
1110
+ let owner: TSApi.Node = declaration
1111
+ while (!ts.isFunctionLike(owner) && !ts.isSourceFile(owner)) owner = owner.parent
1112
+ const writes = writesTo(ts, owner, name)
1113
+ return {
1114
+ key: declaration,
1115
+ writes:
1116
+ declaration.initializer === undefined
1117
+ ? writes
1118
+ : [{ value: declaration.initializer, appends: false }, ...writes],
1119
+ }
1120
+ }
1121
+ if (binding !== undefined) {
1122
+ return { key: binding.initializer, writes: [{ value: binding.initializer, appends: false }] }
1123
+ }
1124
+ if (ts.isSourceFile(scope)) break
1125
+ }
1126
+ return undefined
1127
+ }
1128
+
1129
+ /** The values assigned to `name` under `root`. A numeric compound assignment stores no text. */
1130
+ function writesTo(ts: TypeScriptApi, root: TSApi.Node, name: string): SqlWrite[] {
1131
+ const writes: SqlWrite[] = []
1132
+ const visit = (node: TSApi.Node): void => {
1133
+ if (ts.isIdentifier(node) && node.text === name) {
1134
+ const parent = node.parent
1135
+ if (ts.isBinaryExpression(parent) && parent.left === node) {
1136
+ const operator = parent.operatorToken.kind
1137
+ if (operator === ts.SyntaxKind.PlusEqualsToken) {
1138
+ writes.push({ value: parent.right, appends: true })
1139
+ } else if (
1140
+ operator === ts.SyntaxKind.EqualsToken ||
1141
+ operator === ts.SyntaxKind.QuestionQuestionEqualsToken ||
1142
+ operator === ts.SyntaxKind.BarBarEqualsToken ||
1143
+ operator === ts.SyntaxKind.AmpersandAmpersandEqualsToken
1144
+ ) {
1145
+ writes.push({ value: parent.right, appends: false })
1146
+ }
1147
+ }
1148
+ }
1149
+ ts.forEachChild(node, visit)
1150
+ }
1151
+ visit(root)
1152
+ return writes
1153
+ }
1154
+
1155
+ function mentionsName(ts: TypeScriptApi, node: TSApi.Node, name: string): boolean {
1156
+ // A member/key named like the variable does not read that variable (`record = client.record()`).
1157
+ if (ts.isPropertyAccessExpression(node)) return mentionsName(ts, node.expression, name)
1158
+ if (ts.isPropertyAssignment(node)) {
1159
+ return (
1160
+ mentionsName(ts, node.initializer, name) ||
1161
+ (ts.isComputedPropertyName(node.name) && mentionsName(ts, node.name.expression, name))
1162
+ )
1163
+ }
1164
+ if (ts.isIdentifier(node)) return node.text === name
1165
+ return ts.forEachChild(node, (child) => mentionsName(ts, child, name) || undefined) === true
1166
+ }
1167
+
1168
+ const UNKNOWN_SQL: SqlExpressionShape = {
1169
+ staticText: "",
1170
+ dynamic: true,
1171
+ concatenated: false,
1172
+ literal: false,
1173
+ parameterizedTag: false,
1174
+ }
1175
+
1176
+ function textShape(text: string): SqlExpressionShape {
1177
+ return {
1178
+ staticText: text,
1179
+ dynamic: false,
1180
+ concatenated: false,
1181
+ literal: true,
1182
+ parameterizedTag: false,
1183
+ }
1184
+ }
1185
+
1186
+ function joinShapes(shapes: readonly SqlExpressionShape[]): SqlExpressionShape {
1187
+ return {
1188
+ staticText: shapes.map((shape) => shape.staticText).join(""),
1189
+ // As with `+`: text glued onto a binding tag's output un-parameterizes it.
1190
+ dynamic: shapes.some((shape) => shape.dynamic || shape.parameterizedTag),
1191
+ concatenated: true,
1192
+ literal: false,
1193
+ parameterizedTag: false,
1194
+ }
1195
+ }
1196
+
1197
+ /** Orders a variable's candidate statements by how surely {@link scanInterpolatedSql} would flag
1198
+ * them: dynamic SQL text, then dynamic glued text, then any dynamic text; outside a binding tag
1199
+ * before inside one. */
1200
+ function sqlRisk(shape: SqlExpressionShape): number {
1201
+ const dynamic = !shape.dynamic
1202
+ ? 0
1203
+ : SQL_KEYWORD.test(shape.staticText) || STATEMENT_START.test(shape.staticText)
1204
+ ? 3
1205
+ : shape.concatenated
1206
+ ? 2
1207
+ : 1
1208
+ return dynamic * 2 + (shape.parameterizedTag ? 0 : 1)
1209
+ }
1210
+
1211
+ /**
1212
+ * The riskiest statement a variable may hold. Each value that replaces the text is one candidate.
1213
+ * The values that build on it (`+=`, or `q = q + more`) are glued onto every replacing value at
1214
+ * once, as a builder that takes each branch would, so a static `SELECT … WHERE 1=1` followed by an
1215
+ * interpolated `AND …` reads as the one statement it becomes.
1216
+ */
1217
+ function writtenShape(
1218
+ ts: TypeScriptApi,
1219
+ name: string,
1220
+ writes: readonly SqlWrite[],
1221
+ scope: SqlScope | undefined,
1222
+ trail: readonly TSApi.Node[],
1223
+ ): SqlExpressionShape {
1224
+ const replacing: SqlExpressionShape[] = []
1225
+ const building: SqlExpressionShape[] = []
1226
+ for (const write of writes) {
1227
+ const shape = sqlExpressionShape(ts, write.value, scope, trail)
1228
+ if (write.appends || mentionsName(ts, write.value, name)) building.push(shape)
1229
+ else replacing.push(shape)
1230
+ }
1231
+ const candidates =
1232
+ building.length === 0 ? replacing : [...replacing, joinShapes([...replacing, ...building])]
1233
+ let worst: SqlExpressionShape | undefined
1234
+ for (const candidate of candidates) {
1235
+ if (worst === undefined || sqlRisk(candidate) > sqlRisk(worst)) worst = candidate
1236
+ }
1237
+ return worst ?? UNKNOWN_SQL
1238
+ }
1239
+
1240
+ const TEXT_METHODS = new Set([
1241
+ "toString",
1242
+ "valueOf",
1243
+ "trim",
1244
+ "trimStart",
1245
+ "trimEnd",
1246
+ "toLowerCase",
1247
+ "toUpperCase",
1248
+ ])
1249
+
1250
+ /** The value a text-preserving call returns: `String(x)`, `x.toString()`, `x.trim()`. */
1251
+ function passedThrough(
1252
+ ts: TypeScriptApi,
1253
+ call: TSApi.CallExpression,
1254
+ ): TSApi.Expression | undefined {
1255
+ const callee = call.expression
1256
+ if (ts.isIdentifier(callee) && callee.text === "String" && call.arguments.length === 1) {
1257
+ return call.arguments[0]
1258
+ }
1259
+ if (
1260
+ ts.isPropertyAccessExpression(callee) &&
1261
+ TEXT_METHODS.has(callee.name.text) &&
1262
+ call.arguments.length === 0
1263
+ ) {
1264
+ return callee.expression
1265
+ }
1266
+ return undefined
1267
+ }
1268
+
1269
+ /** The parts `[a, b].join(sep)` and `a.concat(b)` glue together, a separator as its text. */
1270
+ function joinedParts(
1271
+ ts: TypeScriptApi,
1272
+ call: TSApi.CallExpression,
1273
+ ): readonly (TSApi.Expression | string)[] | undefined {
1274
+ const callee = call.expression
1275
+ if (!ts.isPropertyAccessExpression(callee)) return undefined
1276
+ if (callee.name.text === "concat") return [callee.expression, ...call.arguments]
1277
+ const items = unwrapExpression(ts, callee.expression)
1278
+ if (callee.name.text !== "join" || !ts.isArrayLiteralExpression(items)) return undefined
1279
+ const separator = call.arguments[0]
1280
+ const glue: TSApi.Expression | string =
1281
+ separator === undefined ? "," : ts.isStringLiteralLike(separator) ? separator.text : separator
1282
+ const parts: (TSApi.Expression | string)[] = []
1283
+ items.elements.forEach((element, index) => {
1284
+ if (index > 0) parts.push(glue)
1285
+ if (ts.isSpreadElement(element)) parts.push(element.expression)
1286
+ else if (!ts.isOmittedExpression(element)) parts.push(element)
1287
+ })
1288
+ return parts
1289
+ }
1290
+
1291
+ /** Whether the `sql` a tag names is a function this file defines (`const sql = (s, ...v) => …`),
1292
+ * which is plain interpolation whatever its name. A parameter, an import, or a driver instance
1293
+ * (`const sql = postgres(url)`) keeps the name's trust. */
1294
+ function definesSqlFunction(ts: TypeScriptApi, tag: TSApi.Identifier): boolean {
1295
+ for (let scope: TSApi.Node | undefined = tag.parent; scope !== undefined; scope = scope.parent) {
1296
+ if (
1297
+ ts.isFunctionLike(scope) &&
1298
+ scope.parameters.some((parameter) => bindingNameCovers(ts, parameter.name, tag.text))
1299
+ ) {
1300
+ return false
1301
+ }
1302
+ for (const statement of scopeStatements(ts, scope) ?? []) {
1303
+ if (ts.isFunctionDeclaration(statement) && statement.name?.text === tag.text) return true
1304
+ }
1305
+ for (const list of scopeDeclarationLists(ts, scope)) {
1306
+ for (const declaration of list.declarations) {
1307
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== tag.text) continue
1308
+ const value =
1309
+ declaration.initializer === undefined
1310
+ ? undefined
1311
+ : unwrapExpression(ts, declaration.initializer)
1312
+ return value !== undefined && (ts.isArrowFunction(value) || ts.isFunctionExpression(value))
1313
+ }
1314
+ }
1315
+ }
1316
+ return false
1317
+ }
1318
+
1319
+ /** Describe only the statement's syntax; comments/strings elsewhere cannot influence the result.
1320
+ * `trail` holds the variables being read through, innermost last. */
1321
+ function sqlExpressionShape(
1322
+ ts: TypeScriptApi,
1323
+ expression: TSApi.Expression,
1324
+ scope?: SqlScope,
1325
+ trail: readonly TSApi.Node[] = [],
1326
+ ): SqlExpressionShape {
1327
+ let node = unwrapExpression(ts, expression)
1328
+ while (ts.isNonNullExpression(node)) node = unwrapExpression(ts, node.expression)
1329
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
1330
+ return {
1331
+ staticText: node.text,
1332
+ dynamic: false,
1333
+ concatenated: false,
1334
+ literal: true,
1335
+ parameterizedTag: false,
1336
+ }
1337
+ }
1338
+ if (ts.isTaggedTemplateExpression(node)) {
1339
+ const tag = node.tag
1340
+ const parameterizedTag =
1341
+ (ts.isIdentifier(tag) && tag.text === "sql" && !definesSqlFunction(ts, tag)) ||
1342
+ (ts.isPropertyAccessExpression(tag) && tag.getText() === "Prisma.sql")
1343
+ const template = node.template
1344
+ const templated = ts.isTemplateExpression(template)
1345
+ ? templateShape(ts, template, parameterizedTag ? undefined : scope)
1346
+ : { staticText: template.text, dynamic: false }
1347
+ const staticText = templated.staticText
1348
+ // Only the ecosystem's binding tags are trusted, by NAME - which is the honest limit of a scanner
1349
+ // that reads syntax and runs no type checker. `sql` is what postgres.js, drizzle, slonik and Bun's
1350
+ // own driver all call theirs, and `Prisma.sql` is Prisma's; taking those at their word is a
1351
+ // deliberate trade, and it is worth stating what it costs: a `sql` this file defines as a
1352
+ // function is read as the interpolation it is, but one imported from anywhere is trusted, so
1353
+ // this rule finds mistakes, not an adversary who reads it first.
1354
+ //
1355
+ // Trusting anything else widens that for no gain. This list briefly also held `sqlIdentifiers`,
1356
+ // a name invented for Nifra's own adapters - a second forgeable name that no user has a
1357
+ // convention for, added so Nifra's source would pass its own rule. Names earn their place here by
1358
+ // being what drivers already call the thing, not by being convenient for the framework.
1359
+ //
1360
+ // Everything else - `String.raw`, an identity tag, a member access that merely ends in `.sql` -
1361
+ // is treated as plain interpolation.
1362
+ return {
1363
+ staticText,
1364
+ dynamic: templated.dynamic && !parameterizedTag,
1365
+ concatenated: false,
1366
+ literal: !ts.isTemplateExpression(template),
1367
+ parameterizedTag,
1368
+ }
1369
+ }
1370
+ if (ts.isTemplateExpression(node)) {
1371
+ const templated = templateShape(ts, node, scope)
1372
+ return {
1373
+ staticText: templated.staticText,
1374
+ dynamic: templated.dynamic,
1375
+ // `${a} ${b}` writes no text of its own; it only glues values together.
1376
+ concatenated: [node.head, ...node.templateSpans.map((span) => span.literal)].every(
1377
+ (part) => part.text.trim() === "",
1378
+ ),
1379
+ literal: false,
1380
+ parameterizedTag: false,
1381
+ }
1382
+ }
1383
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
1384
+ const left = sqlExpressionShape(ts, node.left, scope, trail)
1385
+ const right = sqlExpressionShape(ts, node.right, scope, trail)
1386
+ return {
1387
+ staticText: left.staticText + right.staticText,
1388
+ // A resolved const operand is static text, not a dynamic part - so the old `!literal` test
1389
+ // narrows to what it always actually meant: an operand that carries runtime data (dynamic) or
1390
+ // a binding tag being concatenated into plain text (which un-parameterizes it).
1391
+ dynamic: left.dynamic || right.dynamic || left.parameterizedTag || right.parameterizedTag,
1392
+ concatenated: true,
1393
+ literal: left.literal && right.literal,
1394
+ parameterizedTag: false,
1395
+ }
1396
+ }
1397
+ // A resolvable expression (a module-`const` name, a literal ternary) contributes its compile-time
1398
+ // text and stays non-dynamic - this is what lets `"SELECT " + COLS + " FROM t"` and
1399
+ // `db.query(`${COLS} FROM t WHERE id = $1`)` pass while a mutable or unprovable name still flags.
1400
+ // `literal` stays false: the named escape hatches (`unsafe`, `$queryRawUnsafe`) keep flagging a
1401
+ // resolved const, because taking statement text from ANY variable is what their rule warns about.
1402
+ if (scope !== undefined) {
1403
+ const resolved = resolveStaticSqlText(ts, node, scope, 0)
1404
+ if (resolved !== undefined) {
1405
+ return {
1406
+ staticText: resolved,
1407
+ dynamic: false,
1408
+ concatenated: false,
1409
+ literal: false,
1410
+ parameterizedTag: false,
1411
+ }
1412
+ }
1413
+ }
1414
+ if (ts.isCallExpression(node)) {
1415
+ const inner = passedThrough(ts, node)
1416
+ if (inner !== undefined)
1417
+ return { ...sqlExpressionShape(ts, inner, scope, trail), literal: false }
1418
+ const parts = joinedParts(ts, node)
1419
+ if (parts !== undefined) {
1420
+ return joinShapes(
1421
+ parts.map((part) =>
1422
+ typeof part === "string" ? textShape(part) : sqlExpressionShape(ts, part, scope, trail),
1423
+ ),
1424
+ )
1425
+ }
1426
+ }
1427
+ // A bare name that did not resolve to compile-time text. If it is a same-file binding, scan the
1428
+ // shapes of what it may hold - so a statement hoisted into `const q = …` or built up in a `let` is
1429
+ // read exactly as if it were written inline at the call, closing the "extract a variable to launder
1430
+ // the finding" hole. `literal` is forced false: the value arrived through a variable, which is the
1431
+ // property the `unsafe`/`$queryRawUnsafe` hatch rule keys on.
1432
+ if (ts.isIdentifier(node)) {
1433
+ const read = variableWrites(ts, node)
1434
+ // Read inside one of its own writes (`q = q + more`), the variable is the text the other writes
1435
+ // already account for.
1436
+ if (read !== undefined && trail.includes(read.key)) return { ...textShape(""), literal: false }
1437
+ if (read !== undefined && trail.length <= CONST_RESOLUTION_DEPTH) {
1438
+ const written = writtenShape(ts, node.text, read.writes, scope, [...trail, read.key])
1439
+ return { ...written, literal: false }
1440
+ }
1441
+ }
1442
+ return UNKNOWN_SQL
1443
+ }
1444
+
1445
+ interface SqlSink {
1446
+ readonly method: string
1447
+ /** `undefined` for a bare call: `const { query } = db` and then `query(…)`. */
1448
+ readonly receiver: string | undefined
1449
+ }
1450
+
1451
+ function sqlMethod(ts: TypeScriptApi, call: TSApi.CallExpression): SqlSink | undefined {
1452
+ const sink = (method: string, receiver: TSApi.Expression | undefined): SqlSink | undefined =>
1453
+ SQL_METHODS.has(method) || DRIVER_READ_METHODS.has(method)
1454
+ ? { method, receiver: receiver?.getText() }
1455
+ : undefined
1456
+ const callee = call.expression
1457
+ // Svelte compiles this unbound rune; it is not a driver's raw-statement escape hatch.
1458
+ if (
1459
+ ts.isPropertyAccessExpression(callee) &&
1460
+ callee.name.text === "raw" &&
1461
+ ts.isIdentifier(callee.expression) &&
1462
+ callee.expression.text === "$state"
1463
+ ) {
1464
+ const source = callee.getSourceFile()
1465
+ const imported = source.statements.some((statement) => {
1466
+ if (ts.isImportEqualsDeclaration(statement)) return statement.name.text === "$state"
1467
+ if (!ts.isImportDeclaration(statement)) return false
1468
+ const clause = statement.importClause
1469
+ const bindings = clause?.namedBindings
1470
+ return (
1471
+ clause?.name?.text === "$state" ||
1472
+ (bindings !== undefined &&
1473
+ (ts.isNamespaceImport(bindings)
1474
+ ? bindings.name.text === "$state"
1475
+ : bindings.elements.some((binding) => binding.name.text === "$state")))
1476
+ )
1477
+ })
1478
+ let bound = imported || isShadowedAt(ts, callee.expression, "$state")
1479
+ for (
1480
+ let scope: TSApi.Node | undefined = callee.parent;
1481
+ scope !== undefined && !bound;
1482
+ scope = scope.parent
1483
+ ) {
1484
+ bound = directBinding(ts, source, scope, "$state") !== undefined
1485
+ }
1486
+ if (/\.svelte(?:\.[jt]s)?$/.test(source.fileName) && !bound) return undefined
1487
+ }
1488
+ if (ts.isIdentifier(callee)) return sink(callee.text, undefined)
1489
+ if (ts.isPropertyAccessExpression(callee)) return sink(callee.name.text, callee.expression)
1490
+ if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
1491
+ return sink(callee.argumentExpression.text, callee.expression)
1492
+ }
1493
+ return undefined
1494
+ }
1495
+
1496
+ const SQL_RECEIVER = /(?:^|\.)(?:db|sql|prisma|drizzle|database|conn|connection|client|tx)$/i
1497
+
1498
+ /** Whether a statement is SQL assembled from runtime values, judged by where it is sent. */
1499
+ function isAssembledSql(sink: SqlSink, shape: SqlExpressionShape): boolean {
1500
+ if (!shape.dynamic) return false
1501
+ if (sink.receiver === undefined || DRIVER_READ_METHODS.has(sink.method)) {
1502
+ return STATEMENT_START.test(shape.staticText)
1503
+ }
1504
+ return (
1505
+ SQL_KEYWORD.test(shape.staticText) || (shape.concatenated && SQL_RECEIVER.test(sink.receiver))
1506
+ )
1507
+ }
1508
+
1509
+ /** The statement a call passes: the argument itself, or the `text`/`sql` of a config object
1510
+ * (`{ text, values }` in pg, `{ sql, values }` in mysql2). */
1511
+ function statementArgument(
1512
+ ts: TypeScriptApi,
1513
+ argument: TSApi.Expression,
1514
+ ): TSApi.Expression | undefined {
1515
+ const node = unwrapExpression(ts, argument)
1516
+ if (!ts.isObjectLiteralExpression(node)) return argument
1517
+ for (const property of node.properties) {
1518
+ if (ts.isShorthandPropertyAssignment(property) && STATEMENT_KEYS.has(property.name.text)) {
1519
+ return property.name
1520
+ }
1521
+ if (
1522
+ ts.isPropertyAssignment(property) &&
1523
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name)) &&
1524
+ STATEMENT_KEYS.has(property.name.text)
1525
+ ) {
1526
+ return property.initializer
1527
+ }
1528
+ }
1529
+ return undefined
1530
+ }
1531
+
1532
+ const STATEMENT_KEYS = new Set(["text", "sql"])
1533
+
1534
+ interface StatementHelper {
1535
+ readonly position: number
1536
+ readonly sink: SqlSink
1537
+ }
1538
+
1539
+ /** Same-file functions that send one of their parameters as a statement - `run(db, q)` calling
1540
+ * `db.query(q)` - by name, with the parameter's position and the sink it reaches. A call to one is
1541
+ * scanned as a call to that sink. One level deep. */
1542
+ function statementHelpers(
1543
+ ts: TypeScriptApi,
1544
+ source: TSApi.SourceFile,
1545
+ ): ReadonlyMap<string, StatementHelper> {
1546
+ const helpers = new Map<string, StatementHelper>()
1547
+ const visit = (node: TSApi.Node): void => {
1548
+ const sink = ts.isCallExpression(node) ? sqlMethod(ts, node) : undefined
1549
+ const passed = sink !== undefined && ts.isCallExpression(node) ? node.arguments[0] : undefined
1550
+ const argument = passed === undefined ? undefined : statementArgument(ts, passed)
1551
+ const statement = argument === undefined ? undefined : unwrapExpression(ts, argument)
1552
+ if (sink !== undefined && statement !== undefined && ts.isIdentifier(statement)) {
1553
+ const binding = nameBinding(ts, statement)
1554
+ const name = binding.kind === "parameter" ? functionName(ts, binding.fn) : undefined
1555
+ if (binding.kind === "parameter" && name !== undefined && !helpers.has(name)) {
1556
+ helpers.set(name, { position: binding.position, sink })
1557
+ }
1558
+ }
1559
+ ts.forEachChild(node, visit)
1560
+ }
1561
+ visit(source)
1562
+ return helpers
1563
+ }
1564
+
1565
+ function functionName(ts: TypeScriptApi, fn: TSApi.SignatureDeclaration): string | undefined {
1566
+ if (ts.isFunctionDeclaration(fn)) return fn.name?.text
1567
+ if (
1568
+ (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) &&
1569
+ ts.isVariableDeclaration(fn.parent) &&
1570
+ ts.isIdentifier(fn.parent.name)
1571
+ ) {
1572
+ return fn.parent.name.text
1573
+ }
1574
+ return undefined
1575
+ }
1576
+
1577
+ /** `content` with every string, template and regex literal blanked, line breaks kept. */
1578
+ function literalsBlanked(ts: TypeScriptApi, source: TSApi.SourceFile, content: string): string {
1579
+ const out = content.split("")
1580
+ const visit = (node: TSApi.Node): void => {
1581
+ if (
1582
+ ts.isStringLiteralLike(node) ||
1583
+ ts.isTemplateHead(node) ||
1584
+ ts.isTemplateMiddle(node) ||
1585
+ ts.isTemplateTail(node) ||
1586
+ ts.isRegularExpressionLiteral(node) ||
1587
+ ts.isJsxText(node)
1588
+ ) {
1589
+ for (let i = node.getStart(source); i < node.end; i++) if (out[i] !== "\n") out[i] = " "
1590
+ return
1591
+ }
1592
+ ts.forEachChild(node, visit)
1593
+ }
1594
+ visit(source)
1595
+ return out.join("")
1596
+ }
1597
+
1598
+ /** What silences one interpolated-SQL finding: `// nifra-expect NF-C006: <reason>` (or the
1599
+ * `sql-dynamic` slug) on the flagged line or in the comment block directly above it. The reason after
1600
+ * the colon is mandatory (see {@link commentBlockExpectation}). Scoped to the single statement it sits on. */
1601
+ const SQL_DYNAMIC_EXPECTATION = ["NF-C006", "sql-dynamic"]
1602
+
1603
+ /**
1604
+ * Scan one file's text for SQL assembled by interpolation. Pure + line-accurate.
1605
+ *
1606
+ * `imports` opts into following a fragment `const` into another module. Without it the scan is
1607
+ * same-file only, which is what the unit tests exercise and what any caller that has no module graph
1608
+ * to offer gets. With it, only what {@link createProjectSqlImports} will hand back is followed.
1609
+ */
1610
+ export function scanInterpolatedSql(
1611
+ file: string,
1612
+ content: string,
1613
+ ts: TypeScriptApi,
1614
+ imports?: SqlImports,
1615
+ ): SourceFinding[] {
1616
+ return scanSqlSites(file, content, ts, imports).filter((site) => site.expected === undefined)
1617
+ }
1618
+
1619
+ /** {@link scanInterpolatedSql}, keeping the sites an expectation comment silences, with its reason. */
1620
+ export function scanSqlSites(
1621
+ file: string,
1622
+ content: string,
1623
+ ts: TypeScriptApi,
1624
+ imports?: SqlImports,
1625
+ parse = (path: string, text: string) => parseSqlSource(ts, path, text),
1626
+ ): SqlFinding[] {
1627
+ const out: SqlFinding[] = []
1628
+ const lines = content.split("\n")
1629
+ // Malformed source is already a typecheck failure. Do not turn parser recovery nodes into a second,
1630
+ // misleading SQL diagnostic (notably an unterminated template recovered as an interpolation).
1631
+ const source = parse(file, content)
1632
+ if (source === undefined) return out
1633
+ // Module-scope bindings, read once per file: an interpolated `const` that resolves to compile-time
1634
+ // text cannot carry request data, so the shared-projection idiom (`const COLS = "id, name"` …
1635
+ // `${COLS}`) stays quiet while mutable, parameter, shadowed, and unprovable names flag as before.
1636
+ const scope: SqlScope = { module: sqlModuleScope(ts, file, source), imports }
1637
+ const helpers = statementHelpers(ts, source)
1638
+ // A marker counts only in a comment: one inside a string the call passes is data, not a reason.
1639
+ let markerLines: readonly string[] | undefined
1640
+ const visit = (node: TSApi.Node): void => {
1641
+ if (ts.isCallExpression(node)) {
1642
+ const helper = ts.isIdentifier(node.expression)
1643
+ ? helpers.get(node.expression.text)
1644
+ : undefined
1645
+ const sink = helper?.sink ?? sqlMethod(ts, node)
1646
+ const passed = node.arguments[helper?.position ?? 0]
1647
+ const argument = passed === undefined ? undefined : statementArgument(ts, passed)
1648
+ if (sink !== undefined && argument !== undefined) {
1649
+ const shape = sqlExpressionShape(ts, argument, scope)
1650
+ // A helper's own hatch call already answers for passing it a variable.
1651
+ const unsafeEscape =
1652
+ helper === undefined &&
1653
+ sink.receiver !== undefined &&
1654
+ ALWAYS_UNSAFE.has(sink.method) &&
1655
+ !shape.literal &&
1656
+ !shape.parameterizedTag
1657
+ if (unsafeEscape || isAssembledSql(sink, shape)) {
1658
+ const index = node.getStart(source)
1659
+ const line = source.getLineAndCharacterOfPosition(index).line + 1
1660
+ // Sanctioned escape hatch for genuinely-dynamic-but-bound SQL (an allowlisted identifier,
1661
+ // placeholders numbered from data the scan cannot prove numeric). The reason is mandatory: a bare `// nifra-expect
1662
+ // NF-C006` with no reason after the colon does NOT silence, so the hatch always leaves a
1663
+ // greppable audit trail instead of becoming a second laundering trick.
1664
+ markerLines ??= literalsBlanked(ts, source, content).split("\n")
1665
+ const reason = commentBlockExpectation(markerLines, line, SQL_DYNAMIC_EXPECTATION)?.reason
1666
+ const site = { file, line, snippet: (lines[line - 1] ?? "").trim() }
1667
+ out.push(reason === undefined ? site : { ...site, expected: reason })
1668
+ }
1669
+ }
1670
+ }
1671
+ ts.forEachChild(node, visit)
1672
+ }
1673
+ visit(source)
1674
+ return out
1675
+ }
1676
+
1677
+ /**
1678
+ * Collect interpolated-SQL findings across the project.
1679
+ *
1680
+ * Returns `undefined` - not an empty array - when TypeScript is not installed. The rule parses source
1681
+ * with the compiler, so without it there is nothing to report and, more to the point, no basis for
1682
+ * reporting nothing. An empty result would read as "no interpolated SQL found", which is the one
1683
+ * answer a security rule must never give when it did not run.
1684
+ */
1685
+ export async function scanProjectSql(cwd: string): Promise<SourceFinding[] | undefined> {
1686
+ const sourceFiles: Array<{ readonly file: string; readonly content: string }> = []
1687
+ await walkSource(cwd, (file, content) => sourceFiles.push({ file, content }))
1688
+ const contents = new Map(sourceFiles.map(({ file, content }) => [file, content]))
1689
+ const sourceIndex: TypeScriptSourceIndex = {
1690
+ files: sourceFiles.map(({ file }) => file),
1691
+ read: (file) => contents.get(file),
1692
+ }
1693
+ const loaded = await loadProjectTypeScript(cwd, undefined, sourceIndex)
1694
+ if (loaded.compiler === undefined) return undefined
1695
+ const out: SourceFinding[] = []
1696
+ const imports = createProjectSqlImports(cwd)
1697
+ try {
1698
+ for (const { file, content } of sourceFiles) {
1699
+ out.push(...scanInterpolatedSql(file, content, loaded.compiler, imports))
1700
+ }
1701
+ return out.sort(bySite)
1702
+ } finally {
1703
+ await loaded.session?.close()
1704
+ }
1705
+ }
1706
+
1707
+ /** A declaration file. Excluded from cross-module resolution: `declare const X: string` has no
1708
+ * initializer to read, so following one could only ever produce a "proved" the source never wrote. */
1709
+ const SQL_DECLARATION_FILE = /\.d\.[cm]?ts$/
1710
+ /** The extensions the SQL scan will parse - the same set {@link walkSource} globs. */
1711
+ const SQL_SOURCE_FILE = /\.[cm]?tsx?$/
1712
+
1713
+ /**
1714
+ * The on-disk loader for cross-module `const` resolution, scoped to one project.
1715
+ *
1716
+ * Deliberately narrow, because every widening here is a way for a real finding to go quiet:
1717
+ *
1718
+ * - **Relative specifiers only.** A bare specifier names a dependency whose exports can change without
1719
+ * this project changing, so "provably a `const` string" is not a property the project owns.
1720
+ * - **Inside `cwd`, outside the ignored trees.** The resolved path is realpath'd and must still sit
1721
+ * under the project root: a symlink pointing out of the tree is not source this scan reads. The
1722
+ * `node_modules` / `dist` / build exclusions are the same ones the walk applies.
1723
+ * - **Real source only.** A `.d.ts` carries no initializer, and a non-TS file is not parsed.
1724
+ *
1725
+ * A miss on any of those returns `undefined`, which leaves the name unresolved and the interpolation
1726
+ * flagged - the pre-feature answer.
1727
+ */
1728
+ export function createProjectSqlImports(cwd: string): SqlImports {
1729
+ const root = realpathOrSelf(resolve(cwd))
1730
+ return createSqlImports((fromModule, specifier) => {
1731
+ if (!isRelativeSpecifier(specifier)) return undefined
1732
+ try {
1733
+ // `fromModule` is the cwd-RELATIVE path the walk supplies for an entry file, and ABSOLUTE for
1734
+ // every module reached through a hop (their ids are the resolved paths).
1735
+ const fromAbs = isAbsolute(fromModule) ? fromModule : join(root, fromModule)
1736
+ const resolved = realpathSync(Bun.resolveSync(specifier, dirname(fromAbs)))
1737
+ if (!resolved.startsWith(root + sep)) return undefined
1738
+ const rel = resolved.slice(root.length + 1)
1739
+ if (IGNORED_DIR.test(rel)) return undefined
1740
+ if (SQL_DECLARATION_FILE.test(resolved) || !SQL_SOURCE_FILE.test(resolved)) return undefined
1741
+ return { id: resolved, content: readFileSync(resolved, "utf8") }
1742
+ } catch {
1743
+ return undefined // unresolvable, unreadable, or outside the project
1744
+ }
1745
+ })
1746
+ }