loadwise 0.0.0-stage → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (804) hide show
  1. package/LICENSE +201 -0
  2. package/PERFORMANCE.md +110 -0
  3. package/README.md +1429 -2
  4. package/bin/github-action.js +58 -0
  5. package/bin/loadwise.js +98 -0
  6. package/editor/README.md +47 -0
  7. package/editor/accessibility-examples.cjs +90 -0
  8. package/editor/apply-fix.cjs +187 -0
  9. package/editor/control-flow-comparison.cjs +133 -0
  10. package/editor/finding-comparison.cjs +77 -0
  11. package/editor/maintainability-examples.cjs +229 -0
  12. package/editor/perf-site-comparison.cjs +85 -0
  13. package/editor/performance-examples.cjs +438 -0
  14. package/editor/reliability-examples.cjs +77 -0
  15. package/editor/security-examples.cjs +59 -0
  16. package/editor/source-example.cjs +66 -0
  17. package/editor/standalone-performance-examples.cjs +487 -0
  18. package/examples/indexed.ts +19 -0
  19. package/examples/labels.py +6 -0
  20. package/examples/mongo-plan.json +8 -0
  21. package/examples/postgres-plan.json +10 -0
  22. package/examples/query-policy.json +24 -0
  23. package/examples/redis-keys.otlp.json +22 -0
  24. package/examples/repeated-db.otlp.json +73 -0
  25. package/examples/slow.ts +10 -0
  26. package/examples/tsconfig.json +4 -0
  27. package/lib/accessibility/analyze.js +26 -0
  28. package/lib/accessibility/angular-inline.js +43 -0
  29. package/lib/accessibility/aria-tables.js +231 -0
  30. package/lib/accessibility/cli.js +11 -0
  31. package/lib/accessibility/frontend-detect.js +98 -0
  32. package/lib/accessibility/jsx-elements.js +110 -0
  33. package/lib/accessibility/markup-files.js +41 -0
  34. package/lib/accessibility/markup.js +24 -0
  35. package/lib/accessibility/rule-ids.js +36 -0
  36. package/lib/accessibility/rules.js +293 -0
  37. package/lib/accessibility/site-fixes/buttons.js +35 -0
  38. package/lib/accessibility/template-attributes.js +137 -0
  39. package/lib/accessibility/template-elements.js +434 -0
  40. package/lib/accessibility/template-file.js +183 -0
  41. package/lib/accessibility/usage.js +12 -0
  42. package/lib/maintainability/advisory-context.js +182 -0
  43. package/lib/maintainability/analyze-source.js +93 -0
  44. package/lib/maintainability/ancestor-aliases.js +35 -0
  45. package/lib/maintainability/apply-fix.js +85 -0
  46. package/lib/maintainability/architecture-nest.js +103 -0
  47. package/lib/maintainability/architecture.js +482 -0
  48. package/lib/maintainability/branch-advice.js +135 -0
  49. package/lib/maintainability/changed-lines.js +135 -0
  50. package/lib/maintainability/changed-output.js +21 -0
  51. package/lib/maintainability/checklist-context.js +74 -0
  52. package/lib/maintainability/child-buffer.js +20 -0
  53. package/lib/maintainability/cli.js +410 -0
  54. package/lib/maintainability/config-entry-points.js +86 -0
  55. package/lib/maintainability/data-access.js +153 -0
  56. package/lib/maintainability/deprecated-apis.js +170 -0
  57. package/lib/maintainability/docker-entry-points.js +98 -0
  58. package/lib/maintainability/duplicates.js +326 -0
  59. package/lib/maintainability/entry-points.js +603 -0
  60. package/lib/maintainability/examples.js +122 -0
  61. package/lib/maintainability/finding-ids.js +46 -0
  62. package/lib/maintainability/fix-cli.js +235 -0
  63. package/lib/maintainability/fix-text.js +11 -0
  64. package/lib/maintainability/functions.js +315 -0
  65. package/lib/maintainability/graph.js +186 -0
  66. package/lib/maintainability/html-entry-points.js +75 -0
  67. package/lib/maintainability/inputs.js +231 -0
  68. package/lib/maintainability/layout.js +56 -0
  69. package/lib/maintainability/limits.js +3 -0
  70. package/lib/maintainability/mocha-entry-points.js +88 -0
  71. package/lib/maintainability/modifiers.js +6 -0
  72. package/lib/maintainability/module-usage-dynamic.js +175 -0
  73. package/lib/maintainability/module-usage.js +574 -0
  74. package/lib/maintainability/notify-editor.js +1 -0
  75. package/lib/maintainability/operator-references.js +84 -0
  76. package/lib/maintainability/polyglot-duplicates.js +121 -0
  77. package/lib/maintainability/polyglot.js +173 -0
  78. package/lib/maintainability/project.js +116 -0
  79. package/lib/maintainability/review-directive.js +91 -0
  80. package/lib/maintainability/rule-ids.js +67 -0
  81. package/lib/maintainability/runtime-directories.js +22 -0
  82. package/lib/maintainability/scan-changed.js +67 -0
  83. package/lib/maintainability/scan-worker.js +38 -0
  84. package/lib/maintainability/scan.js +238 -0
  85. package/lib/maintainability/site-fix.js +221 -0
  86. package/lib/maintainability/site-fixes/boolean-returns.js +79 -0
  87. package/lib/maintainability/site-fixes/branches.js +418 -0
  88. package/lib/maintainability/site-fixes/control-flow.js +67 -0
  89. package/lib/maintainability/site-fixes/cycles.js +101 -0
  90. package/lib/maintainability/site-fixes/deprecated-apis.js +67 -0
  91. package/lib/maintainability/site-fixes/duplicate-arrows.js +343 -0
  92. package/lib/maintainability/site-fixes/duplicate-bindings.js +149 -0
  93. package/lib/maintainability/site-fixes/duplicate-edits.js +396 -0
  94. package/lib/maintainability/site-fixes/duplicate-methods.js +407 -0
  95. package/lib/maintainability/site-fixes/duplicates.js +125 -0
  96. package/lib/maintainability/site-fixes/exports.js +25 -0
  97. package/lib/maintainability/site-fixes/extract-block-ast.js +130 -0
  98. package/lib/maintainability/site-fixes/extract-block-edits.js +156 -0
  99. package/lib/maintainability/site-fixes/extract-block-flow.js +265 -0
  100. package/lib/maintainability/site-fixes/extract-block-measure.js +131 -0
  101. package/lib/maintainability/site-fixes/extract-block-naming.js +164 -0
  102. package/lib/maintainability/site-fixes/extract-block-narrowing.js +141 -0
  103. package/lib/maintainability/site-fixes/extract-block.js +38 -0
  104. package/lib/maintainability/site-fixes/helpers.js +308 -0
  105. package/lib/maintainability/site-fixes/if-rewrites.js +468 -0
  106. package/lib/maintainability/site-fixes/isolated-program.js +85 -0
  107. package/lib/maintainability/site-fixes/large-module.js +175 -0
  108. package/lib/maintainability/site-fixes/parameters.js +460 -0
  109. package/lib/maintainability/site-fixes/stray-console.js +21 -0
  110. package/lib/maintainability/site-fixes/unused-bindings.js +158 -0
  111. package/lib/maintainability/size-limits.js +94 -0
  112. package/lib/maintainability/snapshot-context.js +63 -0
  113. package/lib/maintainability/source-exclusions.js +68 -0
  114. package/lib/maintainability/source-facts.js +39 -0
  115. package/lib/maintainability/stray-console.js +352 -0
  116. package/lib/maintainability/traversal-context.js +76 -0
  117. package/lib/maintainability/types/changed-lines.js +1 -0
  118. package/lib/maintainability/types/created-module.js +1 -0
  119. package/lib/maintainability/types/duplicate-sites.js +1 -0
  120. package/lib/maintainability/types/duplicates.js +1 -0
  121. package/lib/maintainability/types/entry-points.js +1 -0
  122. package/lib/maintainability/types/extract-block.js +1 -0
  123. package/lib/maintainability/types/extraction-drafts.js +1 -0
  124. package/lib/maintainability/types/finding-comparison.js +1 -0
  125. package/lib/maintainability/types/fix-files.js +1 -0
  126. package/lib/maintainability/types/module-graph.js +1 -0
  127. package/lib/maintainability/types/module-resolver.js +1 -0
  128. package/lib/maintainability/types/module-usage.js +1 -0
  129. package/lib/maintainability/types/policy.js +1 -0
  130. package/lib/maintainability/types/polyglot-scan.js +1 -0
  131. package/lib/maintainability/types/scan-report.js +1 -0
  132. package/lib/maintainability/types/scan-worker.js +1 -0
  133. package/lib/maintainability/types/site-fix-edits.js +1 -0
  134. package/lib/maintainability/types/site-fix-loader.js +1 -0
  135. package/lib/maintainability/types/site-fix-nodes.js +1 -0
  136. package/lib/maintainability/types/source-analysis.js +1 -0
  137. package/lib/maintainability/types/source-facts.js +1 -0
  138. package/lib/maintainability/types/typescript-jsdoc-internals.js +1 -0
  139. package/lib/maintainability/types/typescript-site-fix-internals.js +1 -0
  140. package/lib/maintainability/unused-bindings.js +182 -0
  141. package/lib/maintainability/unused-modules.js +258 -0
  142. package/lib/maintainability/verified-private-types.js +142 -0
  143. package/lib/maintainability/walk.js +17 -0
  144. package/lib/maintainability/workflow-entry-points.js +83 -0
  145. package/lib/performance/analyze.js +251 -0
  146. package/lib/performance/async-errors.js +190 -0
  147. package/lib/performance/await-before-early-exit.js +176 -0
  148. package/lib/performance/awaits.js +70 -0
  149. package/lib/performance/backend-mastery.js +444 -0
  150. package/lib/performance/cache-reads.js +170 -0
  151. package/lib/performance/call-syntax.js +27 -0
  152. package/lib/performance/cartesian-includes.js +364 -0
  153. package/lib/performance/changed-lines.js +141 -0
  154. package/lib/performance/cli-arguments.js +61 -0
  155. package/lib/performance/cli-output.js +175 -0
  156. package/lib/performance/cli-policy.js +79 -0
  157. package/lib/performance/cli-scan.js +419 -0
  158. package/lib/performance/cli-types.js +1 -0
  159. package/lib/performance/cli.js +120 -0
  160. package/lib/performance/collection-bindings.js +283 -0
  161. package/lib/performance/collection-bounds.js +247 -0
  162. package/lib/performance/collection-copy.js +169 -0
  163. package/lib/performance/collection-lookups.js +432 -0
  164. package/lib/performance/collection-reduce.js +340 -0
  165. package/lib/performance/collections.js +25 -0
  166. package/lib/performance/compiler.js +52 -0
  167. package/lib/performance/contracts/cli.js +230 -0
  168. package/lib/performance/contracts/dto.js +244 -0
  169. package/lib/performance/contracts/git-files.js +37 -0
  170. package/lib/performance/contracts/graphql.js +360 -0
  171. package/lib/performance/contracts/openapi.js +363 -0
  172. package/lib/performance/db/checks.js +398 -0
  173. package/lib/performance/db/cli-format.js +9 -0
  174. package/lib/performance/db/cli-mysql.js +82 -0
  175. package/lib/performance/db/cli.js +469 -0
  176. package/lib/performance/db/drivers.js +241 -0
  177. package/lib/performance/db/gateway.js +194 -0
  178. package/lib/performance/db/hypopg.js +52 -0
  179. package/lib/performance/db/measure.js +141 -0
  180. package/lib/performance/db/mongo.js +272 -0
  181. package/lib/performance/db/mysql-catalog.js +64 -0
  182. package/lib/performance/db/pg-catalog.js +114 -0
  183. package/lib/performance/db/plan-estimates.js +188 -0
  184. package/lib/performance/db/redact.js +126 -0
  185. package/lib/performance/db/snapshot.js +82 -0
  186. package/lib/performance/dependent-writes.js +228 -0
  187. package/lib/performance/discarded-error-result.js +46 -0
  188. package/lib/performance/drizzle-write-preflight.js +195 -0
  189. package/lib/performance/drizzle.js +288 -0
  190. package/lib/performance/editor-report.js +191 -0
  191. package/lib/performance/editor-setup.js +189 -0
  192. package/lib/performance/editor-signal.js +57 -0
  193. package/lib/performance/editor-watch-supervisor.js +104 -0
  194. package/lib/performance/editor-watch.js +193 -0
  195. package/lib/performance/emit-options.js +29 -0
  196. package/lib/performance/filter-existence.js +149 -0
  197. package/lib/performance/find-then-create.js +281 -0
  198. package/lib/performance/finding-ids.js +48 -0
  199. package/lib/performance/finding-text.js +117 -0
  200. package/lib/performance/fix-cli.js +200 -0
  201. package/lib/performance/floating-promises.js +248 -0
  202. package/lib/performance/frontend-dom-perf.js +310 -0
  203. package/lib/performance/frontend-helpers.js +93 -0
  204. package/lib/performance/frontend-perf.js +472 -0
  205. package/lib/performance/function-kinds.js +9 -0
  206. package/lib/performance/guard-queries.js +356 -0
  207. package/lib/performance/http-timeouts.js +492 -0
  208. package/lib/performance/impact.js +53 -0
  209. package/lib/performance/index-rules-foreign-keys.js +81 -0
  210. package/lib/performance/index-rules-order.js +152 -0
  211. package/lib/performance/index-rules-pattern.js +137 -0
  212. package/lib/performance/index-rules-table.js +288 -0
  213. package/lib/performance/index-rules.js +107 -0
  214. package/lib/performance/json-clone.js +28 -0
  215. package/lib/performance/json-parse-context.js +99 -0
  216. package/lib/performance/last-insert-id.js +120 -0
  217. package/lib/performance/list-counts.js +321 -0
  218. package/lib/performance/list-overfetch.js +216 -0
  219. package/lib/performance/literal-awaits.js +190 -0
  220. package/lib/performance/memory-growth.js +516 -0
  221. package/lib/performance/migrations/cli.js +203 -0
  222. package/lib/performance/migrations/discover.js +354 -0
  223. package/lib/performance/migrations/enforce.js +177 -0
  224. package/lib/performance/migrations/extract-code-builders.js +291 -0
  225. package/lib/performance/migrations/extract-code-discovery.js +179 -0
  226. package/lib/performance/migrations/extract-code-sql.js +196 -0
  227. package/lib/performance/migrations/extract-code-types.js +1 -0
  228. package/lib/performance/migrations/extract-code.js +123 -0
  229. package/lib/performance/migrations/extract-sql.js +452 -0
  230. package/lib/performance/migrations/operations.js +156 -0
  231. package/lib/performance/migrations/postgres-registry.js +135 -0
  232. package/lib/performance/migrations/rules-mysql.js +105 -0
  233. package/lib/performance/migrations/rules-postgres-add-column.js +145 -0
  234. package/lib/performance/migrations/rules-postgres-shared.js +22 -0
  235. package/lib/performance/migrations/rules-postgres.js +464 -0
  236. package/lib/performance/missing-packages.js +116 -0
  237. package/lib/performance/models/index.js +284 -0
  238. package/lib/performance/mongoose-patterns.js +245 -0
  239. package/lib/performance/native-checker.js +312 -0
  240. package/lib/performance/native-runtime.js +24 -0
  241. package/lib/performance/native-syntax.js +132 -0
  242. package/lib/performance/native-workspaces.js +31 -0
  243. package/lib/performance/native.js +342 -0
  244. package/lib/performance/node-fs-context.js +390 -0
  245. package/lib/performance/node-fs.js +452 -0
  246. package/lib/performance/notification-loops.js +176 -0
  247. package/lib/performance/notify-editor.js +1 -0
  248. package/lib/performance/offset-pagination.js +166 -0
  249. package/lib/performance/orm-owners.js +145 -0
  250. package/lib/performance/orm-queries.js +496 -0
  251. package/lib/performance/package-types.js +57 -0
  252. package/lib/performance/page-counts.js +262 -0
  253. package/lib/performance/parallel-reads-policy.js +41 -0
  254. package/lib/performance/parallel-reads.js +139 -0
  255. package/lib/performance/password-hashing.js +218 -0
  256. package/lib/performance/pg-fragments.js +300 -0
  257. package/lib/performance/pg-integrity.js +115 -0
  258. package/lib/performance/phase5-rules.js +539 -0
  259. package/lib/performance/plans.js +283 -0
  260. package/lib/performance/polyglot.js +193 -0
  261. package/lib/performance/pooling.js +200 -0
  262. package/lib/performance/postgres.js +182 -0
  263. package/lib/performance/prisma-aggregates.js +125 -0
  264. package/lib/performance/prisma-integrity.js +239 -0
  265. package/lib/performance/prisma.js +399 -0
  266. package/lib/performance/projects.js +431 -0
  267. package/lib/performance/promise-return-escapes-catch.js +96 -0
  268. package/lib/performance/pure-js-hashing.js +96 -0
  269. package/lib/performance/query-loop-batch.js +188 -0
  270. package/lib/performance/query-loop-bounds.js +219 -0
  271. package/lib/performance/query-loop-exits.js +171 -0
  272. package/lib/performance/query-loop-helpers.js +42 -0
  273. package/lib/performance/query-loop-memo.js +81 -0
  274. package/lib/performance/query-loop-pagination.js +130 -0
  275. package/lib/performance/query-loops.js +29 -0
  276. package/lib/performance/query-policy.js +94 -0
  277. package/lib/performance/query-results.js +179 -0
  278. package/lib/performance/queue-loops.js +87 -0
  279. package/lib/performance/recursive-watch.js +181 -0
  280. package/lib/performance/redis-client.js +19 -0
  281. package/lib/performance/redis-keys.js +78 -0
  282. package/lib/performance/redis.js +188 -0
  283. package/lib/performance/redundant-indexes.js +403 -0
  284. package/lib/performance/reference-checks.js +22 -0
  285. package/lib/performance/repeated.js +200 -0
  286. package/lib/performance/request-handlers.js +429 -0
  287. package/lib/performance/request-heavy-work.js +135 -0
  288. package/lib/performance/request-inputs.js +303 -0
  289. package/lib/performance/retry-backoff.js +132 -0
  290. package/lib/performance/return-in-finally.js +12 -0
  291. package/lib/performance/return-newline.js +54 -0
  292. package/lib/performance/review-context.js +434 -0
  293. package/lib/performance/rule-ids.js +357 -0
  294. package/lib/performance/scan-outcome.js +37 -0
  295. package/lib/performance/schema/context.js +145 -0
  296. package/lib/performance/schema/drizzle-schema.js +278 -0
  297. package/lib/performance/schema/model.js +169 -0
  298. package/lib/performance/schema/mongoose-schema.js +189 -0
  299. package/lib/performance/schema/prisma-schema.js +472 -0
  300. package/lib/performance/schema/project-indexes-events.js +494 -0
  301. package/lib/performance/schema/project-indexes.js +240 -0
  302. package/lib/performance/schema/query-site-support.js +61 -0
  303. package/lib/performance/schema/query-sites-drizzle.js +220 -0
  304. package/lib/performance/schema/query-sites-mongoose.js +140 -0
  305. package/lib/performance/schema/query-sites-prisma.js +201 -0
  306. package/lib/performance/schema/query-sites-sequelize.js +133 -0
  307. package/lib/performance/schema/query-sites-typeorm.js +180 -0
  308. package/lib/performance/schema/query-sites.js +19 -0
  309. package/lib/performance/schema/raw-sql-sites.js +284 -0
  310. package/lib/performance/schema/sequelize-schema.js +322 -0
  311. package/lib/performance/schema/ts-helpers.js +130 -0
  312. package/lib/performance/schema/typeorm-schema.js +262 -0
  313. package/lib/performance/schema-tooling.js +193 -0
  314. package/lib/performance/scope-evidence.js +137 -0
  315. package/lib/performance/sequential-loops.js +557 -0
  316. package/lib/performance/service-call-resolution.js +54 -0
  317. package/lib/performance/service-loop-collections.js +263 -0
  318. package/lib/performance/service-loop-operations.js +235 -0
  319. package/lib/performance/service-loops.js +416 -0
  320. package/lib/performance/session-store.js +86 -0
  321. package/lib/performance/site-fix.js +271 -0
  322. package/lib/performance/site-fixes/await-before-early-exit.js +121 -0
  323. package/lib/performance/site-fixes/backend-mastery-fixes.js +90 -0
  324. package/lib/performance/site-fixes/batch-loops.js +449 -0
  325. package/lib/performance/site-fixes/collection-copy.js +310 -0
  326. package/lib/performance/site-fixes/collection-existence.js +200 -0
  327. package/lib/performance/site-fixes/collection-find.js +195 -0
  328. package/lib/performance/site-fixes/collection-helpers.js +349 -0
  329. package/lib/performance/site-fixes/collection-lookup-declarations.js +47 -0
  330. package/lib/performance/site-fixes/collection-lookups.js +101 -0
  331. package/lib/performance/site-fixes/collection-membership.js +124 -0
  332. package/lib/performance/site-fixes/collections.js +18 -0
  333. package/lib/performance/site-fixes/database.js +455 -0
  334. package/lib/performance/site-fixes/delete-preflight.js +99 -0
  335. package/lib/performance/site-fixes/drizzle-index.js +239 -0
  336. package/lib/performance/site-fixes/error-handling.js +99 -0
  337. package/lib/performance/site-fixes/frontend-fixes.js +193 -0
  338. package/lib/performance/site-fixes/guard-queries.js +172 -0
  339. package/lib/performance/site-fixes/helpers.js +200 -0
  340. package/lib/performance/site-fixes/hoisting.js +155 -0
  341. package/lib/performance/site-fixes/http-timeouts.js +56 -0
  342. package/lib/performance/site-fixes/indexes.js +454 -0
  343. package/lib/performance/site-fixes/integrity-drizzle.js +188 -0
  344. package/lib/performance/site-fixes/integrity-wrap.js +45 -0
  345. package/lib/performance/site-fixes/integrity.js +555 -0
  346. package/lib/performance/site-fixes/json-parse.js +114 -0
  347. package/lib/performance/site-fixes/last-insert-id.js +230 -0
  348. package/lib/performance/site-fixes/list-queries.js +164 -0
  349. package/lib/performance/site-fixes/literal-awaits.js +431 -0
  350. package/lib/performance/site-fixes/method-calls.js +6 -0
  351. package/lib/performance/site-fixes/migration-column-rules.js +208 -0
  352. package/lib/performance/site-fixes/migration-context.js +317 -0
  353. package/lib/performance/site-fixes/migration-lock-rules.js +204 -0
  354. package/lib/performance/site-fixes/migration-placement.js +252 -0
  355. package/lib/performance/site-fixes/migrations.js +34 -0
  356. package/lib/performance/site-fixes/page-counts.js +88 -0
  357. package/lib/performance/site-fixes/prisma-aggregates.js +455 -0
  358. package/lib/performance/site-fixes/promise-catch.js +147 -0
  359. package/lib/performance/site-fixes/pure-js-hashing.js +68 -0
  360. package/lib/performance/site-fixes/query-loop-collections.js +202 -0
  361. package/lib/performance/site-fixes/query-loop-lookups.js +98 -0
  362. package/lib/performance/site-fixes/query-loop-materialization.js +279 -0
  363. package/lib/performance/site-fixes/query-loop-names.js +35 -0
  364. package/lib/performance/site-fixes/query-loop-nodes.js +162 -0
  365. package/lib/performance/site-fixes/query-loop-pg-redis.js +203 -0
  366. package/lib/performance/site-fixes/query-loop-prisma.js +304 -0
  367. package/lib/performance/site-fixes/query-loop-sites.js +317 -0
  368. package/lib/performance/site-fixes/query-loop-typeorm.js +294 -0
  369. package/lib/performance/site-fixes/query-loops.js +57 -0
  370. package/lib/performance/site-fixes/query-shapes.js +573 -0
  371. package/lib/performance/site-fixes/queue-loops.js +231 -0
  372. package/lib/performance/site-fixes/redis-keys.js +213 -0
  373. package/lib/performance/site-fixes/scope-names.js +30 -0
  374. package/lib/performance/site-fixes/service-loop-ast.js +85 -0
  375. package/lib/performance/site-fixes/service-loop-callee.js +57 -0
  376. package/lib/performance/site-fixes/service-loop-concurrent.js +88 -0
  377. package/lib/performance/site-fixes/service-loop-imports.js +68 -0
  378. package/lib/performance/site-fixes/service-loop-read-batch.js +255 -0
  379. package/lib/performance/site-fixes/service-loop-siblings.js +170 -0
  380. package/lib/performance/site-fixes/service-loop-signature.js +33 -0
  381. package/lib/performance/site-fixes/service-loop-sites.js +141 -0
  382. package/lib/performance/site-fixes/service-loop-write-batch.js +94 -0
  383. package/lib/performance/site-fixes/service-loops.js +153 -0
  384. package/lib/performance/site-fixes/small-rewrites.js +210 -0
  385. package/lib/performance/site-fixes/streams.js +150 -0
  386. package/lib/performance/site-fixes/sync-calls.js +485 -0
  387. package/lib/performance/site-fixes/sync-imports.js +170 -0
  388. package/lib/performance/site-fixes/transaction-escape.js +40 -0
  389. package/lib/performance/site-fixes/transaction-io.js +280 -0
  390. package/lib/performance/site-fixes/typeorm-updates.js +277 -0
  391. package/lib/performance/site-fixes/typeorm.js +239 -0
  392. package/lib/performance/site-fixes/types/module-binding.js +1 -0
  393. package/lib/performance/site-fixes/upload-limits.js +74 -0
  394. package/lib/performance/site-fixes/workbook-decodes.js +254 -0
  395. package/lib/performance/site-fixes/writes.js +342 -0
  396. package/lib/performance/sort-extreme.js +142 -0
  397. package/lib/performance/source-inputs.js +71 -0
  398. package/lib/performance/source-options.js +103 -0
  399. package/lib/performance/source-pillars.js +23 -0
  400. package/lib/performance/source-text.js +59 -0
  401. package/lib/performance/span-timing.js +54 -0
  402. package/lib/performance/sql/locations.js +91 -0
  403. package/lib/performance/sql/mysql-tokens.js +393 -0
  404. package/lib/performance/sql/pg-parser.js +330 -0
  405. package/lib/performance/stream-errors.js +650 -0
  406. package/lib/performance/traces.js +363 -0
  407. package/lib/performance/transaction-io.js +427 -0
  408. package/lib/performance/typeorm-projection.js +261 -0
  409. package/lib/performance/typeorm-transaction-loops.js +143 -0
  410. package/lib/performance/typeorm-unused-count.js +36 -0
  411. package/lib/performance/typeorm-updates.js +268 -0
  412. package/lib/performance/types/ast-grep-match.js +2 -0
  413. package/lib/performance/types/batch-plan.js +1 -0
  414. package/lib/performance/types/batched-fix-input.js +1 -0
  415. package/lib/performance/types/call-site.js +1 -0
  416. package/lib/performance/types/callee-helper.js +1 -0
  417. package/lib/performance/types/client-family.js +1 -0
  418. package/lib/performance/types/collections.js +1 -0
  419. package/lib/performance/types/contract-findings.js +3 -0
  420. package/lib/performance/types/db-cli.js +1 -0
  421. package/lib/performance/types/db-connection.js +1 -0
  422. package/lib/performance/types/db-model.js +3 -0
  423. package/lib/performance/types/db-plan-findings.js +1 -0
  424. package/lib/performance/types/db-plan.js +2 -0
  425. package/lib/performance/types/db-snapshot.js +1 -0
  426. package/lib/performance/types/declaration-link.js +2 -0
  427. package/lib/performance/types/decorator-call.js +1 -0
  428. package/lib/performance/types/drizzle-query.js +1 -0
  429. package/lib/performance/types/editor-report.js +1 -0
  430. package/lib/performance/types/find-lookup-facts.js +3 -0
  431. package/lib/performance/types/helper-function.js +1 -0
  432. package/lib/performance/types/hoist-anchor.js +1 -0
  433. package/lib/performance/types/http-call.js +1 -0
  434. package/lib/performance/types/lookup-construction.js +1 -0
  435. package/lib/performance/types/lookup-placement.js +1 -0
  436. package/lib/performance/types/loop-key-site.js +1 -0
  437. package/lib/performance/types/loop-lookup.js +1 -0
  438. package/lib/performance/types/method-call.js +1 -0
  439. package/lib/performance/types/migration-extraction.js +1 -0
  440. package/lib/performance/types/migration-files.js +1 -0
  441. package/lib/performance/types/migration-operations.js +1 -0
  442. package/lib/performance/types/migrations.js +1 -0
  443. package/lib/performance/types/model-fallback.js +2 -0
  444. package/lib/performance/types/mysql-statements.js +2 -0
  445. package/lib/performance/types/native-modules.js +1 -0
  446. package/lib/performance/types/native-typescript.js +1 -0
  447. package/lib/performance/types/otlp-attributes.js +1 -0
  448. package/lib/performance/types/otlp-trace.js +1 -0
  449. package/lib/performance/types/page-count-pair.js +1 -0
  450. package/lib/performance/types/parallel-reads.js +1 -0
  451. package/lib/performance/types/performance-policy.js +1 -0
  452. package/lib/performance/types/pg-statements.js +1 -0
  453. package/lib/performance/types/plain-property.js +1 -0
  454. package/lib/performance/types/postgres-registry.js +1 -0
  455. package/lib/performance/types/prisma-schema.js +1 -0
  456. package/lib/performance/types/program-scan.js +1 -0
  457. package/lib/performance/types/project-indexes.js +1 -0
  458. package/lib/performance/types/query-loops.js +1 -0
  459. package/lib/performance/types/query-site.js +1 -0
  460. package/lib/performance/types/related-location.js +2 -0
  461. package/lib/performance/types/repeat-owner.js +1 -0
  462. package/lib/performance/types/request-handler.js +1 -0
  463. package/lib/performance/types/request-input.js +1 -0
  464. package/lib/performance/types/schema-model.js +3 -0
  465. package/lib/performance/types/sibling-declaration.js +1 -0
  466. package/lib/performance/types/source-analyzer.js +1 -0
  467. package/lib/performance/types/source-check-values.js +1 -0
  468. package/lib/performance/types/source-command.js +1 -0
  469. package/lib/performance/types/source-position.js +2 -0
  470. package/lib/performance/types/source-scan-values.js +1 -0
  471. package/lib/performance/types/statement-range.js +2 -0
  472. package/lib/performance/types/typeorm-save-shape.js +1 -0
  473. package/lib/performance/types/typescript-binder.js +1 -0
  474. package/lib/performance/types/typescript-token-lookup.js +1 -0
  475. package/lib/performance/types/typescript-token-position.js +1 -0
  476. package/lib/performance/unbounded-list-queries.js +600 -0
  477. package/lib/performance/unscanned-javascript.js +29 -0
  478. package/lib/performance/upload-limits.js +68 -0
  479. package/lib/performance/vendor/README.md +7 -0
  480. package/lib/performance/vendor/typescript/LICENSE +55 -0
  481. package/lib/performance/vendor/typescript/NOTICE.txt +405 -0
  482. package/lib/performance/vendor/typescript/dist/api/compilerOptions.generated.js +8 -0
  483. package/lib/performance/vendor/typescript/dist/api/diagnosticFormatter.js +169 -0
  484. package/lib/performance/vendor/typescript/dist/api/fs.js +70 -0
  485. package/lib/performance/vendor/typescript/dist/api/fsCallbacks.js +111 -0
  486. package/lib/performance/vendor/typescript/dist/api/node/encoder.generated.js +74 -0
  487. package/lib/performance/vendor/typescript/dist/api/node/encoder.js +292 -0
  488. package/lib/performance/vendor/typescript/dist/api/node/msgpack.js +212 -0
  489. package/lib/performance/vendor/typescript/dist/api/node/node.generated.js +884 -0
  490. package/lib/performance/vendor/typescript/dist/api/node/node.infrastructure.js +102 -0
  491. package/lib/performance/vendor/typescript/dist/api/node/node.js +453 -0
  492. package/lib/performance/vendor/typescript/dist/api/node/protocol.generated.js +241 -0
  493. package/lib/performance/vendor/typescript/dist/api/node/protocol.js +33 -0
  494. package/lib/performance/vendor/typescript/dist/api/node/wtf8.js +130 -0
  495. package/lib/performance/vendor/typescript/dist/api/options.js +32 -0
  496. package/lib/performance/vendor/typescript/dist/api/path.js +884 -0
  497. package/lib/performance/vendor/typescript/dist/api/prepareCompilerOptions.generated.js +24 -0
  498. package/lib/performance/vendor/typescript/dist/api/proto.generated.js +21 -0
  499. package/lib/performance/vendor/typescript/dist/api/proto.js +50 -0
  500. package/lib/performance/vendor/typescript/dist/api/sourceFileCache.js +300 -0
  501. package/lib/performance/vendor/typescript/dist/api/sync/api.js +5408 -0
  502. package/lib/performance/vendor/typescript/dist/api/sync/client.js +174 -0
  503. package/lib/performance/vendor/typescript/dist/api/sync/generatorSupport.js +338 -0
  504. package/lib/performance/vendor/typescript/dist/api/syncChannel.js +526 -0
  505. package/lib/performance/vendor/typescript/dist/api/timing.js +149 -0
  506. package/lib/performance/vendor/typescript/dist/api/timingDump.js +38 -0
  507. package/lib/performance/vendor/typescript/dist/api/userPreferences.generated.js +3 -0
  508. package/lib/performance/vendor/typescript/dist/ast/ast.generated.js +4 -0
  509. package/lib/performance/vendor/typescript/dist/ast/ast.js +8 -0
  510. package/lib/performance/vendor/typescript/dist/ast/astnav.js +741 -0
  511. package/lib/performance/vendor/typescript/dist/ast/clone.js +104 -0
  512. package/lib/performance/vendor/typescript/dist/ast/factory.generated.js +5751 -0
  513. package/lib/performance/vendor/typescript/dist/ast/index.js +25 -0
  514. package/lib/performance/vendor/typescript/dist/ast/is.generated.js +1400 -0
  515. package/lib/performance/vendor/typescript/dist/ast/is.js +456 -0
  516. package/lib/performance/vendor/typescript/dist/ast/jsdoc.js +208 -0
  517. package/lib/performance/vendor/typescript/dist/ast/modifiers.js +41 -0
  518. package/lib/performance/vendor/typescript/dist/ast/scanner.js +2231 -0
  519. package/lib/performance/vendor/typescript/dist/ast/spanMap.js +417 -0
  520. package/lib/performance/vendor/typescript/dist/ast/utils.js +318 -0
  521. package/lib/performance/vendor/typescript/dist/ast/visitor.generated.js +979 -0
  522. package/lib/performance/vendor/typescript/dist/ast/visitor.js +87 -0
  523. package/lib/performance/vendor/typescript/dist/enums/caseSensitivity.js +7 -0
  524. package/lib/performance/vendor/typescript/dist/enums/characterCodes.js +130 -0
  525. package/lib/performance/vendor/typescript/dist/enums/checkFlags.js +36 -0
  526. package/lib/performance/vendor/typescript/dist/enums/commentDirectiveType.js +6 -0
  527. package/lib/performance/vendor/typescript/dist/enums/completionItemKind.js +30 -0
  528. package/lib/performance/vendor/typescript/dist/enums/diagnosticCategory.js +9 -0
  529. package/lib/performance/vendor/typescript/dist/enums/diagnosticDirectivePolicy.js +7 -0
  530. package/lib/performance/vendor/typescript/dist/enums/elementFlags.js +14 -0
  531. package/lib/performance/vendor/typescript/dist/enums/emitOnly.js +8 -0
  532. package/lib/performance/vendor/typescript/dist/enums/indexKind.js +7 -0
  533. package/lib/performance/vendor/typescript/dist/enums/internalSymbolName.js +25 -0
  534. package/lib/performance/vendor/typescript/dist/enums/jsDeclarationKind.js +12 -0
  535. package/lib/performance/vendor/typescript/dist/enums/jsxEmit.js +11 -0
  536. package/lib/performance/vendor/typescript/dist/enums/languageVariant.js +6 -0
  537. package/lib/performance/vendor/typescript/dist/enums/modifierFlags.js +44 -0
  538. package/lib/performance/vendor/typescript/dist/enums/moduleDetectionKind.js +9 -0
  539. package/lib/performance/vendor/typescript/dist/enums/moduleKind.js +19 -0
  540. package/lib/performance/vendor/typescript/dist/enums/moduleResolutionKind.js +11 -0
  541. package/lib/performance/vendor/typescript/dist/enums/newLineKind.js +8 -0
  542. package/lib/performance/vendor/typescript/dist/enums/nodeBuilderFlags.js +38 -0
  543. package/lib/performance/vendor/typescript/dist/enums/nodeFlags.js +46 -0
  544. package/lib/performance/vendor/typescript/dist/enums/objectFlags.js +53 -0
  545. package/lib/performance/vendor/typescript/dist/enums/outerExpressionKinds.js +18 -0
  546. package/lib/performance/vendor/typescript/dist/enums/regularExpressionFlags.js +14 -0
  547. package/lib/performance/vendor/typescript/dist/enums/scriptKind.js +11 -0
  548. package/lib/performance/vendor/typescript/dist/enums/scriptTarget.js +20 -0
  549. package/lib/performance/vendor/typescript/dist/enums/signatureFlags.js +17 -0
  550. package/lib/performance/vendor/typescript/dist/enums/signatureKind.js +7 -0
  551. package/lib/performance/vendor/typescript/dist/enums/spanMapFeature.js +27 -0
  552. package/lib/performance/vendor/typescript/dist/enums/spanMapFidelity.js +9 -0
  553. package/lib/performance/vendor/typescript/dist/enums/spanMapKind.js +8 -0
  554. package/lib/performance/vendor/typescript/dist/enums/symbolFlags.js +72 -0
  555. package/lib/performance/vendor/typescript/dist/enums/symbolOwnerKind.js +7 -0
  556. package/lib/performance/vendor/typescript/dist/enums/syntaxKind.js +392 -0
  557. package/lib/performance/vendor/typescript/dist/enums/tokenFlags.js +32 -0
  558. package/lib/performance/vendor/typescript/dist/enums/typeFlags.js +78 -0
  559. package/lib/performance/vendor/typescript/dist/enums/typeFormatFlags.js +31 -0
  560. package/lib/performance/vendor/typescript/dist/enums/typePredicateKind.js +9 -0
  561. package/lib/performance/vendor/typescript/dist/internal/utils.js +25 -0
  562. package/lib/performance/vendor/typescript/lib/getExePath.js +70 -0
  563. package/lib/performance/vendor/typescript/package.json +93 -0
  564. package/lib/performance/vendor/typescript/vendor/vscode-jsonrpc/License.txt +11 -0
  565. package/lib/performance/watch.js +99 -0
  566. package/lib/performance/workbook-decodes.js +147 -0
  567. package/lib/reliability/analyze.js +29 -0
  568. package/lib/reliability/boundary-access.js +521 -0
  569. package/lib/reliability/cli.js +20 -0
  570. package/lib/reliability/resource-leaks.js +526 -0
  571. package/lib/reliability/rule-ids.js +225 -0
  572. package/lib/reliability/site-fixes/boundary-access.js +80 -0
  573. package/lib/reliability/site-fixes/resource-leaks.js +125 -0
  574. package/lib/reliability/site-fixes/suspicious-logic.js +115 -0
  575. package/lib/reliability/source-helpers.js +32 -0
  576. package/lib/reliability/sql-insert-terminator.js +106 -0
  577. package/lib/reliability/standalone-sources.js +54 -0
  578. package/lib/reliability/suspicious-logic.js +364 -0
  579. package/lib/reliability/swallowed-errors.js +321 -0
  580. package/lib/reliability/usage.js +16 -0
  581. package/lib/reliability/walk.js +16 -0
  582. package/lib/security/analyze.js +129 -0
  583. package/lib/security/auth-crypto/comparison.js +97 -0
  584. package/lib/security/auth-crypto/hashing.js +302 -0
  585. package/lib/security/auth-crypto/index.js +32 -0
  586. package/lib/security/auth-crypto/jwt.js +468 -0
  587. package/lib/security/auth-crypto/plaintext-password.js +171 -0
  588. package/lib/security/auth-crypto/random.js +124 -0
  589. package/lib/security/auth-crypto/rate-limits.js +326 -0
  590. package/lib/security/auth-crypto/rule-ids.js +17 -0
  591. package/lib/security/auth-crypto/secrets.js +331 -0
  592. package/lib/security/auth-crypto/shared.js +105 -0
  593. package/lib/security/auth-crypto/transport-and-ciphers.js +217 -0
  594. package/lib/security/bindings.js +286 -0
  595. package/lib/security/cli.js +293 -0
  596. package/lib/security/declarations.js +25 -0
  597. package/lib/security/deps/advisory.js +142 -0
  598. package/lib/security/deps/cli.js +75 -0
  599. package/lib/security/deps/lockfiles.js +310 -0
  600. package/lib/security/deps/osv.js +217 -0
  601. package/lib/security/deps/rule-ids.js +6 -0
  602. package/lib/security/deps/scan.js +69 -0
  603. package/lib/security/examples/auth-crypto.cjs +57 -0
  604. package/lib/security/examples/deps.cjs +9 -0
  605. package/lib/security/examples/exposure.cjs +98 -0
  606. package/lib/security/examples/files.cjs +29 -0
  607. package/lib/security/examples/injection.cjs +53 -0
  608. package/lib/security/examples/moved.cjs +17 -0
  609. package/lib/security/examples/request-forgery.cjs +25 -0
  610. package/lib/security/exposure/backend-security-mastery.js +80 -0
  611. package/lib/security/exposure/cookies.js +173 -0
  612. package/lib/security/exposure/cors-origin-regex.js +177 -0
  613. package/lib/security/exposure/cors.js +217 -0
  614. package/lib/security/exposure/error-responses.js +437 -0
  615. package/lib/security/exposure/frontend-security.js +547 -0
  616. package/lib/security/exposure/graphql.js +131 -0
  617. package/lib/security/exposure/index.js +52 -0
  618. package/lib/security/exposure/literals.js +133 -0
  619. package/lib/security/exposure/logging.js +168 -0
  620. package/lib/security/exposure/mass-assignment.js +165 -0
  621. package/lib/security/exposure/password-response.js +315 -0
  622. package/lib/security/exposure/prototype-pollution.js +291 -0
  623. package/lib/security/exposure/reflected-xss.js +57 -0
  624. package/lib/security/exposure/report.js +10 -0
  625. package/lib/security/exposure/rule-ids.js +28 -0
  626. package/lib/security/exposure/storage-acl.js +87 -0
  627. package/lib/security/exposure/template-autoescape.js +39 -0
  628. package/lib/security/exposure/url-secrets.js +164 -0
  629. package/lib/security/exposure/validation-pipe.js +36 -0
  630. package/lib/security/exposure/xml.js +28 -0
  631. package/lib/security/file-context.js +82 -0
  632. package/lib/security/files/compose.js +79 -0
  633. package/lib/security/files/dockerfile.js +206 -0
  634. package/lib/security/files/index.js +100 -0
  635. package/lib/security/files/project-files.js +103 -0
  636. package/lib/security/files/review-directive.js +30 -0
  637. package/lib/security/files/rule-ids.js +10 -0
  638. package/lib/security/files/secret-values.js +98 -0
  639. package/lib/security/files/secrets.js +121 -0
  640. package/lib/security/injection/code.js +108 -0
  641. package/lib/security/injection/command.js +127 -0
  642. package/lib/security/injection/index.js +13 -0
  643. package/lib/security/injection/nosql.js +266 -0
  644. package/lib/security/injection/redos.js +609 -0
  645. package/lib/security/injection/regex.js +48 -0
  646. package/lib/security/injection/rule-ids.js +16 -0
  647. package/lib/security/injection/shared.js +119 -0
  648. package/lib/security/injection/sql.js +432 -0
  649. package/lib/security/pg-dynamic-query.js +30 -0
  650. package/lib/security/pg-identifier-guards.js +155 -0
  651. package/lib/security/phase5-rules.js +515 -0
  652. package/lib/security/polyglot.js +8 -0
  653. package/lib/security/request-forgery/index.js +11 -0
  654. package/lib/security/request-forgery/open-redirect.js +336 -0
  655. package/lib/security/request-forgery/path-traversal.js +103 -0
  656. package/lib/security/request-forgery/rule-ids.js +9 -0
  657. package/lib/security/request-forgery/shared.js +355 -0
  658. package/lib/security/request-forgery/ssrf.js +133 -0
  659. package/lib/security/request-forgery/upload-filename.js +75 -0
  660. package/lib/security/request-forgery/zip-slip.js +42 -0
  661. package/lib/security/rule-descriptions.js +84 -0
  662. package/lib/security/rule-ids.js +142 -0
  663. package/lib/security/scope/drizzle-policy.js +197 -0
  664. package/lib/security/scope/query-policy.js +156 -0
  665. package/lib/security/site-fixes/auth-crypto.js +223 -0
  666. package/lib/security/site-fixes/backend-security-fixes.js +86 -0
  667. package/lib/security/site-fixes/error-responses.js +84 -0
  668. package/lib/security/site-fixes/exposure.js +120 -0
  669. package/lib/security/site-fixes/files.js +45 -0
  670. package/lib/security/site-fixes/frontend-security-fixes.js +73 -0
  671. package/lib/security/site-fixes/injection.js +119 -0
  672. package/lib/security/site-fixes/jwt.js +89 -0
  673. package/lib/security/site-fixes/list-edits.js +16 -0
  674. package/lib/security/site-fixes/request-forgery.js +117 -0
  675. package/lib/security/site-fixes/secret-comparison.js +107 -0
  676. package/lib/security/site-fixes/template-autoescape.js +25 -0
  677. package/lib/security/taint/archive-sources.js +127 -0
  678. package/lib/security/taint/filename-guard.js +110 -0
  679. package/lib/security/taint/guards.js +274 -0
  680. package/lib/security/taint/index.js +559 -0
  681. package/lib/security/taint/propagate.js +117 -0
  682. package/lib/security/taint/sanitizers.js +67 -0
  683. package/lib/security/taint/sources.js +357 -0
  684. package/lib/security/taint/summaries.js +207 -0
  685. package/lib/security/taint/url-parts.js +264 -0
  686. package/lib/security/taint/validators.js +420 -0
  687. package/lib/security/types/condition-guards.js +1 -0
  688. package/lib/security/types/file-finding.js +1 -0
  689. package/lib/security/types/inspectable-type.js +1 -0
  690. package/lib/security/types/lockfile.js +1 -0
  691. package/lib/security/types/osv-vulnerability.js +1 -0
  692. package/lib/security/types/project-files.js +1 -0
  693. package/lib/security/types/propagation.js +1 -0
  694. package/lib/security/types/rule-example.js +1 -0
  695. package/lib/security/types/schema-call.js +1 -0
  696. package/lib/security/types/security-check.js +1 -0
  697. package/lib/shared/agent-init.js +235 -0
  698. package/lib/shared/agent-session.js +28 -0
  699. package/lib/shared/agent-verify.js +239 -0
  700. package/lib/shared/atomic-write.js +52 -0
  701. package/lib/shared/baseline-flags.js +33 -0
  702. package/lib/shared/baseline.js +237 -0
  703. package/lib/shared/build-output.js +22 -0
  704. package/lib/shared/check.js +254 -0
  705. package/lib/shared/config.js +286 -0
  706. package/lib/shared/coverage-notes.js +27 -0
  707. package/lib/shared/error-code.js +9 -0
  708. package/lib/shared/execution-context.js +278 -0
  709. package/lib/shared/explain.js +34 -0
  710. package/lib/shared/fix-command.js +23 -0
  711. package/lib/shared/fix-convergence.js +389 -0
  712. package/lib/shared/fix-handoff.js +57 -0
  713. package/lib/shared/fix-history.js +303 -0
  714. package/lib/shared/fix-hunks.js +108 -0
  715. package/lib/shared/fix-imports.js +233 -0
  716. package/lib/shared/fix-presentation-comments.js +253 -0
  717. package/lib/shared/fix-presentation-prettier.js +233 -0
  718. package/lib/shared/fix-presentation-rows.js +157 -0
  719. package/lib/shared/fix-presentation-style.js +230 -0
  720. package/lib/shared/fix-presentation.js +177 -0
  721. package/lib/shared/fix-rationales.js +151 -0
  722. package/lib/shared/fix-recipes.js +101 -0
  723. package/lib/shared/fix-safety.js +64 -0
  724. package/lib/shared/fix-terminal.js +65 -0
  725. package/lib/shared/fix-typecheck.js +188 -0
  726. package/lib/shared/fix.js +257 -0
  727. package/lib/shared/formats/contract-rules.js +9 -0
  728. package/lib/shared/formats/finding-location.js +31 -0
  729. package/lib/shared/formats/github.js +36 -0
  730. package/lib/shared/formats/index.js +29 -0
  731. package/lib/shared/formats/sarif.js +91 -0
  732. package/lib/shared/function-summaries.js +571 -0
  733. package/lib/shared/function-syntax.js +86 -0
  734. package/lib/shared/git-hook.js +153 -0
  735. package/lib/shared/git-paths.js +38 -0
  736. package/lib/shared/glob.js +53 -0
  737. package/lib/shared/heap-limit.js +71 -0
  738. package/lib/shared/hot-path-graph.js +268 -0
  739. package/lib/shared/hot-path.js +20 -0
  740. package/lib/shared/impact-levels.js +49 -0
  741. package/lib/shared/is-record.js +5 -0
  742. package/lib/shared/managed-blocks.js +54 -0
  743. package/lib/shared/notify-editor.js +50 -0
  744. package/lib/shared/pending-review.js +117 -0
  745. package/lib/shared/pillar-rules.js +6 -0
  746. package/lib/shared/pillars.js +384 -0
  747. package/lib/shared/polyglot-compatibility.js +105 -0
  748. package/lib/shared/project-root.js +35 -0
  749. package/lib/shared/real-target.js +23 -0
  750. package/lib/shared/reason-groups.js +20 -0
  751. package/lib/shared/review-delivery.js +33 -0
  752. package/lib/shared/review-mcp.js +262 -0
  753. package/lib/shared/review-request.js +59 -0
  754. package/lib/shared/rule-registry.js +57 -0
  755. package/lib/shared/scan-cache.js +234 -0
  756. package/lib/shared/shell-argument.js +9 -0
  757. package/lib/shared/source-report.js +156 -0
  758. package/lib/shared/types/baseline.js +1 -0
  759. package/lib/shared/types/checker-run.js +1 -0
  760. package/lib/shared/types/cli-finding.js +1 -0
  761. package/lib/shared/types/fix-hunks.js +1 -0
  762. package/lib/shared/types/fix-presentation.js +1 -0
  763. package/lib/shared/types/fix-run.js +1 -0
  764. package/lib/shared/types/function-summaries.js +1 -0
  765. package/lib/shared/types/managed-blocks.js +1 -0
  766. package/lib/shared/types/pillar-name.js +1 -0
  767. package/lib/shared/types/report-formats.js +1 -0
  768. package/lib/shared/types/review-event.js +1 -0
  769. package/lib/shared/types/review-history.js +1 -0
  770. package/lib/shared/types/settings.js +1 -0
  771. package/lib/shared/types/source-report.js +1 -0
  772. package/lib/shared/types/typescript-assignment-target.js +1 -0
  773. package/lib/shared/types/typescript-internals.js +1 -0
  774. package/lib/shared/types/typescript-module-resolution.js +1 -0
  775. package/lib/shared/types/typescript-outer-expression.js +1 -0
  776. package/lib/shared/types.js +1 -0
  777. package/lib/shared/workspaces.js +299 -0
  778. package/package.json +127 -4
  779. package/plugin/.claude-plugin/plugin.json +9 -0
  780. package/plugin/commands/loadwise.md +24 -0
  781. package/plugin/hooks/check-edited-file.js +142 -0
  782. package/plugin/hooks/hooks.json +17 -0
  783. package/polyglot/maintainability/rules.js +159 -0
  784. package/polyglot/maintainability/sgconfig.yml +12 -0
  785. package/polyglot/performance/rules/csharp.yml +104 -0
  786. package/polyglot/performance/rules/go.yml +123 -0
  787. package/polyglot/performance/rules/input.yml +37 -0
  788. package/polyglot/performance/rules/java.yml +115 -0
  789. package/polyglot/performance/rules/python.yml +159 -0
  790. package/polyglot/performance/rules/rust.yml +88 -0
  791. package/polyglot/performance/sgconfig.yml +8 -0
  792. package/polyglot/reliability/rules/csharp.yml +65 -0
  793. package/polyglot/reliability/rules/go.yml +76 -0
  794. package/polyglot/reliability/rules/java.yml +41 -0
  795. package/polyglot/reliability/rules/python.yml +32 -0
  796. package/polyglot/reliability/rules/rust.yml +34 -0
  797. package/polyglot/reliability/sgconfig.yml +8 -0
  798. package/polyglot/security/rules/csharp.yml +28 -0
  799. package/polyglot/security/rules/go.yml +42 -0
  800. package/polyglot/security/rules/java.yml +17 -0
  801. package/polyglot/security/rules/python.yml +48 -0
  802. package/polyglot/security/rules/rust.yml +23 -0
  803. package/polyglot/security/sgconfig.yml +8 -0
  804. package/schema/loadwise.config.schema.json +725 -0
@@ -0,0 +1,241 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { createRequire } from 'node:module';
4
+ import { parseEnv } from 'node:util';
5
+ import { isTempRoot, safeExists } from '../../shared/project-root.js';
6
+ import { createRedactor, parseConnectionUrl } from './redact.js';
7
+ const defaultUrlEnv = 'DATABASE_URL';
8
+ const connectTimeoutMs = 10_000;
9
+ const applicationName = 'loadwise';
10
+ const engineBySchemes = new Map([
11
+ ['postgres', 'postgres'],
12
+ ['postgresql', 'postgres'],
13
+ ['mysql', 'mysql'],
14
+ ['mysql2', 'mysql'],
15
+ ['mongodb', 'mongo'],
16
+ ['mongodb+srv', 'mongo'],
17
+ ]);
18
+ const engineByDefaultPort = new Map([
19
+ ['5432', 'postgres'],
20
+ ['3306', 'mysql'],
21
+ ['27017', 'mongo'],
22
+ ]);
23
+ const discreteVariables = {
24
+ host: ['DB_HOST'],
25
+ port: ['DB_PORT'],
26
+ user: ['DB_USER', 'DB_USERNAME'],
27
+ password: ['DB_PASSWORD'],
28
+ database: ['DB_NAME', 'DB_DATABASE'],
29
+ };
30
+ const driverPackages = { postgres: 'pg', mysql: 'mysql2', mongo: 'mongodb' };
31
+ // Usage and setup problems: exit 2 with a message that never contains connection values.
32
+ class DbUsageError extends Error {
33
+ }
34
+ function pickVariable(source, names) {
35
+ for (const name of names) {
36
+ const value = source[name];
37
+ if (typeof value === 'string' && value !== '')
38
+ return { name, value };
39
+ }
40
+ }
41
+ // --env-file is read as data, never loaded into process.env, so the rest of the process cannot see
42
+ // it.
43
+ function readVariables({ env, envFile, readFile }) {
44
+ if (!envFile)
45
+ return env;
46
+ let text;
47
+ try {
48
+ text = readFile(envFile);
49
+ }
50
+ catch {
51
+ throw new DbUsageError('Could not read the --env-file.');
52
+ }
53
+ return parseEnv(text);
54
+ }
55
+ function fromUrl(urlEnv, url, requestedEngine) {
56
+ const parsed = parseConnectionUrl(url);
57
+ if (!parsed || parsed.hosts.length === 0) {
58
+ throw new DbUsageError(`\`${urlEnv}\` does not hold a connection URL of the form scheme://user:password@host/db.`);
59
+ }
60
+ const engine = engineBySchemes.get(parsed.scheme);
61
+ if (!engine)
62
+ throw new DbUsageError(`\`${urlEnv}\` uses an unsupported scheme; expected postgres, mysql or mongodb.`);
63
+ if (requestedEngine && requestedEngine !== engine) {
64
+ throw new DbUsageError(`--engine ${requestedEngine} does not match the ${engine} URL in \`${urlEnv}\`.`);
65
+ }
66
+ return {
67
+ engine,
68
+ url,
69
+ envVarNames: [urlEnv],
70
+ databaseName: parsed.database,
71
+ redact: createRedactor({
72
+ url,
73
+ user: parsed.user,
74
+ password: parsed.password,
75
+ hosts: parsed.hosts,
76
+ extra: [parsed.rawUserInfo],
77
+ }),
78
+ };
79
+ }
80
+ function fromParts(source, requestedEngine) {
81
+ const picked = Object.fromEntries(Object.entries(discreteVariables).map(([field, names]) => [field, pickVariable(source, names)]));
82
+ const parts = Object.fromEntries(Object.entries(picked).map(([field, entry]) => [field, entry?.value]));
83
+ const engine = requestedEngine ?? (parts.port === undefined ? undefined : engineByDefaultPort.get(parts.port));
84
+ if (!engine)
85
+ throw new DbUsageError('Pass --engine postgres|mysql|mongo: DB_PORT does not identify the database.');
86
+ return {
87
+ engine,
88
+ parts,
89
+ envVarNames: Object.values(picked).flatMap((entry) => (entry ? [entry.name] : [])),
90
+ databaseName: parts.database ?? '',
91
+ redact: createRedactor({
92
+ user: parts.user,
93
+ password: parts.password,
94
+ hosts: parts.host === undefined ? [] : [parts.host],
95
+ }),
96
+ };
97
+ }
98
+ function resolveConnection({ env = process.env, urlEnv, envFile, engine, readFile = (file) => fs.readFileSync(file, 'utf8'), }) {
99
+ const source = readVariables({ env, envFile, readFile });
100
+ const urlVariable = urlEnv ?? defaultUrlEnv;
101
+ const url = source[urlVariable];
102
+ if (typeof url === 'string' && url !== '')
103
+ return fromUrl(urlVariable, url, engine);
104
+ if (urlEnv)
105
+ throw new DbUsageError(`\`${urlEnv}\` is not set${envFile ? ' in the --env-file' : ''}.`);
106
+ if (pickVariable(source, discreteVariables.host))
107
+ return fromParts(source, engine);
108
+ throw new DbUsageError(`No connection: set ${defaultUrlEnv} (or name another variable with --url-env), ` +
109
+ 'or DB_HOST, DB_PORT, DB_USER, DB_PASSWORD and DB_NAME.');
110
+ }
111
+ // The nearest package.json marks the project whose own driver is used.
112
+ function findProjectRoot(start) {
113
+ const begin = path.resolve(start);
114
+ for (let directory = begin;; directory = path.dirname(directory)) {
115
+ if (isTempRoot(directory))
116
+ return begin;
117
+ if (safeExists(path.join(directory, 'package.json')))
118
+ return directory;
119
+ if (path.dirname(directory) === directory)
120
+ return begin;
121
+ }
122
+ }
123
+ function isMissing(error, specifier) {
124
+ return (typeof error === 'object' &&
125
+ error !== null &&
126
+ 'code' in error &&
127
+ error.code === 'MODULE_NOT_FOUND' &&
128
+ 'message' in error &&
129
+ String(error.message).includes(`'${specifier}'`));
130
+ }
131
+ function loadDriver(engine, projectRoot) {
132
+ const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
133
+ const attempts = engine === 'postgres'
134
+ ? [['pg', (module) => module]]
135
+ : engine === 'mysql'
136
+ ? [['mysql2/promise', (module) => module]]
137
+ : [
138
+ ['mongodb', (module) => module],
139
+ ['mongoose', (module) => module.mongo],
140
+ ];
141
+ for (const [specifier, select] of attempts) {
142
+ try {
143
+ const loaded = projectRequire(specifier);
144
+ return select(loaded);
145
+ }
146
+ catch (error) {
147
+ if (!isMissing(error, specifier))
148
+ throw error;
149
+ }
150
+ }
151
+ throw new DbUsageError(`\`${driverPackages[engine]}\` is not installed in this project. ` +
152
+ "`db` uses the project's own driver; install it there or run from the project root.");
153
+ }
154
+ async function connectPostgres(driver, connection) {
155
+ const settings = connection.url === undefined
156
+ ? {
157
+ host: connection.parts.host,
158
+ port: connection.parts.port ? Number(connection.parts.port) : undefined,
159
+ user: connection.parts.user,
160
+ password: connection.parts.password,
161
+ database: connection.parts.database,
162
+ }
163
+ : { connectionString: connection.url };
164
+ const client = new driver.Client({ ...settings, connectionTimeoutMillis: connectTimeoutMs });
165
+ // An idle-socket error must not crash the process with an unredacted stack.
166
+ client.on('error', () => { });
167
+ await client.connect();
168
+ return {
169
+ engine: 'postgres',
170
+ query: async (text, params) => (await client.query(params ? { text, values: params } : text)).rows,
171
+ close: () => client.end(),
172
+ // Destroying the socket ends the server session, so an open transaction cannot linger.
173
+ destroy: async () => {
174
+ client.connection?.stream?.destroy();
175
+ await client.end().catch(() => { });
176
+ },
177
+ };
178
+ }
179
+ async function connectMysql(driver, connection) {
180
+ const settings = connection.url === undefined
181
+ ? {
182
+ host: connection.parts.host,
183
+ port: connection.parts.port ? Number(connection.parts.port) : undefined,
184
+ user: connection.parts.user,
185
+ password: connection.parts.password,
186
+ database: connection.parts.database,
187
+ }
188
+ : { uri: connection.url };
189
+ const client = await driver.createConnection({
190
+ ...settings,
191
+ connectTimeout: connectTimeoutMs,
192
+ multipleStatements: false,
193
+ });
194
+ client.on?.('error', () => { });
195
+ return {
196
+ engine: 'mysql',
197
+ query: async (text, params) => (await client.query(text, params))[0],
198
+ close: () => client.end(),
199
+ destroy: async () => client.destroy(),
200
+ };
201
+ }
202
+ function mongoUrl(connection) {
203
+ if (connection.url !== undefined)
204
+ return connection.url;
205
+ const { host, port, user, password, database } = connection.parts;
206
+ const credentials = user ? `${encodeURIComponent(user)}:${encodeURIComponent(password ?? '')}@` : '';
207
+ return `mongodb://${credentials}${host}${port ? ':' + port : ''}/${encodeURIComponent(database ?? '')}`;
208
+ }
209
+ async function connectMongo(driver, connection) {
210
+ const client = new driver.MongoClient(mongoUrl(connection), {
211
+ readPreference: 'secondaryPreferred',
212
+ serverSelectionTimeoutMS: connectTimeoutMs,
213
+ appName: applicationName,
214
+ });
215
+ await client.connect();
216
+ let databaseName;
217
+ try {
218
+ databaseName = connection.databaseName || client.db().databaseName;
219
+ }
220
+ catch (error) {
221
+ await client.close(true).catch(() => { });
222
+ throw error;
223
+ }
224
+ return {
225
+ engine: 'mongo',
226
+ databaseName,
227
+ command: (document, databaseOverride) => client.db(databaseOverride ?? databaseName).command(document, { readPreference: 'secondaryPreferred' }),
228
+ close: () => client.close(),
229
+ destroy: () => client.close(true),
230
+ };
231
+ }
232
+ function connect(driver, connection) {
233
+ if (connection.engine === 'postgres' && 'Client' in driver)
234
+ return connectPostgres(driver, connection);
235
+ if (connection.engine === 'mysql' && 'createConnection' in driver)
236
+ return connectMysql(driver, connection);
237
+ if (connection.engine === 'mongo' && 'MongoClient' in driver)
238
+ return connectMongo(driver, connection);
239
+ throw new TypeError(`The loaded driver does not match the ${connection.engine} connection.`);
240
+ }
241
+ export { DbUsageError, applicationName, defaultUrlEnv, resolveConnection, findProjectRoot, loadDriver, connect };
@@ -0,0 +1,194 @@
1
+ import { ensureLoaded, parseExplainCandidate } from '../sql/pg-parser.js';
2
+ import * as pgCatalog from './pg-catalog.js';
3
+ import * as mysqlCatalog from './mysql-catalog.js';
4
+ const explainableKinds = new Set(['SelectStmt', 'InsertStmt', 'UpdateStmt', 'DeleteStmt']);
5
+ const interruptExitCode = 130;
6
+ // The gateway refused to send something. Messages never quote the refused SQL.
7
+ class GatewayRefusal extends Error {
8
+ }
9
+ function loadMysqlCatalog() {
10
+ return mysqlCatalog;
11
+ }
12
+ function stripTerminator(sql) {
13
+ return sql.trim().replace(/;\s*$/, '');
14
+ }
15
+ async function validatePostgresExplain(sql, { analyze }) {
16
+ if (typeof sql !== 'string' || sql.trim() === '')
17
+ throw new GatewayRefusal('EXPLAIN needs a statement.');
18
+ await ensureLoaded();
19
+ const candidate = parseExplainCandidate(sql);
20
+ if ('error' in candidate)
21
+ throw new GatewayRefusal(`The statement does not parse: ${candidate.error.message}`);
22
+ if (!explainableKinds.has(candidate.kind ?? '')) {
23
+ throw new GatewayRefusal('Only SELECT, INSERT, UPDATE and DELETE statements can be explained.');
24
+ }
25
+ if (!analyze)
26
+ return;
27
+ // EXPLAIN ANALYZE executes the statement, so only a plain SELECT may reach it.
28
+ if (candidate.kind !== 'SelectStmt' || candidate.hasInto || candidate.hasLockingClause) {
29
+ throw new GatewayRefusal('EXPLAIN ANALYZE runs only plain SELECT statements (no INTO, FOR UPDATE or writes).');
30
+ }
31
+ if (candidate.hasDataModifyingCte) {
32
+ throw new GatewayRefusal('EXPLAIN ANALYZE refuses a SELECT whose WITH clause modifies data.');
33
+ }
34
+ }
35
+ function postgresExplainPrefix({ generic, analyze }) {
36
+ if (analyze)
37
+ return 'EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ';
38
+ return generic ? 'EXPLAIN (GENERIC_PLAN, FORMAT JSON) ' : 'EXPLAIN (FORMAT JSON) ';
39
+ }
40
+ function firstPlanDocument(rows) {
41
+ const value = rows?.[0]?.['QUERY PLAN'] ?? rows?.[0]?.EXPLAIN;
42
+ return typeof value === 'string' ? JSON.parse(value) : value;
43
+ }
44
+ /**
45
+ * The only code that talks to the driver. It exposes catalog(id), explain(validated SQL) and
46
+ * unit(); nothing that takes free SQL. `allowAnalyze` is set only by --analyze or --measure,
47
+ * `allowMeasure` only by --measure.
48
+ */
49
+ function createGateway(adapter, options = {}) {
50
+ const { allowAnalyze = false, allowMeasure = false, signals = process, exit = process.exit } = options;
51
+ const engine = adapter.engine;
52
+ const mysqlCatalog = engine === 'mysql' ? loadMysqlCatalog() : undefined;
53
+ const catalog = mysqlCatalog ?? pgCatalog;
54
+ let depth = 0;
55
+ let broken = false;
56
+ async function send(text, params) {
57
+ if (broken)
58
+ throw new GatewayRefusal('The connection was closed after an error.');
59
+ return adapter.query(text, params);
60
+ }
61
+ async function destroy() {
62
+ broken = true;
63
+ await adapter.destroy();
64
+ }
65
+ async function rollbackOrDestroy(rollbackStatement) {
66
+ try {
67
+ await send(rollbackStatement);
68
+ }
69
+ catch {
70
+ await destroy();
71
+ }
72
+ }
73
+ // Ctrl+C mid-transaction still rolls back, then ends the session so nothing can stay open.
74
+ async function withInterruptGuard(rollbackStatement, body) {
75
+ let interrupted = false;
76
+ const onInterrupt = () => {
77
+ if (interrupted)
78
+ return;
79
+ interrupted = true;
80
+ rollbackOrDestroy(rollbackStatement)
81
+ .then(() => destroy())
82
+ .catch(() => { })
83
+ .finally(() => exit(interruptExitCode));
84
+ };
85
+ signals.on('SIGINT', onInterrupt);
86
+ try {
87
+ return await body();
88
+ }
89
+ finally {
90
+ signals.off('SIGINT', onInterrupt);
91
+ }
92
+ }
93
+ async function open() {
94
+ for (const statement of catalog.sessionSetup)
95
+ await send(statement);
96
+ }
97
+ async function unit(body) {
98
+ if (depth > 0)
99
+ return body();
100
+ depth += 1;
101
+ try {
102
+ return await withInterruptGuard(catalog.control.rollback, async () => {
103
+ await send(catalog.control.begin);
104
+ try {
105
+ for (const statement of catalog.unitSetup) {
106
+ await send(statement);
107
+ }
108
+ return await body();
109
+ }
110
+ finally {
111
+ await rollbackOrDestroy(catalog.control.rollback);
112
+ }
113
+ });
114
+ }
115
+ finally {
116
+ depth -= 1;
117
+ }
118
+ }
119
+ async function catalogQuery(id, params) {
120
+ if (!Object.hasOwn(catalog.statements, id))
121
+ throw new GatewayRefusal(`Unknown catalog statement ${id}.`);
122
+ return unit(() => send(catalog.statements[id], params));
123
+ }
124
+ async function explain(sql, { generic = false, analyze = false } = {}) {
125
+ if (analyze && !allowAnalyze)
126
+ throw new GatewayRefusal('EXPLAIN ANALYZE needs --analyze or --measure.');
127
+ if (mysqlCatalog) {
128
+ if (analyze)
129
+ throw new GatewayRefusal('EXPLAIN ANALYZE is never run on MySQL.');
130
+ try {
131
+ mysqlCatalog.validateExplain(sql);
132
+ }
133
+ catch (error) {
134
+ throw new GatewayRefusal(error instanceof Error ? error.message : String(error));
135
+ }
136
+ return firstPlanDocument(await unit(() => send(mysqlCatalog.explainPrefix + stripTerminator(sql))));
137
+ }
138
+ await validatePostgresExplain(sql, { analyze });
139
+ const text = postgresExplainPrefix({ generic, analyze }) + stripTerminator(sql);
140
+ return firstPlanDocument(await unit(() => send(text)));
141
+ }
142
+ // --measure only: one read-write transaction that builds the index and is always rolled back.
143
+ async function measureTransaction(body) {
144
+ if (!allowMeasure || engine !== 'postgres')
145
+ throw new GatewayRefusal('Index measurement needs --measure.');
146
+ if (depth > 0)
147
+ throw new GatewayRefusal('A measurement cannot run inside another transaction.');
148
+ const { measureControl } = pgCatalog;
149
+ depth += 1;
150
+ let failed = false;
151
+ try {
152
+ return await withInterruptGuard(measureControl.rollback, async () => {
153
+ await send(measureControl.begin);
154
+ try {
155
+ await send(measureControl.localLockTimeout);
156
+ await send(measureControl.localStatementTimeout);
157
+ return await body({
158
+ createIndex: (index) => send(pgCatalog.indexDefinition(index)),
159
+ readOnly: () => send(measureControl.readOnly),
160
+ explainAnalyze: async (sql) => {
161
+ await validatePostgresExplain(sql, { analyze: true });
162
+ return firstPlanDocument(await send(postgresExplainPrefix({ analyze: true }) + stripTerminator(sql)));
163
+ },
164
+ });
165
+ }
166
+ catch (error) {
167
+ failed = true;
168
+ throw error;
169
+ }
170
+ finally {
171
+ await rollbackOrDestroy(measureControl.rollback);
172
+ // On any error the session is destroyed, not reused, so a half-finished transaction
173
+ // cannot linger.
174
+ if (failed && !broken)
175
+ await destroy();
176
+ }
177
+ });
178
+ }
179
+ finally {
180
+ depth -= 1;
181
+ }
182
+ }
183
+ return {
184
+ engine,
185
+ open,
186
+ unit,
187
+ catalog: catalogQuery,
188
+ explain,
189
+ measureTransaction,
190
+ close: () => (broken ? undefined : adapter.close()),
191
+ destroy,
192
+ };
193
+ }
194
+ export { createGateway, GatewayRefusal };
@@ -0,0 +1,52 @@
1
+ import { indexDefinition } from './pg-catalog.js';
2
+ import { totalCost, planUsesIndex } from './plan-estimates.js';
3
+ const extensionName = 'hypopg';
4
+ const missingNote = 'HypoPG is not installed in this database, so suggested indexes are not validated against the planner. ' +
5
+ 'On staging, `CREATE EXTENSION hypopg;` lets `db` report estimated cost before and after.';
6
+ function hypopgAvailable(extensions) {
7
+ return extensions.some((row) => row.name === extensionName);
8
+ }
9
+ async function resetHypotheticalIndexes(gateway) {
10
+ try {
11
+ await gateway.catalog('hypopgReset');
12
+ return true;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ /**
19
+ * EXPLAIN, create a hypothetical index (planner-only, nothing is built), EXPLAIN again, reset; all in one read-only
20
+ * transaction. Hypothetical indexes live in session memory and survive ROLLBACK, so the reset is retried outside
21
+ * the transaction when the first attempt fails.
22
+ */
23
+ async function evaluateHypotheticalIndex(gateway, { sql, generic, candidate }) {
24
+ const definition = indexDefinition({
25
+ schema: candidate.table.schema,
26
+ table: candidate.table.name,
27
+ columns: candidate.columns,
28
+ });
29
+ let resetDone = false;
30
+ try {
31
+ return await gateway.unit(async () => {
32
+ try {
33
+ const before = await gateway.explain(sql, { generic });
34
+ const [created] = await gateway.catalog('hypopgCreateIndex', [definition]);
35
+ const after = await gateway.explain(sql, { generic });
36
+ return {
37
+ before: totalCost(before),
38
+ after: totalCost(after),
39
+ used: Boolean(created?.indexname) && planUsesIndex(after, created.indexname),
40
+ };
41
+ }
42
+ finally {
43
+ resetDone = await resetHypotheticalIndexes(gateway);
44
+ }
45
+ });
46
+ }
47
+ finally {
48
+ if (!resetDone)
49
+ await resetHypotheticalIndexes(gateway);
50
+ }
51
+ }
52
+ export { hypopgAvailable, evaluateHypotheticalIndex, missingNote };
@@ -0,0 +1,141 @@
1
+ import { formatCount } from './checks.js';
2
+ import { walk, planRoot } from './plan-estimates.js';
3
+ // The one mode that is not read-only. Everything here is opt-in and refused unless every guard
4
+ // passes.
5
+ const maxMeasureRows = 5_000_000;
6
+ const productionPattern = /prod/i;
7
+ const confirmationFlag = '--i-understand-this-locks-tables';
8
+ const indexNamePrefix = 'loadwise_measure_';
9
+ class MeasureRefusal extends Error {
10
+ }
11
+ /**
12
+ * Guards known before connecting: the confirmation flag and production-looking variable or database
13
+ * names.
14
+ */
15
+ function preconnectRefusals({ engine, confirmed, envVarNames = [], databaseName = '' }) {
16
+ const reasons = [];
17
+ if (engine !== 'postgres')
18
+ reasons.push('--measure supports PostgreSQL only (MySQL and MongoDB have no transactional index builds).');
19
+ if (!confirmed)
20
+ reasons.push(`--measure builds real indexes under a lock; pass ${confirmationFlag} to confirm.`);
21
+ const productionVariable = envVarNames.find((name) => productionPattern.test(name));
22
+ if (productionVariable)
23
+ reasons.push(`--measure refuses connection variable \`${productionVariable}\`, whose name looks like production.`);
24
+ if (productionPattern.test(databaseName))
25
+ reasons.push('--measure refuses a database whose name looks like production.');
26
+ return reasons;
27
+ }
28
+ /** Guards that need the server: its database name and whether it is a replica. */
29
+ function serverRefusals({ databaseName = '', inRecovery }) {
30
+ const reasons = [];
31
+ if (productionPattern.test(databaseName))
32
+ reasons.push('--measure refuses a database whose name looks like production.');
33
+ if (inRecovery !== false)
34
+ reasons.push('--measure refuses a replica (pg_is_in_recovery() is true).');
35
+ return reasons;
36
+ }
37
+ function tableRefusal(table) {
38
+ if (table.rowEstimate === undefined)
39
+ return `--measure skips \`${table.schema}.${table.name}\`: its size is unknown.`;
40
+ if (table.rowEstimate > maxMeasureRows) {
41
+ return (`--measure skips \`${table.schema}.${table.name}\`: about ${formatCount(table.rowEstimate)} rows (estimated) is ` +
42
+ `above the ${formatCount(maxMeasureRows)}-row limit for building an index under a lock.`);
43
+ }
44
+ }
45
+ function lockWarning(table) {
46
+ return (`--measure: CREATE INDEX inside a transaction holds a SHARE lock on \`${table.schema}.${table.name}\` that ` +
47
+ 'blocks writes to it until the rollback (at most 30 s statement timeout per statement).');
48
+ }
49
+ function median(values) {
50
+ const sorted = [...values].sort((left, right) => left - right);
51
+ const middle = Math.floor(sorted.length / 2);
52
+ return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
53
+ }
54
+ function round(value) {
55
+ return Math.round(value * 1000) / 1000;
56
+ }
57
+ // Rows each scan node read, including those its filter discarded, over all loops.
58
+ function rowsExamined(plan) {
59
+ let total = 0;
60
+ for (const node of walk(planRoot(plan))) {
61
+ if (!node['Relation Name'])
62
+ continue;
63
+ const perLoop = (node['Actual Rows'] ?? 0) + (node['Rows Removed by Filter'] ?? 0) + (node['Rows Removed by Index Recheck'] ?? 0);
64
+ total += perLoop * (node['Actual Loops'] ?? 1);
65
+ }
66
+ return Math.round(total);
67
+ }
68
+ function runStatistics(plans) {
69
+ const executionTimes = plans.map((plan) => {
70
+ const time = (Array.isArray(plan) ? plan[0] : plan)?.['Execution Time'];
71
+ if (typeof time !== 'number')
72
+ throw new MeasureRefusal('EXPLAIN ANALYZE returned no execution time.');
73
+ return time;
74
+ });
75
+ const roots = plans.map(planRoot);
76
+ return {
77
+ medianMs: round(median(executionTimes)),
78
+ rowsExamined: median(plans.map(rowsExamined)),
79
+ sharedHit: median(roots.map((root) => root?.['Shared Hit Blocks'] ?? 0)),
80
+ sharedRead: median(roots.map((root) => root?.['Shared Read Blocks'] ?? 0)),
81
+ };
82
+ }
83
+ // The impact keeps the shared finding shape; row and buffer counts travel beside it.
84
+ function measurement(runs, before, after) {
85
+ return {
86
+ impact: {
87
+ kind: 'measured',
88
+ before: before.medianMs,
89
+ after: after.medianMs,
90
+ unit: 'ms',
91
+ method: `median of ${runs} EXPLAIN ANALYZE runs, index built inside a rolled-back transaction`,
92
+ },
93
+ rowsExamined: { before: before.rowsExamined, after: after.rowsExamined },
94
+ sharedBuffers: {
95
+ before: { hit: before.sharedHit, read: before.sharedRead },
96
+ after: { hit: after.sharedHit, read: after.sharedRead },
97
+ },
98
+ };
99
+ }
100
+ /**
101
+ * Before: `runs` EXPLAIN ANALYZE in read-only rolled-back transactions. After: one transaction that
102
+ * builds the index, turns read-only, runs EXPLAIN ANALYZE `runs` times and is rolled back.
103
+ */
104
+ async function measureCandidate(gateway, { sql, candidate, runs, indexName }) {
105
+ const beforePlans = [];
106
+ for (let run = 0; run < runs; run += 1)
107
+ beforePlans.push(await gateway.explain(sql, { analyze: true }));
108
+ const afterPlans = await gateway.measureTransaction(async (transaction) => {
109
+ await transaction.createIndex({
110
+ schema: candidate.table.schema,
111
+ table: candidate.table.name,
112
+ columns: candidate.columns,
113
+ name: indexName,
114
+ });
115
+ await transaction.readOnly();
116
+ const plans = [];
117
+ for (let run = 0; run < runs; run += 1)
118
+ plans.push(await transaction.explainAnalyze(sql));
119
+ return plans;
120
+ });
121
+ return measurement(runs, runStatistics(beforePlans), runStatistics(afterPlans));
122
+ }
123
+ // After the run: none of the indexes this process named may exist.
124
+ async function assertNoIndexesLeft(gateway, indexNames) {
125
+ if (indexNames.length === 0)
126
+ return;
127
+ const [row] = await gateway.catalog('indexesNamed', [indexNames]);
128
+ if (Number(row?.remaining) !== 0) {
129
+ throw new MeasureRefusal(`--measure left ${row?.remaining} index(es) named ${indexNamePrefix}*; drop them by hand.`);
130
+ }
131
+ }
132
+ function createIndexNamer(processId = process.pid) {
133
+ let counter = 0;
134
+ return () => `${indexNamePrefix}${processId}_${(counter += 1)}`;
135
+ }
136
+ function describeMeasurement({ rowsExamined: rows, sharedBuffers }) {
137
+ return (`rows examined ${formatCount(rows.before)} -> ${formatCount(rows.after)} (measured); shared buffers hit/read ` +
138
+ `${formatCount(sharedBuffers.before.hit)}/${formatCount(sharedBuffers.before.read)} -> ` +
139
+ `${formatCount(sharedBuffers.after.hit)}/${formatCount(sharedBuffers.after.read)} (measured)`);
140
+ }
141
+ export { maxMeasureRows, confirmationFlag, MeasureRefusal, preconnectRefusals, serverRefusals, tableRefusal, lockWarning, median, measureCandidate, assertNoIndexesLeft, createIndexNamer, describeMeasurement, };