loadwise 0.9.0 → 0.10.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 (155) hide show
  1. package/README.md +88 -19
  2. package/agent/hooks/check-edited-file.mjs +146 -28
  3. package/dist/bin/github-action.js +3 -74
  4. package/dist/bin/loadwise.js +12 -12
  5. package/dist/lib/accessibility/aria-tables.js +10 -6
  6. package/dist/lib/accessibility/document-reference-rules.js +13 -3
  7. package/dist/lib/accessibility/jsx-elements.js +34 -16
  8. package/dist/lib/accessibility/native-interactive.js +51 -13
  9. package/dist/lib/accessibility/rules.js +4 -2
  10. package/dist/lib/accessibility/site-fixes/aria-typo.js +65 -0
  11. package/dist/lib/accessibility/site-fixes/html-language.js +45 -9
  12. package/dist/lib/accessibility/template-elements.js +5 -3
  13. package/dist/lib/editor/actions.js +15 -9
  14. package/dist/lib/editor/diagnostics.js +110 -107
  15. package/dist/lib/editor/finding-comparison.js +4 -25
  16. package/dist/lib/editor/hover-markdown.js +104 -0
  17. package/dist/lib/editor/inline-fix.js +50 -0
  18. package/dist/lib/editor/inline-recommendation.js +27 -0
  19. package/dist/lib/editor/language-server.js +94 -18
  20. package/dist/lib/editor/scan-session.js +2 -1
  21. package/dist/lib/editor/standalone-performance-examples.js +48 -0
  22. package/dist/lib/maintainability/analysis/analyze-source.js +2 -0
  23. package/dist/lib/maintainability/architecture/architecture.js +50 -2
  24. package/dist/lib/maintainability/cli/inputs.js +12 -5
  25. package/dist/lib/maintainability/cli/site-fix.js +3 -0
  26. package/dist/lib/maintainability/cli.js +6 -3
  27. package/dist/lib/maintainability/examples.js +48 -0
  28. package/dist/lib/maintainability/quality/modern-node-callbacks.js +188 -0
  29. package/dist/lib/maintainability/quality/modern-syntax.js +301 -0
  30. package/dist/lib/maintainability/quality/tsconfig-strict.js +307 -15
  31. package/dist/lib/maintainability/rule-ids.js +18 -0
  32. package/dist/lib/maintainability/scan-changed.js +33 -2
  33. package/dist/lib/maintainability/scan.js +10 -1
  34. package/dist/lib/maintainability/site-fixes/unused-bindings.js +15 -6
  35. package/dist/lib/maintainability/unused/module-usage-signatures.js +116 -0
  36. package/dist/lib/maintainability/unused/module-usage.js +67 -106
  37. package/dist/lib/maintainability/unused/unused-bindings.js +143 -8
  38. package/dist/lib/maintainability/unused/unused-dependencies.js +218 -0
  39. package/dist/lib/maintainability/unused/unused-modules.js +4 -0
  40. package/dist/lib/performance/analysis/missing-packages.js +3 -0
  41. package/dist/lib/performance/analysis/source-text.js +2 -2
  42. package/dist/lib/performance/analyze.js +4 -1
  43. package/dist/lib/performance/async/floating-promises.js +25 -4
  44. package/dist/lib/performance/cli/cli-output.js +9 -3
  45. package/dist/lib/performance/cli/cli-policy.js +25 -2
  46. package/dist/lib/performance/cli/cli-scan.js +25 -24
  47. package/dist/lib/performance/cli/scan-outcome.js +19 -1
  48. package/dist/lib/performance/cli/shared-security-inputs.js +27 -0
  49. package/dist/lib/performance/cli/watch.js +27 -8
  50. package/dist/lib/performance/collections/collection-lookups.js +27 -10
  51. package/dist/lib/performance/collections/collection-reduce.js +32 -2
  52. package/dist/lib/performance/collections/collections.js +28 -0
  53. package/dist/lib/performance/collections/repeated.js +25 -1
  54. package/dist/lib/performance/contracts/cli.js +22 -11
  55. package/dist/lib/performance/contracts/git-files.js +46 -1
  56. package/dist/lib/performance/datastores/pooling.js +1 -17
  57. package/dist/lib/performance/datastores/postgres.js +41 -33
  58. package/dist/lib/performance/engine/native.js +5 -1
  59. package/dist/lib/performance/frontend/angular-template-calls.js +187 -0
  60. package/dist/lib/performance/frontend/frontend-dom-perf.js +68 -8
  61. package/dist/lib/performance/frontend/frontend-perf.js +115 -171
  62. package/dist/lib/performance/frontend/frontend-render-perf.js +7 -3
  63. package/dist/lib/performance/frontend/jsx-element-perf.js +171 -0
  64. package/dist/lib/performance/frontend/next-fetch-waterfall.js +346 -29
  65. package/dist/lib/performance/frontend/rxjs-subscriptions.js +155 -0
  66. package/dist/lib/performance/frontend/seo/client-fetched-content.js +196 -0
  67. package/dist/lib/performance/frontend/seo/navigation-without-link.js +116 -0
  68. package/dist/lib/performance/frontend/seo/next-routes.js +114 -0
  69. package/dist/lib/performance/frontend/seo/route-metadata.js +158 -0
  70. package/dist/lib/performance/frontend/seo/seo-rules.js +9 -0
  71. package/dist/lib/performance/frontend/seo/sitewide-noindex.js +103 -0
  72. package/dist/lib/performance/frontend/template-tracking.js +86 -2
  73. package/dist/lib/performance/frontend/vue-options-hooks.js +108 -0
  74. package/dist/lib/performance/orm/prisma.js +1 -25
  75. package/dist/lib/performance/projects.js +3 -2
  76. package/dist/lib/performance/query-loops/service-loops.js +38 -8
  77. package/dist/lib/performance/request/json-stringify-output.js +82 -4
  78. package/dist/lib/performance/request/promise-schedulers.js +180 -0
  79. package/dist/lib/performance/request/request-handlers.js +43 -4
  80. package/dist/lib/performance/request/unbounded-promise-all.js +13 -52
  81. package/dist/lib/performance/rule-ids.js +26 -2
  82. package/dist/lib/performance/site-fix.js +1 -0
  83. package/dist/lib/reliability/react-bugs.js +9 -0
  84. package/dist/lib/reliability/react-state-aliases.js +94 -4
  85. package/dist/lib/reliability/react-state.js +24 -5
  86. package/dist/lib/security/auth-crypto/secrets.js +121 -16
  87. package/dist/lib/security/cli.js +1 -1
  88. package/dist/lib/security/credential-entropy.js +12 -0
  89. package/dist/lib/security/deps/lockfiles.js +3 -1
  90. package/dist/lib/security/examples/files.js +110 -0
  91. package/dist/lib/security/examples/request-forgery.js +1 -1
  92. package/dist/lib/security/exposure/frontend-security.js +11 -2
  93. package/dist/lib/security/exposure/prototype-pollution.js +73 -4
  94. package/dist/lib/security/files/azure-pipelines.js +69 -0
  95. package/dist/lib/security/files/bitbucket-pipelines.js +32 -0
  96. package/dist/lib/security/files/ci-platforms.js +16 -0
  97. package/dist/lib/security/files/ci-shared.js +260 -0
  98. package/dist/lib/security/files/circleci.js +81 -0
  99. package/dist/lib/security/files/dockerfile.js +188 -3
  100. package/dist/lib/security/files/github-actions.js +490 -0
  101. package/dist/lib/security/files/gitlab-ci.js +90 -0
  102. package/dist/lib/security/files/hcl.js +264 -0
  103. package/dist/lib/security/files/hosting-config.js +159 -0
  104. package/dist/lib/security/files/http-headers.js +65 -0
  105. package/dist/lib/security/files/index.js +62 -7
  106. package/dist/lib/security/files/jenkinsfile.js +482 -0
  107. package/dist/lib/security/files/json-nodes.js +67 -0
  108. package/dist/lib/security/files/nginx.js +501 -0
  109. package/dist/lib/security/files/package-scripts.js +175 -0
  110. package/dist/lib/security/files/rule-ids.js +29 -0
  111. package/dist/lib/security/files/secret-values.js +31 -5
  112. package/dist/lib/security/files/secrets.js +44 -13
  113. package/dist/lib/security/files/terraform.js +345 -0
  114. package/dist/lib/security/injection/nosql.js +2 -1
  115. package/dist/lib/security/injection/sql.js +2 -2
  116. package/dist/lib/security/lexical-declaration.js +28 -0
  117. package/dist/lib/security/pg-identifier-guards.js +90 -1
  118. package/dist/lib/security/request-forgery/member-chain.js +41 -0
  119. package/dist/lib/security/request-forgery/open-redirect.js +45 -8
  120. package/dist/lib/security/request-forgery/shared.js +18 -3
  121. package/dist/lib/security/rule-descriptions.js +29 -0
  122. package/dist/lib/security/rule-ids.js +29 -0
  123. package/dist/lib/security/taint/original-string-validation.js +229 -0
  124. package/dist/lib/security/taint/validators.js +1 -1
  125. package/dist/lib/shared/agent/review-delivery.js +3 -1
  126. package/dist/lib/shared/analysis/ast-semantics.js +17 -1
  127. package/dist/lib/shared/analysis/hot-path-graph.js +55 -19
  128. package/dist/lib/shared/analysis/next-env-config.js +232 -0
  129. package/dist/lib/shared/analysis/scan-cache-git.js +114 -0
  130. package/dist/lib/shared/analysis/scan-cache-loadwise-packages.js +54 -0
  131. package/dist/lib/shared/analysis/scan-cache-project-inputs.js +221 -0
  132. package/dist/lib/shared/analysis/scan-cache-sources.js +235 -0
  133. package/dist/lib/shared/analysis/scan-cache-storage.js +24 -0
  134. package/dist/lib/shared/analysis/scan-cache.js +158 -174
  135. package/dist/lib/shared/check-watch.js +3 -3
  136. package/dist/lib/shared/check.js +25 -4
  137. package/dist/lib/shared/config.js +1 -1
  138. package/dist/lib/shared/conventional-projects.js +40 -0
  139. package/dist/lib/shared/fix/fix-command.js +2 -0
  140. package/dist/lib/shared/fix/fix-usage.js +47 -0
  141. package/dist/lib/shared/fix/project-file-access.js +43 -20
  142. package/dist/lib/shared/fix.js +4 -35
  143. package/dist/lib/shared/formats/security-cwe.js +29 -0
  144. package/dist/lib/shared/project-root.js +1 -1
  145. package/dist/lib/shared/reporting/action-comparison.js +78 -0
  146. package/dist/lib/shared/reporting/automatic-fix-signal.js +7 -2
  147. package/dist/lib/shared/reporting/check-text.js +7 -5
  148. package/dist/lib/shared/reporting/pillars.js +28 -8
  149. package/dist/lib/shared/reporting/source-report.js +4 -4
  150. package/dist/lib/shared/system/git.js +31 -16
  151. package/dist/lib/shared/system/glob.js +146 -19
  152. package/dist/lib/shared/system/terminal-style.js +2 -2
  153. package/dist/lib/shared/workspaces.js +6 -1
  154. package/package.json +4 -1
  155. package/schema/loadwise.config.schema.json +86 -0
@@ -0,0 +1,103 @@
1
+ // next-sitewide-noindex: the App Router root layout or the Pages Router `_app`/`_document` marks
2
+ // every route noindex with no condition around it, so a production deploy drops out of search.
3
+ import { ts } from '../../engine/compiler.js';
4
+ import { staticPropertyName, unwrapExpression } from '../../../shared/analysis/ast-semantics.js';
5
+ import { isSiteWideShell } from './next-routes.js';
6
+ const RULE_ID = 'next-sitewide-noindex';
7
+ const NOINDEX_DIRECTIVES = new Set(['noindex', 'none']);
8
+ const ROBOTS_META_NAMES = new Set(['robots', 'googlebot']);
9
+ const CONTEXTUAL_REASON = 'Intentional for private, internal or staging-only apps; confirm this layout ships to the public production site.';
10
+ const MESSAGE = 'This site-wide layout marks every route noindex with no environment condition, so search engines drop the whole production site. Set it only outside production (for example when `process.env.VERCEL_ENV !== "production"`), or only on the routes that must stay out of search.';
11
+ // Robots directives are comma-separated; `max-image-preview:none` must not read as `none`.
12
+ function hasNoindexDirective(content) {
13
+ return content.split(',').some((directive) => NOINDEX_DIRECTIVES.has(directive.trim().toLowerCase()));
14
+ }
15
+ function literalText(expression) {
16
+ const value = unwrapExpression(expression);
17
+ if (value && ts.isStringLiteralLike(value))
18
+ return value.text;
19
+ }
20
+ function propertyValue(object, name) {
21
+ if (!ts.isObjectLiteralExpression(object))
22
+ return;
23
+ for (const property of object.properties) {
24
+ if (ts.isPropertyAssignment(property) && staticPropertyName(property.name) === name)
25
+ return unwrapExpression(property.initializer);
26
+ }
27
+ }
28
+ // `robots: 'noindex'` or `robots: { index: false }`, both written as literals.
29
+ function robotsNoindex(robots) {
30
+ if (!robots)
31
+ return false;
32
+ const text = literalText(robots);
33
+ if (text !== undefined)
34
+ return hasNoindexDirective(text);
35
+ return propertyValue(robots, 'index')?.kind === ts.SyntaxKind.FalseKeyword;
36
+ }
37
+ function metadataRobots(sourceFile) {
38
+ for (const statement of sourceFile.statements) {
39
+ if (!ts.isVariableStatement(statement))
40
+ continue;
41
+ if (!ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword))
42
+ continue;
43
+ for (const declaration of statement.declarationList.declarations) {
44
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== 'metadata' || !declaration.initializer)
45
+ continue;
46
+ const robots = propertyValue(unwrapExpression(declaration.initializer), 'robots');
47
+ if (robotsNoindex(robots))
48
+ return robots;
49
+ }
50
+ }
51
+ }
52
+ function attributeText(attributes, name) {
53
+ for (const attribute of attributes.properties) {
54
+ if (!ts.isJsxAttribute(attribute) || !ts.isIdentifier(attribute.name) || attribute.name.text !== name)
55
+ continue;
56
+ const value = attribute.initializer;
57
+ if (value && ts.isStringLiteral(value))
58
+ return value.text;
59
+ if (value && ts.isJsxExpression(value))
60
+ return literalText(value.expression);
61
+ }
62
+ }
63
+ // A branch, short-circuit or conditional render means the tag can be environment-gated.
64
+ function isConditional(node) {
65
+ for (let current = node.parent; current && !ts.isSourceFile(current); current = current.parent) {
66
+ if (ts.isConditionalExpression(current) || ts.isIfStatement(current) || ts.isSwitchStatement(current))
67
+ return true;
68
+ if (ts.isBinaryExpression(current) &&
69
+ [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(current.operatorToken.kind))
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ function robotsMetaTags(sourceFile) {
75
+ const tags = [];
76
+ (function walk(node) {
77
+ if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {
78
+ const tag = node.tagName;
79
+ const name = attributeText(node.attributes, 'name')?.toLowerCase();
80
+ const content = attributeText(node.attributes, 'content');
81
+ if (ts.isIdentifier(tag) &&
82
+ tag.text === 'meta' &&
83
+ name &&
84
+ ROBOTS_META_NAMES.has(name) &&
85
+ content &&
86
+ hasNoindexDirective(content) &&
87
+ !isConditional(node))
88
+ tags.push(node);
89
+ }
90
+ ts.forEachChild(node, walk);
91
+ })(sourceFile);
92
+ return tags;
93
+ }
94
+ function checkSitewideNoindex(sourceFile, { report }) {
95
+ if (!isSiteWideShell(sourceFile))
96
+ return;
97
+ const robots = metadataRobots(sourceFile);
98
+ if (robots)
99
+ report(robots, RULE_ID, MESSAGE, CONTEXTUAL_REASON);
100
+ for (const tag of robotsMetaTags(sourceFile))
101
+ report(tag, RULE_ID, MESSAGE, CONTEXTUAL_REASON);
102
+ }
103
+ export { checkSitewideNoindex, robotsNoindex };
@@ -69,18 +69,102 @@ function* vueLoops(document, elements, starts) {
69
69
  yield* vueLoops(document, element.children, starts);
70
70
  }
71
71
  }
72
+ // The left side of `v-for`: `item`, `(item, index)`, `{ id, name }` or `({ id }, index)`.
73
+ const vueLoopTarget = /^\s*(\([^)]*\)|\{[^}]*\}|\[[^\]]*\]|[$A-Z_a-z][$\w]*)\s+(?:in|of)\s/;
74
+ // A binding name, not a destructured property key (`{ id: key }` binds `key`).
75
+ const bindingName = /(?<![$\w])[$A-Z_a-z][$\w]*(?![$\w])(?!\s*:)/g;
76
+ const quotedText = /'(?:\\[\s\S]|[^'\\])*'|"(?:\\[\s\S]|[^"\\])*"|`(?:\\[\s\S]|[^`\\])*`/g;
77
+ // A destructuring default such as `= fallback` in `{ id: rowId = fallback }`: it reads a name and binds none.
78
+ const destructuringDefault = /=[^,)\]}]*/g;
79
+ // The parameters of an arrow callback: `item =>` or `(item, index) =>`.
80
+ const arrowParameters = /(\([^()]*\)|[$A-Z_a-z][$\w]*)\s*=>/g;
81
+ function attributePosition(element, attribute, starts) {
82
+ let line = element.line;
83
+ while (starts[line] !== undefined && starts[line] <= attribute.start)
84
+ line++;
85
+ return { line, column: attribute.start - starts[line - 1] + 1 };
86
+ }
87
+ // Where an arrow callback body that starts at `start` ends: the first unmatched closer or top-level comma.
88
+ function callbackEnd(text, start) {
89
+ let depth = 0;
90
+ for (let index = start; index < text.length; index++) {
91
+ const character = text[index];
92
+ if ('([{'.includes(character))
93
+ depth++;
94
+ else if (')]}'.includes(character) && depth-- === 0)
95
+ return index;
96
+ else if (character === ',' && depth === 0)
97
+ return index;
98
+ }
99
+ return text.length;
100
+ }
101
+ // Blanks out callbacks such as `other.some(item => item.active)` whose parameter shadows `alias`: their reads of
102
+ // that name are not the loop variable. Blanking instead of cutting keeps the later match offsets valid.
103
+ function withoutShadowingCallbacks(expression, alias) {
104
+ let result = expression;
105
+ for (const match of expression.matchAll(arrowParameters)) {
106
+ if (!match[1].match(bindingName)?.includes(alias))
107
+ continue;
108
+ const end = callbackEnd(expression, match.index + match[0].length);
109
+ result = result.slice(0, match.index) + ' '.repeat(end - match.index) + result.slice(end);
110
+ }
111
+ return result;
112
+ }
113
+ // A key such as `item` in `{ item: true }` names a property and reads nothing; the shorthand `{ item }` is a read.
114
+ const objectKeyBefore = /[{,]\s*$/;
115
+ const objectKeyAfter = /^\s*:/;
116
+ function isObjectKey(text, start, length) {
117
+ return objectKeyBefore.test(text.slice(0, start)) && objectKeyAfter.test(text.slice(start + length));
118
+ }
119
+ function readsLoopVariable(loop, condition) {
120
+ const target = loop.value && vueLoopTarget.exec(loop.value);
121
+ if (!target || !condition.value)
122
+ return false;
123
+ const aliases = target[1].replaceAll(destructuringDefault, '').match(bindingName) ?? [];
124
+ const expression = condition.value.replaceAll(quotedText, "''");
125
+ return aliases.some((alias) => {
126
+ const escaped = alias.replaceAll('$', String.raw `\$`);
127
+ const visible = withoutShadowingCallbacks(expression, alias);
128
+ const reads = new RegExp(String.raw `(?<![.\w$])${escaped}(?![\w$])`, 'g');
129
+ return Array.from(visible.matchAll(reads)).some((match) => !isObjectKey(visible, match.index, alias.length));
130
+ });
131
+ }
132
+ // `<li v-for="order in orders" v-if="order.paid">`: a per-item filter on the loop element itself.
133
+ function* vueFilteredLoops(document, elements, starts) {
134
+ for (const element of elements) {
135
+ if (element.vuePre)
136
+ continue;
137
+ const attributes = openingAttributes(document, element, starts);
138
+ const loops = attributes.filter(({ name }) => name === 'v-for');
139
+ const condition = attributes.find(({ name }) => name === 'v-if');
140
+ if (loops.length === 1 && condition && readsLoopVariable(loops[0], condition))
141
+ yield attributePosition(element, condition, starts);
142
+ yield* vueFilteredLoops(document, element.children, starts);
143
+ }
144
+ }
72
145
  const vueRule = 'vue-v-for-missing-key';
146
+ const vueFilterRule = 'vue-v-if-with-v-for';
73
147
  function scanVueTracking(file, text) {
74
148
  const document = readVueTemplate(file, text);
75
149
  if (!document)
76
150
  return { findings: [] };
77
- const findings = Array.from(vueLoops(document, document.roots, lineStarts(text)), ({ line, column }) => ({
151
+ const starts = lineStarts(text);
152
+ const findings = Array.from(vueLoops(document, document.roots, starts), ({ line, column }) => ({
78
153
  file,
79
154
  line,
80
155
  column,
81
156
  ruleId: vueRule,
82
157
  message: 'This `v-for` has no `key`. Use a stable unique item identifier so Vue can reuse the matching nodes when the list changes.',
83
158
  }));
159
+ for (const { line, column } of vueFilteredLoops(document, document.roots, starts)) {
160
+ findings.push({
161
+ file,
162
+ line,
163
+ column,
164
+ ruleId: vueFilterRule,
165
+ message: 'This `v-if` filters the items of the `v-for` on the same element. Vue 2 re-checks every item of the whole list on every render; Vue 3 evaluates the `v-if` before the loop, where the loop variable does not exist. Loop over a `computed` list that is already filtered, or move the `v-if` to an inner element.',
166
+ });
167
+ }
84
168
  return { findings: withReviewedReasons(text, findings) };
85
169
  }
86
170
  function vueTrackingPreview(file, text, line, column) {
@@ -128,4 +212,4 @@ function angularTrackingCandidate(template, expression) {
128
212
  });
129
213
  return matches.length === 1 ? matches[0] : undefined;
130
214
  }
131
- export { angularTrackingCandidate, scanVueTracking, vueRule, vueTrackingPreview };
215
+ export { angularLocalNames, angularTrackingCandidate, scanVueTracking, vueRule, vueTrackingPreview };
@@ -0,0 +1,108 @@
1
+ // Vue Options API hooks for vue-watch-missing-cleanup: which `mounted` and teardown hooks are in effect after spreads,
2
+ // what each teardown runs, and whether it may release a resource that `mounted` started.
3
+ import { ts } from '../engine/compiler.js';
4
+ import { constInitializer, symbolOf } from '../../shared/analysis/ast-semantics.js';
5
+ import { propertyName } from '../schema/ts-helpers.js';
6
+ import { calleeName, walkAll } from './frontend-helpers.js';
7
+ const VUE_OPTIONS_TEARDOWN_HOOKS = new Set(['beforeUnmount', 'unmounted', 'beforeDestroy', 'destroyed']);
8
+ function optionsHookBody(property) {
9
+ if (ts.isMethodDeclaration(property))
10
+ return property.body;
11
+ if (!ts.isPropertyAssignment(property))
12
+ return;
13
+ const value = ts.skipOuterExpressions(property.initializer);
14
+ return ts.isArrowFunction(value) || ts.isFunctionExpression(value) ? value.body : undefined;
15
+ }
16
+ // A computed key may name any hook, so it leaves the options unknown.
17
+ function addOption(effective, property) {
18
+ const name = propertyName(property);
19
+ if (name !== undefined)
20
+ effective.set(name, property);
21
+ return name !== undefined;
22
+ }
23
+ // Each spread object's answer, so a file with many components spreading the same object is walked once per object.
24
+ const onlySpreadBySymbol = new WeakMap();
25
+ // True when the file uses the object `name` holds only by spreading it, so no write can add or remove a hook first.
26
+ function onlySpread(name, checker) {
27
+ const symbol = symbolOf(name, checker);
28
+ if (!symbol)
29
+ return false;
30
+ const known = onlySpreadBySymbol.get(symbol);
31
+ if (known !== undefined)
32
+ return known;
33
+ let other = false;
34
+ walkAll(name.getSourceFile(), (node) => {
35
+ if (other || !ts.isIdentifier(node) || node.text !== name.text || symbolOf(node, checker) !== symbol)
36
+ return;
37
+ const parent = node.parent;
38
+ other = !ts.isSpreadAssignment(parent) && !(ts.isVariableDeclaration(parent) && parent.name === node);
39
+ });
40
+ onlySpreadBySymbol.set(symbol, !other);
41
+ return !other;
42
+ }
43
+ // The properties a spread adds: those of a local `const` object literal the file only spreads. Any other spread may
44
+ // supply or replace any hook, so its properties are unknown.
45
+ function spreadProperties(spread, checker) {
46
+ const expression = ts.skipOuterExpressions(spread.expression);
47
+ if (ts.isIdentifier(expression) && !onlySpread(expression, checker))
48
+ return;
49
+ const source = ts.isIdentifier(expression) ? constInitializer(expression, checker) : expression;
50
+ if (!source || !ts.isObjectLiteralExpression(source) || source.properties.some(ts.isSpreadAssignment))
51
+ return;
52
+ return source.properties;
53
+ }
54
+ // The option properties in effect, later keys replacing earlier ones, or undefined when a spread or computed key
55
+ // leaves them unknown.
56
+ function effectiveOptions(options, checker) {
57
+ const effective = new Map();
58
+ for (const property of options.properties) {
59
+ const added = ts.isSpreadAssignment(property) ? spreadProperties(property, checker) : [property];
60
+ if (!added?.every((item) => addOption(effective, item)))
61
+ return;
62
+ }
63
+ return effective;
64
+ }
65
+ // The body of a teardown hook, or 'unknown' when it is a value whose function cannot be read here, such as an imported
66
+ // `beforeUnmount: cleanup` or a factory call.
67
+ function teardownBody(property, checker) {
68
+ const inline = optionsHookBody(property);
69
+ if (inline)
70
+ return inline;
71
+ const reference = ts.isShorthandPropertyAssignment(property)
72
+ ? property.name
73
+ : ts.isPropertyAssignment(property)
74
+ ? ts.skipOuterExpressions(property.initializer)
75
+ : undefined;
76
+ if (!reference || !ts.isIdentifier(reference))
77
+ return 'unknown';
78
+ const declaration = symbolOf(reference, checker)?.declarations?.[0];
79
+ if (declaration && ts.isFunctionDeclaration(declaration) && declaration.body)
80
+ return declaration.body;
81
+ const initializer = constInitializer(reference, checker);
82
+ return initializer && (ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer))
83
+ ? initializer.body
84
+ : 'unknown';
85
+ }
86
+ const VUE_RELEASE_METHODS = new Set(['clearInterval', 'removeEventListener', 'close', 'disconnect', 'unsubscribe']);
87
+ // A teardown may release the resource when it calls that release or any helper whose effect is not known
88
+ // (`this.stopPolling()`); one that only releases other kinds of resource, or calls nothing, leaves it running.
89
+ function teardownMayRelease(teardown, release) {
90
+ if (teardown === 'unknown')
91
+ return true;
92
+ let mayRelease = false;
93
+ walkAll(teardown, (node) => {
94
+ if (!ts.isCallExpression(node))
95
+ return;
96
+ const name = calleeName(node);
97
+ mayRelease ||= name === release || name === undefined || !VUE_RELEASE_METHODS.has(name);
98
+ });
99
+ return mayRelease;
100
+ }
101
+ // The bodies of the teardown hooks in effect.
102
+ function teardownBodies(effective, checker) {
103
+ return [...VUE_OPTIONS_TEARDOWN_HOOKS].flatMap((hook) => {
104
+ const property = effective.get(hook);
105
+ return property ? [teardownBody(property, checker)] : [];
106
+ });
107
+ }
108
+ export { effectiveOptions, optionsHookBody, teardownBodies, teardownMayRelease };
@@ -4,7 +4,7 @@ import { prismaClientReceiver } from '../models/client-imports.js';
4
4
  import { schemaDelegates, schemaOwnerDirectories } from '../schema/prisma-owners.js';
5
5
  import { findPrismaSchemaFiles, loadPrismaSchema } from '../schema/prisma-schema.js';
6
6
  import { awaitedResult, chainedMethod, clientSideQuery, consumesLazyQuery, firstElementRead, isDiscardedValue, outsideWrappers, } from '../query-loops/query-results.js';
7
- import { findRepeatOwner } from '../collections/repeated.js';
7
+ import { findRepeatOwner, UNTYPED_COLLECTION_REASON, untypedIterationCallback } from '../collections/repeated.js';
8
8
  import { shouldReportLoopQuery } from '../query-loops/query-loops.js';
9
9
  import { awaitedWriteConstraint } from '../query-loops/query-write-context.js';
10
10
  import { isSequentialByDesign } from '../query-loops/sequential-loops.js';
@@ -35,8 +35,6 @@ const existenceThresholds = () => new Map([
35
35
  [ts.SyntaxKind.GreaterThanEqualsToken, { left: 1, right: 0 }],
36
36
  [ts.SyntaxKind.LessThanToken, { left: 1, right: 0 }],
37
37
  ]);
38
- const ITERATING_METHODS = new Set(['map', 'forEach', 'flatMap']);
39
- const UNTYPED_COLLECTION_REASON = 'The iterated collection is untyped, so its size is unknown. Review whether it can grow large.';
40
38
  const FIRST_OPTIONS = new Set(['where', 'orderBy', 'select', 'include', 'omit']);
41
39
  const FILTER_SORT_OPTIONS = new Set(['where', 'orderBy', 'select']);
42
40
  const PRISMA_PACKAGE_PATH = /\/node_modules\/(?:@prisma\/client|\.prisma\/client)\//;
@@ -147,28 +145,6 @@ function modelIdField(sourceFile, modelName) {
147
145
  }
148
146
  return idFields.size === 1 ? [...idFields][0] : undefined;
149
147
  }
150
- // A callback passed to `.map`/`.forEach` on a receiver of type `any` is not recognised as an array
151
- // iteration, so its queries would never count as per-item. The callback is still the repeating
152
- // scope, at lower precision.
153
- function untypedIterationCallback(call, checker) {
154
- const callback = ts.findAncestor(call, ts.isFunctionLike);
155
- if (!callback ||
156
- (!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback) && !ts.isMethodDeclaration(callback)) ||
157
- callback.asteriskToken)
158
- return;
159
- let argument = callback;
160
- while (ts.isOuterExpression(argument.parent) && argument.parent.expression === argument)
161
- argument = argument.parent;
162
- const iteration = argument.parent;
163
- if (!ts.isCallExpression(iteration) ||
164
- iteration.arguments[0] !== argument ||
165
- !ts.isPropertyAccessExpression(iteration.expression) ||
166
- !ITERATING_METHODS.has(iteration.expression.name.text))
167
- return;
168
- const receiverType = checker.getTypeAtLocation(iteration.expression.expression);
169
- if (receiverType.flags & ts.TypeFlags.Any)
170
- return callback;
171
- }
172
148
  // An await earlier in the same callback defers the call past the tick in which the other items'
173
149
  // calls start.
174
150
  function awaitsBefore(call, owner) {
@@ -5,6 +5,7 @@ import { withPrismaPackageInventory } from './schema/prisma-owners.js';
5
5
  import { analyzeFile } from './analyze.js';
6
6
  import { analyzeFile as analyzeReliabilityFile } from '../reliability/analyze.js';
7
7
  import { withManifestInventory } from '../reliability/manifest-snapshot.js';
8
+ import { withNextEnvInventory } from '../shared/analysis/next-env-config.js';
8
9
  import { standaloneFindings, sweptFolders } from '../reliability/standalone-sources.js';
9
10
  import { analyzeFile as analyzeAccessibilityFile } from '../accessibility/analyze.js';
10
11
  import { sourcePillarOf } from '../shared/rule-registry.js';
@@ -207,7 +208,7 @@ function runAnalyzers({ program, source, file, policy, forEachSourceCandidate, s
207
208
  return findings;
208
209
  }
209
210
  function analyzeProgram(options) {
210
- return withManifestInventory(() => withPrismaPackageInventory(() => scanProgram(options)));
211
+ return withManifestInventory(() => withNextEnvInventory(() => withPrismaPackageInventory(() => scanProgram(options))));
211
212
  }
212
213
  function scanProgram({ program, inputs = program.getRootFileNames(), scanned = new Set(), policy, forEachSourceCandidate, unresolvedPackages = new Set(), analyzers = performanceAnalyzers, skippedFiles, }) {
213
214
  const optionErrors = program.getOptionsDiagnostics();
@@ -265,7 +266,7 @@ function standaloneReliabilityFindings({ roots, scanned, analyzers, skippedFiles
265
266
  // `project` is one config or an array of them. `onlyFiles` limits reportable roots while retaining configured declarations;
266
267
  // imports still resolve through the config.
267
268
  function analyzeSources(options) {
268
- return withManifestInventory(() => withPrismaPackageInventory(() => withCallNameInventory(() => scanSources(options))));
269
+ return withManifestInventory(() => withNextEnvInventory(() => withPrismaPackageInventory(() => withCallNameInventory(() => scanSources(options)))));
269
270
  }
270
271
  function scanSources({ project, ownership, files, standaloneFiles = [], standaloneScope, standaloneExcluded, standaloneReliabilitySkips, policy, onlyFiles, analyzers, preRead, allowNoSourceFiles, }) {
271
272
  const findings = [];
@@ -260,18 +260,48 @@ const batchReads = {
260
260
  payload: 'one `find` with `where: { id: { in: ids } }`',
261
261
  pg: 'one `= ANY($1)` read',
262
262
  };
263
+ // The site fixes read the client family from these markers, so a write-only loop names its key
264
+ // shape too.
265
+ const batchWrites = {
266
+ prisma: 'one bulk write over `{ in: ids }`',
267
+ typeorm: 'one bulk write over `In(ids)`',
268
+ };
263
269
  const cacheFamilies = new Set(['redis', 'queue']);
264
- function batchAdvice(families) {
265
- const read = [...families].map((family) => batchReads[family]).find(Boolean);
266
- const parts = [];
267
- if (read)
268
- parts.push(read, 'one bulk write');
270
+ // The verb a client method starts with tells reads from writes. Generic entry points such as
271
+ // `query`, `execute` and `$transaction` can do either, so they stay unclassified.
272
+ const readMethod = /^(?:find|get|fetch|load|read|select|list|search|lookup|retrieve|count|exists|aggregate)/i;
273
+ const writeMethod = /^(?:create|insert|update|upsert|delete|destroy|remove|save|set|add|put|patch|increment|decrement)/i;
274
+ const NEUTRAL_ADVICE = 'one batched query';
275
+ function accessOf(operation) {
276
+ const method = operation.label.split('.').pop() ?? '';
277
+ if (readMethod.test(method))
278
+ return 'read';
279
+ if (writeMethod.test(method))
280
+ return 'write';
281
+ }
282
+ // Suggests the batch that matches what the loop does: a batch read when it only reads, a bulk
283
+ // write when it only writes, both when it does both, and a neutral query when the methods do not
284
+ // say.
285
+ function databaseAdvice(operations) {
286
+ if (!operations.length)
287
+ return [];
288
+ const accesses = new Set(operations.map(accessOf));
289
+ const families = [...new Set(operations.map((operation) => operation.family))];
290
+ const readAdvice = families.map((family) => batchReads[family]).find(Boolean) ?? 'one set-based read';
291
+ const writeAdvice = families.map((family) => batchWrites[family]).find(Boolean) ?? 'one bulk write';
292
+ if (accesses.has(undefined))
293
+ return [NEUTRAL_ADVICE];
294
+ if (accesses.has('read') && accesses.has('write'))
295
+ return [readAdvice, writeAdvice];
296
+ return accesses.has('read') ? [readAdvice] : [writeAdvice];
297
+ }
298
+ function batchAdvice(operations) {
299
+ const families = new Set(operations.map((operation) => operation.family));
300
+ const parts = databaseAdvice(operations.filter((operation) => !cacheFamilies.has(operation.family)));
269
301
  if (families.has('redis'))
270
302
  parts.push('one Redis pipeline or multi-key command');
271
303
  if (families.has('queue'))
272
304
  parts.push('one `addBulk()`');
273
- if (!parts.length)
274
- parts.push('one set-based read', 'one bulk write');
275
305
  return parts.join(', ');
276
306
  }
277
307
  function operationNoun(families, count) {
@@ -435,7 +465,7 @@ function check(node, context) {
435
465
  const { amount, trips } = roundTrips(count, complete);
436
466
  const reachedVia = deep && operationPath(operations);
437
467
  const cost = perItemCost(loopCall.owner, trips);
438
- context.report(ts.isPropertyAccessExpression(callee) ? callee.name : callee, RULE_ID, `\`${label}()\` makes ${amount} ${operationNoun(families, count)} per item (${describe(operations)}${reachedVia ? `, reached through ${reachedVia}` : ''}), ${cost}. Add a batch variant that takes all ids (${batchAdvice(families)}) and call it once outside the loop. Keep per-item validation, error isolation, ordering and transaction needs.`, perItemTransactionReason(node, loopCall.owner, operations, checker) ?? (deep && DEEP_REASON), {
468
+ context.report(ts.isPropertyAccessExpression(callee) ? callee.name : callee, RULE_ID, `\`${label}()\` makes ${amount} ${operationNoun(families, count)} per item (${describe(operations)}${reachedVia ? `, reached through ${reachedVia}` : ''}), ${cost}. Add a batch variant that takes all ids (${batchAdvice(operations)}) and call it once outside the loop. Keep per-item validation, error isolation, ordering and transaction needs.`, perItemTransactionReason(node, loopCall.owner, operations, checker) ?? (deep && DEEP_REASON), {
439
469
  related: operations.slice(0, MAX_LISTED_OPERATIONS).map((operation) => ({
440
470
  file: relativeToWorkingDirectory(operation.file),
441
471
  line: operation.line,
@@ -3,6 +3,18 @@ import { effectiveProperty, isUnshadowedGlobal, unwrapExpression } from '../../s
3
3
  import { identifiersByName, isGlobalMethodCall, valueSymbol } from './phase5-ast.js';
4
4
  const MAPPING_METHODS = new Set(['map', 'flatMap']);
5
5
  const OUTPUT_METHODS = new Set(['push', 'write']);
6
+ // What a project `write()` or `push()` helper may hand its line to: a stream, array, file or response.
7
+ const HELPER_OUTPUT_CALLS = new Set([
8
+ ...OUTPUT_METHODS,
9
+ 'appendFile',
10
+ 'appendFileSync',
11
+ 'end',
12
+ 'enqueue',
13
+ 'send',
14
+ 'writeFile',
15
+ 'writeFileSync',
16
+ 'writeSync',
17
+ ]);
6
18
  // The whole string expression that `node` is concatenated or interpolated into.
7
19
  function enclosingText(node) {
8
20
  let value = node;
@@ -21,12 +33,78 @@ function isConsoleOutput(call, checker) {
21
33
  consoleOutputMethods.has(callee.name.text) &&
22
34
  isGlobalMethodCall(call, 'console', callee.name.text, checker));
23
35
  }
36
+ // The call that receives `value` as an argument, and its callee.
37
+ function receivingCall(value, allowWrappedCallee) {
38
+ const call = value.parent;
39
+ if (!ts.isCallExpression(call) || !call.arguments.some((argument) => argument === value))
40
+ return undefined;
41
+ return { call, callee: allowWrappedCallee ? unwrapExpression(call.expression) : call.expression };
42
+ }
43
+ // `stream.write(line)`, `chunks.push(line)` or `console.log(line)`.
44
+ function isMethodOutput(call, callee, checker) {
45
+ return (ts.isPropertyAccessExpression(callee) && (OUTPUT_METHODS.has(callee.name.text) || isConsoleOutput(call, checker)));
46
+ }
47
+ // A function this file or project declares, such as `function write(line) {}` or `const push = (row) => {}`.
48
+ function projectHelper(callee, checker) {
49
+ let symbol = checker.getSymbolAtLocation(callee);
50
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias)
51
+ symbol = checker.getAliasedSymbol(symbol);
52
+ // An overloaded function lists its body-less signatures before the implementation.
53
+ const declaration = symbol?.declarations?.find((candidate) => !ts.isFunctionDeclaration(candidate) || candidate.body);
54
+ if (!declaration || declaration.getSourceFile().isDeclarationFile)
55
+ return undefined;
56
+ if (ts.isFunctionDeclaration(declaration))
57
+ return declaration;
58
+ if (!ts.isVariableDeclaration(declaration) || !declaration.initializer)
59
+ return undefined;
60
+ const initializer = unwrapExpression(declaration.initializer);
61
+ return ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer) ? initializer : undefined;
62
+ }
63
+ // `fs.appendFileSync(file, line)`, `appendFileSync(file, line)` or `console.log(line)` inside a helper.
64
+ function isHelperOutput(call, callee, checker) {
65
+ if (ts.isIdentifier(callee))
66
+ return HELPER_OUTPUT_CALLS.has(callee.text);
67
+ return (ts.isPropertyAccessExpression(callee) &&
68
+ (HELPER_OUTPUT_CALLS.has(callee.name.text) || isConsoleOutput(call, checker)));
69
+ }
70
+ // The helper hands its first parameter straight to a stream, array, file, response or console call.
71
+ function forwardsToOutput(helper, checker) {
72
+ // A `this: Type` parameter only types the receiver; the line is the first real parameter.
73
+ const parameter = helper.parameters.find(({ name }) => !ts.isIdentifier(name) || name.text !== 'this')?.name;
74
+ if (!parameter || !ts.isIdentifier(parameter) || !helper.body)
75
+ return false;
76
+ const symbol = checker.getSymbolAtLocation(parameter);
77
+ // An explicit stack keeps operator chains thousands deep off the call stack.
78
+ const pending = [helper.body];
79
+ for (let node = pending.pop(); node; node = pending.pop()) {
80
+ if (ts.isIdentifier(node) && node.text === parameter.text && valueSymbol(node, checker) === symbol) {
81
+ const receiver = receivingCall(outermostTypeWrapper(enclosingText(outermostTypeWrapper(node))), true);
82
+ if (receiver && isHelperOutput(receiver.call, receiver.callee, checker))
83
+ return true;
84
+ continue;
85
+ }
86
+ ts.forEachChild(node, (child) => {
87
+ pending.push(child);
88
+ });
89
+ }
90
+ return false;
91
+ }
92
+ // A bare `write(line)` is a sink when it is injected, such as a stream writer passed in by the caller, or
93
+ // comes from a library. A project helper counts only when it forwards the line to a real output method,
94
+ // because one that collects or compares its argument leaves the repeated serialization in the loop.
95
+ function isBareOutput(callee, checker) {
96
+ if (!OUTPUT_METHODS.has(callee.text))
97
+ return false;
98
+ const helper = projectHelper(callee, checker);
99
+ return !helper || forwardsToOutput(helper, checker);
100
+ }
24
101
  function isOutputArgument(value, checker, allowWrappedCallee = false) {
25
- const parent = value.parent;
26
- if (!ts.isCallExpression(parent) || !parent.arguments.some((argument) => argument === value))
102
+ const receiver = receivingCall(value, allowWrappedCallee);
103
+ if (!receiver)
27
104
  return false;
28
- const output = allowWrappedCallee ? unwrapExpression(parent.expression) : parent.expression;
29
- return (ts.isPropertyAccessExpression(output) && (OUTPUT_METHODS.has(output.name.text) || isConsoleOutput(parent, checker)));
105
+ if (ts.isIdentifier(receiver.callee))
106
+ return isBareOutput(receiver.callee, checker);
107
+ return isMethodOutput(receiver.call, receiver.callee, checker);
30
108
  }
31
109
  const queryParameterMethods = new Set(['query', 'execute']);
32
110
  // `manager.query(sql, [row.line, JSON.stringify(outcome)])`: the value is one bound parameter of this