loadwise 0.5.1 → 0.6.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.
- package/PERFORMANCE.md +31 -6
- package/README.md +580 -1024
- package/bin/loadwise.js +4 -0
- package/lib/accessibility/frontend-detect.js +2 -1
- package/lib/accessibility/rule-ids.js +12 -9
- package/{editor/accessibility-examples.cjs → lib/editor/accessibility-examples.js} +20 -21
- package/lib/editor/actions.js +117 -0
- package/{editor/apply-fix.cjs → lib/editor/apply-fix.js} +1 -6
- package/{editor/control-flow-comparison.cjs → lib/editor/control-flow-comparison.js} +1 -3
- package/lib/editor/diagnostics.js +365 -0
- package/lib/editor/dismissals.js +111 -0
- package/lib/editor/editor-document.js +99 -0
- package/{editor/finding-comparison.cjs → lib/editor/finding-comparison.js} +4 -7
- package/lib/editor/fix-edits.js +200 -0
- package/lib/editor/language-server.js +437 -0
- package/{editor/maintainability-examples.cjs → lib/editor/maintainability-examples.js} +1 -3
- package/{editor/perf-site-comparison.cjs → lib/editor/perf-site-comparison.js} +1 -3
- package/lib/editor/perf-watch.js +78 -0
- package/{editor/performance-examples.cjs → lib/editor/performance-examples.js} +129 -128
- package/{editor/reliability-examples.cjs → lib/editor/reliability-examples.js} +100 -41
- package/lib/editor/scan-session.js +334 -0
- package/{editor/security-examples.cjs → lib/editor/security-examples.js} +28 -32
- package/lib/editor/server-commands.js +232 -0
- package/{editor/source-example.cjs → lib/editor/source-example.js} +3 -5
- package/{editor/standalone-performance-examples.cjs → lib/editor/standalone-performance-examples.js} +349 -333
- package/lib/editor/types/dismissal.js +1 -0
- package/lib/editor/types/fix-example.js +1 -0
- package/lib/editor/types/source-document.js +1 -0
- package/lib/editor/workspace-files.js +78 -0
- package/lib/editor/workspace-paths.js +22 -0
- package/lib/maintainability/analyze-source.js +2 -0
- package/lib/maintainability/apply-fix.js +1 -1
- package/lib/maintainability/cli.js +1 -1
- package/lib/maintainability/examples.js +58 -41
- package/lib/maintainability/rule-ids.js +29 -14
- package/lib/maintainability/scan-changed.js +3 -0
- package/lib/maintainability/scan.js +13 -9
- package/lib/maintainability/tsconfig-strict.js +69 -0
- package/lib/maintainability/type-safety-hygiene.js +204 -0
- package/lib/performance/analyze.js +2 -0
- package/lib/performance/cli-arguments.js +0 -2
- package/lib/performance/cli-policy.js +17 -9
- package/lib/performance/cli-scan.js +10 -8
- package/lib/performance/cli.js +4 -23
- package/lib/performance/editor-signal.js +1 -1
- package/lib/performance/finding-text.js +3 -3
- package/lib/performance/fix-cli.js +1 -1
- package/lib/performance/frontend-perf.js +7 -0
- package/lib/performance/frontend-render-perf.js +200 -0
- package/lib/performance/llm-max-tokens.js +56 -0
- package/lib/performance/native.js +46 -26
- package/lib/performance/polyglot.js +22 -1
- package/lib/performance/pooling.js +38 -23
- package/lib/performance/projects.js +42 -21
- package/lib/performance/rule-ids.js +236 -222
- package/lib/performance/site-fixes/database.js +3 -1
- package/lib/performance/site-fixes/integrity.js +15 -1
- package/lib/performance/source-inputs.js +18 -6
- package/lib/performance/unscanned-javascript.js +66 -19
- package/lib/reliability/analyze.js +12 -0
- package/lib/reliability/child-process.js +106 -0
- package/lib/reliability/error-values.js +177 -0
- package/lib/reliability/pool-timeout.js +79 -0
- package/lib/reliability/react-bugs.js +602 -0
- package/lib/reliability/resource-leaks.js +3 -6
- package/lib/reliability/rule-ids.js +169 -127
- package/lib/reliability/switch-exhaustive.js +284 -0
- package/lib/reliability/uncaught-exception.js +223 -0
- package/lib/security/auth-crypto/rule-ids.js +3 -2
- package/lib/security/cli.js +6 -5
- package/lib/security/deps/rule-ids.js +1 -0
- package/lib/security/examples/auth-crypto.cjs +5 -4
- package/lib/security/examples/deps.cjs +1 -0
- package/lib/security/examples/exposure.cjs +55 -42
- package/lib/security/examples/files.cjs +1 -0
- package/lib/security/examples/injection.cjs +1 -0
- package/lib/security/examples/moved.cjs +5 -4
- package/lib/security/examples/request-forgery.cjs +1 -0
- package/lib/security/exposure/client-env.js +113 -0
- package/lib/security/exposure/frontend-security.js +12 -10
- package/lib/security/exposure/index.js +14 -3
- package/lib/security/exposure/jsx-url.js +267 -0
- package/lib/security/exposure/next-image-config.js +34 -0
- package/lib/security/exposure/package-manifest.js +45 -0
- package/lib/security/exposure/react-version.js +45 -0
- package/lib/security/exposure/rule-ids.js +16 -12
- package/lib/security/files/index.js +1 -1
- package/lib/security/files/rule-ids.js +1 -0
- package/lib/security/injection/code.js +24 -10
- package/lib/security/injection/command.js +81 -28
- package/lib/security/injection/nosql.js +109 -22
- package/lib/security/injection/redos.js +152 -308
- package/lib/security/injection/regex-pattern.js +290 -0
- package/lib/security/injection/regex.js +30 -11
- package/lib/security/injection/rule-ids.js +2 -1
- package/lib/security/injection/shared.js +19 -1
- package/lib/security/injection/sql.js +83 -2
- package/lib/security/request-forgery/rule-ids.js +1 -0
- package/lib/security/rule-descriptions.js +36 -32
- package/lib/security/rule-ids.js +74 -67
- package/lib/security/taint/filename-guard.js +3 -1
- package/lib/security/taint/guards.js +84 -10
- package/lib/security/taint/index.js +124 -13
- package/lib/security/taint/propagate.js +10 -7
- package/lib/security/taint/sanitizers.js +7 -3
- package/lib/security/taint/sources.js +6 -3
- package/lib/security/taint/summaries.js +13 -1
- package/lib/security/taint/url-parts.js +14 -5
- package/lib/shared/agent-session.js +2 -2
- package/lib/shared/check.js +9 -6
- package/lib/shared/explain.js +5 -5
- package/lib/shared/fix-convergence.js +1 -1
- package/lib/shared/formats/finding-location.js +6 -2
- package/lib/shared/formats/sarif.js +3 -3
- package/lib/shared/heap-limit.js +6 -0
- package/lib/shared/pillars.js +7 -7
- package/lib/shared/rule-docs.js +12 -0
- package/lib/shared/scan-cache.js +0 -1
- package/lib/shared/workspaces.js +31 -9
- package/package.json +25 -17
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/schema/loadwise.config.schema.json +44 -0
- package/editor/README.md +0 -47
- package/examples/redis-keys.otlp.json +0 -22
- package/lib/maintainability/notify-editor.js +0 -1
- package/lib/performance/editor-report.js +0 -191
- package/lib/performance/editor-setup.js +0 -189
- package/lib/performance/editor-watch-supervisor.js +0 -104
- package/lib/performance/editor-watch.js +0 -193
- package/lib/performance/notify-editor.js +0 -1
- package/lib/performance/recursive-watch.js +0 -181
- /package/lib/{performance/types/editor-report.js → editor/types/comparison.js} +0 -0
|
@@ -1,101 +1,59 @@
|
|
|
1
|
-
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.exampleFor = exampleFor;
|
|
4
|
-
const standalone_performance_examples_cjs_1 = require("./standalone-performance-examples.cjs");
|
|
1
|
+
import { standaloneExamples } from './standalone-performance-examples.js';
|
|
5
2
|
// Examples are illustrative fragments. The scanner knows the site, but cannot choose a
|
|
6
3
|
// business-preserving rewrite.
|
|
4
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
7
5
|
const examples = {
|
|
8
|
-
'known-reads-awaited-serially': [
|
|
9
|
-
'const [profile, preferences] = await Promise.all([readProfile(), readPreferences()]);',
|
|
10
|
-
'Use this for independent reads whose ordering, failure behavior and concurrency budget allow it.',
|
|
11
|
-
],
|
|
12
|
-
'array-repeated-membership': [
|
|
13
|
-
'const allowed = new Set(allowedIds);\nconst visible = rows.filter(row => allowed.has(row.id));',
|
|
14
|
-
'Build the set once while allowedIds is stable.',
|
|
15
|
-
],
|
|
16
6
|
'array-repeated-find': [
|
|
17
7
|
'const firstById = new Map();\nfor (const row of rows) {\n if (!firstById.has(row.id)) firstById.set(row.id, row);\n}\nconst matches = ids.map(id => firstById.get(id));',
|
|
18
8
|
'For stable string IDs this preserves the first match, duplicate requests and undefined for missing IDs. Check equality semantics for other key types.',
|
|
19
9
|
],
|
|
20
|
-
'
|
|
21
|
-
'const
|
|
22
|
-
'
|
|
23
|
-
],
|
|
24
|
-
'loop-copy-accumulator': [
|
|
25
|
-
'const result = [];\nfor (const batch of batches) {\n for (const item of batch) result.push(item);\n}',
|
|
26
|
-
'For dense arrays, build one fresh result if nothing observes intermediate copies.',
|
|
27
|
-
],
|
|
28
|
-
'filter-for-existence': [
|
|
29
|
-
'const hasPending = rows.some(row => row.status === pendingStatus);',
|
|
30
|
-
'Use for a pure predicate when the consumer needs only a yes/no answer.',
|
|
31
|
-
],
|
|
32
|
-
'pg-query-in-loop': [
|
|
33
|
-
"const { rows } = await client.query(\n 'SELECT id, name FROM users WHERE organization_id = $1 AND id = ANY($2::uuid[])',\n [authorizedOrganizationId, ids]\n);\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));",
|
|
34
|
-
'For independent reads with unique UUID keys. Preserve every original scope predicate, the transaction client, missing-row behavior and query batch limits.',
|
|
10
|
+
'array-repeated-membership': [
|
|
11
|
+
'const allowed = new Set(allowedIds);\nconst visible = rows.filter(row => allowed.has(row.id));',
|
|
12
|
+
'Build the set once while allowedIds is stable.',
|
|
35
13
|
],
|
|
36
|
-
'
|
|
37
|
-
'const
|
|
38
|
-
'For
|
|
14
|
+
'drizzle-last-insert-id': [
|
|
15
|
+
'const [result] = await db.insert(orders).values(order);\nconst id = result.insertId;',
|
|
16
|
+
'For one row with an auto-increment key, verify that the mysql2 result has the ID type expected by the caller.',
|
|
39
17
|
],
|
|
40
18
|
'drizzle-query-in-loop': [
|
|
41
19
|
'const rows = ids.length\n ? await db.select().from(users).where(and(scope, inArray(users.id, ids)))\n : [];\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));',
|
|
42
20
|
'and and inArray come from drizzle-orm. This example batches independent reads by a unique key.',
|
|
43
21
|
],
|
|
44
|
-
'
|
|
45
|
-
|
|
46
|
-
'
|
|
47
|
-
],
|
|
48
|
-
'prisma-count-materialization': [
|
|
49
|
-
'const total = await prisma.order.count({ where });',
|
|
50
|
-
'Keep the original filters and verify that pagination or distinct rows do not change the count.',
|
|
51
|
-
],
|
|
52
|
-
'prisma-count-for-existence': [
|
|
53
|
-
'const hasOrder = (await prisma.order.findFirst({ where, select: { id: true } })) !== null;',
|
|
54
|
-
'Keep the original filter and select a small field from the actual model when you only need to know whether a row exists.',
|
|
55
|
-
],
|
|
56
|
-
'typeorm-unused-count': [
|
|
57
|
-
'const orders = await orderRepository.find({ where, order, skip, take });',
|
|
58
|
-
'When only the rows are used, keep the original filters, ordering and pagination and choose the equivalent method that returns rows alone.',
|
|
22
|
+
'drizzle-unfiltered-write': [
|
|
23
|
+
'await db.update(orders).set(changes).where(and(scope, eq(orders.id, orderId)));',
|
|
24
|
+
'Use the intended filter for this operation. Confirm explicitly if a whole-table mutation is intentional.',
|
|
59
25
|
],
|
|
60
26
|
'drizzle-write-preflight': [
|
|
61
27
|
'const [result] = await db.delete(items).where(eq(items.id, id));\nif (result.affectedRows === 0) throw new NotFoundError();',
|
|
62
28
|
'For MySQL deletes, preserve the original scope and error contract. For inserts, check for a matching unique constraint and translate only its duplicate-key error.',
|
|
63
29
|
],
|
|
64
|
-
'
|
|
65
|
-
'const
|
|
66
|
-
'
|
|
67
|
-
],
|
|
68
|
-
'repeated-workbook-decode': [
|
|
69
|
-
'const workbook = new Workbook();\nawait workbook.xlsx.load(bytes);\nconst rows = readRows(workbook);\nconst images = readImages(workbook);',
|
|
70
|
-
'Share a workbook only when both readers can use the same decoded data and preserve each other’s view of the sheets.',
|
|
71
|
-
],
|
|
72
|
-
'pg-first-materialization': [
|
|
73
|
-
"const { rows: [first] } = await client.query(\n 'SELECT id FROM orders WHERE status = $1 ORDER BY id LIMIT 1', [status]\n);",
|
|
74
|
-
'Preserve the intended ordering, filters and projection. An empty result leaves first undefined.',
|
|
30
|
+
'filter-for-existence': [
|
|
31
|
+
'const hasPending = rows.some(row => row.status === pendingStatus);',
|
|
32
|
+
'Use for a pure predicate when the consumer needs only a yes/no answer.',
|
|
75
33
|
],
|
|
76
|
-
'
|
|
77
|
-
'const
|
|
78
|
-
'
|
|
34
|
+
'graphql-n-plus-one-resolver': [
|
|
35
|
+
'const resolvers = {\n Order: {\n items: (order, _args, ctx) => ctx.itemsLoader.load(order.id),\n },\n};',
|
|
36
|
+
'Batch per-parent field queries through a request-scoped DataLoader.',
|
|
79
37
|
],
|
|
80
|
-
'
|
|
81
|
-
|
|
82
|
-
'
|
|
38
|
+
'json-stringify-in-loop': [
|
|
39
|
+
'const serialized = JSON.stringify(items);\nlogger.info(serialized);',
|
|
40
|
+
'Serialize once outside the loop or stream NDJSON instead of stringifying per iteration.',
|
|
83
41
|
],
|
|
84
|
-
'
|
|
85
|
-
'const
|
|
86
|
-
'
|
|
42
|
+
'known-reads-awaited-serially': [
|
|
43
|
+
'const [profile, preferences] = await Promise.all([readProfile(), readPreferences()]);',
|
|
44
|
+
'Use this for independent reads whose ordering, failure behavior and concurrency budget allow it.',
|
|
87
45
|
],
|
|
88
|
-
'
|
|
89
|
-
|
|
90
|
-
'
|
|
46
|
+
'loop-copy-accumulator': [
|
|
47
|
+
'const result = [];\nfor (const batch of batches) {\n for (const item of batch) result.push(item);\n}',
|
|
48
|
+
'For dense arrays, build one fresh result if nothing observes intermediate copies.',
|
|
91
49
|
],
|
|
92
|
-
'
|
|
93
|
-
|
|
94
|
-
'
|
|
50
|
+
'mongoose-missing-lean': [
|
|
51
|
+
'const users = await UserModel.find({ active: true }).lean();',
|
|
52
|
+
'Add .lean() on read-only queries when Document methods (.save, .markModified) are not needed.',
|
|
95
53
|
],
|
|
96
|
-
'node-
|
|
97
|
-
"
|
|
98
|
-
'
|
|
54
|
+
'node-event-listener-leak': [
|
|
55
|
+
"useEffect(() => {\n window.addEventListener('resize', onResize);\n return () => window.removeEventListener('resize', onResize);\n}, []);",
|
|
56
|
+
'Remove listeners on cleanup, or use .once() / { once: true } / AbortSignal.',
|
|
99
57
|
],
|
|
100
58
|
'node-sync-compression-in-async': [
|
|
101
59
|
"const { promisify } = require('node:util');\nconst gzip = promisify(require('node:zlib').gzip);\nconst compressed = await gzip(contents, options);",
|
|
@@ -105,98 +63,139 @@ const examples = {
|
|
|
105
63
|
"const { promisify } = require('node:util');\nconst scrypt = promisify(require('node:crypto').scrypt);\nconst key = await scrypt(password, salt, keyLength, options);",
|
|
106
64
|
'scrypt example. Preserve the selected algorithm and cost parameters, and bound concurrent work.',
|
|
107
65
|
],
|
|
66
|
+
'node-sync-fs-in-async': [
|
|
67
|
+
"const { readFile } = require('node:fs/promises');\nconst contents = await readFile(filename, 'utf8');",
|
|
68
|
+
'readFile example. Choose the asynchronous counterpart of the original operation and preserve its options and errors.',
|
|
69
|
+
],
|
|
108
70
|
'node-sync-process-in-async': [
|
|
109
71
|
"const { promisify } = require('node:util');\nconst execFile = promisify(require('node:child_process').execFile);\nconst { stdout } = await execFile(executable, args, options);",
|
|
110
72
|
'Use a trusted executable and pass arguments separately. For streaming output use spawn and handle completion and errors.',
|
|
111
73
|
],
|
|
112
|
-
'
|
|
113
|
-
"const {
|
|
114
|
-
'PostgreSQL
|
|
74
|
+
'pg-count-materialization': [
|
|
75
|
+
"const { rows } = await client.query(\n 'SELECT count(*) AS total FROM orders WHERE status = $1', [status]\n);\nconst total = BigInt(rows[0].total);",
|
|
76
|
+
'PostgreSQL COUNT returns bigint. If your API returns a JavaScript number, convert only within its safe integer range.',
|
|
115
77
|
],
|
|
116
|
-
'pg-
|
|
117
|
-
"const { rows } = await
|
|
118
|
-
'
|
|
78
|
+
'pg-filter-materialization': [
|
|
79
|
+
"const { rows } = await client.query(\n 'SELECT id, status FROM orders WHERE status = $1', [status]\n);",
|
|
80
|
+
'Combine the filter with all existing predicates. Check collation and NULL handling against the JavaScript comparison.',
|
|
81
|
+
],
|
|
82
|
+
'pg-first-materialization': [
|
|
83
|
+
"const { rows: [first] } = await client.query(\n 'SELECT id FROM orders WHERE status = $1 ORDER BY id LIMIT 1', [status]\n);",
|
|
84
|
+
'Preserve the intended ordering, filters and projection. An empty result leaves first undefined.',
|
|
85
|
+
],
|
|
86
|
+
'pg-query-in-loop': [
|
|
87
|
+
"const { rows } = await client.query(\n 'SELECT id, name FROM users WHERE organization_id = $1 AND id = ANY($2::uuid[])',\n [authorizedOrganizationId, ids]\n);\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id));",
|
|
88
|
+
'For independent reads with unique UUID keys. Preserve every original scope predicate, the transaction client, missing-row behavior and query batch limits.',
|
|
89
|
+
],
|
|
90
|
+
'pg-top-k-materialization': [
|
|
91
|
+
"const { rows } = await client.query(\n 'SELECT id, score FROM entries WHERE category = $1 ORDER BY score DESC, id ASC LIMIT $2',\n [category, limit]\n);",
|
|
92
|
+
'Use the original ordering and tie-break rule, including NULL handling. Here ties are ordered by ID.',
|
|
119
93
|
],
|
|
120
94
|
'pg-transaction-on-pool': [
|
|
121
95
|
"const client = await pool.connect();\ntry {\n await client.query('BEGIN'); await updateOrders(client); await client.query('COMMIT');\n} catch (error) { await client.query('ROLLBACK'); throw error; }\nfinally { client.release(); }",
|
|
122
96
|
'Send every operation in the transaction through this client; discard an unusable connection if rollback itself fails.',
|
|
123
97
|
],
|
|
124
|
-
'
|
|
125
|
-
|
|
126
|
-
'
|
|
98
|
+
'pg-unreleased-checkout': [
|
|
99
|
+
"const { rows } = await pool.query('SELECT id FROM orders WHERE status = $1', [status]);",
|
|
100
|
+
'For a single statement, the pool borrows and returns the client. A multi-statement transaction needs its own checked-out client.',
|
|
127
101
|
],
|
|
128
|
-
'
|
|
129
|
-
'
|
|
130
|
-
'
|
|
102
|
+
'pool-created-per-request-or-item': [
|
|
103
|
+
"const { Pool } = require('pg');\nconst pool = new Pool(databaseOptions); // module scope\nasync function loadOrders(status) {\n return pool.query('SELECT id FROM orders WHERE status = $1', [status]);\n}",
|
|
104
|
+
'PostgreSQL example. Share the client only across compatible credentials, endpoint and lifecycle. Close it at application shutdown.',
|
|
105
|
+
],
|
|
106
|
+
'prisma-count-for-existence': [
|
|
107
|
+
'const hasOrder = (await prisma.order.findFirst({ where, select: { id: true } })) !== null;',
|
|
108
|
+
'Keep the original filter and select a small field from the actual model when you only need to know whether a row exists.',
|
|
109
|
+
],
|
|
110
|
+
'prisma-count-materialization': [
|
|
111
|
+
'const total = await prisma.order.count({ where });',
|
|
112
|
+
'Keep the original filters and verify that pagination or distinct rows do not change the count.',
|
|
131
113
|
],
|
|
132
114
|
'prisma-dependent-writes': [
|
|
133
115
|
'await prisma.$transaction(async tx => {\n const order = await tx.order.create({ data: orderData });\n await tx.lineItem.create({ data: { ...lineData, orderId: order.id } });\n});',
|
|
134
116
|
'Use when the writes must succeed or fail together. A nested write is another option for an existing relation.',
|
|
135
117
|
],
|
|
136
|
-
'
|
|
137
|
-
'await
|
|
138
|
-
'
|
|
118
|
+
'prisma-filter-materialization': [
|
|
119
|
+
'const rows = await prisma.order.findMany({\n where: { AND: [where, { status }] }, orderBy, select\n});',
|
|
120
|
+
'For an unbounded read with an equivalent database equality comparison. Check collation and NULL handling.',
|
|
139
121
|
],
|
|
140
|
-
'
|
|
141
|
-
|
|
142
|
-
'
|
|
122
|
+
'prisma-first-materialization': [
|
|
123
|
+
'const first = (await prisma.order.findFirst({ where, orderBy, select })) ?? undefined;',
|
|
124
|
+
'Carry over the original filters, ordering and projection. Here null is converted to match array indexing.',
|
|
143
125
|
],
|
|
144
|
-
'
|
|
145
|
-
'const
|
|
146
|
-
'
|
|
126
|
+
'prisma-query-in-loop': [
|
|
127
|
+
'const rows = await prisma.user.findMany({ where: { AND: [scope, { id: { in: ids } }] } });\nconst byId = new Map(rows.map(row => [row.id, row]));\nconst matches = ids.map(id => byId.get(id) ?? null);',
|
|
128
|
+
'For independent findUnique-style reads on unique IDs. Keep projection, authorization scope, transaction and original missing-row behavior.',
|
|
147
129
|
],
|
|
148
|
-
'
|
|
149
|
-
'
|
|
150
|
-
'
|
|
130
|
+
'prisma-read-modify-write': [
|
|
131
|
+
'await prisma.counter.update({\n where: uniqueCounterFilter, data: { value: { increment: delta } }\n});',
|
|
132
|
+
'For a non-null counter and a simple addition. Conditional business rules may require a guarded update or version check.',
|
|
133
|
+
],
|
|
134
|
+
'prisma-top-k-materialization': [
|
|
135
|
+
"const top = await prisma.entry.findMany({\n where, orderBy: [{ score: 'desc' }, { id: 'asc' }], take: limit, select\n});",
|
|
136
|
+
'Use a nonnegative limit and preserve the previous sort direction, tie behavior and NULL handling.',
|
|
137
|
+
],
|
|
138
|
+
'prisma-transaction-client-escape': [
|
|
139
|
+
'await prisma.$transaction(async tx => {\n await tx.order.create({ data: orderData });\n await tx.auditEntry.create({ data: auditData });\n});',
|
|
140
|
+
'Pass tx to any helper that participates in this transaction.',
|
|
151
141
|
],
|
|
152
142
|
'react-context-value-recreated': [
|
|
153
143
|
'const value = useMemo(() => ({ user, logout }), [user, logout]);\nreturn <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;',
|
|
154
144
|
'Memoize Context.Provider values so consumers do not re-render on every parent render.',
|
|
155
145
|
],
|
|
156
|
-
'
|
|
157
|
-
|
|
158
|
-
'
|
|
146
|
+
'reduce-copy-accumulator': [
|
|
147
|
+
'const labels = [];\nfor (const row of rows) labels.push(row.label);',
|
|
148
|
+
'Mutate only a fresh result whose intermediate versions are never observed.',
|
|
159
149
|
],
|
|
160
|
-
'
|
|
161
|
-
'const
|
|
162
|
-
'
|
|
150
|
+
'repeated-workbook-decode': [
|
|
151
|
+
'const workbook = new Workbook();\nawait workbook.xlsx.load(bytes);\nconst rows = readRows(workbook);\nconst images = readImages(workbook);',
|
|
152
|
+
'Share a workbook only when both readers can use the same decoded data and preserve each other’s view of the sheets.',
|
|
153
|
+
],
|
|
154
|
+
'typeorm-unused-count': [
|
|
155
|
+
'const orders = await orderRepository.find({ where, order, skip, take });',
|
|
156
|
+
'When only the rows are used, keep the original filters, ordering and pagination and choose the equivalent method that returns rows alone.',
|
|
157
|
+
],
|
|
158
|
+
'unbounded-promise-all': [
|
|
159
|
+
"import pLimit from 'p-limit';\nconst limit = pLimit(10);\nawait Promise.all(items.map((item) => limit(() => processItem(item))));",
|
|
160
|
+
'Cap concurrency with p-limit, p-map, PromisePool, or chunked batches.',
|
|
163
161
|
],
|
|
164
162
|
};
|
|
163
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
165
164
|
const polyglot = {
|
|
166
|
-
'
|
|
167
|
-
'
|
|
168
|
-
'
|
|
169
|
-
'
|
|
165
|
+
'csharp-fixed-regex-in-loop': [
|
|
166
|
+
'csharp',
|
|
167
|
+
'var digits = new Regex("^[0-9]+$");\nforeach (var value in values) {\n if (digits.IsMatch(value)) Collect(value);\n}',
|
|
168
|
+
'Preserve the original options and timeout.',
|
|
170
169
|
],
|
|
171
|
-
'
|
|
172
|
-
'
|
|
173
|
-
'
|
|
174
|
-
'For
|
|
170
|
+
'go-fixed-regexp-in-loop': [
|
|
171
|
+
'go',
|
|
172
|
+
'pattern := regexp.MustCompile(`^[0-9]+$`)\nfor _, value := range values {\n if pattern.MatchString(value) { collect(value) }\n}',
|
|
173
|
+
'For a known valid constant pattern. Keep error handling if the original used regexp.Compile.',
|
|
174
|
+
],
|
|
175
|
+
'java-fixed-regex-in-loop': [
|
|
176
|
+
'java',
|
|
177
|
+
'Pattern digits = Pattern.compile("^[0-9]+$");\nfor (String value : values) {\n if (digits.matcher(value).matches()) collect(value);\n}',
|
|
178
|
+
'Reuse the Pattern and create a matcher per input. Preserve the original matching method and flags.',
|
|
175
179
|
],
|
|
176
180
|
'python-blocking-sleep-in-async': [
|
|
177
181
|
'python',
|
|
178
182
|
'async def wait():\n await asyncio.sleep(1)',
|
|
179
183
|
'For code running on the asyncio event loop.',
|
|
180
184
|
],
|
|
185
|
+
'python-copy-growing-list': [
|
|
186
|
+
'python',
|
|
187
|
+
'items = []\nfor value in values:\n items.append(value)',
|
|
188
|
+
'For a list with no observers depending on intermediate copies.',
|
|
189
|
+
],
|
|
181
190
|
'python-fixed-regex-in-loop': [
|
|
182
191
|
'python',
|
|
183
192
|
'pattern = re.compile(r"^[0-9]+$")\nfor value in values:\n pattern.match(value)',
|
|
184
193
|
'For a constant pattern; hoist the compile out of the loop.',
|
|
185
194
|
],
|
|
186
|
-
'
|
|
187
|
-
'
|
|
188
|
-
'
|
|
189
|
-
'For
|
|
190
|
-
],
|
|
191
|
-
'java-fixed-regex-in-loop': [
|
|
192
|
-
'java',
|
|
193
|
-
'Pattern digits = Pattern.compile("^[0-9]+$");\nfor (String value : values) {\n if (digits.matcher(value).matches()) collect(value);\n}',
|
|
194
|
-
'Reuse the Pattern and create a matcher per input. Preserve the original matching method and flags.',
|
|
195
|
-
],
|
|
196
|
-
'csharp-fixed-regex-in-loop': [
|
|
197
|
-
'csharp',
|
|
198
|
-
'var digits = new Regex("^[0-9]+$");\nforeach (var value in values) {\n if (digits.IsMatch(value)) Collect(value);\n}',
|
|
199
|
-
'Preserve the original options and timeout.',
|
|
195
|
+
'python-sync-requests-in-async': [
|
|
196
|
+
'python',
|
|
197
|
+
'async def fetch(client, url):\n return await client.get(url)',
|
|
198
|
+
'For an httpx.AsyncClient or aiohttp session.',
|
|
200
199
|
],
|
|
201
200
|
'rust-fixed-regex-in-loop': [
|
|
202
201
|
'rust',
|
|
@@ -392,6 +391,7 @@ function specializedExample(ruleId, message, language) {
|
|
|
392
391
|
}
|
|
393
392
|
// A Mongoose finding's message names a `schema.index(...)` fix; the SQL example would point at the
|
|
394
393
|
// wrong database.
|
|
394
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
395
395
|
const mongooseIndexExamples = {
|
|
396
396
|
'index-missing-filter': {
|
|
397
397
|
language: 'javascript',
|
|
@@ -409,8 +409,8 @@ const mongooseIndexExamples = {
|
|
|
409
409
|
function exampleFor(ruleId, languageId, message = '') {
|
|
410
410
|
if (Object.hasOwn(mongooseIndexExamples, ruleId) && message.includes('.index({'))
|
|
411
411
|
return { ...mongooseIndexExamples[ruleId] };
|
|
412
|
-
if (Object.hasOwn(
|
|
413
|
-
return { ...
|
|
412
|
+
if (Object.hasOwn(standaloneExamples, ruleId))
|
|
413
|
+
return { ...standaloneExamples[ruleId] };
|
|
414
414
|
if (Object.hasOwn(polyglot, ruleId)) {
|
|
415
415
|
const [language, code, note] = polyglot[ruleId];
|
|
416
416
|
return languageId === language ? { language, code, note } : undefined;
|
|
@@ -436,3 +436,4 @@ function exampleFor(ruleId, languageId, message = '') {
|
|
|
436
436
|
return { language: snippetLanguage, code, note };
|
|
437
437
|
}
|
|
438
438
|
}
|
|
439
|
+
export { exampleFor };
|
|
@@ -1,77 +1,136 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.exampleFor = exampleFor;
|
|
4
1
|
// Generic fix examples for the reliability rules the shared source pass reports outside the performance examples.
|
|
5
2
|
// The moved performance rules keep their examples in performance-examples.cts, which exampleFor consults first.
|
|
6
|
-
|
|
3
|
+
import { exampleFor as performanceExample } from './performance-examples.js';
|
|
4
|
+
// Keep sorted by rule id; test/shared/registry-order.test.ts checks it.
|
|
7
5
|
const examples = {
|
|
8
|
-
'swallowed-error': {
|
|
9
|
-
before: 'try {\n await saveOrder(order);\n} catch {}\nnotifyCustomer(order);',
|
|
10
|
-
code: 'try {\n await saveOrder(order);\n} catch (error) {\n throw new OrderNotSavedError(order.id, { cause: error });\n}',
|
|
11
|
-
note: 'Handle, rethrow or report the error so the code after the try does not run as if it succeeded.',
|
|
12
|
-
},
|
|
13
|
-
'sql-insert-truncated-at-semicolon': {
|
|
14
|
-
before: 'const inserts = /INSERT INTO orders VALUES ([\\s\\S]*?);/gi;\nwhile ((match = inserts.exec(dump)) !== null) {\n const values = match[1]; // stops inside a quoted semicolon\n}',
|
|
15
|
-
code: '// Use your SQL dialect parser to read complete statements and literal values.\nfor (const insert of readInsertStatements(dump)) {\n importRows(insert.rows);\n}',
|
|
16
|
-
note: 'A semicolon inside a quoted value ends the regular expression match early and drops the rest of the row.',
|
|
17
|
-
},
|
|
18
|
-
'unguarded-boundary-access': {
|
|
19
|
-
before: 'const email = req.body.user.email;',
|
|
20
|
-
code: 'const email = req.body.user?.email;',
|
|
21
|
-
note: 'The read now yields undefined instead of throwing when user is missing. Add `?? default` or answer with a 400 when the input is required.',
|
|
22
|
-
},
|
|
23
6
|
'assignment-in-condition': {
|
|
24
7
|
before: 'if (user.role = "admin") {\n grantAccess(user);\n}',
|
|
25
8
|
code: 'if (user.role === "admin") {\n grantAccess(user);\n}',
|
|
26
9
|
note: 'Assigns instead of comparing; review that no later code needs the assigned value.',
|
|
27
10
|
},
|
|
28
|
-
'
|
|
29
|
-
before: '
|
|
30
|
-
code: '
|
|
31
|
-
note: '
|
|
11
|
+
'browser-not-closed': {
|
|
12
|
+
before: 'const browser = await chromium.launch();\nawait run(browser);\nawait browser.close();',
|
|
13
|
+
code: 'const browser = await chromium.launch();\ntry {\n await run(browser);\n} finally {\n await browser.close();\n}',
|
|
14
|
+
note: 'A failed run leaves the browser process running.',
|
|
15
|
+
},
|
|
16
|
+
'child-process-without-error-listener': {
|
|
17
|
+
before: "const child = spawn('convert', [input, output]);",
|
|
18
|
+
code: "const child = spawn('convert', [input, output]);\nchild.on('error', (error) => {\n logger.error({ err: error }, 'convert failed to start');\n});",
|
|
19
|
+
note: "Without an 'error' listener a failed spawn throws an uncaught exception and crashes the process.",
|
|
20
|
+
},
|
|
21
|
+
'error-logged-without-stack': {
|
|
22
|
+
before: 'try {\n await sync();\n} catch (error) {\n logger.error(error.message);\n}',
|
|
23
|
+
code: "try {\n await sync();\n} catch (error) {\n logger.error({ err: error }, 'sync failed');\n}",
|
|
24
|
+
note: 'Pass the error itself so the logger records the stack.',
|
|
25
|
+
},
|
|
26
|
+
'error-rethrown-without-cause': {
|
|
27
|
+
before: "try {\n await saveOrder(order);\n} catch (error) {\n throw new Error('Order not saved');\n}",
|
|
28
|
+
code: "try {\n await saveOrder(order);\n} catch (error) {\n throw new Error('Order not saved', { cause: error });\n}",
|
|
29
|
+
note: 'The cause keeps the original message and stack reachable.',
|
|
30
|
+
},
|
|
31
|
+
'file-handle-not-closed': {
|
|
32
|
+
before: 'const handle = await open(path);\nawait handle.stat();\nawait handle.close();',
|
|
33
|
+
code: 'const handle = await open(path);\ntry {\n await handle.stat();\n} finally {\n await handle.close();\n}',
|
|
34
|
+
note: 'An error before close() leaks the file descriptor.',
|
|
35
|
+
},
|
|
36
|
+
'interval-not-cleared': {
|
|
37
|
+
before: 'function start() {\n setInterval(poll, 1000);\n}',
|
|
38
|
+
code: 'function start() {\n const timer = setInterval(poll, 1000);\n return () => clearInterval(timer);\n}',
|
|
39
|
+
note: 'Keep the handle so the owner can stop the timer.',
|
|
32
40
|
},
|
|
33
41
|
'invalid-typeof-comparison': {
|
|
34
42
|
before: 'if (typeof value === "strnig") {\n value = value.trim();\n}',
|
|
35
43
|
code: 'if (typeof value === "string") {\n value = value.trim();\n}',
|
|
36
44
|
note: "'strnig' looks like a misspelling of 'string', so the branch never ran.",
|
|
37
45
|
},
|
|
38
|
-
'unreachable-code': {
|
|
39
|
-
before: 'function total(items) {\n return sum(items);\n cleanup();\n}',
|
|
40
|
-
code: 'function total(items) {\n return sum(items);\n}',
|
|
41
|
-
note: 'The statements after the exit are deleted; review that nothing there was needed.',
|
|
42
|
-
},
|
|
43
46
|
'loop-index-past-length': {
|
|
44
47
|
before: 'for (let i = 0; i <= items.length; i++) {\n use(items[i]);\n}',
|
|
45
48
|
code: 'for (let i = 0; i < items.length; i++) {\n use(items[i]);\n}',
|
|
46
49
|
note: 'Valid indexes stop at length - 1.',
|
|
47
50
|
},
|
|
48
|
-
'
|
|
49
|
-
before: '
|
|
50
|
-
code: '
|
|
51
|
-
note: '
|
|
51
|
+
'nan-comparison': {
|
|
52
|
+
before: 'if (value === NaN) {\n value = 0;\n}',
|
|
53
|
+
code: 'if (Number.isNaN(value)) {\n value = 0;\n}',
|
|
54
|
+
note: 'NaN is never equal to anything, itself included.',
|
|
55
|
+
},
|
|
56
|
+
'next-server-env-in-client': {
|
|
57
|
+
before: "'use client';\nconst url = process.env.API_URL;",
|
|
58
|
+
code: "'use client';\nconst url = process.env.NEXT_PUBLIC_API_URL;",
|
|
59
|
+
note: 'Next.js only inlines NEXT_PUBLIC_ variables into the browser bundle.',
|
|
60
|
+
},
|
|
61
|
+
'pool-without-connection-timeout': {
|
|
62
|
+
before: 'const pool = new Pool({ connectionString });',
|
|
63
|
+
code: 'const pool = new Pool({ connectionString, connectionTimeoutMillis: 5000 });',
|
|
64
|
+
note: 'The default of 0 waits forever for a connection; pick a timeout that suits your slowest healthy checkout.',
|
|
52
65
|
},
|
|
53
66
|
'query-runner-not-released': {
|
|
54
67
|
before: 'const runner = dataSource.createQueryRunner();\nawait runner.connect();',
|
|
55
68
|
code: 'const runner = dataSource.createQueryRunner();\ntry {\n await runner.connect();\n} finally {\n await runner.release();\n}',
|
|
56
69
|
note: 'An unreleased runner holds a pooled connection.',
|
|
57
70
|
},
|
|
58
|
-
'
|
|
59
|
-
before: '
|
|
60
|
-
code: '
|
|
61
|
-
note: '
|
|
71
|
+
'react-async-effect-callback': {
|
|
72
|
+
before: 'useEffect(async () => {\n await load();\n}, []);',
|
|
73
|
+
code: 'useEffect(() => {\n load().catch(reportError);\n}, []);',
|
|
74
|
+
note: 'The effect callback must return nothing or a cleanup function, not a promise.',
|
|
62
75
|
},
|
|
63
|
-
'
|
|
64
|
-
before: '
|
|
65
|
-
code: '
|
|
66
|
-
note: '
|
|
76
|
+
'react-effect-sets-state-every-render': {
|
|
77
|
+
before: 'useEffect(() => {\n setItems([...items, next]);\n});',
|
|
78
|
+
code: 'useEffect(() => {\n setItems((previous) => [...previous, next]);\n}, [next]);',
|
|
79
|
+
note: 'Without a dependency array the effect runs after every render, and each run renders again. Keep `next` stable (a primitive or memoised value) or the loop continues.',
|
|
80
|
+
},
|
|
81
|
+
'react-list-missing-key': {
|
|
82
|
+
before: 'rows.map((row) => <li>{row.name}</li>)',
|
|
83
|
+
code: 'rows.map((row) => <li key={row.id}>{row.name}</li>)',
|
|
84
|
+
note: 'A stable key lets React match items between renders.',
|
|
85
|
+
},
|
|
86
|
+
'react-state-mutated-in-place': {
|
|
87
|
+
before: 'items.push(item);\nsetItems(items);',
|
|
88
|
+
code: 'setItems([...items, item]);',
|
|
89
|
+
note: 'React skips the render when the setter receives the same reference.',
|
|
90
|
+
},
|
|
91
|
+
'sql-insert-truncated-at-semicolon': {
|
|
92
|
+
before: 'const inserts = /INSERT INTO orders VALUES ([\\s\\S]*?);/gi;\nwhile ((match = inserts.exec(dump)) !== null) {\n const values = match[1]; // stops inside a quoted semicolon\n}',
|
|
93
|
+
code: '// Use your SQL dialect parser to read complete statements and literal values.\nfor (const insert of readInsertStatements(dump)) {\n importRows(insert.rows);\n}',
|
|
94
|
+
note: 'A semicolon inside a quoted value ends the regular expression match early and drops the rest of the row.',
|
|
95
|
+
},
|
|
96
|
+
'swallowed-error': {
|
|
97
|
+
before: 'try {\n await saveOrder(order);\n} catch {}\nnotifyCustomer(order);',
|
|
98
|
+
code: 'try {\n await saveOrder(order);\n} catch (error) {\n throw new OrderNotSavedError(order.id, { cause: error });\n}',
|
|
99
|
+
note: 'Handle, rethrow or report the error so the code after the try does not run as if it succeeded.',
|
|
100
|
+
},
|
|
101
|
+
'switch-not-exhaustive': {
|
|
102
|
+
before: 'switch (status) {\n case "paid": return 1;\n case "open": return 2;\n}',
|
|
103
|
+
code: 'switch (status) {\n case "paid": return 1;\n case "open": return 2;\n default: throw new Error(status);\n}',
|
|
104
|
+
note: 'Add the missing cases, or a default that throws so a new member cannot fall through unnoticed.',
|
|
105
|
+
},
|
|
106
|
+
'throw-non-error': {
|
|
107
|
+
before: "throw 'order not found';",
|
|
108
|
+
code: "throw new Error('order not found');",
|
|
109
|
+
note: 'An Error carries a stack trace; a thrown string or object does not.',
|
|
110
|
+
},
|
|
111
|
+
'uncaught-exception-continues': {
|
|
112
|
+
before: "process.on('uncaughtException', (error) => {\n logger.error(error);\n});",
|
|
113
|
+
code: "process.on('uncaughtException', (error) => {\n logger.error(error);\n logger.flush(() => process.exit(1));\n});",
|
|
114
|
+
note: 'The process is in an unknown state after an uncaught exception; flush logs, then exit non-zero.',
|
|
115
|
+
},
|
|
116
|
+
'unguarded-boundary-access': {
|
|
117
|
+
before: 'const email = req.body.user.email;',
|
|
118
|
+
code: 'const email = req.body.user?.email;',
|
|
119
|
+
note: 'The read now yields undefined instead of throwing when user is missing. Add `?? default` or answer with a 400 when the input is required.',
|
|
120
|
+
},
|
|
121
|
+
'unreachable-code': {
|
|
122
|
+
before: 'function total(items) {\n return sum(items);\n cleanup();\n}',
|
|
123
|
+
code: 'function total(items) {\n return sum(items);\n}',
|
|
124
|
+
note: 'The statements after the exit are deleted; review that nothing there was needed.',
|
|
67
125
|
},
|
|
68
126
|
};
|
|
69
127
|
const scriptLanguages = ['javascript', 'javascriptreact', 'typescript', 'typescriptreact'];
|
|
70
128
|
function exampleFor(ruleId, languageId, message = '') {
|
|
71
129
|
if (!Object.hasOwn(examples, ruleId))
|
|
72
|
-
return (
|
|
130
|
+
return performanceExample(ruleId, languageId, message);
|
|
73
131
|
if (!scriptLanguages.includes(languageId))
|
|
74
132
|
return;
|
|
75
133
|
const { before, code, note } = examples[ruleId];
|
|
76
134
|
return { language: languageId.startsWith('typescript') ? 'typescript' : 'javascript', before, code, note };
|
|
77
135
|
}
|
|
136
|
+
export { exampleFor };
|