architecture-harness 0.10.0 → 0.12.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.
- package/package.json +1 -1
- package/src/cli/check.mjs +168 -6
- package/src/cli/registry-history.mjs +53 -0
- package/src/cli/registry-history.test.mjs +88 -0
- package/src/config.mjs +55 -0
- package/src/descriptions.mjs +7 -0
- package/src/gates/closed-set-writers.mjs +36 -0
- package/src/gates/closed-set-writers.test.mjs +46 -0
- package/src/gates/doc-claims.mjs +45 -0
- package/src/gates/doc-claims.test.mjs +33 -0
- package/src/gates/integration-imports.mjs +49 -0
- package/src/gates/integration-imports.test.mjs +35 -0
- package/src/gates/migration-numbers.mjs +33 -0
- package/src/gates/migration-numbers.test.mjs +35 -0
- package/src/gates/parity.mjs +163 -0
- package/src/gates/parity.test.mjs +108 -0
- package/src/gates/registry-literal.mjs +137 -0
- package/src/gates/registry-literal.test.mjs +68 -0
- package/src/gates/sql-identifiers.mjs +72 -9
- package/src/gates/sql-identifiers.test.mjs +70 -1
- package/src/gates/tenant-predicate.mjs +108 -58
- package/src/gates/tenant-predicate.test.mjs +61 -39
- package/src/gates/threshold-ratchet.mjs +46 -0
- package/src/gates/threshold-ratchet.test.mjs +60 -0
- package/templates/quality-thresholds.json +2 -2
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { checkRegistryLiteral } from "./registry-literal.mjs";
|
|
4
|
+
|
|
5
|
+
const thresholds = {
|
|
6
|
+
coverage: { value: 70, unit: "percent", comparator: "min", match: ["coverage threshold", "coverage on new code"] },
|
|
7
|
+
filelength: { value: 500, unit: "lines", comparator: "max", match: ["max-lines", "file length"] },
|
|
8
|
+
holdpress: { value: 500, unit: "ms", comparator: "max" },
|
|
9
|
+
};
|
|
10
|
+
const libraries = { node: { label: "Node.js", version: "24" }, drizzle: { label: "Drizzle ORM", version: "0.44" } };
|
|
11
|
+
const registries = { thresholds, libraries, exempt: ["docs/decisions/**"] };
|
|
12
|
+
const check = (contents, file = "docs/architecture.md") => checkRegistryLiteral([{ path: file, contents }], registries);
|
|
13
|
+
const rules = (contents) => check(contents).map((problem) => problem.rule);
|
|
14
|
+
|
|
15
|
+
test("a threshold stated as a number beside its phrase fails", () => {
|
|
16
|
+
const problems = check("Intro.\n\nThe coverage threshold of 70% holds on every package.");
|
|
17
|
+
assert.equal(problems.length, 1);
|
|
18
|
+
assert.equal(problems[0].rule, "threshold-literal");
|
|
19
|
+
assert.equal(problems[0].path, "docs/architecture.md:3");
|
|
20
|
+
assert.match(problems[0].detail, /\{\{q:coverage\}\}/);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("the token passes", () => {
|
|
24
|
+
assert.deepEqual(check("The coverage threshold of {{q:coverage}} holds."), []);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
test("another number near the phrase passes", () => {
|
|
28
|
+
assert.deepEqual(check("The coverage threshold rose twice in 2024, across 3 packages and 1700 files."), []);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
test("the number before the phrase, in a table row, fails", () => {
|
|
32
|
+
assert.deepEqual(rules("| 70% | coverage on new code |"), ["threshold-literal"]);
|
|
33
|
+
assert.deepEqual(rules("70 percent coverage on new code"), ["threshold-literal"]);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
test("a phrase that holds a hyphen matches as a whole word", () => {
|
|
37
|
+
assert.deepEqual(rules("`max-lines` stops at 500 lines."), ["threshold-literal"]);
|
|
38
|
+
assert.deepEqual(check("`max-lines-per-function` stops at 500."), []);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test("the unit of another entry keeps the number quiet, and no unit reports it", () => {
|
|
42
|
+
assert.deepEqual(check("The file length check runs in 500 ms."), []);
|
|
43
|
+
assert.deepEqual(rules("The file length is 500."), ["threshold-literal"]);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("a number is whole: an id, a date or a decimal holding the digits passes", () => {
|
|
47
|
+
assert.deepEqual(check("The coverage threshold is in ADR-0070, dated 2026-07-70, at 0.70 weight."), []);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("the window is six words, and a paragraph ends it", () => {
|
|
51
|
+
assert.deepEqual(rules("The coverage threshold is one that we hold at\n70% here."), ["threshold-literal"]);
|
|
52
|
+
assert.deepEqual(check("The coverage threshold is one that we all hold firmly at 70%."), []);
|
|
53
|
+
assert.deepEqual(check("The coverage threshold.\n\n70% of the files."), []);
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test("a library label beside a version number fails, and its token passes", () => {
|
|
57
|
+
const problems = check("The api runs on Node.js 24 and\nDrizzle ORM 0.44.");
|
|
58
|
+
assert.deepEqual(problems.map((problem) => [problem.rule, problem.path]), [
|
|
59
|
+
["version-literal", "docs/architecture.md:1"],
|
|
60
|
+
["version-literal", "docs/architecture.md:2"],
|
|
61
|
+
]);
|
|
62
|
+
assert.match(problems[0].detail, /\{\{ver:node\}\}/);
|
|
63
|
+
assert.deepEqual(check("The api runs on Node.js {{v:node}} and {{ver:drizzle}}."), []);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("an exempt file passes", () => {
|
|
67
|
+
assert.deepEqual(check("The coverage threshold of 70% on Node.js 24.", "docs/decisions/0001-coverage.md"), []);
|
|
68
|
+
});
|
|
@@ -11,7 +11,11 @@
|
|
|
11
11
|
const CONSTRAINT_OPENER = new Set(["primary", "unique", "check", "constraint", "foreign", "exclude", "like"]);
|
|
12
12
|
const COLUMN_LINE = /^([a-z_][a-z0-9_]*)\s+\S/;
|
|
13
13
|
const CREATE_TABLE = /create table (?:if not exists )?(\w+)\s*\(/g;
|
|
14
|
-
const
|
|
14
|
+
const ALTER_TABLE = /\balter table (?:if exists )?(?:only )?(\w+)\s/g;
|
|
15
|
+
const ADD_COLUMN = /\badd column (?:if not exists )?([a-z_][a-z0-9_]*)\s/g;
|
|
16
|
+
// A statement ends at a semicolon outside a quoted string. A missed one must not hand a column to
|
|
17
|
+
// the table before it, so the next statement's opening word ends the slice too.
|
|
18
|
+
const STATEMENT_END = /;|\b(?:alter|create)\s+table\b/g;
|
|
15
19
|
const INDEX_NAME = /\bindex\("([a-z_]+)"\)/g;
|
|
16
20
|
// Columns are matched by shape — every column in this schema is snake_case.
|
|
17
21
|
const SNAKE = /\b([a-z][a-z0-9]*_[a-z0-9_]+)\b/g;
|
|
@@ -83,18 +87,33 @@ export function declaredColumns(sources) {
|
|
|
83
87
|
tables.set(match[1], columns);
|
|
84
88
|
match = CREATE_TABLE.exec(sql);
|
|
85
89
|
}
|
|
86
|
-
|
|
87
|
-
let added = ADD_COLUMN.exec(sql);
|
|
88
|
-
while (added !== null) {
|
|
89
|
-
const columns = tables.get(added[1]) ?? new Set();
|
|
90
|
-
columns.add(added[2]);
|
|
91
|
-
tables.set(added[1], columns);
|
|
92
|
-
added = ADD_COLUMN.exec(sql);
|
|
93
|
-
}
|
|
90
|
+
addedColumns(tables, sql);
|
|
94
91
|
}
|
|
95
92
|
return tables;
|
|
96
93
|
}
|
|
97
94
|
|
|
95
|
+
/**
|
|
96
|
+
* Quoted strings and line comments declare nothing, and a semicolon inside one ends nothing. One pass
|
|
97
|
+
* reads them in order, so an apostrophe inside a comment opens no string.
|
|
98
|
+
*/
|
|
99
|
+
const blanked = (sql) => sql.replace(/--[^\n]*|'(?:[^']|'')*'/g, (found) => (found.startsWith("--") ? "" : "''"));
|
|
100
|
+
|
|
101
|
+
/** Every `add column` of each `alter table` statement, a comma list included. */
|
|
102
|
+
function addedColumns(tables, sql) {
|
|
103
|
+
const plain = blanked(sql);
|
|
104
|
+
ALTER_TABLE.lastIndex = 0;
|
|
105
|
+
for (let alter = ALTER_TABLE.exec(plain); alter !== null; alter = ALTER_TABLE.exec(plain)) {
|
|
106
|
+
const rest = plain.slice(alter.index + alter[0].length);
|
|
107
|
+
STATEMENT_END.lastIndex = 0;
|
|
108
|
+
const end = STATEMENT_END.exec(rest);
|
|
109
|
+
const added = [...(end === null ? rest : rest.slice(0, end.index)).matchAll(ADD_COLUMN)];
|
|
110
|
+
if (added.length === 0) continue;
|
|
111
|
+
const columns = tables.get(alter[1]) ?? new Set();
|
|
112
|
+
for (const [, column] of added) columns.add(column);
|
|
113
|
+
tables.set(alter[1], columns);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
98
117
|
/**
|
|
99
118
|
* Quoted literals are stripped first: a rank name inside a statement is a value,
|
|
100
119
|
* not a column.
|
|
@@ -242,3 +261,47 @@ export function checkSqlIdentifiers(tables, resources, owners = new Map()) {
|
|
|
242
261
|
}
|
|
243
262
|
return problems;
|
|
244
263
|
}
|
|
264
|
+
|
|
265
|
+
// The other direction. A schema declaration with no migration behind it typechecks, passes every
|
|
266
|
+
// statement check, and fails at runtime. This is the text-level half: it cannot see a type or a
|
|
267
|
+
// default that differs, and a column a later migration dropped still matches the one that added it.
|
|
268
|
+
const SCHEMA_COLUMN = /\b(?:uuid|text|integer|bigint|boolean|jsonb|timestamp|numeric|real|doublePrecision|date|smallint)\(\s*"([a-z0-9_]+)"/g;
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Each table a schema file declares, with the columns under it. A column belongs to the table
|
|
272
|
+
* whose factory call precedes it: one table, then its columns.
|
|
273
|
+
* @param {string} source
|
|
274
|
+
* @param {{tableFactory?: string}} [options]
|
|
275
|
+
* @returns {{table: string, columns: string[]}[]}
|
|
276
|
+
*/
|
|
277
|
+
export function schemaTables(source, { tableFactory = "pgTable" } = {}) {
|
|
278
|
+
const factory = tableFactory.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
279
|
+
const starts = [...source.matchAll(new RegExp(`${factory}\\(\\s*"([a-z0-9_]+)"`, "g"))].map((match) => ({ table: match[1], at: match.index }));
|
|
280
|
+
return starts.map((start, index) => {
|
|
281
|
+
const body = source.slice(start.at, starts[index + 1]?.at ?? source.length);
|
|
282
|
+
return { table: start.table, columns: [...new Set([...body.matchAll(SCHEMA_COLUMN)].map((match) => match[1]))] };
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Every name the migrations write down. A name anywhere in the SQL is enough: the question is whether it was ever written. */
|
|
287
|
+
export function migrationNames(sources) {
|
|
288
|
+
const names = new Set();
|
|
289
|
+
for (const sql of sources) for (const [name] of sql.matchAll(/[a-z0-9_]+/g)) names.add(name);
|
|
290
|
+
return names;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* @param {{path: string, table: string, columns: string[]}[]} declared
|
|
295
|
+
* @param {Set<string>} names
|
|
296
|
+
* @returns {{path: string, rule: string, detail: string}[]}
|
|
297
|
+
*/
|
|
298
|
+
export function checkSchemaInMigrations(declared, names) {
|
|
299
|
+
const problems = [];
|
|
300
|
+
for (const { path, table, columns } of declared) {
|
|
301
|
+
const missing = names.has(table) ? columns.filter((column) => !names.has(column)).map((column) => `${table}.${column}`) : [`table ${table}`];
|
|
302
|
+
for (const name of missing) {
|
|
303
|
+
problems.push({ path, rule: "schema-without-migration", detail: `${name} is declared here and named by no migration` });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return problems;
|
|
307
|
+
}
|
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import {
|
|
3
|
+
import {
|
|
4
|
+
checkSchemaInMigrations,
|
|
5
|
+
checkSqlIdentifiers,
|
|
6
|
+
declaredColumns,
|
|
7
|
+
migrationNames,
|
|
8
|
+
schemaTables,
|
|
9
|
+
tableOwners,
|
|
10
|
+
usedIdentifiers,
|
|
11
|
+
} from "./sql-identifiers.mjs";
|
|
4
12
|
|
|
5
13
|
const ddl = `
|
|
6
14
|
create table if not exists projects (
|
|
@@ -24,6 +32,33 @@ test("a later expand migration adds its column to the same table", () => {
|
|
|
24
32
|
|
|
25
33
|
const resource = (sql) => `const SQL = \`${sql}\`;`;
|
|
26
34
|
|
|
35
|
+
test("every column of a comma list of add column is declared, and each is checked", () => {
|
|
36
|
+
const expand = `alter table projects
|
|
37
|
+
add column archived_at timestamptz,
|
|
38
|
+
add column if not exists site_code2 text default 'a;b',
|
|
39
|
+
add column owner_id uuid;`;
|
|
40
|
+
const tables = declaredColumns([ddl, expand]);
|
|
41
|
+
assert.deepEqual(
|
|
42
|
+
["archived_at", "site_code2", "owner_id"].filter((column) => !tables.get("projects").has(column)),
|
|
43
|
+
[],
|
|
44
|
+
);
|
|
45
|
+
const agreeing = resource("select owner_id, site_code2 from projects where tenant_id = $1");
|
|
46
|
+
assert.deepEqual(checkSqlIdentifiers(tables, [{ path: "r.ts", source: agreeing }]), []);
|
|
47
|
+
const unknown = resource("select owner_id, owner_name from projects where tenant_id = $1");
|
|
48
|
+
const problems = checkSqlIdentifiers(tables, [{ path: "r.ts", source: unknown }]);
|
|
49
|
+
assert.equal(problems.length, 1);
|
|
50
|
+
assert.match(problems[0].detail, /'owner_name'/);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
test("an add column belongs to its own alter table, never to the one before it", () => {
|
|
54
|
+
const tables = declaredColumns([
|
|
55
|
+
ddl,
|
|
56
|
+
"alter table projects enable row level security\ncreate table sites (id uuid);\n-- a site's name\nalter table sites add column site_name text;",
|
|
57
|
+
]);
|
|
58
|
+
assert.equal(tables.get("projects").has("site_name"), false);
|
|
59
|
+
assert.ok(tables.get("sites").has("site_name"));
|
|
60
|
+
});
|
|
61
|
+
|
|
27
62
|
test("an agreeing slice has no finding", () => {
|
|
28
63
|
const tables = declaredColumns([ddl]);
|
|
29
64
|
const source = resource("select id, tenant_id, code from projects where tenant_id = $1");
|
|
@@ -195,3 +230,37 @@ test("a slug matching no feature keeps its own name, so an unowned table is stil
|
|
|
195
230
|
const owners = tableOwners([{ file: "0010_orphan.sql", sql: ddl }], ["blueprints"]);
|
|
196
231
|
assert.equal(owners.get("projects"), "orphan");
|
|
197
232
|
});
|
|
233
|
+
|
|
234
|
+
const schema = `
|
|
235
|
+
export const projects = pgTable("projects", {
|
|
236
|
+
id: uuid("id").primaryKey(),
|
|
237
|
+
tenantId: uuid("tenant_id").notNull(),
|
|
238
|
+
code: text("code").notNull(),
|
|
239
|
+
});
|
|
240
|
+
export const folders = pgTable("folders", {
|
|
241
|
+
id: uuid("id").primaryKey(),
|
|
242
|
+
sortOrder: integer("sort_order"),
|
|
243
|
+
});`;
|
|
244
|
+
|
|
245
|
+
test("a schema file yields each table with the columns declared under it", () => {
|
|
246
|
+
assert.deepEqual(schemaTables(schema), [
|
|
247
|
+
{ table: "projects", columns: ["id", "tenant_id", "code"] },
|
|
248
|
+
{ table: "folders", columns: ["id", "sort_order"] },
|
|
249
|
+
]);
|
|
250
|
+
assert.deepEqual(schemaTables('export const t = table("things", { id: uuid("id") });', { tableFactory: "table" }), [{ table: "things", columns: ["id"] }]);
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test("a schema whose every table and column a migration names passes", () => {
|
|
254
|
+
const declared = schemaTables(schema).map((entry) => ({ path: "f/schema.ts", ...entry }));
|
|
255
|
+
const names = migrationNames([ddl, "create table folders (id uuid, sort_order integer);"]);
|
|
256
|
+
assert.deepEqual(checkSchemaInMigrations(declared, names), []);
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
test("a table or a column no migration names fails, one finding each", () => {
|
|
260
|
+
const declared = schemaTables(schema).map((entry) => ({ path: "f/schema.ts", ...entry }));
|
|
261
|
+
const problems = checkSchemaInMigrations(declared, migrationNames([ddl]));
|
|
262
|
+
assert.deepEqual(problems.map((problem) => problem.rule), ["schema-without-migration"]);
|
|
263
|
+
assert.equal(problems[0].detail, "table folders is declared here and named by no migration");
|
|
264
|
+
const column = checkSchemaInMigrations([{ path: "f/schema.ts", table: "projects", columns: ["id", "archived_at"] }], migrationNames([ddl]));
|
|
265
|
+
assert.equal(column[0].detail, "projects.archived_at is declared here and named by no migration");
|
|
266
|
+
});
|
|
@@ -7,8 +7,10 @@
|
|
|
7
7
|
// It reads the predicate, not the value. That a predicate is present is
|
|
8
8
|
// structural; that it is correct is what the two-tenant test is for.
|
|
9
9
|
|
|
10
|
+
import { posix } from "node:path";
|
|
11
|
+
|
|
10
12
|
const DEFAULT_TENANT_COLUMN = "tenant_id";
|
|
11
|
-
const
|
|
13
|
+
const DEFAULT_TENANT_IDENTIFIER = "tenantId";
|
|
12
14
|
|
|
13
15
|
function escape(text) {
|
|
14
16
|
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -66,19 +68,39 @@ export function checkTenantPredicate(resources, owned, options = {}) {
|
|
|
66
68
|
return problems;
|
|
67
69
|
}
|
|
68
70
|
|
|
69
|
-
//
|
|
70
|
-
//
|
|
71
|
-
//
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
function sharedInsertPattern(helper) {
|
|
77
|
-
return new RegExp(`(?<!function\\s)${escape(helper)}\\s*(?:<[^>]*>)?\\s*\\(`, "g");
|
|
71
|
+
// A helper that takes its table or its columns from the caller carries an exemption above,
|
|
72
|
+
// because the tenant is not readable inside it. The tenant is readable at each call, so each
|
|
73
|
+
// call is checked instead, or moving a statement into a shared helper buys a weaker gate.
|
|
74
|
+
|
|
75
|
+
/** A call, not the declaration: the helper's own parameters are not a tenant argument. */
|
|
76
|
+
function callPattern(name) {
|
|
77
|
+
return new RegExp(`(?<![\\w$.]|function\\s)${escape(name)}\\s*(?:<[^>]*>)?\\s*\\(`, "g");
|
|
78
78
|
}
|
|
79
79
|
|
|
80
|
-
|
|
81
|
-
|
|
80
|
+
/** The tenant as a quoted column, as a row key, or as the tenant identifier. */
|
|
81
|
+
function tenantPattern(column, identifier) {
|
|
82
|
+
return new RegExp(`["'\`]${escape(column)}["'\`]|\\b${escape(column)}\\s*:|\\b${escape(identifier)}\\b`);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The index just past the bracket that closes the one at `open`. */
|
|
86
|
+
function closeOf(source, open) {
|
|
87
|
+
let depth = 0;
|
|
88
|
+
for (let i = open; i < source.length; i += 1) {
|
|
89
|
+
if ("([{".includes(source[i])) depth += 1;
|
|
90
|
+
else if (")]}".includes(source[i]) && (depth -= 1) === 0) return i + 1;
|
|
91
|
+
}
|
|
92
|
+
return source.length;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** From `at` to the semicolon that ends its statement, outside any bracket. */
|
|
96
|
+
function statementFrom(source, at) {
|
|
97
|
+
let depth = 0;
|
|
98
|
+
for (let i = at; i < source.length; i += 1) {
|
|
99
|
+
if ("([{".includes(source[i])) depth += 1;
|
|
100
|
+
else if (")]}".includes(source[i])) depth -= 1;
|
|
101
|
+
if (depth < 0 || (depth === 0 && source[i] === ";")) return source.slice(at, i);
|
|
102
|
+
}
|
|
103
|
+
return source.slice(at);
|
|
82
104
|
}
|
|
83
105
|
|
|
84
106
|
/** The arguments of a call, split at the top level so a nested array stays whole. */
|
|
@@ -106,61 +128,89 @@ function callArguments(source, openIndex) {
|
|
|
106
128
|
return args;
|
|
107
129
|
}
|
|
108
130
|
|
|
131
|
+
/** The nearest declaration of `name` inside the enclosing function, else at the top level. */
|
|
132
|
+
function declarationOf(source, name, from, callAt) {
|
|
133
|
+
const id = escape(name);
|
|
134
|
+
const declares = `\\b(?:const|let|var)\\s+(?:\\{[^}]*\\b${id}\\b[^}]*\\}|\\[[^\\]]*\\b${id}\\b[^\\]]*\\]|${id}\\b)`;
|
|
135
|
+
const local = [...source.slice(from, callAt).matchAll(new RegExp(declares, "g"))].at(-1);
|
|
136
|
+
if (local) return statementFrom(source, from + local.index);
|
|
137
|
+
const top = new RegExp(`^(?:export\\s+)?${declares}`, "m").exec(source);
|
|
138
|
+
return top ? statementFrom(source, top.index) : "";
|
|
139
|
+
}
|
|
140
|
+
|
|
109
141
|
/**
|
|
110
|
-
* The
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* columns` in the file and let a correct list two functions away vouch for this one.
|
|
142
|
+
* The text an argument stands for. A call `f()` is followed to the body of `function f`, one
|
|
143
|
+
* indirection. A bare name is followed to its own declaration only, so a neighbour's local of
|
|
144
|
+
* the same name, or a values list beside it, cannot vouch for it.
|
|
114
145
|
*/
|
|
115
|
-
function
|
|
116
|
-
const called = /^([A-Za-z_$][\w$]*)\s*\(/.exec(argument
|
|
117
|
-
if (called
|
|
118
|
-
|
|
119
|
-
|
|
146
|
+
function resolved(source, argument, from, callAt) {
|
|
147
|
+
const called = /^([A-Za-z_$][\w$]*)\s*\(/.exec(argument);
|
|
148
|
+
if (called) {
|
|
149
|
+
const declared = new RegExp(`function\\s+${escape(called[1])}\\s*(?:<[^>]*>)?\\s*\\(`).exec(source);
|
|
150
|
+
if (declared === null) return declarationOf(source, called[1], from, callAt);
|
|
151
|
+
const open = source.indexOf("{", closeOf(source, declared.index + declared[0].length - 1));
|
|
152
|
+
return open === -1 ? "" : source.slice(open, closeOf(source, open));
|
|
153
|
+
}
|
|
154
|
+
return /^[A-Za-z_$][\w$]*$/.test(argument) ? declarationOf(source, argument, from, callAt) : "";
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The local names a file imports `helper.name` under from `helper.module`. */
|
|
158
|
+
function importedNames(file, source, helper) {
|
|
159
|
+
const stem = (spec) => spec.replace(/\.[cm]?[jt]sx?$/, "");
|
|
160
|
+
const folder = posix.dirname(file);
|
|
161
|
+
const names = [];
|
|
162
|
+
for (const [, list, specifier] of source.matchAll(/\bimport\s+\{([^}]*)\}\s*from\s*["']([^"']+)["']/g)) {
|
|
163
|
+
if (!specifier.startsWith(".") || stem(posix.join(folder, specifier)) !== stem(helper.module)) continue;
|
|
164
|
+
for (const part of list.split(",")) {
|
|
165
|
+
const [imported, local] = part.trim().split(/\s+as\s+/);
|
|
166
|
+
if (imported === helper.name) names.push(local ?? imported);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return names;
|
|
120
170
|
}
|
|
121
171
|
|
|
122
172
|
/**
|
|
123
|
-
* Every call
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
*
|
|
128
|
-
* @
|
|
129
|
-
* @returns {{path: string, rule: string, detail: string}[]}
|
|
173
|
+
* Every call of an exempt helper, in a file that imports it from its module, with the argument
|
|
174
|
+
* that carries the tenant and whether that argument names it.
|
|
175
|
+
* @param {{path: string, contents: string}[]} files
|
|
176
|
+
* @param {{module: string, name: string, argument: number}[]} helpers
|
|
177
|
+
* @param {{column?: string, identifier?: string}} [options]
|
|
178
|
+
* @returns {{path: string, line: number, name: string, index: number, argument: string, scoped: boolean}[]}
|
|
130
179
|
*/
|
|
131
|
-
export function
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
before.lastIndexOf("function "),
|
|
146
|
-
before.lastIndexOf("=> {"),
|
|
147
|
-
before.lastIndexOf("\n}"),
|
|
148
|
-
);
|
|
149
|
-
const from = boundary === -1 ? Math.max(0, match.index - 400) : boundary;
|
|
150
|
-
const args = callArguments(source, match.index + match[0].length - 1);
|
|
151
|
-
const followed = factoryBody(source, args[2] ?? "");
|
|
152
|
-
const neighbourhood = source.slice(from, match.index + 700) + followed;
|
|
153
|
-
if (!tenantLiteral.test(neighbourhood)) {
|
|
154
|
-
problems.push({
|
|
155
|
-
path,
|
|
156
|
-
rule: "insert-without-tenant",
|
|
157
|
-
detail: `line ${before.split("\n").length}: a shared insert names no ${column} column — the tenant moved into the caller's list, so the caller is what carries it`,
|
|
158
|
-
});
|
|
180
|
+
export function exemptHelperCalls(files, helpers, options = {}) {
|
|
181
|
+
const tenant = tenantPattern(options.column ?? DEFAULT_TENANT_COLUMN, options.identifier ?? DEFAULT_TENANT_IDENTIFIER);
|
|
182
|
+
const calls = [];
|
|
183
|
+
for (const { path, contents: source } of files) {
|
|
184
|
+
for (const helper of helpers) {
|
|
185
|
+
for (const local of importedNames(path, source, helper)) {
|
|
186
|
+
for (const match of source.matchAll(callPattern(local))) {
|
|
187
|
+
// The enclosing function starts the window, so a neighbour cannot vouch for this call.
|
|
188
|
+
const before = source.slice(0, match.index);
|
|
189
|
+
const from = Math.max(0, before.lastIndexOf("function "), before.lastIndexOf("=> {"), before.lastIndexOf("\n}"));
|
|
190
|
+
const argument = (callArguments(source, match.index + match[0].length - 1)[helper.argument] ?? "").trim();
|
|
191
|
+
const scoped = tenant.test(argument) || tenant.test(resolved(source, argument, from, match.index));
|
|
192
|
+
calls.push({ path, line: before.split("\n").length, name: helper.name, index: helper.argument, argument, scoped });
|
|
193
|
+
}
|
|
159
194
|
}
|
|
160
|
-
match = sharedInsert.exec(source);
|
|
161
195
|
}
|
|
162
196
|
}
|
|
163
|
-
return
|
|
197
|
+
return calls.sort((a, b) => a.path.localeCompare(b.path) || a.line - b.line);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* @param {{path: string, contents: string}[]} files
|
|
202
|
+
* @param {{module: string, name: string, argument: number}[]} helpers
|
|
203
|
+
* @param {{column?: string, identifier?: string}} [options]
|
|
204
|
+
* @returns {{path: string, rule: string, detail: string}[]}
|
|
205
|
+
*/
|
|
206
|
+
export function checkExemptHelperCalls(files, helpers, options = {}) {
|
|
207
|
+
return exemptHelperCalls(files, helpers, options)
|
|
208
|
+
.filter((call) => !call.scoped)
|
|
209
|
+
.map((call) => ({
|
|
210
|
+
path: call.path,
|
|
211
|
+
rule: "unscoped-helper-call",
|
|
212
|
+
detail: `line ${call.line}: ${call.name} is exempt from the statement scan, and its argument ${call.index + 1} (${call.argument}) names no tenant — the caller is what carries it`,
|
|
213
|
+
}));
|
|
164
214
|
}
|
|
165
215
|
|
|
166
216
|
/** Every statement whose exemption was taken, so a reviewer can count them. */
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import test from "node:test";
|
|
2
2
|
import assert from "node:assert/strict";
|
|
3
|
-
import {
|
|
3
|
+
import { checkExemptHelperCalls, checkTenantPredicate, exemptHelperCalls } from "./tenant-predicate.mjs";
|
|
4
4
|
|
|
5
5
|
const owned = new Set(["projects", "pin_annotations"]);
|
|
6
6
|
const one = (sql, bound = new Set()) => [{ path: "r.ts", statements: [{ sql, bound }] }];
|
|
@@ -39,36 +39,44 @@ test("a table whose name merely starts the same is not matched", () => {
|
|
|
39
39
|
assert.deepEqual(checkTenantPredicate(one("select id from projects_archive where id = $1"), owned), []);
|
|
40
40
|
});
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
const CRUD = "backend/src/application/sql/crud.ts";
|
|
43
|
+
const helpers = [
|
|
44
|
+
{ module: CRUD, name: "insertReturning", argument: 2 },
|
|
45
|
+
{ module: CRUD, name: "updateVersionedRow", argument: 3 },
|
|
46
|
+
];
|
|
47
|
+
const IMPORT = 'import { insertReturning, updateVersionedRow } from "../../../application/sql/crud.js";\n';
|
|
48
|
+
const FILE = "backend/src/features/projects/shared/queries.ts";
|
|
49
|
+
const calls = (source, options = {}) => checkExemptHelperCalls([{ path: FILE, contents: IMPORT + source }], helpers, options);
|
|
50
|
+
|
|
51
|
+
test("a call that names the tenant inline passes", () => {
|
|
52
|
+
assert.deepEqual(calls(`return insertReturning(tx, "projects", ["id", "tenant_id", "code"], [a, b, c], COLS, onDup, signal);`), []);
|
|
45
53
|
});
|
|
46
54
|
|
|
47
|
-
test("a
|
|
55
|
+
test("a call whose columns array just above names the tenant passes", () => {
|
|
48
56
|
const source = `
|
|
49
57
|
async function insertProject(tx, input, signal) {
|
|
50
58
|
const columns = ["id", "tenant_id", "code", "name"];
|
|
51
59
|
const values = [input.id, input.tenantId, input.code, input.name];
|
|
52
60
|
return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
|
|
53
61
|
}`;
|
|
54
|
-
assert.deepEqual(
|
|
62
|
+
assert.deepEqual(calls(source), []);
|
|
55
63
|
});
|
|
56
64
|
|
|
57
|
-
test("a
|
|
65
|
+
test("a call that forgot the tenant fails, and a tenant in the values beside it does not vouch", () => {
|
|
58
66
|
const source = `
|
|
59
67
|
async function insertProject(tx, input, signal) {
|
|
60
68
|
const columns = ["id", "code", "name"];
|
|
61
|
-
const values = [input.id, input.code, input.name];
|
|
69
|
+
const values = [input.id, input.tenantId, input.code, input.name];
|
|
62
70
|
return insertReturning(tx, "projects", columns, values, COLS, onDup, signal);
|
|
63
71
|
}`;
|
|
64
|
-
const problems =
|
|
72
|
+
const problems = calls(source);
|
|
65
73
|
assert.equal(problems.length, 1);
|
|
66
|
-
assert.equal(problems[0].rule, "
|
|
74
|
+
assert.equal(problems[0].rule, "unscoped-helper-call");
|
|
75
|
+
assert.equal(problems[0].path, FILE);
|
|
67
76
|
});
|
|
68
77
|
|
|
69
78
|
test("a generic call with a type argument is still matched", () => {
|
|
70
|
-
|
|
71
|
-
assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
|
|
79
|
+
assert.equal(calls(`return insertReturning<{ id: string }>(tx, "projects", ["id", "code"], [a, b], COLS, onDup);`).length, 1);
|
|
72
80
|
});
|
|
73
81
|
|
|
74
82
|
test("every call is checked, and a neighbour naming the tenant cannot vouch for one that does not", () => {
|
|
@@ -82,29 +90,19 @@ function insertB(tx, v) {
|
|
|
82
90
|
function insertC(tx, v) {
|
|
83
91
|
return insertReturning(tx, "c", ["id"], v, C, f);
|
|
84
92
|
}`;
|
|
85
|
-
assert.equal(
|
|
93
|
+
assert.equal(calls(source).length, 2);
|
|
86
94
|
});
|
|
87
95
|
|
|
88
|
-
test("a columns factory one call away is followed,
|
|
89
|
-
const
|
|
96
|
+
test("a columns factory one call away is followed, and one that forgets the tenant is caught", () => {
|
|
97
|
+
const factory = (columns) => `
|
|
90
98
|
function newPhotoColumns() {
|
|
91
|
-
return [
|
|
99
|
+
return [${columns}];
|
|
92
100
|
}
|
|
93
101
|
export async function insertPhoto(tx, input, signal) {
|
|
94
|
-
return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
|
|
102
|
+
return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input.tenantId), COLS, onDup, signal);
|
|
95
103
|
}`;
|
|
96
|
-
assert.deepEqual(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
test("a columns factory that forgets the tenant is still caught through the indirection", () => {
|
|
100
|
-
const source = `
|
|
101
|
-
function newPhotoColumns() {
|
|
102
|
-
return ["id", "delivery_id"];
|
|
103
|
-
}
|
|
104
|
-
export async function insertPhoto(tx, input, signal) {
|
|
105
|
-
return insertReturning(tx, "photos", newPhotoColumns(), newPhotoValues(input), COLS, onDup, signal);
|
|
106
|
-
}`;
|
|
107
|
-
assert.equal(checkSharedInsertCallSites([{ path: "r.ts", source }]).length, 1);
|
|
104
|
+
assert.deepEqual(calls(factory('"id", "tenant_id", "delivery_id"')), []);
|
|
105
|
+
assert.equal(calls(factory('"id", "delivery_id"')).length, 1);
|
|
108
106
|
});
|
|
109
107
|
|
|
110
108
|
test("a repeated local name is not resolved to the first one in the file", () => {
|
|
@@ -117,11 +115,42 @@ export async function insertTwo(tx, input, signal) {
|
|
|
117
115
|
const columns = ["id", "name"];
|
|
118
116
|
return insertReturning(tx, "b", columns, values(input), COLS, onDup, signal);
|
|
119
117
|
}`;
|
|
120
|
-
const found =
|
|
118
|
+
const found = calls(source);
|
|
121
119
|
assert.equal(found.length, 1);
|
|
122
|
-
assert.match(found[0].detail, /line
|
|
120
|
+
assert.match(found[0].detail, /line 9:/);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test("a row object must carry the tenant key: the must-fail and must-pass of the issue", () => {
|
|
124
|
+
const helper = [{ module: CRUD, name: "insertRow", argument: 2 }];
|
|
125
|
+
const run = (source) => checkExemptHelperCalls([{ path: FILE, contents: `import { insertRow } from "../../../application/sql/crud.js";\n${source}` }], helper);
|
|
126
|
+
assert.equal(run('await insertRow(tx, "items", { id, name }, "id");').length, 1);
|
|
127
|
+
assert.deepEqual(run('await insertRow(tx, "items", { tenant_id: tenantId, id, name }, "id");'), []);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("a tenant value argument must name the tenant, so swapped arguments fail", () => {
|
|
131
|
+
assert.deepEqual(calls('return updateVersionedRow(tx, "pins", fields, tenantId, pinId, expectedVersion, COLS, signal);'), []);
|
|
132
|
+
assert.deepEqual(calls('return updateVersionedRow(tx, "pins", fields, input.tenantId, pinId, 3, COLS, signal);'), []);
|
|
133
|
+
assert.equal(calls('return updateVersionedRow(tx, "pins", fields, pinId, tenantId, expectedVersion, COLS, signal);').length, 1);
|
|
123
134
|
});
|
|
124
135
|
|
|
136
|
+
test("only a file that imports the helper from its module is checked, under the name it imports", () => {
|
|
137
|
+
const other = 'import { insertReturning } from "./local.js";\ninsertReturning(tx, "a", ["id"], v, C, f);';
|
|
138
|
+
assert.deepEqual(checkExemptHelperCalls([{ path: FILE, contents: other }], helpers), []);
|
|
139
|
+
const renamed = 'import { insertReturning as insert } from "../../../application/sql/crud.js";\ninsert(tx, "a", ["id"], v, C, f);';
|
|
140
|
+
assert.equal(checkExemptHelperCalls([{ path: FILE, contents: renamed }], helpers).length, 1);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
test("every call is listed with its verdict, so a reviewer can count them", () => {
|
|
144
|
+
const source = 'insertReturning(tx, "a", ["tenant_id"], v, C, f);\nupdateVersionedRow(tx, "b", f, id, id, 1, C);';
|
|
145
|
+
const found = exemptHelperCalls([{ path: FILE, contents: IMPORT + source }], helpers);
|
|
146
|
+
assert.deepEqual(found.map((call) => [call.name, call.line, call.scoped]), [["insertReturning", 2, true], ["updateVersionedRow", 3, false]]);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test("the tenant column and identifier come from options", () => {
|
|
150
|
+
const source = 'insertReturning(tx, "a", ["org_id"], v, C, f);\nupdateVersionedRow(tx, "b", f, orgId, id, 1, C);';
|
|
151
|
+
assert.deepEqual(calls(source, { column: "org_id", identifier: "orgId" }), []);
|
|
152
|
+
assert.equal(calls(source).length, 2);
|
|
153
|
+
});
|
|
125
154
|
|
|
126
155
|
test("a statement on a table named at runtime is still checked", () => {
|
|
127
156
|
const sql = "select id from ${table} where id = $1";
|
|
@@ -142,7 +171,7 @@ test("an insert into a runtime-named table must list the tenant column", () => {
|
|
|
142
171
|
assert.deepEqual(checkTenantPredicate(one(good), owned), []);
|
|
143
172
|
});
|
|
144
173
|
|
|
145
|
-
test("the tenant column
|
|
174
|
+
test("the tenant column comes from options", () => {
|
|
146
175
|
const resources = [
|
|
147
176
|
{ path: "a/resource.ts", statements: [{ sql: "select * from pins where org_id = $1", bound: new Set() }] },
|
|
148
177
|
];
|
|
@@ -152,10 +181,3 @@ test("the tenant column and the shared insert helper come from options", () => {
|
|
|
152
181
|
assert.equal(problems.length, 1);
|
|
153
182
|
assert.ok(problems[0].detail.includes("tenant_id"));
|
|
154
183
|
});
|
|
155
|
-
|
|
156
|
-
test("a renamed shared insert helper is still followed to its call sites", () => {
|
|
157
|
-
const resources = [{ path: "a/resource.ts", source: 'await addRow(uow, "pins", ["name"], [n]);' }];
|
|
158
|
-
const problems = checkSharedInsertCallSites(resources, { insertHelper: "addRow", column: "org_id" });
|
|
159
|
-
assert.equal(problems.length, 1);
|
|
160
|
-
assert.ok(problems[0].detail.includes("org_id"));
|
|
161
|
-
});
|