loadwise 0.7.0 → 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 (228) hide show
  1. package/README.md +23 -15
  2. package/dist/bin/loadwise.js +12 -24
  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/jsx-elements.js +13 -3
  10. package/dist/lib/accessibility/markup-files.js +7 -2
  11. package/dist/lib/accessibility/rule-ids.js +3 -0
  12. package/dist/lib/accessibility/rules.js +128 -41
  13. package/dist/lib/accessibility/site-fixes/buttons.js +5 -1
  14. package/dist/lib/accessibility/template-attributes.js +5 -3
  15. package/dist/lib/accessibility/template-elements.js +25 -6
  16. package/dist/lib/accessibility/template-file.js +40 -25
  17. package/dist/lib/editor/accessibility-examples.js +6 -1
  18. package/dist/lib/editor/actions.js +46 -7
  19. package/dist/lib/editor/apply-fix.js +69 -4
  20. package/dist/lib/editor/configured-setup.js +5 -3
  21. package/dist/lib/editor/diagnostics.js +206 -17
  22. package/dist/lib/editor/dismissals.js +85 -26
  23. package/dist/lib/editor/editor-document.js +5 -2
  24. package/dist/lib/editor/editor-launcher.js +7 -2
  25. package/dist/lib/editor/language-server.js +64 -25
  26. package/dist/lib/editor/native-setup.js +3 -2
  27. package/dist/lib/editor/perf-watch.js +8 -6
  28. package/dist/lib/editor/reliability-examples.js +15 -0
  29. package/dist/lib/editor/scan-session.js +29 -8
  30. package/dist/lib/editor/server-commands.js +36 -9
  31. package/dist/lib/editor/setup-server.js +1 -1
  32. package/dist/lib/editor/setup-vim.js +6 -4
  33. package/dist/lib/editor/workspace-files.js +61 -7
  34. package/dist/lib/editor/workspace-paths.js +41 -1
  35. package/dist/lib/maintainability/analysis/analyze-source.js +1 -1
  36. package/dist/lib/maintainability/architecture/architecture.js +4 -4
  37. package/dist/lib/maintainability/cli/changed-lines.js +20 -2
  38. package/dist/lib/maintainability/cli/inputs.js +9 -1
  39. package/dist/lib/maintainability/cli.js +4 -0
  40. package/dist/lib/maintainability/entry-points/entry-points.js +44 -15
  41. package/dist/lib/maintainability/entry-points/html-entry-points.js +5 -1
  42. package/dist/lib/maintainability/quality/functions.js +9 -6
  43. package/dist/lib/maintainability/quality/limits.js +19 -0
  44. package/dist/lib/maintainability/quality/size-limits.js +8 -2
  45. package/dist/lib/maintainability/quality/stray-console.js +62 -1
  46. package/dist/lib/maintainability/quality/tsconfig-strict.js +2 -0
  47. package/dist/lib/maintainability/scan-changed.js +4 -1
  48. package/dist/lib/maintainability/scan-worker.js +6 -2
  49. package/dist/lib/maintainability/scan.js +21 -8
  50. package/dist/lib/maintainability/unused/module-usage.js +43 -21
  51. package/dist/lib/maintainability/unused/unused-modules.js +5 -10
  52. package/dist/lib/performance/analysis/source-inputs.js +7 -2
  53. package/dist/lib/performance/analysis/source-options.js +7 -6
  54. package/dist/lib/performance/analyze.js +16 -3
  55. package/dist/lib/performance/cli/cli-output.js +1 -0
  56. package/dist/lib/performance/cli/cli-scan.js +21 -2
  57. package/dist/lib/performance/cli.js +8 -3
  58. package/dist/lib/performance/collections/memory-growth.js +55 -12
  59. package/dist/lib/performance/contracts/openapi.js +13 -4
  60. package/dist/lib/performance/datastores/pg-integrity.js +61 -22
  61. package/dist/lib/performance/datastores/pg-session-release.js +114 -0
  62. package/dist/lib/performance/datastores/pg-session-sql.js +144 -0
  63. package/dist/lib/performance/datastores/pooling.js +56 -2
  64. package/dist/lib/performance/datastores/redis.js +94 -18
  65. package/dist/lib/performance/datastores/session-store.js +2 -1
  66. package/dist/lib/performance/db/checks.js +19 -8
  67. package/dist/lib/performance/db/gateway.js +3 -1
  68. package/dist/lib/performance/db/plan-estimates.js +4 -4
  69. package/dist/lib/performance/engine/native.js +11 -7
  70. package/dist/lib/performance/evidence/plans.js +7 -5
  71. package/dist/lib/performance/evidence/traces.js +21 -1
  72. package/dist/lib/performance/frontend/angular-teardown.js +96 -0
  73. package/dist/lib/performance/frontend/effect-cleanup.js +148 -0
  74. package/dist/lib/performance/frontend/frontend-dom-perf.js +14 -2
  75. package/dist/lib/performance/frontend/frontend-helpers.js +1 -9
  76. package/dist/lib/performance/frontend/frontend-perf.js +72 -57
  77. package/dist/lib/performance/migrations/extract-code-sql.js +16 -4
  78. package/dist/lib/performance/migrations/extract-code.js +13 -5
  79. package/dist/lib/performance/migrations/extract-sql.js +82 -38
  80. package/dist/lib/performance/migrations/operations.js +56 -13
  81. package/dist/lib/performance/migrations/postgres-lock-timeout.js +52 -0
  82. package/dist/lib/performance/migrations/postgres-registry.js +127 -26
  83. package/dist/lib/performance/migrations/postgres-settings.js +78 -0
  84. package/dist/lib/performance/migrations/rules-postgres-add-column.js +3 -3
  85. package/dist/lib/performance/migrations/rules-postgres-shared.js +9 -0
  86. package/dist/lib/performance/migrations/rules-postgres.js +88 -39
  87. package/dist/lib/performance/orm/offset-pagination.js +6 -4
  88. package/dist/lib/performance/orm/prisma-aggregates.js +69 -18
  89. package/dist/lib/performance/orm/unbounded-list-chain.js +29 -0
  90. package/dist/lib/performance/orm/unbounded-list-queries.js +18 -13
  91. package/dist/lib/performance/polyglot.js +111 -14
  92. package/dist/lib/performance/projects.js +3 -3
  93. package/dist/lib/performance/query-loops/sequential-loops.js +1 -0
  94. package/dist/lib/performance/request/backend-mastery.js +151 -42
  95. package/dist/lib/performance/request/mongoose-lean.js +175 -10
  96. package/dist/lib/performance/request/phase5-rules.js +74 -13
  97. package/dist/lib/performance/request/sql-select-star.js +150 -0
  98. package/dist/lib/performance/request/unbounded-promise-all.js +54 -29
  99. package/dist/lib/performance/request/upload-limits.js +5 -1
  100. package/dist/lib/performance/site-fix.js +4 -4
  101. package/dist/lib/performance/site-fixes/backend-mastery-fixes.js +298 -16
  102. package/dist/lib/performance/site-fixes/frontend-fixes.js +350 -10
  103. package/dist/lib/performance/site-fixes/migration-context.js +8 -1
  104. package/dist/lib/performance/site-fixes/migration-lock-rules.js +66 -30
  105. package/dist/lib/performance/site-fixes/prisma-aggregates.js +29 -9
  106. package/dist/lib/performance/site-fixes/small-rewrites.js +168 -10
  107. package/dist/lib/performance/site-fixes/sync-calls.js +14 -12
  108. package/dist/lib/performance/site-fixes/upload-limits.js +13 -7
  109. package/dist/lib/performance/sql/mysql-tokens.js +38 -12
  110. package/dist/lib/reliability/boundary-access.js +114 -57
  111. package/dist/lib/reliability/react-bugs.js +18 -4
  112. package/dist/lib/reliability/resource-leak-intervals.js +258 -0
  113. package/dist/lib/reliability/resource-leaks.js +209 -195
  114. package/dist/lib/reliability/rule-ids.js +10 -1
  115. package/dist/lib/reliability/site-fixes/resource-leaks.js +16 -1
  116. package/dist/lib/reliability/swallowed-errors.js +107 -21
  117. package/dist/lib/reliability/test-cleanup-after-await.js +92 -18
  118. package/dist/lib/reliability/walk.js +3 -2
  119. package/dist/lib/security/auth-crypto/hashing.js +24 -8
  120. package/dist/lib/security/auth-crypto/jwt.js +21 -6
  121. package/dist/lib/security/auth-crypto/secrets.js +44 -1
  122. package/dist/lib/security/auth-crypto/shared.js +3 -1
  123. package/dist/lib/security/auth-crypto/signing-algorithm.js +79 -0
  124. package/dist/lib/security/auth-crypto/transport-and-ciphers.js +85 -1
  125. package/dist/lib/security/cli.js +6 -2
  126. package/dist/lib/security/cookie-credentials.js +115 -0
  127. package/dist/lib/security/cookie-csrf.js +241 -0
  128. package/dist/lib/security/deps/advisory.js +50 -109
  129. package/dist/lib/security/deps/cli.js +1 -1
  130. package/dist/lib/security/deps/cvss-score.js +14 -0
  131. package/dist/lib/security/deps/fixed-version.js +97 -0
  132. package/dist/lib/security/deps/lockfiles.js +135 -74
  133. package/dist/lib/security/deps/osv.js +11 -3
  134. package/dist/lib/security/deps/scan.js +47 -20
  135. package/dist/lib/security/deps/yarn-lock.js +158 -0
  136. package/dist/lib/security/examples/injection.cjs +4 -0
  137. package/dist/lib/security/exposure/cookies.js +17 -2
  138. package/dist/lib/security/exposure/cors-origin-regex.js +2 -3
  139. package/dist/lib/security/exposure/frontend-security.js +21 -14
  140. package/dist/lib/security/exposure/jsx-url.js +18 -33
  141. package/dist/lib/security/exposure/logging.js +49 -10
  142. package/dist/lib/security/exposure/prototype-pollution.js +126 -56
  143. package/dist/lib/security/exposure/react-html.js +26 -0
  144. package/dist/lib/security/exposure/reflected-xss.js +34 -5
  145. package/dist/lib/security/files/compose.js +126 -1
  146. package/dist/lib/security/files/dockerfile.js +62 -4
  147. package/dist/lib/security/files/index.js +1 -1
  148. package/dist/lib/security/injection/command.js +46 -18
  149. package/dist/lib/security/injection/index.js +2 -0
  150. package/dist/lib/security/injection/ldap.js +86 -0
  151. package/dist/lib/security/injection/nosql.js +28 -4
  152. package/dist/lib/security/injection/redos.js +1 -1
  153. package/dist/lib/security/injection/rule-ids.js +1 -0
  154. package/dist/lib/security/injection/shared.js +5 -1
  155. package/dist/lib/security/injection/sql.js +28 -13
  156. package/dist/lib/security/lexical-declaration.js +113 -0
  157. package/dist/lib/security/pg-dynamic-query.js +28 -1
  158. package/dist/lib/security/pg-identifier-guards.js +107 -3
  159. package/dist/lib/security/phase5-rules.js +26 -135
  160. package/dist/lib/security/polyglot.js +2 -2
  161. package/dist/lib/security/redirect-settings.js +98 -0
  162. package/dist/lib/security/request-forgery/open-redirect.js +18 -5
  163. package/dist/lib/security/request-forgery/path-traversal.js +84 -6
  164. package/dist/lib/security/request-forgery/shared.js +1 -7
  165. package/dist/lib/security/request-forgery/ssrf.js +176 -14
  166. package/dist/lib/security/rule-descriptions.js +5 -1
  167. package/dist/lib/security/rule-ids.js +7 -0
  168. package/dist/lib/security/site-fixes/auth-crypto.js +5 -78
  169. package/dist/lib/security/site-fixes/exposure.js +21 -3
  170. package/dist/lib/security/site-fixes/files.js +11 -13
  171. package/dist/lib/security/site-fixes/frontend-security-fixes.js +2 -2
  172. package/dist/lib/security/site-fixes/injection.js +17 -4
  173. package/dist/lib/security/site-fixes/jwt.js +1 -20
  174. package/dist/lib/security/site-fixes/request-forgery.js +37 -29
  175. package/dist/lib/security/taint/binding-inputs.js +236 -0
  176. package/dist/lib/security/taint/filename-guard.js +45 -45
  177. package/dist/lib/security/taint/guards.js +14 -8
  178. package/dist/lib/security/taint/index.js +126 -154
  179. package/dist/lib/security/taint/propagate.js +43 -9
  180. package/dist/lib/security/taint/record-writes.js +161 -0
  181. package/dist/lib/security/taint/resolution-cache.js +13 -7
  182. package/dist/lib/security/taint/sanitizers.js +89 -5
  183. package/dist/lib/security/taint/trace-nodes.js +61 -0
  184. package/dist/lib/security/taint/validators.js +89 -9
  185. package/dist/lib/shared/agent/agent-init.js +2 -1
  186. package/dist/lib/shared/agent/agent-verify.js +4 -1
  187. package/dist/lib/shared/agent/git-hook.js +17 -6
  188. package/dist/lib/shared/agent/review-mcp.js +8 -2
  189. package/dist/lib/shared/analysis/ast-semantics.js +2 -2
  190. package/dist/lib/shared/analysis/scan-cache.js +96 -12
  191. package/dist/lib/shared/cli-dispatch.js +17 -0
  192. package/dist/lib/shared/config.js +27 -10
  193. package/dist/lib/shared/explain.js +1 -1
  194. package/dist/lib/shared/fix/fix-convergence.js +5 -3
  195. package/dist/lib/shared/fix/fix-imports.js +4 -171
  196. package/dist/lib/shared/fix/fix-presentation-comments.js +23 -9
  197. package/dist/lib/shared/fix/fix-presentation.js +5 -3
  198. package/dist/lib/shared/fix/fix-safety.js +7 -1
  199. package/dist/lib/shared/fix/fix-typecheck.js +8 -4
  200. package/dist/lib/shared/fix/import-text-edits.js +148 -0
  201. package/dist/lib/shared/fix.js +31 -7
  202. package/dist/lib/shared/formats/finding-location.js +4 -1
  203. package/dist/lib/shared/formats/github.js +3 -3
  204. package/dist/lib/shared/formats/sarif.js +9 -3
  205. package/dist/lib/shared/report-fp.js +6 -2
  206. package/dist/lib/shared/reporting/baseline.js +7 -5
  207. package/dist/lib/shared/reporting/pillars.js +9 -3
  208. package/dist/lib/shared/reporting/source-report.js +1 -0
  209. package/dist/lib/shared/system/glob.js +34 -8
  210. package/dist/lib/shared/system/sentry.js +26 -7
  211. package/dist/lib/shared/workspaces.js +15 -3
  212. package/package.json +5 -1
  213. package/plugin/.claude-plugin/plugin.json +1 -1
  214. package/plugin/hooks/check-edited-file.mjs +27 -5
  215. package/polyglot/performance/rules/csharp.yml +34 -5
  216. package/polyglot/performance/rules/java.yml +24 -1
  217. package/polyglot/performance/rules/python.yml +74 -2
  218. package/polyglot/performance/sgconfig.yml +1 -0
  219. package/polyglot/reliability/rules/csharp.yml +12 -6
  220. package/polyglot/reliability/rules/go.yml +86 -6
  221. package/polyglot/reliability/rules/java.yml +22 -1
  222. package/polyglot/reliability/sgconfig.yml +1 -0
  223. package/polyglot/security/rules/go.yml +100 -22
  224. package/polyglot/security/rules/python.yml +74 -6
  225. package/polyglot/security/rules/rust.yml +65 -0
  226. package/polyglot/security/sgconfig.yml +1 -0
  227. package/schema/loadwise.config.schema.json +554 -76
  228. /package/polyglot/{performance/rules → shared-rules}/input.yml +0 -0
@@ -0,0 +1,78 @@
1
+ const MILLISECONDS_PER_UNIT = {
2
+ us: 0.001,
3
+ ms: 1,
4
+ s: 1000,
5
+ min: 60000,
6
+ h: 3600000,
7
+ d: 86400000,
8
+ };
9
+ const NEXT_SMALLER_UNIT_MS = {
10
+ ms: MILLISECONDS_PER_UNIT.us,
11
+ s: MILLISECONDS_PER_UNIT.ms,
12
+ min: MILLISECONDS_PER_UNIT.s,
13
+ h: MILLISECONDS_PER_UNIT.min,
14
+ d: MILLISECONDS_PER_UNIT.h,
15
+ };
16
+ const MAX_POSTGRES_INTEGER = 2_147_483_647;
17
+ function roundToEven(value) {
18
+ const floor = Math.floor(value);
19
+ return value - floor === 0.5 && floor % 2 === 0 ? floor : Math.round(value);
20
+ }
21
+ function timeoutValue(node) {
22
+ const constant = node?.A_Const;
23
+ const value = constant?.sval?.sval ?? constant?.fval?.fval ?? (constant?.ival ? String(constant.ival.ival ?? 0) : '');
24
+ const duration = /^\s*([+-]?\d+(?:\.\d+)?)\s*(us|ms|s|min|h|d)?\s*$/.exec(value);
25
+ if (!duration)
26
+ return 'unknown';
27
+ const unit = duration[2];
28
+ const milliseconds = Number(duration[1]) * MILLISECONDS_PER_UNIT[unit ?? 'ms'];
29
+ const smallerUnit = unit && NEXT_SMALLER_UNIT_MS[unit];
30
+ const converted = smallerUnit ? roundToEven(milliseconds / smallerUnit) * smallerUnit : milliseconds;
31
+ const timeout = roundToEven(converted);
32
+ if (timeout === 0)
33
+ return 'disabled';
34
+ return timeout > 0 && timeout <= MAX_POSTGRES_INTEGER ? 'enabled' : 'unknown';
35
+ }
36
+ export function variableSettings(statement) {
37
+ const changesSearchPath = statement.name === 'search_path' || statement.name === 'role' || statement.kind === 'VAR_RESET_ALL';
38
+ if (statement.name !== 'lock_timeout' && statement.kind !== 'VAR_RESET_ALL')
39
+ return { changesSearchPath };
40
+ const argument = statement.args?.[0];
41
+ return {
42
+ changesSearchPath,
43
+ lockTimeout: {
44
+ value: statement.kind === 'VAR_SET_VALUE' ? timeoutValue(argument) : 'unknown',
45
+ scope: statement.is_local ? 'local' : 'session',
46
+ },
47
+ };
48
+ }
49
+ function directSetConfig(target) {
50
+ const expression = target.ResTarget?.val;
51
+ const call = expression?.FuncCall;
52
+ const parts = call?.funcname;
53
+ const names = parts?.map((name) => name.String?.sval).join('.');
54
+ if (names === 'set_config' || names === 'pg_catalog.set_config')
55
+ return call?.args;
56
+ }
57
+ export function selectedSettings(statement) {
58
+ const targets = statement.targetList ?? [];
59
+ const calls = targets.map(directSetConfig);
60
+ const setting = calls.find((args) => args?.[0]?.A_Const?.sval?.sval === 'lock_timeout');
61
+ const changesSearchPath = calls.some((args) => args?.[0]?.A_Const?.sval?.sval === 'search_path');
62
+ if (!setting)
63
+ return { changesSearchPath };
64
+ const local = setting[2]?.A_Const?.boolval;
65
+ const unconditional = targets.length === 1 &&
66
+ !statement.fromClause &&
67
+ !statement.whereClause &&
68
+ !statement.withClause &&
69
+ !statement.limitCount &&
70
+ !statement.limitOffset;
71
+ return {
72
+ changesSearchPath,
73
+ lockTimeout: {
74
+ value: unconditional ? timeoutValue(setting[1]) : 'unknown',
75
+ scope: local ? (local.boolval ? 'local' : 'session') : 'unknown',
76
+ },
77
+ };
78
+ }
@@ -1,6 +1,6 @@
1
1
  // PostgreSQL migration rules for ADD COLUMN: NOT NULL without a default and volatile defaults.
2
2
  import { containsPlaceholder, createFinding } from './operations.js';
3
- import { display, displaySql, holdsRows } from './rules-postgres-shared.js';
3
+ import { display, displaySql, displayTable, holdsRows } from './rules-postgres-shared.js';
4
4
  // Functions whose value is fixed for the statement, so PostgreSQL 11+ stores the default without a
5
5
  // rewrite.
6
6
  const NON_VOLATILE_FUNCTIONS = new Set([
@@ -101,7 +101,7 @@ export function notNullWithoutDefault(operation, unit) {
101
101
  const column = display(operation.columnName);
102
102
  const fix = builderFix(NULLABLE_FIX, unit.framework, operation);
103
103
  return createFinding(operation, 'migration-not-null-without-default', {
104
- message: `\`ADD COLUMN ${column} ... NOT NULL\` has no default, so it fails on \`${display(operation.table)}\` once the table has rows, and app versions still running that insert without \`${operation.columnName}\` fail too. ${fix}, backfill in batches, then enforce (see \`migration-set-not-null-scan\`). An empty table accepts it, but production tables rarely stay empty.`,
104
+ message: `\`ADD COLUMN ${column} ... NOT NULL\` has no default, so it fails on \`${displayTable(operation)}\` once the table has rows, and app versions still running that insert without \`${operation.columnName}\` fail too. ${fix}, backfill in batches, then enforce (see \`migration-set-not-null-scan\`). An empty table accepts it, but production tables rarely stay empty.`,
105
105
  suggestion: `${fix}, backfill in batches, then enforce.`,
106
106
  example: {
107
107
  before: displaySql(operation.sql),
@@ -129,7 +129,7 @@ export function volatileDefault(operation) {
129
129
  const volatile = volatileDefaultReason(operation);
130
130
  if (!volatile)
131
131
  return null;
132
- const table = display(operation.table);
132
+ const table = displayTable(operation);
133
133
  const column = display(operation.columnName);
134
134
  const setDefault = volatile.call
135
135
  ? `then \`ALTER TABLE ${table} ALTER COLUMN ${column} SET DEFAULT ${volatile.call};\` so only new rows get it, and backfill existing rows in batches`
@@ -1,5 +1,6 @@
1
1
  // Display helpers and table-existence checks shared by the PostgreSQL migration rule modules.
2
2
  import { DYNAMIC_PLACEHOLDER_PREFIX, compactSql, containsPlaceholder, quoteIdentifier } from './operations.js';
3
+ import { quoteIdent } from '../db/pg-catalog.js';
3
4
  const PLACEHOLDER_PATTERN = new RegExp(DYNAMIC_PLACEHOLDER_PREFIX + '\\d+', 'g');
4
5
  export function display(name, dialect = 'postgres') {
5
6
  if (!name)
@@ -9,6 +10,14 @@ export function display(name, dialect = 'postgres') {
9
10
  export function displaySql(text) {
10
11
  return compactSql(text).replaceAll(PLACEHOLDER_PATTERN, '${...}');
11
12
  }
13
+ export function displayTable(operation, dialect = 'postgres') {
14
+ return displayRelation(operation.table, operation.tableSchema, dialect);
15
+ }
16
+ export function displayRelation(name, schema, dialect) {
17
+ if (dialect === 'postgres' && name && schema)
18
+ return `${quoteIdent(schema)}.${quoteIdent(name)}`.replaceAll(PLACEHOLDER_PATTERN, '${...}');
19
+ return display(name, dialect);
20
+ }
12
21
  // Lock, rewrite and constraint rules apply only to tables that existed before this migration.
13
22
  export function isExistingTable(operation) {
14
23
  return (Boolean(operation.table) &&
@@ -1,9 +1,10 @@
1
1
  // PostgreSQL >= 12 migration rules. Each finding reads: observation, fix (snippets in backticks),
2
2
  // caveat.
3
3
  import { containsPlaceholder, createFinding } from './operations.js';
4
- import { createPostgresRegistry, hasValidatedNotNullCheck, resolveDroppedIndexTable, recordOperation, } from './postgres-registry.js';
4
+ import { operationsWithoutLockTimeout } from './postgres-lock-timeout.js';
5
+ import { createPostgresRegistry, hasValidatedNotNullCheck, postgresTableIdentity, resolveDroppedIndexTable, recordOperation, } from './postgres-registry.js';
5
6
  import { notNullWithoutDefault, volatileDefault } from './rules-postgres-add-column.js';
6
- import { display, displaySql, holdsRows, isExistingTable } from './rules-postgres-shared.js';
7
+ import { display, displaySql, displayTable, holdsRows, isExistingTable } from './rules-postgres-shared.js';
7
8
  const LOCK_TIMEOUT_STATEMENT = "SET lock_timeout = '5s';";
8
9
  const NON_TRANSACTIONAL_HOW = {
9
10
  prisma: 'in a migration file containing only this statement, because Prisma runs a multi-statement file in one transaction',
@@ -50,7 +51,12 @@ function concurrentIndexSql(operation) {
50
51
  }
51
52
  // DROP INDEX names no table; it is only known when an earlier scanned migration created the index.
52
53
  function isDropOfUnknownIndex(operation) {
53
- return operation.kind === 'drop-index' && !operation.table && !operation.concurrent && Boolean(operation.index);
54
+ return (operation.kind === 'drop-index' &&
55
+ !operation.table &&
56
+ !operation.concurrent &&
57
+ Boolean(operation.index) &&
58
+ !operation.createdInSameUnit &&
59
+ !operation.emptiedInSameUnit);
54
60
  }
55
61
  function indexNotConcurrent(operation, unit) {
56
62
  if (operation.kind === 'drop-index')
@@ -59,7 +65,7 @@ function indexNotConcurrent(operation, unit) {
59
65
  return null;
60
66
  if (!holdsRows(operation))
61
67
  return null;
62
- const table = display(operation.table);
68
+ const table = displayTable(operation);
63
69
  const label = '`' + (operation.builder ? displaySql(operation.sql) : displaySql(operation.sql).split(/\s+ON\s+/i)[0]) + '`';
64
70
  const fixedSql = concurrentIndexSql(operation);
65
71
  const fix = operation.builder
@@ -79,22 +85,36 @@ function dropIndexNotConcurrent(operation, unit) {
79
85
  return null;
80
86
  if (!isDropOfUnknownIndex(operation) && !holdsRows(operation))
81
87
  return null;
82
- const subject = operation.table ? `existing table \`${display(operation.table)}\`` : 'its table';
83
- const fixedSql = operation.builder ? null : concurrentDropSql(operation);
84
- const fix = operation.builder
85
- ? builderConcurrentDropFix(unit.framework, operation)
86
- : 'Use `' + displaySql(fixedSql) + '`';
88
+ const multiple = (operation.dropIndexes?.length ?? 0) > 1;
89
+ const subject = operation.table
90
+ ? `existing table \`${displayTable(operation)}\``
91
+ : multiple
92
+ ? 'the affected tables'
93
+ : 'its table';
94
+ const original = operation.sql?.trim().replace(/;$/, '') ?? '';
95
+ const fixedSql = concurrentDropSql(operation, original);
87
96
  const where = operation.inTransaction
88
97
  ? NON_TRANSACTIONAL_HOW[frameworkKey(unit.framework)]
89
98
  : 'in this migration, which already runs outside a transaction';
99
+ const fix = dropIndexAdvice(operation, unit.framework, fixedSql, where);
90
100
  return createFinding(operation, 'migration-index-not-concurrent', {
91
- message: `\`${displaySql(operation.sql)}\` takes an ACCESS EXCLUSIVE lock on ${subject}, blocking reads and writes while it waits for running queries and while it drops. ${fix} ${where}. \`DROP INDEX CONCURRENTLY\` drops one index per statement and does not support \`CASCADE\`.`,
92
- suggestion: `${fix} ${where}.`,
93
- example: { before: displaySql(operation.sql), after: fixedSql ? displaySql(fixedSql) : fix },
101
+ message: `\`${original}\` takes an ACCESS EXCLUSIVE lock on ${subject}, blocking reads and writes while it waits for running queries and while it drops. ${fix}. \`DROP INDEX CONCURRENTLY\` drops one index per statement and does not support \`CASCADE\`.`,
102
+ suggestion: `${fix}.`,
103
+ example: { before: original, after: fixedSql ?? fix },
94
104
  });
95
105
  }
96
- function concurrentDropSql(operation) {
97
- return operation.sql === null ? null : operation.sql.replace(/^(\s*DROP\s+INDEX)\s+/i, '$1 CONCURRENTLY ');
106
+ function concurrentDropSql(operation, sql) {
107
+ if (operation.builder || operation.dropCascade || operation.dropIndexes?.length !== 1)
108
+ return null;
109
+ const fixed = sql.replace(/^(DROP\s+INDEX)\s+/i, '$1 CONCURRENTLY ');
110
+ return fixed === sql ? null : fixed;
111
+ }
112
+ function dropIndexAdvice(operation, framework, fixedSql, where) {
113
+ if (operation.builder)
114
+ return builderConcurrentDropFix(framework, operation) + ' ' + where;
115
+ if (fixedSql)
116
+ return 'Use `' + fixedSql + '` ' + where;
117
+ return 'Review the affected indexes and plan the drop in a maintenance window';
98
118
  }
99
119
  function builderConcurrentDropFix(framework, operation) {
100
120
  if (framework === 'sequelize')
@@ -102,7 +122,7 @@ function builderConcurrentDropFix(framework, operation) {
102
122
  return 'Use a raw `DROP INDEX CONCURRENTLY ...` query';
103
123
  }
104
124
  function builderConcurrentFix(framework, operation) {
105
- const table = display(operation.table);
125
+ const table = displayTable(operation);
106
126
  if (framework === 'sequelize')
107
127
  return "Pass `{ concurrently: true }` to `queryInterface.addIndex('" + operation.table + "', ...)`";
108
128
  if (framework === 'knex')
@@ -156,29 +176,27 @@ function tableRewriteCommand(operation) {
156
176
  }
157
177
  function lockTimeoutFix(framework) {
158
178
  if (framework === 'typeorm')
159
- return `Start \`up()\` with \`await queryRunner.query("${LOCK_TIMEOUT_STATEMENT}")\``;
179
+ return `Before the affected DDL, run \`await queryRunner.query("${LOCK_TIMEOUT_STATEMENT}")\``;
160
180
  if (framework === 'knex')
161
- return `Start \`up()\` with \`await knex.raw("${LOCK_TIMEOUT_STATEMENT}")\``;
181
+ return `Before the affected DDL, run \`await knex.raw("${LOCK_TIMEOUT_STATEMENT}")\``;
162
182
  if (framework === 'mikro-orm')
163
- return `Start \`up()\` with \`this.addSql("${LOCK_TIMEOUT_STATEMENT}")\``;
183
+ return `Before the affected DDL, run \`this.addSql("${LOCK_TIMEOUT_STATEMENT}")\``;
164
184
  if (framework === 'sequelize')
165
- return `Start \`up()\` with \`await queryInterface.sequelize.query("${LOCK_TIMEOUT_STATEMENT}")\``;
166
- return `Start the migration with \`${LOCK_TIMEOUT_STATEMENT}\``;
185
+ return `Before the affected DDL, run \`await queryInterface.sequelize.query("${LOCK_TIMEOUT_STATEMENT}")\``;
186
+ return `Before the affected DDL, run \`${LOCK_TIMEOUT_STATEMENT}\``;
167
187
  }
168
188
  // Once per file: the first statement that queues for a lock on an existing table with no
169
189
  // lock_timeout set before it.
170
190
  function missingLockTimeout(operations, unit) {
171
- for (const operation of operations) {
172
- if (operation.kind === 'set-lock-timeout')
173
- return null;
191
+ for (const operation of operationsWithoutLockTimeout(operations)) {
174
192
  if (!LOCK_TAKING_KINDS.has(operation.kind) || operation.concurrent)
175
193
  continue;
176
194
  if (!holdsRows(operation) && !isDropOfUnknownIndex(operation))
177
195
  continue;
178
196
  const fix = lockTimeoutFix(unit.framework);
179
- const lockTarget = operation.table ? `\`${display(operation.table)}\`` : 'its table';
197
+ const lockTarget = operation.table ? `\`${displayTable(operation)}\`` : 'its table';
180
198
  return createFinding(operation, 'migration-missing-lock-timeout', {
181
- message: `\`${displaySql(operation.sql)}\` waits for a lock on ${lockTarget} with no \`lock_timeout\`, and every later query on that table queues behind the wait. ${fix} so a blocked DDL fails fast instead of queueing every query behind it, then retry. Skip this if the migration runner already sets \`lock_timeout\` on its connection.`,
199
+ message: `\`${displaySql(operation.sql)}\` waits for a lock on ${lockTarget} without a known positive \`lock_timeout\`, and every later query on that table queues behind the wait. ${fix} so a blocked DDL fails fast instead of queueing every query behind it, then retry. Verify the effective timeout on the connection that runs the DDL.`,
182
200
  suggestion: fix + '.',
183
201
  example: { before: displaySql(operation.sql), after: `${LOCK_TIMEOUT_STATEMENT} ${displaySql(operation.sql)}` },
184
202
  });
@@ -237,12 +255,12 @@ function columnTypeRewrite(operation, unit, registry) {
237
255
  return null;
238
256
  if (containsPlaceholder(operation.columnName) || containsPlaceholder(JSON.stringify(operation.type ?? null)))
239
257
  return null;
240
- const previous = (operation.table === null ? undefined : registry.columnTypes.get(operation.table))?.get(operation.columnName) ??
241
- null;
258
+ const tableIdentity = postgresTableIdentity(operation);
259
+ const previous = (tableIdentity === null ? undefined : registry.columnTypes.get(tableIdentity))?.get(operation.columnName) ?? null;
242
260
  const next = operation.type;
243
261
  if (previous && next && !operation.hasUsing && isSafeTypeChange(previous, next))
244
262
  return null;
245
- const table = display(operation.table);
263
+ const table = displayTable(operation);
246
264
  const column = display(operation.columnName);
247
265
  const change = previous && next ? ` from \`${typeText(previous)}\` to \`${typeText(next)}\`` : '';
248
266
  const label = operation.builder
@@ -268,9 +286,9 @@ function setNotNullScan(operation, unit, registry) {
268
286
  return null;
269
287
  if (containsPlaceholder(operation.columnName))
270
288
  return null;
271
- if (hasValidatedNotNullCheck(registry, operation.table, operation.columnName))
289
+ if (hasValidatedNotNullCheck(registry, operation))
272
290
  return null;
273
- const table = display(operation.table);
291
+ const table = displayTable(operation);
274
292
  const column = display(operation.columnName);
275
293
  const constraint = display(`${operation.table}_${operation.columnName}_not_null`);
276
294
  const steps = `\`ALTER TABLE ${table} ADD CONSTRAINT ${constraint} CHECK (${column} IS NOT NULL) NOT VALID;\`, then in a later migration \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${constraint};\` and \`SET NOT NULL\``;
@@ -294,17 +312,23 @@ function constraintLabel(operation) {
294
312
  return ('`ADD CONSTRAINT' + (operation.constraintName ? ' ' + display(operation.constraintName) : '') + ' ' + kind + '`');
295
313
  }
296
314
  function addedWithoutNotValid(operation) {
297
- const table = display(operation.table);
315
+ const table = displayTable(operation);
298
316
  const name = display(operation.constraintName ?? `${operation.table}_constraint`);
299
- const fix = operation.builder
300
- ? `Add it with a raw query ending in \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`
301
- : `Add \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`;
317
+ const inline = operation.kind === 'add-column';
318
+ const locks = inline && operation.constraintType === 'foreign'
319
+ ? 'an ACCESS EXCLUSIVE lock on it (from `ADD COLUMN`) and a SHARE ROW EXCLUSIVE lock on the referenced table'
320
+ : CONSTRAINT_LOCKS[operation.constraintType ?? ''];
321
+ const fix = inline
322
+ ? `Drop the inline constraint from \`ADD COLUMN\`, add it with \`ALTER TABLE ${table} ADD CONSTRAINT ${name} ... NOT VALID;\` (a column definition cannot carry \`NOT VALID\`), then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`
323
+ : operation.builder
324
+ ? `Add it with a raw query ending in \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`
325
+ : `Add \`NOT VALID\`, then run \`ALTER TABLE ${table} VALIDATE CONSTRAINT ${name};\` in a later migration`;
302
326
  return createFinding(operation, 'migration-constraint-not-valid', {
303
- message: `${constraintLabel(operation)} on existing table \`${table}\` checks every row while holding ${CONSTRAINT_LOCKS[operation.constraintType ?? '']}. ${fix}; validation takes a lock that allows reads and writes. New and updated rows are checked as soon as the \`NOT VALID\` constraint exists.`,
327
+ message: `${constraintLabel(operation)} on existing table \`${table}\` checks every row while holding ${locks}. ${fix}; validation takes a lock that allows reads and writes. New and updated rows are checked as soon as the \`NOT VALID\` constraint exists.`,
304
328
  suggestion: fix + '.',
305
329
  example: {
306
330
  before: displaySql(operation.sql),
307
- after: operation.builder
331
+ after: operation.builder || inline
308
332
  ? `ALTER TABLE ${table} ADD CONSTRAINT ${name} ... NOT VALID; -- later: VALIDATE CONSTRAINT ${name}`
309
333
  : `${displaySql(operation.sql)} NOT VALID; -- later: ALTER TABLE ${table} VALIDATE CONSTRAINT ${name}`,
310
334
  },
@@ -332,9 +356,34 @@ function validatedInSameTransaction(operation, unit) {
332
356
  },
333
357
  });
334
358
  }
359
+ function hasNonNullDefaultOrComputed(operation) {
360
+ if (operation.identity || operation.generatedStored)
361
+ return true;
362
+ if (!operation.hasDefault)
363
+ return false;
364
+ const raw = operation.defaultExpression;
365
+ const aConst = raw && typeof raw === 'object' && 'A_Const' in raw ? raw.A_Const : undefined;
366
+ return !(aConst && typeof aConst === 'object' && 'isnull' in aConst && aConst.isnull === true);
367
+ }
335
368
  function constraintNotValid(operation, unit) {
336
369
  if (operation.kind === 'validate-constraint')
337
370
  return validatedInSameTransaction(operation, unit);
371
+ if (operation.kind === 'add-column' && holdsRows(operation) && operation.inlineConstraints?.length) {
372
+ for (const inline of operation.inlineConstraints) {
373
+ if (inline.notValid)
374
+ continue;
375
+ if (inline.constraintType === 'foreign' && !hasNonNullDefaultOrComputed(operation))
376
+ continue;
377
+ if (CONSTRAINT_LOCKS[inline.constraintType]) {
378
+ return addedWithoutNotValid({
379
+ ...operation,
380
+ constraintType: inline.constraintType,
381
+ constraintName: inline.constraintName,
382
+ });
383
+ }
384
+ }
385
+ return null;
386
+ }
338
387
  if (operation.kind !== 'add-constraint' || operation.notValid || !holdsRows(operation))
339
388
  return null;
340
389
  if (!CONSTRAINT_LOCKS[operation.constraintType ?? ''])
@@ -346,7 +395,7 @@ function constraintWithoutIndex(operation) {
346
395
  return null;
347
396
  if (!operation.constraintType || !['unique', 'primary'].includes(operation.constraintType))
348
397
  return null;
349
- const table = display(operation.table);
398
+ const table = displayTable(operation);
350
399
  const kind = operation.constraintType === 'primary' ? 'PRIMARY KEY' : 'UNIQUE';
351
400
  const index = display(operation.constraintName ?? `${operation.table}_${operation.constraintType === 'primary' ? 'pkey' : 'key'}`);
352
401
  const unique = `\`CREATE UNIQUE INDEX CONCURRENTLY ${index} ON ${table} (...);\``;
@@ -364,7 +413,7 @@ function constraintWithoutIndex(operation) {
364
413
  });
365
414
  }
366
415
  function dropTarget(operation, dialect) {
367
- const table = display(operation.table, dialect);
416
+ const table = displayTable(operation, dialect);
368
417
  if (operation.kind === 'drop-table')
369
418
  return { label: `DROP TABLE ${table}`, subject: `\`${table}\`` };
370
419
  const column = display(operation.columnName, dialect);
@@ -392,7 +441,7 @@ function breakingRename(operation, unit) {
392
441
  if (operation.nameRecreatedInSameUnit)
393
442
  return null;
394
443
  const dialect = unit.dialect;
395
- const table = display(operation.table, dialect);
444
+ const table = displayTable(operation, dialect);
396
445
  const isColumn = operation.kind === 'rename-column';
397
446
  const from = isColumn ? display(operation.columnName, dialect) : table;
398
447
  const to = display(operation.newName, dialect);
@@ -83,8 +83,8 @@ const SKIPPED_ROWS = 'the database reads and discards every skipped row, so deep
83
83
  function inputMessage(label) {
84
84
  return `${label} comes from request input with no upper bound, so ${SKIPPED_ROWS}`;
85
85
  }
86
- function literalMessage(label, offset) {
87
- return `${label} is ${offset}, above ${MAX_LITERAL_OFFSET}, so ${SKIPPED_ROWS}`;
86
+ function literalMessage(label, offset, maxOffset) {
87
+ return `${label} is ${offset}, above ${maxOffset}, so ${SKIPPED_ROWS}`;
88
88
  }
89
89
  function offsetLabel(access) {
90
90
  return `The offset of ${access.name.text}()`;
@@ -156,8 +156,10 @@ function check(call, context) {
156
156
  return handler && checkOneHop(call, handler, context);
157
157
  const offset = literalOffset(value);
158
158
  if (offset !== undefined) {
159
- if (offset > MAX_LITERAL_OFFSET)
160
- context.report(access.name, RULE_ID, literalMessage(offsetLabel(access), offset));
159
+ const configuredMax = context.ruleOptions?.(RULE_ID)?.maxOffset;
160
+ const maxOffset = typeof configuredMax === 'number' ? configuredMax : MAX_LITERAL_OFFSET;
161
+ if (offset > maxOffset)
162
+ context.report(access.name, RULE_ID, literalMessage(offsetLabel(access), offset, maxOffset));
161
163
  return;
162
164
  }
163
165
  if (handler)
@@ -6,7 +6,6 @@ import { prismaModelName } from './prisma.js';
6
6
  import { findProjectRoot } from '../schema/context.js';
7
7
  const SCHEMA_LOCATIONS = [path.join('prisma', 'schema.prisma'), 'schema.prisma'];
8
8
  const NATIVE_DISTINCT_FEATURE = /previewFeatures\s*=\s*\[[^\]]*["']nativeDistinct["']/;
9
- const schemaEnablesNativeDistinct = new Map();
10
9
  function propertyKey(property) {
11
10
  if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
12
11
  return;
@@ -30,10 +29,64 @@ function distinctFields(property) {
30
29
  return;
31
30
  return literals.map((element) => element.text);
32
31
  }
33
- function readNativeDistinctFlag(projectRoot) {
32
+ // Comments are dropped and string literals emptied so attributes inside them never count as keys.
33
+ const COMMENT_OR_STRING = /"(?:\\.|[^"\\\n])*"|\/\/[^\n]*/g;
34
+ function parsePrismaSchema(rawContent) {
35
+ const nativeDistinct = NATIVE_DISTINCT_FEATURE.test(rawContent);
36
+ const content = rawContent.replaceAll(COMMENT_OR_STRING, (token) => (token.startsWith('"') ? '""' : ''));
37
+ const primaryKeys = new Map();
38
+ const modelPattern = /\bmodel\s+([A-Za-z_]\w*)\s*\{([^}]*)\}/g;
39
+ for (const match of content.matchAll(modelPattern)) {
40
+ const [, modelName, body] = match;
41
+ const keys = compoundPrimaryKey(body) ?? singlePrimaryKey(body);
42
+ if (keys)
43
+ primaryKeys.set(modelName, keys);
44
+ }
45
+ return { nativeDistinct, primaryKeys };
46
+ }
47
+ // Commas inside `field(length: 10, sort: Desc)` arguments do not separate fields.
48
+ function splitTopLevel(list) {
49
+ const parts = [];
50
+ let depth = 0;
51
+ let start = 0;
52
+ for (let index = 0; index < list.length; index++) {
53
+ if (list[index] === '(')
54
+ depth++;
55
+ else if (list[index] === ')')
56
+ depth--;
57
+ else if (list[index] === ',' && depth === 0) {
58
+ parts.push(list.slice(start, index));
59
+ start = index + 1;
60
+ }
61
+ }
62
+ parts.push(list.slice(start));
63
+ return parts;
64
+ }
65
+ function compoundPrimaryKey(modelBody) {
66
+ const compoundMatch = /@@id\(\s*\[([^\]]+)\]/.exec(modelBody);
67
+ if (!compoundMatch)
68
+ return;
69
+ const keys = splitTopLevel(compoundMatch[1])
70
+ .map((part) => part.trim().replace(/\(.*/, ''))
71
+ .filter(Boolean);
72
+ return keys.length ? keys : undefined;
73
+ }
74
+ function singlePrimaryKey(modelBody) {
75
+ for (const line of modelBody.split(/\r?\n/)) {
76
+ const trimmed = line.trim();
77
+ if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('@@'))
78
+ continue;
79
+ if (!/@id(?:\s*\(|\s|$)/.test(trimmed))
80
+ continue;
81
+ const fieldMatch = /^([A-Za-z_]\w*)\b/.exec(trimmed);
82
+ if (fieldMatch)
83
+ return [fieldMatch[1]];
84
+ }
85
+ }
86
+ function readSchemaInfo(projectRoot) {
34
87
  for (const location of SCHEMA_LOCATIONS) {
35
88
  try {
36
- return NATIVE_DISTINCT_FEATURE.test(fs.readFileSync(path.join(projectRoot, location), 'utf8'));
89
+ return parsePrismaSchema(fs.readFileSync(path.join(projectRoot, location), 'utf8'));
37
90
  }
38
91
  catch (error) {
39
92
  // Try the next conventional location; only a schema that exists but cannot be read is worth
@@ -46,30 +99,28 @@ function readNativeDistinctFlag(projectRoot) {
46
99
  });
47
100
  }
48
101
  }
49
- return false;
102
+ return { nativeDistinct: false, primaryKeys: new Map() };
50
103
  }
51
- // The nearest project's schema decides, as `prisma generate` would.
52
- function nativeDistinctEnabled(sourceFile) {
53
- const projectRoot = findProjectRoot(path.dirname(sourceFile.fileName));
54
- let enabled = schemaEnablesNativeDistinct.get(projectRoot);
55
- if (enabled === undefined) {
56
- enabled = readNativeDistinctFlag(projectRoot);
57
- schemaEnablesNativeDistinct.set(projectRoot, enabled);
58
- }
59
- return enabled;
104
+ // The nearest project's schema decides, as `prisma generate` would. Read on each use (only calls
105
+ // with `distinct`) so a schema edit in a long-lived watch session is never served stale.
106
+ function prismaSchemaInfo(sourceFile) {
107
+ return readSchemaInfo(findProjectRoot(path.dirname(sourceFile.fileName)));
60
108
  }
61
109
  function checkDistinct(call, access, options, context) {
62
110
  const distinctProperty = optionProperty(options, 'distinct');
63
111
  const fields = distinctProperty && distinctFields(distinctProperty);
64
- // Rows already differ on the conventional primary key, so there are no duplicates to read and
65
- // drop.
66
- if (!fields || fields.includes('id'))
67
- return;
68
- if (nativeDistinctEnabled(call.getSourceFile()))
112
+ if (!fields)
69
113
  return;
70
114
  const model = prismaModelName(access.name, context.checker);
71
115
  if (!model)
72
116
  return;
117
+ const schemaInfo = prismaSchemaInfo(call.getSourceFile());
118
+ if (schemaInfo.nativeDistinct)
119
+ return;
120
+ const primaryKey = schemaInfo.primaryKeys.get(model);
121
+ // Rows already differ on the resolved primary key (or conventional `id` when schema is absent).
122
+ if (primaryKey?.length ? primaryKey.every((key) => fields.includes(key)) : fields.includes('id'))
123
+ return;
73
124
  const list = fields.join(', ');
74
125
  context.report(access.name, 'prisma-distinct-in-memory', `${model}.findMany({ distinct: [${list}] }) reads every matching row and removes duplicates inside Prisma's query engine, not with SQL DISTINCT, so the database still returns all duplicates. Use \`groupBy({ by: [${list}], where })\` when only those fields are selected, or a raw \`SELECT DISTINCT\`/\`DISTINCT ON\` query otherwise. Ignore this if the schema enables the nativeDistinct preview feature.`);
75
126
  }
@@ -0,0 +1,29 @@
1
+ import { ts } from '../engine/compiler.js';
2
+ import { propertyName } from '../schema/ts-helpers.js';
3
+ // Query steps that keep a Mongoose find() a list of documents; `limit` among them bounds it.
4
+ export const MONGOOSE_CHAIN_STEPS = new Set([
5
+ 'sort',
6
+ 'select',
7
+ 'lean',
8
+ 'populate',
9
+ 'skip',
10
+ 'limit',
11
+ 'exec',
12
+ 'where',
13
+ 'session',
14
+ 'collation',
15
+ 'hint',
16
+ 'maxTimeMS',
17
+ 'read',
18
+ 'batchSize',
19
+ 'setOptions',
20
+ ]);
21
+ const ID_LIST_OPERATORS = new Set(['in', '$in']);
22
+ export function isIdListOperator(property) {
23
+ if (!ts.isPropertyAssignment(property))
24
+ return false;
25
+ const name = propertyName(property);
26
+ if (name)
27
+ return ID_LIST_OPERATORS.has(name);
28
+ return ts.isComputedPropertyName(property.name) && property.name.expression.getText().endsWith('.in');
29
+ }
@@ -3,6 +3,7 @@
3
3
  import { ts } from '../engine/compiler.js';
4
4
  import { unwrapExpression as unwrap } from '../../shared/analysis/ast-semantics.js';
5
5
  import { prismaModelName } from './prisma.js';
6
+ import { MONGOOSE_CHAIN_STEPS, isIdListOperator } from './unbounded-list-chain.js';
6
7
  import { querySite } from '../schema/query-sites.js';
7
8
  import { declaredInPackage, propertyName, objectProperty } from '../schema/ts-helpers.js';
8
9
  import { drizzleColumn } from '../schema/drizzle-schema.js';
@@ -14,8 +15,6 @@ const PG_RECEIVERS = ['Pool', 'Client', 'ClientBase', 'PoolClient'];
14
15
  const TYPEORM_LIST_METHODS = new Set(['find', 'findBy']);
15
16
  const SEQUELIZE_PACKAGES = ['sequelize', 'sequelize-typescript'];
16
17
  const SEQUELIZE_LIST_METHODS = new Set(['findAll', 'findAndCountAll']);
17
- // Query steps that keep a Mongoose find() a list of documents; `limit` among them bounds it.
18
- const MONGOOSE_CHAIN_STEPS = new Set(['sort', 'select', 'lean', 'populate', 'skip', 'limit', 'exec']);
19
18
  const BUILDER_LIMITS = new Set(['take', 'limit']);
20
19
  const DRIZZLE_SELECTS = new Set(['select', 'selectDistinct']);
21
20
  const DRIZZLE_CHAIN_STEPS = new Set([
@@ -41,7 +40,6 @@ const SQL_PINNED_ROW = /\bwhere\s+(?:\w+\.)?id\s*=\s*(?:\$\d+|\?)/i;
41
40
  const SERVICE_QUERY_REASON = 'The query is in a service method a handler returns, so how large the table is and whether paging is applied upstream could not be checked.';
42
41
  const PAGING_PARAMETER = /pagin|page|take|limit|first|cursor|offset|skip|size/i;
43
42
  const SQL_ID_ANY = /\b(?:\w+\.)?_?id\s*=\s*any\s*\(\s*\$(\d+)\s*\)/i;
44
- const ID_LIST_OPERATORS = new Set(['in', '$in']);
45
43
  const ID_LIST_REASON = 'The id list comes from request input and no size cap on it was found; a cap applied by the caller or a validation layer could not be ruled out.';
46
44
  const BUILDER_PINNED_ROW = /(?:^|\.)id\s*=\s*:/i;
47
45
  function isUniqueColumn(table, name) {
@@ -69,14 +67,6 @@ function isBoundedValue(value) {
69
67
  }
70
68
  return true;
71
69
  }
72
- function isIdListOperator(property) {
73
- if (!ts.isPropertyAssignment(property))
74
- return false;
75
- const name = propertyName(property);
76
- if (name)
77
- return ID_LIST_OPERATORS.has(name);
78
- return ts.isComputedPropertyName(property.name) && property.name.expression.getText().endsWith('.in');
79
- }
80
70
  // `id: { in: ids }`, `_id: { $in: ids }`, `id: { [Op.in]: ids }` and `id: In(ids)`: the list a
81
71
  // unique column is matched against. Such a query returns at most as many rows as the list holds.
82
72
  function idListOf(filter, table) {
@@ -180,15 +170,30 @@ const mongooseList = (call, access, context) => {
180
170
  if (!lacksLimit(options, 'limit') || pinsDocumentId(filter))
181
171
  return;
182
172
  let top = call;
173
+ let chainedIdList;
183
174
  while (ts.isPropertyAccessExpression(top.parent) &&
184
175
  top.parent.expression === top &&
185
176
  ts.isCallExpression(top.parent.parent) &&
186
177
  MONGOOSE_CHAIN_STEPS.has(top.parent.name.text)) {
187
- if (top.parent.name.text === 'limit')
178
+ const step = top.parent.name.text;
179
+ const [stepArgument] = top.parent.parent.arguments;
180
+ if (step === 'limit')
181
+ return;
182
+ // Bounds supplied through chained modifiers: `.where({ _id })` and `.setOptions({ limit })`.
183
+ if (step === 'where' && pinsDocumentId(stepArgument))
184
+ return;
185
+ if (step === 'where') {
186
+ const stepIdList = idListOf(stepArgument, undefined);
187
+ // A repeated id-list predicate replaces the earlier one in Mongoose; the effective list is unclear, so stay silent.
188
+ if (stepIdList && (chainedIdList || idListOf(filter, undefined)))
189
+ return;
190
+ chainedIdList ??= stepIdList;
191
+ }
192
+ if (step === 'setOptions' && !lacksLimit(stepArgument, 'limit'))
188
193
  return;
189
194
  top = top.parent.parent;
190
195
  }
191
- return { label: 'find()', top, reportNode: access.name, idList: idListOf(filter, undefined) };
196
+ return { label: 'find()', top, reportNode: access.name, idList: idListOf(filter, undefined) ?? chainedIdList };
192
197
  };
193
198
  function chainSteps(expression) {
194
199
  const methods = new Set();