loadwise 0.6.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (278) hide show
  1. package/README.md +175 -115
  2. package/dist/bin/loadwise.js +132 -67
  3. package/dist/lib/accessibility/analyze.js +5 -3
  4. package/dist/lib/accessibility/angular-inline.js +9 -11
  5. package/dist/lib/accessibility/angular-literal.js +39 -0
  6. package/dist/lib/accessibility/form-context.js +36 -0
  7. package/dist/lib/accessibility/frame-head.js +92 -0
  8. package/dist/lib/accessibility/frame-viewport.js +149 -0
  9. package/dist/lib/accessibility/frontend-detect.js +6 -5
  10. package/dist/lib/accessibility/jsx-elements.js +13 -3
  11. package/dist/lib/accessibility/markup-files.js +7 -2
  12. package/dist/lib/accessibility/rule-ids.js +3 -0
  13. package/dist/lib/accessibility/rules.js +128 -41
  14. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  15. package/dist/lib/accessibility/template-attributes.js +5 -3
  16. package/dist/lib/accessibility/template-elements.js +25 -6
  17. package/dist/lib/accessibility/template-file.js +40 -25
  18. package/dist/lib/accessibility/usage.js +10 -2
  19. package/dist/lib/editor/accessibility-examples.js +6 -1
  20. package/dist/lib/editor/actions.js +46 -7
  21. package/dist/lib/editor/apply-fix.js +69 -4
  22. package/dist/lib/editor/configured-setup.js +63 -0
  23. package/dist/lib/editor/diagnostics.js +206 -17
  24. package/dist/lib/editor/dismissals.js +85 -26
  25. package/dist/lib/editor/editor-document.js +5 -2
  26. package/dist/lib/editor/editor-launcher.js +170 -0
  27. package/dist/lib/editor/fix-edits.js +19 -0
  28. package/dist/lib/editor/jetbrains-setup.js +53 -0
  29. package/dist/lib/editor/language-server.js +80 -24
  30. package/dist/lib/editor/managed-config.js +37 -0
  31. package/dist/lib/editor/native-setup.js +86 -0
  32. package/dist/lib/editor/perf-watch.js +8 -6
  33. package/dist/lib/editor/release-vsix.js +61 -0
  34. package/dist/lib/editor/reliability-examples.js +15 -0
  35. package/dist/lib/editor/scan-session.js +29 -8
  36. package/dist/lib/editor/server-commands.js +38 -9
  37. package/dist/lib/editor/setup-server.js +87 -0
  38. package/dist/lib/editor/setup-vim.js +63 -0
  39. package/dist/lib/editor/setup.js +131 -0
  40. package/dist/lib/editor/stdio-setup.js +6 -0
  41. package/dist/lib/editor/workspace-files.js +61 -7
  42. package/dist/lib/editor/workspace-paths.js +41 -1
  43. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  44. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  45. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  46. package/dist/lib/maintainability/cli/inputs.js +12 -3
  47. package/dist/lib/maintainability/cli.js +18 -5
  48. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  49. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  50. package/dist/lib/maintainability/examples.js +4 -0
  51. package/dist/lib/maintainability/quality/functions.js +9 -6
  52. package/dist/lib/maintainability/quality/limits.js +19 -0
  53. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  54. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  55. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  56. package/dist/lib/maintainability/rule-ids.js +3 -0
  57. package/dist/lib/maintainability/scan-changed.js +4 -1
  58. package/dist/lib/maintainability/scan-worker.js +6 -2
  59. package/dist/lib/maintainability/scan.js +21 -8
  60. package/dist/lib/maintainability/site-fixes/unused-bindings.js +138 -3
  61. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  62. package/dist/lib/maintainability/unused/unused-bindings.js +39 -4
  63. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  64. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  65. package/dist/lib/performance/analysis/source-options.js +7 -6
  66. package/dist/lib/performance/analyze.js +16 -3
  67. package/dist/lib/performance/cli/changed-lines.js +8 -1
  68. package/dist/lib/performance/cli/cli-arguments.js +19 -8
  69. package/dist/lib/performance/cli/cli-output.js +4 -0
  70. package/dist/lib/performance/cli/cli-scan.js +21 -2
  71. package/dist/lib/performance/cli.js +16 -7
  72. package/dist/lib/performance/collections/memory-growth.js +55 -12
  73. package/dist/lib/performance/contracts/openapi.js +13 -4
  74. package/dist/lib/performance/datastores/pg-integrity.js +68 -22
  75. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  76. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  77. package/dist/lib/performance/datastores/pooling.js +62 -3
  78. package/dist/lib/performance/datastores/redis.js +94 -18
  79. package/dist/lib/performance/datastores/session-store.js +2 -1
  80. package/dist/lib/performance/db/checks.js +19 -8
  81. package/dist/lib/performance/db/gateway.js +3 -1
  82. package/dist/lib/performance/db/plan-estimates.js +4 -4
  83. package/dist/lib/performance/engine/native-syntax.js +3 -0
  84. package/dist/lib/performance/engine/native.js +11 -7
  85. package/dist/lib/performance/evidence/plans.js +7 -5
  86. package/dist/lib/performance/evidence/traces.js +21 -1
  87. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  88. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  89. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  90. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  91. package/dist/lib/performance/frontend/frontend-perf.js +149 -74
  92. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  93. package/dist/lib/performance/migrations/extract-code.js +13 -5
  94. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  95. package/dist/lib/performance/migrations/operations.js +56 -13
  96. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  97. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  98. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  99. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  100. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  101. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  102. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  103. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  104. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  105. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  106. package/dist/lib/performance/polyglot.js +111 -14
  107. package/dist/lib/performance/projects.js +3 -3
  108. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  109. package/dist/lib/performance/request/backend-mastery.js +151 -42
  110. package/dist/lib/performance/request/bulk-listener-registration.js +111 -0
  111. package/dist/lib/performance/request/fastify-receivers.js +93 -0
  112. package/dist/lib/performance/request/fresh-loop-socket.js +103 -0
  113. package/dist/lib/performance/request/mongoose-lean.js +298 -46
  114. package/dist/lib/performance/request/node-event-listener-leak.js +99 -5
  115. package/dist/lib/performance/request/phase5-ast.js +6 -7
  116. package/dist/lib/performance/request/phase5-rules.js +204 -23
  117. package/dist/lib/performance/request/request-handlers.js +120 -23
  118. package/dist/lib/performance/request/sql-select-star.js +150 -0
  119. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  120. package/dist/lib/performance/request/upload-limits.js +5 -1
  121. package/dist/lib/performance/site-fix.js +4 -4
  122. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  123. package/dist/lib/performance/site-fixes/collection-existence.js +2 -1
  124. package/dist/lib/performance/site-fixes/collections.js +1 -2
  125. package/dist/lib/performance/site-fixes/frontend-fixes.js +358 -14
  126. package/dist/lib/performance/site-fixes/helpers.js +3 -4
  127. package/dist/lib/performance/site-fixes/integrity.js +2 -4
  128. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  129. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  130. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  131. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  132. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  133. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  134. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  135. package/dist/lib/reliability/boundary-access.js +114 -57
  136. package/dist/lib/reliability/react-bugs.js +29 -7
  137. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  138. package/dist/lib/reliability/resource-leaks.js +209 -195
  139. package/dist/lib/reliability/rule-ids.js +10 -1
  140. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  141. package/dist/lib/reliability/swallowed-errors.js +107 -21
  142. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  143. package/dist/lib/reliability/usage.js +16 -5
  144. package/dist/lib/reliability/walk.js +3 -2
  145. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  146. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  147. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  148. package/dist/lib/security/auth-crypto/shared.js +3 -1
  149. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  150. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  151. package/dist/lib/security/cli.js +21 -6
  152. package/dist/lib/security/cookie-credentials.js +115 -0
  153. package/dist/lib/security/cookie-csrf.js +241 -0
  154. package/dist/lib/security/deps/advisory.js +50 -109
  155. package/dist/lib/security/deps/cli.js +1 -1
  156. package/dist/lib/security/deps/cvss-score.js +14 -0
  157. package/dist/lib/security/deps/fixed-version.js +97 -0
  158. package/dist/lib/security/deps/lockfiles.js +135 -74
  159. package/dist/lib/security/deps/osv.js +11 -3
  160. package/dist/lib/security/deps/scan.js +47 -20
  161. package/dist/lib/security/deps/yarn-lock.js +158 -0
  162. package/dist/lib/security/examples/injection.cjs +4 -0
  163. package/dist/lib/security/exposure/cookies.js +17 -2
  164. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  165. package/dist/lib/security/exposure/frontend-security.js +21 -14
  166. package/dist/lib/security/exposure/jsx-url.js +18 -33
  167. package/dist/lib/security/exposure/logging.js +49 -10
  168. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  169. package/dist/lib/security/exposure/react-html.js +26 -0
  170. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  171. package/dist/lib/security/files/compose.js +126 -1
  172. package/dist/lib/security/files/dockerfile.js +62 -4
  173. package/dist/lib/security/files/index.js +1 -1
  174. package/dist/lib/security/injection/command.js +46 -18
  175. package/dist/lib/security/injection/index.js +2 -0
  176. package/dist/lib/security/injection/ldap.js +86 -0
  177. package/dist/lib/security/injection/nosql.js +28 -4
  178. package/dist/lib/security/injection/redos.js +1 -1
  179. package/dist/lib/security/injection/rule-ids.js +1 -0
  180. package/dist/lib/security/injection/shared.js +5 -1
  181. package/dist/lib/security/injection/sql.js +28 -13
  182. package/dist/lib/security/lexical-declaration.js +113 -0
  183. package/dist/lib/security/pg-dynamic-query.js +28 -1
  184. package/dist/lib/security/pg-identifier-guards.js +107 -3
  185. package/dist/lib/security/phase5-rules.js +26 -135
  186. package/dist/lib/security/polyglot.js +2 -2
  187. package/dist/lib/security/redirect-settings.js +98 -0
  188. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  189. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  190. package/dist/lib/security/request-forgery/shared.js +1 -7
  191. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  192. package/dist/lib/security/rule-descriptions.js +5 -1
  193. package/dist/lib/security/rule-ids.js +7 -0
  194. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  195. package/dist/lib/security/site-fixes/exposure.js +21 -3
  196. package/dist/lib/security/site-fixes/files.js +11 -13
  197. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  198. package/dist/lib/security/site-fixes/injection.js +17 -4
  199. package/dist/lib/security/site-fixes/jwt.js +1 -20
  200. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  201. package/dist/lib/security/taint/binding-inputs.js +236 -0
  202. package/dist/lib/security/taint/filename-guard.js +45 -45
  203. package/dist/lib/security/taint/guards.js +14 -8
  204. package/dist/lib/security/taint/index.js +126 -154
  205. package/dist/lib/security/taint/propagate.js +43 -9
  206. package/dist/lib/security/taint/record-writes.js +161 -0
  207. package/dist/lib/security/taint/resolution-cache.js +13 -7
  208. package/dist/lib/security/taint/sanitizers.js +89 -5
  209. package/dist/lib/security/taint/trace-nodes.js +61 -0
  210. package/dist/lib/security/taint/validators.js +89 -9
  211. package/dist/lib/shared/agent/agent-init.js +28 -5
  212. package/dist/lib/shared/agent/agent-prompt.js +74 -0
  213. package/dist/lib/shared/agent/agent-session.js +6 -1
  214. package/dist/lib/shared/agent/agent-verify.js +58 -11
  215. package/dist/lib/shared/agent/git-hook.js +17 -6
  216. package/dist/lib/shared/agent/review-delivery.js +1 -1
  217. package/dist/lib/shared/agent/review-mcp.js +8 -2
  218. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  219. package/dist/lib/shared/analysis/scan-cache.js +99 -14
  220. package/dist/lib/shared/check.js +172 -20
  221. package/dist/lib/shared/cli-dispatch.js +17 -0
  222. package/dist/lib/shared/config.js +27 -10
  223. package/dist/lib/shared/explain.js +1 -1
  224. package/dist/lib/shared/fix/fix-convergence.js +19 -31
  225. package/dist/lib/shared/fix/fix-handoff.js +16 -11
  226. package/dist/lib/shared/fix/fix-imports.js +4 -162
  227. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  228. package/dist/lib/shared/fix/fix-presentation-prettier.js +1 -46
  229. package/dist/lib/shared/fix/fix-presentation-rows.js +45 -1
  230. package/dist/lib/shared/fix/fix-presentation.js +9 -6
  231. package/dist/lib/shared/fix/fix-safety.js +32 -1
  232. package/dist/lib/shared/fix/fix-scope.js +82 -0
  233. package/dist/lib/shared/fix/fix-terminal.js +28 -1
  234. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  235. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  236. package/dist/lib/shared/fix/project-file-access.js +17 -26
  237. package/dist/lib/shared/fix/read-fix-text.js +20 -0
  238. package/dist/lib/shared/fix.js +241 -104
  239. package/dist/lib/shared/formats/finding-location.js +4 -1
  240. package/dist/lib/shared/formats/github.js +3 -3
  241. package/dist/lib/shared/formats/sarif.js +9 -3
  242. package/dist/lib/shared/report-fp.js +97 -0
  243. package/dist/lib/shared/reporting/automatic-fix-signal.js +10 -0
  244. package/dist/lib/shared/reporting/baseline.js +7 -5
  245. package/dist/lib/shared/reporting/check-text.js +50 -0
  246. package/dist/lib/shared/reporting/pillars.js +54 -19
  247. package/dist/lib/shared/reporting/source-report.js +3 -0
  248. package/dist/lib/shared/system/atomic-write.js +5 -2
  249. package/dist/lib/shared/system/glob.js +34 -8
  250. package/dist/lib/shared/system/sentry.js +222 -0
  251. package/dist/lib/shared/system/shell-argument.js +5 -1
  252. package/dist/lib/shared/system/terminal-safe.js +3 -2
  253. package/dist/lib/shared/system/terminal-style.js +131 -0
  254. package/dist/lib/shared/workspaces.js +15 -3
  255. package/docs/assets/cli-workflow.gif +0 -0
  256. package/integrations/sublime/plugin.py +22 -0
  257. package/integrations/zed/Cargo.lock +845 -0
  258. package/integrations/zed/Cargo.toml +11 -0
  259. package/integrations/zed/extension.toml +11 -0
  260. package/integrations/zed/src/lib.rs +25 -0
  261. package/package.json +15 -3
  262. package/plugin/.claude-plugin/plugin.json +1 -1
  263. package/plugin/commands/loadwise.md +11 -6
  264. package/plugin/hooks/check-edited-file.mjs +27 -5
  265. package/polyglot/performance/rules/csharp.yml +34 -5
  266. package/polyglot/performance/rules/java.yml +24 -1
  267. package/polyglot/performance/rules/python.yml +74 -2
  268. package/polyglot/performance/sgconfig.yml +1 -0
  269. package/polyglot/reliability/rules/csharp.yml +12 -6
  270. package/polyglot/reliability/rules/go.yml +86 -6
  271. package/polyglot/reliability/rules/java.yml +22 -1
  272. package/polyglot/reliability/sgconfig.yml +1 -0
  273. package/polyglot/security/rules/go.yml +100 -22
  274. package/polyglot/security/rules/python.yml +74 -6
  275. package/polyglot/security/rules/rust.yml +65 -0
  276. package/polyglot/security/sgconfig.yml +1 -0
  277. package/schema/loadwise.config.schema.json +556 -76
  278. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -116,28 +116,34 @@ function compositeParts(document, schema, segments, seen) {
116
116
  }
117
117
  // Flattens an object schema to `field.path` -> { type, required, enumValues, segments }. oneOf and
118
118
  // anyOf are not walked.
119
- function flattenSchema({ document, rawSchema, segments }, fields = new Map(), prefix = '', depth = 0, seen = new Set()) {
119
+ function flattenSchema({ document, rawSchema, segments }, { fields = new Map(), prefix = '', depth = 0, seen = new Set(), parentReadOnly = false, } = {}) {
120
120
  if (depth > maxSchemaDepth)
121
121
  return fields;
122
122
  const { schema, segments: schemaSegments } = resolveSchema(document, rawSchema, segments);
123
123
  if (schema?.type === 'array') {
124
- return flattenSchema({ document, rawSchema: schema.items, segments: [...schemaSegments, 'items'] }, fields, `${prefix}[]`, depth + 1, seen);
124
+ return flattenSchema({ document, rawSchema: schema.items, segments: [...schemaSegments, 'items'] }, { fields, prefix: `${prefix}[]`, depth: depth + 1, seen, parentReadOnly });
125
125
  }
126
126
  const visited = new Set(seen);
127
127
  const parts = compositeParts(document, schema, schemaSegments, visited);
128
128
  const required = new Set(parts.flatMap((part) => (Array.isArray(part.schema.required) ? part.schema.required : [])));
129
+ // allOf composes definitions, so any read-only member makes the property response-only whatever the order.
130
+ const readOnlyNames = new Set(parts.flatMap((part) => Object.entries(part.schema.properties ?? {})
131
+ .filter(([name, property]) => resolveSchema(document, property, [...part.segments, 'properties', name]).schema?.readOnly === true)
132
+ .map(([name]) => name)));
129
133
  for (const part of parts) {
130
134
  for (const [name, property] of Object.entries(part.schema.properties ?? {})) {
131
135
  const propertySegments = [...part.segments, 'properties', name];
132
136
  const resolved = resolveSchema(document, property, propertySegments);
133
137
  const fieldPath = prefix ? `${prefix}.${name}` : name;
138
+ const readOnly = parentReadOnly || readOnlyNames.has(name);
134
139
  fields.set(fieldPath, {
135
140
  type: schemaType(document, property),
136
141
  required: required.has(name),
142
+ readOnly,
137
143
  enumValues: resolved.schema?.enum,
138
144
  segments: propertySegments,
139
145
  });
140
- flattenSchema({ document, rawSchema: property, segments: propertySegments }, fields, fieldPath, depth + 1, visited);
146
+ flattenSchema({ document, rawSchema: property, segments: propertySegments }, { fields, prefix: fieldPath, depth: depth + 1, seen: visited, parentReadOnly: readOnly });
141
147
  }
142
148
  }
143
149
  return fields;
@@ -291,7 +297,10 @@ function compareRequestBody({ report, label }, oldPart, newPart) {
291
297
  const parentPath = fieldPath.replace(/\.?[^.]+$/, '');
292
298
  if (!oldField && parentPath && !oldFields.has(parentPath))
293
299
  continue;
294
- if (newField.required && !oldField?.required) {
300
+ // A descendant of an optional read-only object only inherits writability; the object itself decides whether it is sent.
301
+ if (oldField?.readOnly && oldFields.get(parentPath)?.readOnly)
302
+ continue;
303
+ if (newField.required && !newField.readOnly && !(oldField?.required && !oldField.readOnly)) {
295
304
  report('api-required-input', 'new', newField.segments, `Request field "${fieldPath}" of ${label} is now required. Clients that do not send it get a 400 response.`);
296
305
  }
297
306
  else if (oldField && requestTypeBreaks(oldField.type, newField.type)) {
@@ -1,5 +1,8 @@
1
1
  import { ts } from '../engine/compiler.js';
2
2
  import { analyzeFragment } from './pg-fragments.js';
3
+ import { effectsAtOrdinaryRelease } from './pg-session-release.js';
4
+ import { newSessionEffects, recordSessionEffects, sessionSqlCandidate } from './pg-session-sql.js';
5
+ import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
3
6
  const pgPackages = ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'];
4
7
  const poolTypes = ['Pool'];
5
8
  const queryTypes = ['Pool', 'Client', 'ClientBase', 'PoolClient'];
@@ -9,6 +12,13 @@ const transactionStart = new RegExp(`^(?:begin(?: work| transaction)?|start tran
9
12
  const setTransaction = new RegExp(`^set transaction ${modes}$`, 'i');
10
13
  const transactionEnd = /^(?:end|abort|commit|rollback)(?: work| transaction)?(?: and (?:no )?chain)?$/i;
11
14
  const savepoint = /^(?:savepoint|release(?: savepoint)?|rollback(?: work| transaction)? to(?: savepoint)?) [a-z_][a-z0-9_$]*$/i;
15
+ // Even a SELECT can change session state through a function. Only rewrite a
16
+ // fixed scalar projection with no table, function, or additional statement.
17
+ const independentSelect = /^select\s+(?:[0-9]+|\$[1-9][0-9]*|null|true|false)\s*;?$/i;
18
+ export function isSessionIndependentCheckoutQuery(call) {
19
+ const argument = call.arguments[0];
20
+ return !!argument && ts.isStringLiteralLike(argument) && independentSelect.test(argument.text.trim());
21
+ }
12
22
  function transactionControl(text) {
13
23
  // Restrict recognition to one command. A complete transaction submitted in
14
24
  // one query uses one connection, and COMMIT PREPARED can use another session.
@@ -81,35 +91,71 @@ function queryMethod(call) {
81
91
  : undefined;
82
92
  return method?.text === 'query' && call.arguments.length ? method : undefined;
83
93
  }
84
- function checkPgIntegrity(call, context) {
85
- const access = call.expression;
86
- const method = queryMethod(call);
87
- if (!method)
88
- return;
89
- // queryMethod found a name, so the callee is a property or element access.
90
- if (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access))
94
+ function querySql(call, receiver, context) {
95
+ if (!call.arguments[0])
91
96
  return;
92
97
  const query = textArgument(call.arguments[0]);
93
98
  if (!query)
94
99
  return;
95
- let text;
96
100
  if (ts.isStringLiteralLike(query))
97
- text = query.text;
98
- else {
99
- const concatenation = ts.isBinaryExpression(query) && query.operatorToken.kind === ts.SyntaxKind.PlusToken;
100
- const assembled = ts.isTemplateExpression(query) || concatenation;
101
- if (!assembled && !ts.isIdentifier(query))
102
- return;
103
- if (assembled && !usesDriverQuery(call, access.expression, queryTypes, context))
104
- return;
105
- if (concatenation && !(context.checker.getTypeAtLocation(query).flags & ts.TypeFlags.StringLike))
106
- return;
107
- text = analyzeFragment(query, context.checker);
101
+ return query.text;
102
+ const concatenation = ts.isBinaryExpression(query) && query.operatorToken.kind === ts.SyntaxKind.PlusToken;
103
+ const assembled = ts.isTemplateExpression(query) || concatenation;
104
+ if (!assembled && !ts.isIdentifier(query))
105
+ return;
106
+ if (assembled && !usesDriverQuery(call, receiver, queryTypes, context))
107
+ return;
108
+ if (concatenation && !(context.checker.getTypeAtLocation(query).flags & ts.TypeFlags.StringLike))
109
+ return;
110
+ const text = analyzeFragment(query, context.checker);
111
+ return typeof text === 'string' ? text : undefined;
112
+ }
113
+ function reportEffects(effects, node, context, source) {
114
+ const pool = source === 'pool';
115
+ if (effects.advisoryLocks.size > 0) {
116
+ const problem = pool
117
+ ? 'This query can acquire a session advisory lock and return its connection to the pool.'
118
+ : 'This release can return the connection to the pool with a session advisory lock still held.';
119
+ context.report(node, 'pg-advisory-lock-session', `${problem} Keep the same checked-out client throughout the protected work and unlock on that client before release. Discard the connection if cleanup fails.`);
120
+ }
121
+ if (effects.subscriptions.size > 0) {
122
+ const problem = pool
123
+ ? 'LISTEN subscribes the connection used by this query, but pool.query() returns that connection to the pool.'
124
+ : 'This release can return a PostgreSQL connection that is still subscribed to notifications.';
125
+ context.report(node, 'pg-listen-session', `${problem} Keep one checked-out client for the listener’s lifetime and unsubscribe on that client before release. Discard the connection if cleanup fails.`);
108
126
  }
109
- if (typeof text === 'string' &&
110
- transactionControl(text) &&
111
- usesDriverQuery(call, access.expression, poolTypes, context)) {
127
+ }
128
+ function checkSessionRelease(call, receiver, context) {
129
+ if (!ts.isIdentifier(receiver) || !usesDriverQuery(call, receiver, queryTypes, context))
130
+ return;
131
+ const effects = effectsAtOrdinaryRelease(call, receiver, {
132
+ context,
133
+ isCheckout: (checkout, pool) => usesDriverQuery(checkout, pool, poolTypes, context),
134
+ isClientQuery: (query, client) => usesDriverQuery(query, client, queryTypes, context),
135
+ queryText: (query) => querySql(query, receiver, context),
136
+ });
137
+ if (effects)
138
+ reportEffects(effects, call.expression, context, 'release');
139
+ }
140
+ function checkPgIntegrity(call, context) {
141
+ const access = call.expression;
142
+ if (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access))
143
+ return;
144
+ if (staticMemberName(access) === 'release')
145
+ checkSessionRelease(call, access.expression, context);
146
+ const method = queryMethod(call);
147
+ if (!method)
148
+ return;
149
+ const text = querySql(call, access.expression, context);
150
+ if (text === undefined)
151
+ return;
152
+ if (transactionControl(text) && usesDriverQuery(call, access.expression, poolTypes, context)) {
112
153
  context.report(method, 'pg-transaction-on-pool', 'Each pool.query() can run on a different connection, so BEGIN and COMMIT do not share one transaction. Use `const client = await pool.connect()`, run every statement on `client`, and call `client.release()` in finally.');
113
154
  }
155
+ if (sessionSqlCandidate.test(text) && usesDriverQuery(call, access.expression, poolTypes, context)) {
156
+ const effects = newSessionEffects();
157
+ if (recordSessionEffects(text, effects))
158
+ reportEffects(effects, method, context, 'pool');
159
+ }
114
160
  }
115
161
  export { checkPgIntegrity, queryMethod, textArgument, usesDriverQuery, queryTypes };
@@ -0,0 +1,114 @@
1
+ import { ts } from '../engine/compiler.js';
2
+ import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
3
+ import { newSessionEffects, recordSessionEffects } from './pg-session-sql.js';
4
+ function expressionCall(statement) {
5
+ if (!ts.isExpressionStatement(statement))
6
+ return;
7
+ const expression = ts.skipOuterExpressions(statement.expression);
8
+ const call = ts.isAwaitExpression(expression) ? ts.skipOuterExpressions(expression.expression) : expression;
9
+ return ts.isCallExpression(call) ? call : undefined;
10
+ }
11
+ function checkoutDeclaration(declaration, probe) {
12
+ if (!declaration.initializer || !(declaration.parent.flags & ts.NodeFlags.Const))
13
+ return;
14
+ const acquisition = ts.skipOuterExpressions(declaration.initializer);
15
+ if (!ts.isAwaitExpression(acquisition))
16
+ return;
17
+ const call = ts.skipOuterExpressions(acquisition.expression);
18
+ if (!ts.isCallExpression(call))
19
+ return;
20
+ const access = ts.skipOuterExpressions(call.expression);
21
+ if ((!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access)) ||
22
+ staticMemberName(access) !== 'connect')
23
+ return;
24
+ if (call.arguments.length || !probe.isCheckout(call, access.expression))
25
+ return;
26
+ const statement = declaration.parent.parent;
27
+ if (ts.isVariableStatement(statement) && statement.declarationList.declarations.length === 1)
28
+ return statement;
29
+ }
30
+ function visiblePath(start, end) {
31
+ const block = start.parent;
32
+ if (!ts.isBlock(block))
33
+ return;
34
+ const statementsAfterCheckout = block.statements.slice(block.statements.indexOf(start) + 1);
35
+ if (end.parent === block)
36
+ return statementsAfterCheckout.slice(0, statementsAfterCheckout.indexOf(end));
37
+ const cleanup = end.parent;
38
+ if (!ts.isBlock(cleanup) || !ts.isTryStatement(cleanup.parent))
39
+ return;
40
+ const attempt = cleanup.parent;
41
+ if (attempt.parent !== block || attempt.catchClause || attempt.finallyBlock !== cleanup)
42
+ return;
43
+ const position = statementsAfterCheckout.indexOf(attempt);
44
+ if (position < 0)
45
+ return;
46
+ return [
47
+ ...statementsAfterCheckout.slice(0, position),
48
+ ...attempt.tryBlock.statements,
49
+ ...cleanup.statements.slice(0, cleanup.statements.indexOf(end)),
50
+ ];
51
+ }
52
+ function statementMentionsClient(statement, client, context) {
53
+ if (ts.isIdentifier(statement) &&
54
+ statement.text === client.name &&
55
+ context.checker.getSymbolAtLocation(statement) === client)
56
+ return true;
57
+ return ts.forEachChild(statement, (child) => statementMentionsClient(child, client, context) || undefined) === true;
58
+ }
59
+ const eventMethods = new Set(['on', 'once', 'off', 'addListener', 'removeListener']);
60
+ function visibleClientSql(statement, client, probe) {
61
+ const call = expressionCall(statement);
62
+ const access = call && ts.skipOuterExpressions(call.expression);
63
+ if (!access || (!ts.isPropertyAccessExpression(access) && !ts.isElementAccessExpression(access)))
64
+ return;
65
+ if (probe.context.checker.getSymbolAtLocation(ts.skipOuterExpressions(access.expression)) !== client)
66
+ return;
67
+ const method = staticMemberName(access);
68
+ if (method && eventMethods.has(method)) {
69
+ return call?.arguments.some((argument) => statementMentionsClient(argument, client, probe.context))
70
+ ? undefined
71
+ : '';
72
+ }
73
+ const expression = ts.isExpressionStatement(statement) && ts.skipOuterExpressions(statement.expression);
74
+ if (method === 'query' &&
75
+ expression &&
76
+ ts.isAwaitExpression(expression) &&
77
+ call &&
78
+ probe.isClientQuery(call, access.expression))
79
+ return probe.queryText(call);
80
+ }
81
+ function releaseStatement(call) {
82
+ if (ts.isExpressionStatement(call.parent))
83
+ return call.parent;
84
+ if (ts.isAwaitExpression(call.parent) && ts.isExpressionStatement(call.parent.parent))
85
+ return call.parent.parent;
86
+ }
87
+ // Follow only straight-line operations and an explicit finally block on one local checkout.
88
+ // Unknown control flow or a reference that could hand off the client ends the proof.
89
+ export function effectsAtOrdinaryRelease(call, receiver, probe) {
90
+ const destroy = call.arguments[0];
91
+ if (destroy && ts.skipOuterExpressions(destroy).kind !== ts.SyntaxKind.FalseKeyword)
92
+ return;
93
+ const client = probe.context.checker.getSymbolAtLocation(receiver);
94
+ const declaration = client?.valueDeclaration;
95
+ const end = releaseStatement(call);
96
+ if (!client || !declaration || !ts.isVariableDeclaration(declaration) || !end)
97
+ return;
98
+ const start = checkoutDeclaration(declaration, probe);
99
+ const statements = start && visiblePath(start, end);
100
+ if (!start || !statements)
101
+ return;
102
+ if (ts.isBlock(start.parent) &&
103
+ start.parent.statements.some((statement) => statement.end <= start.getStart() && statementMentionsClient(statement, client, probe.context)))
104
+ return;
105
+ const effects = newSessionEffects();
106
+ for (const statement of statements) {
107
+ if (!statementMentionsClient(statement, client, probe.context))
108
+ continue;
109
+ const sql = visibleClientSql(statement, client, probe);
110
+ if (sql === undefined || !recordSessionEffects(sql, effects))
111
+ return;
112
+ }
113
+ return effects;
114
+ }
@@ -0,0 +1,144 @@
1
+ import { parseStatements } from '../sql/pg-parser.js';
2
+ export const sessionSqlCandidate = /\b(?:listen|unlisten|discard|pg_(?:try_)?advisory_)/i;
3
+ const transactionCandidate = /\b(?:begin|start\s+transaction|commit|rollback|abort|end|savepoint|release)\b/i;
4
+ const advisoryAcquire = new Set([
5
+ 'pg_advisory_lock',
6
+ 'pg_advisory_lock_shared',
7
+ 'pg_try_advisory_lock',
8
+ 'pg_try_advisory_lock_shared',
9
+ ]);
10
+ const advisoryRelease = new Set(['pg_advisory_unlock', 'pg_advisory_unlock_shared']);
11
+ export function newSessionEffects() {
12
+ return { advisoryLocks: new Map(), subscriptions: new Set(), savepoints: [] };
13
+ }
14
+ function knownLockKey(args) {
15
+ const numbers = args.map(({ A_Const: constant }) => {
16
+ if (constant?.ival)
17
+ return String(constant.ival.ival ?? 0);
18
+ const bigInteger = constant?.fval?.fval;
19
+ return bigInteger && /^-?\d+$/.test(bigInteger) ? bigInteger : undefined;
20
+ });
21
+ if (numbers.length && numbers.every((number) => number !== undefined))
22
+ return numbers.join(',');
23
+ }
24
+ function decrementLock(locks, exactKey, kind) {
25
+ const candidates = [...locks.keys()].filter((held) => held === exactKey || held === kind || (exactKey === kind && held.startsWith(kind)));
26
+ // An ambiguous unlock can discharge any matching entry. Keep the remaining count while
27
+ // deferring which specific key remains, so a later literal unlock can still match it.
28
+ if (candidates.length > 1) {
29
+ let remaining = -1;
30
+ for (const candidate of candidates) {
31
+ remaining += locks.get(candidate) ?? 0;
32
+ locks.delete(candidate);
33
+ }
34
+ if (remaining > 0)
35
+ locks.set(kind, remaining);
36
+ return;
37
+ }
38
+ const [key] = candidates;
39
+ if (key === undefined)
40
+ return;
41
+ const count = locks.get(key) ?? 0;
42
+ if (count > 1)
43
+ locks.set(key, count - 1);
44
+ else
45
+ locks.delete(key);
46
+ }
47
+ function applyAdvisoryEffect(node, effects) {
48
+ let value = node.ResTarget?.val;
49
+ while (value?.TypeCast)
50
+ value = value.TypeCast.arg;
51
+ const call = value?.FuncCall;
52
+ const names = call?.funcname ?? [];
53
+ if (names.length > 2 || (names.length === 2 && names[0].String?.sval !== 'pg_catalog'))
54
+ return;
55
+ const name = names.at(-1)?.String?.sval;
56
+ if (!name)
57
+ return;
58
+ const kind = name.endsWith('_shared') ? 'shared:' : 'exclusive:';
59
+ const key = kind + (knownLockKey(call?.args ?? []) ?? '');
60
+ const locks = effects.advisoryLocks;
61
+ if (advisoryAcquire.has(name))
62
+ locks.set(key, (locks.get(key) ?? 0) + 1);
63
+ else if (advisoryRelease.has(name))
64
+ decrementLock(locks, key, kind);
65
+ else if (name === 'pg_advisory_unlock_all')
66
+ locks.clear();
67
+ }
68
+ function updateSubscriptionSavepoints(transaction, effects) {
69
+ const name = transaction.savepoint_name;
70
+ if (!name || !effects.pendingSubscriptions)
71
+ return;
72
+ if (transaction.kind === 'TRANS_STMT_SAVEPOINT') {
73
+ effects.savepoints.push({ name, subscriptions: new Set(effects.pendingSubscriptions) });
74
+ return;
75
+ }
76
+ const position = effects.savepoints.findLastIndex((savepoint) => savepoint.name === name);
77
+ if (position < 0)
78
+ return;
79
+ if (transaction.kind === 'TRANS_STMT_ROLLBACK_TO') {
80
+ effects.pendingSubscriptions = new Set(effects.savepoints[position].subscriptions);
81
+ effects.savepoints.length = position + 1;
82
+ }
83
+ else if (transaction.kind === 'TRANS_STMT_RELEASE')
84
+ effects.savepoints.length = position;
85
+ }
86
+ function applySubscriptionEffect(node, effects) {
87
+ const transaction = node.TransactionStmt;
88
+ if (transaction?.kind === 'TRANS_STMT_BEGIN' || transaction?.kind === 'TRANS_STMT_START')
89
+ effects.pendingSubscriptions ??= new Set(effects.subscriptions);
90
+ if (transaction?.kind === 'TRANS_STMT_COMMIT' || transaction?.kind === 'TRANS_STMT_ROLLBACK') {
91
+ if (transaction.kind === 'TRANS_STMT_COMMIT' && effects.pendingSubscriptions)
92
+ effects.subscriptions = effects.pendingSubscriptions;
93
+ effects.pendingSubscriptions = transaction.chain ? new Set(effects.subscriptions) : undefined;
94
+ effects.savepoints.length = 0;
95
+ }
96
+ if (transaction)
97
+ updateSubscriptionSavepoints(transaction, effects);
98
+ const subscriptions = effects.pendingSubscriptions ?? effects.subscriptions;
99
+ const added = node.ListenStmt?.conditionname;
100
+ if (added)
101
+ subscriptions.add(added);
102
+ if (node.UnlistenStmt) {
103
+ const removed = node.UnlistenStmt.conditionname;
104
+ if (removed)
105
+ subscriptions.delete(removed);
106
+ else
107
+ subscriptions.clear();
108
+ }
109
+ }
110
+ function applyNode(node, effects) {
111
+ applySubscriptionEffect(node, effects);
112
+ if (node.DiscardStmt?.target === 'DISCARD_ALL' && !effects.pendingSubscriptions) {
113
+ effects.subscriptions.clear();
114
+ effects.advisoryLocks.clear();
115
+ }
116
+ const selection = node.SelectStmt;
117
+ const filter = selection?.whereClause;
118
+ const limit = selection?.limitCount;
119
+ const condition = filter?.A_Const;
120
+ if (condition?.isnull || (condition?.boolval && !condition.boolval.boolval))
121
+ return;
122
+ if (limit?.A_Const?.ival && !limit.A_Const.ival.ival)
123
+ return;
124
+ for (const target of selection?.targetList ?? [])
125
+ applyAdvisoryEffect(target, effects);
126
+ }
127
+ // The main scanner initializes the parser before scanning source files. Callers that skip that
128
+ // preparation cannot establish a session effect for SQL that needs parsing.
129
+ export function recordSessionEffects(text, effects) {
130
+ if (!sessionSqlCandidate.test(text) && !transactionCandidate.test(text))
131
+ return true;
132
+ try {
133
+ const statements = parseStatements(text);
134
+ if (statements.some(({ error }) => error !== undefined))
135
+ return false;
136
+ for (const { node } of statements)
137
+ if (node)
138
+ applyNode(node, effects);
139
+ return true;
140
+ }
141
+ catch {
142
+ return false;
143
+ }
144
+ }
@@ -1,5 +1,6 @@
1
1
  import { ts } from '../engine/compiler.js';
2
2
  import { findRepeatOwner, outerExpression } from '../collections/repeated.js';
3
+ import { isSessionIndependentCheckoutQuery } from './pg-integrity.js';
3
4
  import { resolveImportedBinding, staticMemberName, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
4
5
  const pgDriver = { member: 'Pool', declarations: ['pg', '@types/pg', 'pg-pool', '@types/pg-pool'] };
5
6
  const drivers = new Map([
@@ -115,12 +116,65 @@ function guardsSharedBinding(guard, destination, owner, checker) {
115
116
  declaration.pos < owner.pos ||
116
117
  declaration.end > owner.end));
117
118
  }
119
+ function isOutsideOwner(node, owner) {
120
+ return node.getSourceFile() !== owner.getSourceFile() || node.pos < owner.pos || node.end > owner.end;
121
+ }
122
+ function isPersistentTarget(target, owner, checker) {
123
+ if (ts.isIdentifier(target)) {
124
+ const declaration = checker.getSymbolAtLocation(target)?.valueDeclaration;
125
+ return Boolean(declaration && isOutsideOwner(declaration, owner));
126
+ }
127
+ let root = target;
128
+ while (ts.isPropertyAccessExpression(root) || ts.isElementAccessExpression(root)) {
129
+ root = unwrapExpression(root.expression);
130
+ }
131
+ if (root.kind === ts.SyntaxKind.ThisKeyword) {
132
+ const thisOwner = thisBindingOwner(target);
133
+ return Boolean(thisOwner && isOutsideOwner(thisOwner, owner));
134
+ }
135
+ if (ts.isIdentifier(root)) {
136
+ const declaration = aliasedDeclaration(root, checker);
137
+ return Boolean(declaration && isOutsideOwner(declaration, owner));
138
+ }
139
+ return false;
140
+ }
141
+ // An object literal only binds `this` for its methods and accessors, not for property initializers.
142
+ function thisBindingOwner(target) {
143
+ for (let child = target, current = target.parent; current; child = current, current = current.parent) {
144
+ if (ts.isClassLike(current))
145
+ return current;
146
+ if (ts.isObjectLiteralExpression(current) && ts.isFunctionLike(child) && !ts.isArrowFunction(child))
147
+ return current;
148
+ }
149
+ }
150
+ // Follows `const alias = other` chains so a loop-local alias of shared storage is still shared.
151
+ function aliasedDeclaration(identifier, checker) {
152
+ let current = identifier;
153
+ for (let depth = 0; depth < 8; depth++) {
154
+ const declaration = resolvedSymbol(current, checker)?.valueDeclaration;
155
+ if (!declaration ||
156
+ !ts.isVariableDeclaration(declaration) ||
157
+ !(declaration.parent.flags & ts.NodeFlags.Const) ||
158
+ !declaration.initializer)
159
+ return declaration;
160
+ const initializer = unwrapExpression(declaration.initializer);
161
+ if (!ts.isIdentifier(initializer))
162
+ return declaration;
163
+ current = initializer;
164
+ }
165
+ return resolvedSymbol(current, checker)?.valueDeclaration;
166
+ }
167
+ // An imported binding has no value declaration of its own; follow it to the exporting module.
168
+ function resolvedSymbol(identifier, checker) {
169
+ const symbol = checker.getSymbolAtLocation(identifier);
170
+ return symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
171
+ }
118
172
  function cachedInitialization(node, owner, checker) {
119
173
  let destination;
120
174
  for (let child = node, parent = node.parent; parent && parent !== owner; child = parent, parent = parent.parent) {
121
175
  if (ts.isBinaryExpression(parent) && parent.right === child) {
122
176
  const operator = parent.operatorToken.kind;
123
- if (cachingOperators().includes(operator))
177
+ if (cachingOperators().includes(operator) && isPersistentTarget(unwrapExpression(parent.left), owner, checker))
124
178
  return true;
125
179
  if (operator === ts.SyntaxKind.EqualsToken)
126
180
  destination = unwrapExpression(parent.left);
@@ -129,7 +183,8 @@ function cachedInitialization(node, owner, checker) {
129
183
  const guard = unwrapExpression(parent.expression);
130
184
  if (ts.isPrefixUnaryExpression(guard) &&
131
185
  guard.operator === ts.SyntaxKind.ExclamationToken &&
132
- unwrapExpression(guard.operand).getText() === destination.getText())
186
+ unwrapExpression(guard.operand).getText() === destination.getText() &&
187
+ isPersistentTarget(destination, owner, checker))
133
188
  return true;
134
189
  if (guardsSharedBinding(guard, destination, owner, checker))
135
190
  return true;
@@ -166,7 +221,11 @@ function checkLostCheckout(query, callee, context) {
166
221
  if (!context.isPackageType(connect.expression.expression, pg, ['Pool']) ||
167
222
  !context.isPackageType(client, pg, ['PoolClient']))
168
223
  return;
169
- context.report(connect, 'pg-unreleased-checkout', 'This checkout discards the client after one query(), so it can never be released and leaks a pooled connection. Call `pool.query()` for a single statement, or keep `client` and call `client.release()` in finally.');
224
+ const advice = isSessionIndependentCheckoutQuery(query)
225
+ ? 'Call `pool.query()` so the pool manages the checkout.'
226
+ : 'Keep the checked-out client for the operation and any session cleanup. Release it in finally after cleanup, or discard it if cleanup fails.';
227
+ context.report(connect, 'pg-unreleased-checkout', 'This checkout discards the client after query(), so it cannot be released and leaks a pooled connection. ' +
228
+ advice);
170
229
  }
171
230
  function checkPoolCreation(node, context) {
172
231
  const target = node.expression;
@@ -126,27 +126,103 @@ function sourceText(node) {
126
126
  const sourceFile = node.getSourceFile();
127
127
  return sourceFile.text.slice(node.getStart(sourceFile), node.end);
128
128
  }
129
- // The first `expire`-family call after `counter` in the same function on the same client and key.
130
- function followingExpire(counter, receiverText, keyText) {
131
- const enclosing = ts.findAncestor(counter.parent, ts.isFunctionLike);
132
- const scope = (enclosing && 'body' in enclosing ? enclosing.body : undefined) ?? counter.getSourceFile();
129
+ function findExpireInSubtree(node, minPos, receiverText, keyText) {
130
+ if (ts.isFunctionLike(node))
131
+ return undefined;
132
+ if (node.pos >= minPos &&
133
+ ts.isCallExpression(node) &&
134
+ ts.isPropertyAccessExpression(node.expression) &&
135
+ expireCommands.has(node.expression.name.text.toLowerCase()) &&
136
+ node.arguments[0] &&
137
+ sourceText(ts.skipOuterExpressions(node.expression.expression)) === receiverText &&
138
+ sourceText(ts.skipOuterExpressions(node.arguments[0])) === keyText) {
139
+ return node.expression;
140
+ }
141
+ if (ts.isBlock(node) || ts.isCaseClause(node) || ts.isDefaultClause(node)) {
142
+ // Statements after an unconditional exit never run, so an expiry there is not a real match.
143
+ for (const statement of node.statements) {
144
+ const match = findExpireInSubtree(statement, minPos, receiverText, keyText);
145
+ if (match)
146
+ return match;
147
+ if (unconditionalExit(statement))
148
+ return undefined;
149
+ }
150
+ return undefined;
151
+ }
133
152
  let found;
134
- (function visit(node) {
135
- if (found)
136
- return;
137
- if (node.pos >= counter.end &&
138
- ts.isCallExpression(node) &&
139
- ts.isPropertyAccessExpression(node.expression) &&
140
- expireCommands.has(node.expression.name.text.toLowerCase()) &&
141
- node.arguments[0] &&
142
- sourceText(ts.skipOuterExpressions(node.expression.expression)) === receiverText &&
143
- sourceText(ts.skipOuterExpressions(node.arguments[0])) === keyText)
144
- found = node.expression;
145
- else
146
- ts.forEachChild(node, visit);
147
- })(scope);
153
+ ts.forEachChild(node, (child) => {
154
+ if (!found)
155
+ found = findExpireInSubtree(child, minPos, receiverText, keyText);
156
+ });
148
157
  return found;
149
158
  }
159
+ function unconditionalExit(statement) {
160
+ if (ts.isReturnStatement(statement) ||
161
+ ts.isThrowStatement(statement) ||
162
+ ts.isBreakStatement(statement) ||
163
+ ts.isContinueStatement(statement)) {
164
+ return true;
165
+ }
166
+ if (ts.isBlock(statement))
167
+ return statement.statements.some(unconditionalExit);
168
+ if (ts.isIfStatement(statement)) {
169
+ return (statement.elseStatement !== undefined &&
170
+ unconditionalExit(statement.thenStatement) &&
171
+ unconditionalExit(statement.elseStatement));
172
+ }
173
+ if (ts.isLabeledStatement(statement))
174
+ return unconditionalExit(statement.statement);
175
+ return false;
176
+ }
177
+ // What follows `statements[startIndex]` in one statement list: the first `expire`-family call, and
178
+ // whether a statement always leaves the path before the list ends.
179
+ function expireAfterStatement(statements, startIndex, counterEnd, receiverText, keyText) {
180
+ if (unconditionalExit(statements[startIndex]))
181
+ return { exited: true };
182
+ for (let index = startIndex + 1; index < statements.length; index++) {
183
+ const match = findExpireInSubtree(statements[index], counterEnd, receiverText, keyText);
184
+ if (match)
185
+ return { match, exited: false };
186
+ if (unconditionalExit(statements[index]))
187
+ return { exited: true };
188
+ }
189
+ return { exited: false };
190
+ }
191
+ // The first `expire`-family call reachable after `counter` on the same execution path, on the same
192
+ // client and key.
193
+ function followingExpire(counter, receiverText, keyText) {
194
+ for (let child = counter, parent = child.parent; parent; child = parent, parent = parent.parent) {
195
+ if (ts.isFunctionLike(parent))
196
+ break;
197
+ if (ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent)) {
198
+ const statements = parent.statements;
199
+ const startIndex = statements.findIndex((statement) => statement === child || (statement.pos <= child.pos && child.end <= statement.end));
200
+ if (startIndex < 0)
201
+ continue;
202
+ const following = expireAfterStatement(statements, startIndex, counter.end, receiverText, keyText);
203
+ if (following.match)
204
+ return following.match;
205
+ if (following.exited)
206
+ return undefined;
207
+ continue;
208
+ }
209
+ if (ts.isIfStatement(parent) ||
210
+ ts.isConditionalExpression(parent) ||
211
+ ts.isSwitchStatement(parent) ||
212
+ ts.isCaseBlock(parent)) {
213
+ continue;
214
+ }
215
+ let found;
216
+ ts.forEachChild(parent, (sibling) => {
217
+ if (!found && sibling !== child && sibling.pos >= child.end) {
218
+ found = findExpireInSubtree(sibling, counter.end, receiverText, keyText);
219
+ }
220
+ });
221
+ if (found)
222
+ return found;
223
+ }
224
+ return undefined;
225
+ }
150
226
  function incrThenExpireMessage(label, counterMethod, expireMethod) {
151
227
  const counter = `${label}.${counterMethod}`;
152
228
  const expire = `${label}.${expireMethod}`;
@@ -1,4 +1,5 @@
1
1
  import { ts } from '../engine/compiler.js';
2
+ import { staticPropertyName } from '../../shared/analysis/ast-semantics.js';
2
3
  const RULE_ID = 'session-memory-store';
3
4
  const EXPRESS_SESSION = 'express-session';
4
5
  const FASTIFY_SESSION = '@fastify/session';
@@ -53,7 +54,7 @@ function resolveObjectLiteral(expression, context) {
53
54
  // A spread may carry a `store`, so only an object with no spread and no `store` key is certain to
54
55
  // use memory.
55
56
  function lacksStore(options) {
56
- return options.properties.every((property) => !ts.isSpreadAssignment(property) && property.name?.getText() !== 'store');
57
+ return options.properties.every((property) => !ts.isSpreadAssignment(property) && staticPropertyName(property.name) !== 'store');
57
58
  }
58
59
  function hasNoStore(optionsArgument, context) {
59
60
  const options = resolveObjectLiteral(optionsArgument, context);