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
@@ -5,22 +5,31 @@ import { findProjectRoot } from '../schema/context.js';
5
5
  import { distinctFields, optionProperty, propertyKey, propertyValue } from '../orm/prisma-aggregates.js';
6
6
  const FIXABLE_OPTIONS = new Set(['where', 'select', 'distinct', 'orderBy', 'take', 'skip']);
7
7
  const PAGING_OPTIONS = ['take', 'skip'];
8
+ // Prisma materializes object-valued scalars separately for each query, so Map cannot join them by identity.
9
+ const primitiveRelationKeys = new Set(['String', 'Int', 'BigInt', 'Float', 'Boolean']);
8
10
  const SORT_DIRECTIONS = new Set(['asc', 'desc']);
9
11
  const SCHEMA_FILES = [path.join('prisma', 'schema.prisma'), 'schema.prisma'];
10
12
  const SCHEMA_FOLDER = path.join('prisma', 'schema');
11
- // `select: { a: true }` whose keys all belong to the distinct fields.
12
13
  // True when the property's key is one of `keys`.
13
14
  function keyIn(property, keys) {
14
15
  const key = propertyKey(property);
15
16
  return key !== undefined && keys.includes(key);
16
17
  }
17
- function selectsOnly(selectProperty, fields) {
18
+ // groupBy returns every field named in by; it cannot preserve a projection that omitted one.
19
+ function selectsExactly(selectProperty, fields) {
18
20
  const value = propertyValue(selectProperty);
19
- if (!value || !ts.isObjectLiteralExpression(value) || !value.properties.length)
21
+ if (!value || !ts.isObjectLiteralExpression(value))
20
22
  return false;
21
- return value.properties.every((property) => ts.isPropertyAssignment(property) &&
22
- keyIn(property, fields) &&
23
- property.initializer.kind === ts.SyntaxKind.TrueKeyword);
23
+ const missing = new Set(fields);
24
+ for (const property of value.properties) {
25
+ const name = propertyKey(property);
26
+ if (!ts.isPropertyAssignment(property) ||
27
+ property.initializer.kind !== ts.SyntaxKind.TrueKeyword ||
28
+ name === undefined ||
29
+ !missing.delete(name))
30
+ return false;
31
+ }
32
+ return missing.size === 0;
24
33
  }
25
34
  // groupBy only orders by its `by` fields (or aggregates), so a sort on anything else cannot move
26
35
  // over.
@@ -74,7 +83,7 @@ function distinctFix({ node }) {
74
83
  const selectProperty = optionProperty(options, 'select');
75
84
  const fields = distinctProperty && distinctFields(distinctProperty);
76
85
  const distinctValue = distinctProperty && propertyValue(distinctProperty);
77
- if (!fields || !distinctValue || !selectProperty || !selectsOnly(selectProperty, fields))
86
+ if (!fields || !distinctValue || !selectProperty || !selectsExactly(selectProperty, fields))
78
87
  return;
79
88
  const orderByProperty = optionProperty(options, 'orderBy');
80
89
  if (orderByProperty && !ordersOnly(orderByProperty, fields))
@@ -165,14 +174,25 @@ function parseModels(text) {
165
174
  // The child model and its single-column foreign key for a one-to-many relation field of
166
175
  // `modelName`.
167
176
  function foreignKeyOf(models, modelName, relationName) {
168
- const listField = models.get(modelName)?.find((field) => field.name === relationName);
177
+ const parentFields = models.get(modelName);
178
+ const listField = parentFields?.find((field) => field.name === relationName);
169
179
  if (!listField?.list)
170
180
  return;
171
- const backFields = (models.get(listField.type) ?? []).filter((field) => field.type === modelName && !field.list && field.relation?.fields?.length === 1);
181
+ const childFields = models.get(listField.type) ?? [];
182
+ const backFields = childFields.filter((field) => field.type === modelName && !field.list && field.relation?.fields?.length === 1);
172
183
  const matching = backFields.filter((field) => field.relation?.name === listField.relation?.name);
173
184
  const relation = matching[0]?.relation;
174
185
  if (matching.length !== 1 || !relation?.fields || relation.references?.length !== 1)
175
186
  return;
187
+ const reference = parentFields?.find((field) => field.name === relation.references?.[0]);
188
+ const foreignKey = childFields.find((field) => field.name === relation.fields?.[0]);
189
+ if (!reference ||
190
+ !foreignKey ||
191
+ reference.list ||
192
+ foreignKey.list ||
193
+ reference.type !== foreignKey.type ||
194
+ !primitiveRelationKeys.has(reference.type))
195
+ return;
176
196
  return {
177
197
  model: listField.type,
178
198
  foreignKey: relation.fields[0],
@@ -1,32 +1,190 @@
1
1
  import { ts, textOf, replaceNode, calleeCall, requireReview } from './helpers.js';
2
+ import { staticMemberName } from '../../shared/analysis/ast-semantics.js';
2
3
  import { awaitedResult, outsideWrappers } from '../query-loops/query-results.js';
3
4
  // --- json-roundtrip-clone ---
4
5
  function isJsonCall(node, methodName) {
5
6
  if (!ts.isCallExpression(node) || ts.isOptionalChain(node))
6
7
  return false;
7
8
  const callee = ts.skipOuterExpressions(node.expression);
8
- return (ts.isPropertyAccessExpression(callee) &&
9
- callee.name.text === methodName &&
9
+ return (staticMemberName(callee) === methodName &&
10
+ (ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee)) &&
10
11
  ts.isIdentifier(callee.expression) &&
11
12
  callee.expression.text === 'JSON');
12
13
  }
14
+ function bindingHasName(binding, name) {
15
+ if (ts.isIdentifier(binding))
16
+ return binding.text === name;
17
+ return binding.elements.some((element) => ts.isBindingElement(element) && bindingHasName(element.name, name));
18
+ }
19
+ function declaresName(statement, name) {
20
+ if (ts.isVariableStatement(statement)) {
21
+ return statement.declarationList.declarations.some((decl) => bindingHasName(decl.name, name));
22
+ }
23
+ if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement))
24
+ return statement.name?.text === name;
25
+ if (ts.isImportDeclaration(statement) && statement.importClause)
26
+ return stmtHasBinding(statement.importClause, name);
27
+ return false;
28
+ }
29
+ function scopeDeclaresName(scope, name) {
30
+ if (ts.isFunctionLike(scope)) {
31
+ if (scope.parameters.some((param) => bindingHasName(param.name, name)))
32
+ return true;
33
+ return (ts.isFunctionDeclaration(scope) || ts.isFunctionExpression(scope)) && scope.name?.text === name;
34
+ }
35
+ if (ts.isCatchClause(scope)) {
36
+ return Boolean(scope.variableDeclaration && bindingHasName(scope.variableDeclaration.name, name));
37
+ }
38
+ if (ts.isForStatement(scope) || ts.isForInStatement(scope) || ts.isForOfStatement(scope)) {
39
+ const { initializer } = scope;
40
+ return Boolean(initializer &&
41
+ ts.isVariableDeclarationList(initializer) &&
42
+ initializer.declarations.some((declaration) => bindingHasName(declaration.name, name)));
43
+ }
44
+ if (ts.isBlock(scope) || ts.isSourceFile(scope))
45
+ return scope.statements.some((st) => declaresName(st, name));
46
+ if (ts.isCaseBlock(scope)) {
47
+ return scope.clauses.some((clause) => clause.statements.some((st) => declaresName(st, name)));
48
+ }
49
+ return false;
50
+ }
51
+ function isIdentifierShadowed(node, name) {
52
+ for (let current = node.parent; current; current = current.parent) {
53
+ if (scopeDeclaresName(current, name))
54
+ return true;
55
+ }
56
+ return false;
57
+ }
58
+ function stmtHasBinding(clause, name) {
59
+ if (clause.name?.text === name)
60
+ return true;
61
+ if (clause.namedBindings && ts.isNamedImports(clause.namedBindings)) {
62
+ return clause.namedBindings.elements.some((element) => element.name.text === name);
63
+ }
64
+ return Boolean(clause.namedBindings && ts.isNamespaceImport(clause.namedBindings) && clause.namedBindings.name.text === name);
65
+ }
66
+ function countIdentifierUses(scope, name) {
67
+ let count = 0;
68
+ (function visit(current) {
69
+ if (ts.isIdentifier(current) && current.text === name)
70
+ count++;
71
+ ts.forEachChild(current, visit);
72
+ })(scope);
73
+ return count;
74
+ }
75
+ function hasSideEffectBefore(statement, target) {
76
+ let found = false;
77
+ (function visit(node) {
78
+ if (found || node.pos >= target.pos)
79
+ return;
80
+ if (node.end <= target.pos) {
81
+ if (ts.isCallExpression(node) ||
82
+ ts.isNewExpression(node) ||
83
+ ts.isDeleteExpression(node) ||
84
+ ts.isAwaitExpression(node) ||
85
+ ts.isYieldExpression(node) ||
86
+ ((ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) &&
87
+ (node.operator === ts.SyntaxKind.PlusPlusToken || node.operator === ts.SyntaxKind.MinusMinusToken)) ||
88
+ (ts.isBinaryExpression(node) &&
89
+ node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment &&
90
+ node.operatorToken.kind <= ts.SyntaxKind.LastAssignment)) {
91
+ found = true;
92
+ return;
93
+ }
94
+ }
95
+ ts.forEachChild(node, visit);
96
+ })(statement);
97
+ return found;
98
+ }
99
+ // The two-step rewrite moves the stringified argument into the parse call, so the parse must run whenever its statement does.
100
+ function runsUnconditionally(parse, statement) {
101
+ let child = parse;
102
+ for (let current = parse.parent; current !== statement; child = current, current = current.parent) {
103
+ if (ts.isFunctionLike(current))
104
+ return false;
105
+ if (ts.isConditionalExpression(current) && current.condition !== child)
106
+ return false;
107
+ if (ts.isOptionalChain(current) && ts.isCallExpression(current) && current.expression !== child)
108
+ return false;
109
+ if (ts.isOptionalChain(current) && ts.isElementAccessExpression(current) && current.argumentExpression === child)
110
+ return false;
111
+ if (ts.isBinaryExpression(current) &&
112
+ current.right === child &&
113
+ (current.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken ||
114
+ current.operatorToken.kind === ts.SyntaxKind.BarBarToken ||
115
+ current.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken))
116
+ return false;
117
+ }
118
+ return true;
119
+ }
120
+ function twoStepStringify(parse, arg) {
121
+ if (!ts.isIdentifier(arg))
122
+ return;
123
+ const parseStatement = ts.findAncestor(parse, ts.isStatement);
124
+ if (!parseStatement || (!ts.isBlock(parseStatement.parent) && !ts.isSourceFile(parseStatement.parent)))
125
+ return;
126
+ const siblings = parseStatement.parent.statements;
127
+ const index = siblings.indexOf(parseStatement);
128
+ if (index <= 0)
129
+ return;
130
+ const previous = siblings[index - 1];
131
+ if (!ts.isVariableStatement(previous) || !(previous.declarationList.flags & ts.NodeFlags.Const))
132
+ return;
133
+ if (previous.declarationList.declarations.length !== 1)
134
+ return;
135
+ const [declaration] = previous.declarationList.declarations;
136
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== arg.text || !declaration.initializer)
137
+ return;
138
+ const stringify = ts.skipOuterExpressions(declaration.initializer);
139
+ if (!isJsonCall(stringify, 'stringify') || stringify.arguments.length !== 1)
140
+ return;
141
+ const [value] = stringify.arguments;
142
+ if (ts.isSpreadElement(value))
143
+ return;
144
+ if (countIdentifierUses(parseStatement.parent, arg.text) !== 2)
145
+ return;
146
+ if (hasSideEffectBefore(parseStatement, parse))
147
+ return;
148
+ // A loop header re-evaluates the parse, and with it the moved stringify argument, on every iteration. A for-in/of header
149
+ // can also declare a binding that shadows the moved argument.
150
+ if (ts.isWhileStatement(parseStatement) ||
151
+ ts.isDoStatement(parseStatement) ||
152
+ ts.isForStatement(parseStatement) ||
153
+ ts.isForInStatement(parseStatement) ||
154
+ ts.isForOfStatement(parseStatement))
155
+ return;
156
+ if (!runsUnconditionally(parse, parseStatement))
157
+ return;
158
+ return { statement: previous, value };
159
+ }
13
160
  function jsonCloneFix({ node }) {
14
161
  if (!node)
15
162
  return;
16
163
  const parse = ts.findAncestor(node, (current) => isJsonCall(current, 'parse'));
17
164
  if (!parse || parse.arguments.length !== 1)
18
165
  return;
19
- const stringify = ts.skipOuterExpressions(parse.arguments[0]);
20
- // A replacer or indentation argument changes what the round trip keeps, so structuredClone is not
21
- // equivalent.
22
- if (!isJsonCall(stringify, 'stringify') || stringify.arguments.length !== 1)
166
+ if (isIdentifierShadowed(parse, 'structuredClone'))
23
167
  return;
24
- const [value] = stringify.arguments;
25
- if (ts.isSpreadElement(value))
168
+ const arg = ts.skipOuterExpressions(parse.arguments[0]);
169
+ const note = 'structuredClone keeps Dates, Maps, Sets and undefined values where the JSON round trip turned Dates into strings and dropped undefined; class instances lose their prototype in both. It throws on functions and symbols, which the round trip silently dropped.';
170
+ if (isJsonCall(arg, 'stringify') && arg.arguments.length === 1) {
171
+ const [value] = arg.arguments;
172
+ if (ts.isSpreadElement(value))
173
+ return;
174
+ return { edits: [replaceNode(parse, `structuredClone(${textOf(value)})`)], note, requiresReview: true };
175
+ }
176
+ const twoStep = twoStepStringify(parse, arg);
177
+ if (!twoStep)
178
+ return;
179
+ const parseStatement = ts.findAncestor(parse, ts.isStatement);
180
+ if (!parseStatement)
26
181
  return;
27
182
  return {
28
- edits: [replaceNode(parse, `structuredClone(${textOf(value)})`)],
29
- note: 'structuredClone keeps Dates, Maps, Sets and undefined values where the JSON round trip turned Dates into strings and dropped undefined; class instances lose their prototype in both. It throws on functions and symbols, which the round trip silently dropped.',
183
+ edits: [
184
+ { start: twoStep.statement.getStart(), end: parseStatement.getStart(), text: '' },
185
+ replaceNode(parse, `structuredClone(${textOf(twoStep.value)})`),
186
+ ],
187
+ note,
30
188
  requiresReview: true,
31
189
  };
32
190
  }
@@ -1,7 +1,6 @@
1
1
  // Rewrites a blocking `xSync(...)` call into its awaited counterpart, keeping the user's receiver
2
2
  // and arguments. Every builder returns undefined whenever the shape is not provably equivalent, so
3
3
  // the generic example is shown.
4
- import { isBuiltin } from 'node:module';
5
4
  import { requireReview, ts, calleeCall, nameTaken } from './helpers.js';
6
5
  import { importLinesEdit, moduleNameOf, requiredModuleName, swappedImportEdits } from './sync-imports.js';
7
6
  const syncSuffix = 'Sync';
@@ -215,14 +214,6 @@ function neededImports(sourceFile, localName, moduleName, importedName = localNa
215
214
  return;
216
215
  return [{ moduleName, importedName }];
217
216
  }
218
- // Notes telling the user which import the rewrite needs; undefined when the local name is already
219
- // taken by something else.
220
- function importNotes(sourceFile, localName, moduleName, importedName = localName) {
221
- return neededImports(sourceFile, localName, moduleName, importedName)?.map((needed) => {
222
- const specifier = isBuiltin(needed.moduleName) ? `node:${needed.moduleName}` : needed.moduleName;
223
- return `Import \`${needed.importedName}\` from '${specifier}'.`;
224
- });
225
- }
226
217
  function result(edits, notes) {
227
218
  return { edits, ...(notes.length ? { note: notes.join(' ') } : {}) };
228
219
  }
@@ -395,10 +386,21 @@ function fixBcrypt({ node, sourceFile }) {
395
386
  : [];
396
387
  if (callee.receiver)
397
388
  return result([...mapEdits, ...awaitedCallEdits(call, `${callee.receiver}.${promiseName}`)], mapNote);
398
- const notes = importNotes(sourceFile, promiseName, callee.binding.moduleName);
399
- if (!notes)
389
+ const imports = neededImports(sourceFile, promiseName, callee.binding.moduleName);
390
+ if (!imports)
400
391
  return;
401
- return result([...mapEdits, ...awaitedCallEdits(call, promiseName)], [...notes, ...mapNote]);
392
+ const edits = [...mapEdits, ...awaitedCallEdits(call, promiseName)];
393
+ if (imports.length) {
394
+ if (ts.isVariableStatement(callee.binding.statement) &&
395
+ (callee.binding.statement.declarationList.declarations.length !== 1 ||
396
+ call.getStart(sourceFile) < callee.binding.statement.end))
397
+ return;
398
+ const importEdit = importLinesEdit(sourceFile, callee.binding.statement, new Map([[callee.binding.moduleName, new Set([promiseName])]]));
399
+ if (!importEdit)
400
+ return;
401
+ edits.push(importEdit);
402
+ }
403
+ return result(edits, mapNote);
402
404
  }
403
405
  // A sync call directly inside a sync `.map(...)` callback that an async function runs.
404
406
  function mapCallbackCall(node) {
@@ -1,8 +1,14 @@
1
1
  import { ts, addProperty, calleeCall, nameTaken, replaceNode } from './helpers.js';
2
2
  import { effectiveProperty, unwrapExpression } from '../../shared/analysis/ast-semantics.js';
3
3
  const LIMIT_NAME = 'MAX_UPLOAD_FILE_SIZE_BYTES';
4
- const LIMIT_DECLARATION = `const ${LIMIT_NAME} = 10 * 1024 * 1024;`;
4
+ const DEFAULT_LIMIT_EXPRESSION = '10 * 1024 * 1024';
5
5
  const SIZE_LIMIT = `fileSize: ${LIMIT_NAME}`;
6
+ function limitDeclarationFor(uploadMaxBytes) {
7
+ const value = typeof uploadMaxBytes === 'number' && Number.isInteger(uploadMaxBytes) && uploadMaxBytes >= 1
8
+ ? String(uploadMaxBytes)
9
+ : DEFAULT_LIMIT_EXPRESSION;
10
+ return `const ${LIMIT_NAME} = ${value};`;
11
+ }
6
12
  // A finding proves the value is unset. Avoid erasing an operand that void still evaluates.
7
13
  function canReplaceUnset(initializer) {
8
14
  const value = unwrapExpression(initializer);
@@ -49,7 +55,7 @@ function uploadLimitEdit({ finding, node, text }) {
49
55
  return replaceNode(fileSize.initializer, LIMIT_NAME);
50
56
  }
51
57
  // Keep the shebang and directive prologue, then place the constant before executable code.
52
- function limitDeclarationEdit(sourceFile, text) {
58
+ function limitDeclarationEdit(sourceFile, text, limitDeclaration) {
53
59
  const newline = text.includes('\r\n') ? '\r\n' : '\n';
54
60
  const header = sourceFile.statements.findIndex((statement) => !ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression));
55
61
  let index = header === -1 ? sourceFile.statements.length : header;
@@ -60,23 +66,23 @@ function limitDeclarationEdit(sourceFile, text) {
60
66
  const lastHeader = sourceFile.statements[index - 1];
61
67
  if (lastHeader) {
62
68
  const position = lastHeader.end;
63
- return { start: position, end: position, text: newline + newline + LIMIT_DECLARATION };
69
+ return { start: position, end: position, text: newline + newline + limitDeclaration };
64
70
  }
65
71
  const position = /^(?:\uFEFF)?(?:#![^\r\n]*(?:\r\n|\n|\r))?/.exec(text)?.[0].length ?? 0;
66
72
  // Leading comments can carry compiler directives or attach to the first declaration.
67
73
  const firstStatement = sourceFile.statements[0];
68
74
  if (!firstStatement || text.slice(position, firstStatement.getStart(sourceFile)).trim())
69
75
  return;
70
- return { start: position, end: position, text: LIMIT_DECLARATION + newline + newline };
76
+ return { start: position, end: position, text: limitDeclaration + newline + newline };
71
77
  }
72
78
  function uploadLimitFix(site) {
73
- const { sourceFile, text } = site;
79
+ const { finding, sourceFile, text } = site;
74
80
  if (!sourceFile || text === undefined)
75
81
  return;
76
82
  if (nameTaken(sourceFile, LIMIT_NAME))
77
83
  return;
78
84
  const edit = uploadLimitEdit(site);
79
- const declaration = limitDeclarationEdit(sourceFile, text);
85
+ const declaration = limitDeclarationEdit(sourceFile, text, limitDeclarationFor(finding.uploadMaxBytes));
80
86
  if (!edit || !declaration)
81
87
  return;
82
88
  return {
@@ -85,7 +91,7 @@ function uploadLimitFix(site) {
85
91
  // Every upload site in a file adds the same declaration, so it has to stay a separate,
86
92
  // shareable hunk.
87
93
  separateEdits: true,
88
- note: `${LIMIT_NAME} is a placeholder of 10 MiB, not a recommendation. Choose the limit against a real upload (a workbook with embedded images can be larger) and check the gateway request limit. Preserve any inherited Multer limits when setting route options.`,
94
+ note: `${LIMIT_NAME} is a starting value, not a recommendation. Choose the limit against a real upload (a workbook with embedded images can be larger) and check the gateway request limit. Preserve any inherited Multer limits when setting route options.`,
89
95
  };
90
96
  }
91
97
  export default { 'upload-without-size-limit': uploadLimitFix };
@@ -183,11 +183,12 @@ function splitTopLevelCommas(tokens) {
183
183
  const groups = [[]];
184
184
  let depth = 0;
185
185
  for (const token of tokens) {
186
- if (token.value === '(')
186
+ const punctuation = token.type === 'punct' ? token.value : undefined;
187
+ if (punctuation === '(')
187
188
  depth += 1;
188
- else if (token.value === ')')
189
+ else if (punctuation === ')')
189
190
  depth -= 1;
190
- if (token.value === ',' && depth === 0)
191
+ if (punctuation === ',' && depth === 0)
191
192
  groups.push([]);
192
193
  else
193
194
  groups[groups.length - 1].push(token);
@@ -265,23 +266,47 @@ function describeAlterAction(tokens) {
265
266
  return { type: 'other' };
266
267
  }
267
268
  function isStatementOption(actionTokens) {
268
- return ['ALGORITHM', 'LOCK'].includes(actionTokens[0].upper);
269
+ return actionTokens[0].type === 'word' && ['ALGORITHM', 'LOCK'].includes(actionTokens[0].upper);
269
270
  }
270
- function recognizeAlterTable(tokens) {
271
+ function alterTableName(tokens) {
271
272
  const position = skipWords(tokens, 1, new Set(['ONLINE', 'IGNORE']));
272
273
  if (tokens[position]?.upper !== 'TABLE')
273
274
  return null;
274
- const name = readQualifiedName(tokens, skipIfClause(tokens, position + 1));
275
+ return readQualifiedName(tokens, skipIfClause(tokens, position + 1));
276
+ }
277
+ function topLevelTokens(tokens) {
278
+ let depth = 0;
279
+ return tokens.filter((token) => {
280
+ if (token.type === 'punct' && token.value === ')')
281
+ depth--;
282
+ const atTop = depth === 0;
283
+ if (token.type === 'punct' && token.value === '(')
284
+ depth++;
285
+ return atTop;
286
+ });
287
+ }
288
+ function mysqlOptionTokens(tokens) {
289
+ if (tokens[0]?.upper !== 'ALTER')
290
+ return topLevelTokens(tokens);
291
+ const name = alterTableName(tokens);
292
+ if (!name)
293
+ return [];
294
+ return splitTopLevelCommas(tokens.slice(name.next)).filter(isStatementOption).flat();
295
+ }
296
+ function recognizeAlterTable(tokens) {
297
+ const name = alterTableName(tokens);
275
298
  if (!name)
276
299
  return null;
277
- const actionGroups = splitTopLevelCommas(tokens.slice(name.next)).filter((group) => !isStatementOption(group));
300
+ const groups = splitTopLevelCommas(tokens.slice(name.next));
301
+ const options = groups.filter(isStatementOption).flat();
302
+ const actionGroups = groups.filter((group) => !isStatementOption(group));
278
303
  return {
279
304
  kind: 'alter-table',
280
305
  table: name.table,
281
306
  schema: name.schema,
282
307
  actions: actionGroups.map((group) => ({ ...describeAlterAction(group), start: group[0].start })),
283
- algorithm: readOptionValue(tokens, 'ALGORITHM'),
284
- lock: readOptionValue(tokens, 'LOCK'),
308
+ algorithm: readOptionValue(options, 'ALGORITHM'),
309
+ lock: readOptionValue(options, 'LOCK'),
285
310
  };
286
311
  }
287
312
  function recognizeCreateIndex(tokens) {
@@ -298,14 +323,15 @@ function recognizeCreateIndex(tokens) {
298
323
  const name = onPosition === -1 ? null : readQualifiedName(tokens, onPosition + 1);
299
324
  if (!name)
300
325
  return null;
326
+ const options = topLevelTokens(tokens.slice(name.next));
301
327
  return {
302
328
  kind: 'create-index',
303
329
  index,
304
330
  table: name.table,
305
331
  schema: name.schema,
306
332
  unique: modifiers.includes('UNIQUE'),
307
- algorithm: readOptionValue(tokens, 'ALGORITHM'),
308
- lock: readOptionValue(tokens, 'LOCK'),
333
+ algorithm: readOptionValue(options, 'ALGORITHM'),
334
+ lock: readOptionValue(options, 'LOCK'),
309
335
  };
310
336
  }
311
337
  function readNameList(tokens, position) {
@@ -390,4 +416,4 @@ function parseMysqlStatements(text) {
390
416
  };
391
417
  });
392
418
  }
393
- export { parseMysqlStatements, splitStatementRanges, tokenizeRange };
419
+ export { parseMysqlStatements, splitStatementRanges, tokenizeRange, mysqlOptionTokens };