@hublo/sentinel 1.7.0-alpha.20 → 1.7.0-alpha.22

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.
@@ -71,7 +71,7 @@ import {
71
71
  uncoveredFor,
72
72
  walk,
73
73
  writtenFileFormatter
74
- } from "./chunk-AVT5FSPO.js";
74
+ } from "./chunk-F3Q3JQJ6.js";
75
75
  import {
76
76
  DEFAULT_MAX_DIAGNOSTICS,
77
77
  WORKSPACE_ROOT_MARKER,
@@ -4574,14 +4574,301 @@ function git(cwd, args) {
4574
4574
 
4575
4575
  // src/roles/sql/configs/resolve.ts
4576
4576
  import { existsSync as existsSync15 } from "node:fs";
4577
- import { join as join24 } from "node:path";
4577
+ import { join as join22 } from "node:path";
4578
4578
  import { pathToFileURL as pathToFileURL2 } from "node:url";
4579
4579
 
4580
+ // src/roles/sql/rule-names.ts
4581
+ var UNSAFE_RULE = "unsafe-sql-pasted-value";
4582
+ var RAW_FRAGMENT_RULE = "unsafe-sql-raw-fragment";
4583
+ var APPLIED_RULE = "applied-migration-changed";
4584
+ var ENUM_VALUE_RULE = "enum-value-used-before-commit";
4585
+
4586
+ // src/roles/sql/configs/rule-levels.ts
4587
+ var SENTINEL_RULES = [
4588
+ UNSAFE_RULE,
4589
+ RAW_FRAGMENT_RULE,
4590
+ APPLIED_RULE,
4591
+ ENUM_VALUE_RULE
4592
+ ];
4593
+ var SYNTAX_ERROR = "syntax-error";
4594
+ var NOT_SQUAWK_CONFIG = [...SENTINEL_RULES, SYNTAX_ERROR];
4595
+ var LEVELS = ["off", "warn", "error"];
4596
+ function levelOf(rules, rule) {
4597
+ return Object.hasOwn(rules, rule) && rules[rule] === "error" ? "error" : "warn";
4598
+ }
4599
+ function rulesOff(rules) {
4600
+ return Object.keys(rules).filter((rule) => rules[rule] === "off").sort();
4601
+ }
4602
+ function rulesOn(rules) {
4603
+ return Object.keys(rules).filter((rule) => rules[rule] !== "off").sort();
4604
+ }
4605
+ function rulesProblem(rules) {
4606
+ if (rules === null || typeof rules !== "object" || Array.isArray(rules)) {
4607
+ return `\`rules\` must be an object of rule names and levels, like { 'ban-drop-column': 'error' }; got ${JSON.stringify(rules)}.`;
4608
+ }
4609
+ for (const [rule, level] of Object.entries(rules)) {
4610
+ const name = nameProblem(rule);
4611
+ if (name) return name;
4612
+ if (rule === SYNTAX_ERROR && level === "off") {
4613
+ return `\`rules['${SYNTAX_ERROR}']\` can be 'warn' or 'error', not 'off': a migration that does not parse is refused by PostgreSQL at deploy, so it is always reported.`;
4614
+ }
4615
+ if (!LEVELS.includes(level)) {
4616
+ return `\`rules['${rule}']\` must be 'off', 'warn' or 'error'; got ${JSON.stringify(level)}.`;
4617
+ }
4618
+ }
4619
+ return null;
4620
+ }
4621
+ function nameProblem(rule) {
4622
+ if (squawkRules.rules.includes(rule) || NOT_SQUAWK_CONFIG.includes(rule)) return null;
4623
+ const standsFor = Object.hasOwn(squawkRules.aliases, rule) ? squawkRules.aliases[rule] : void 0;
4624
+ if (standsFor !== void 0) {
4625
+ const names = standsFor.map((name) => `'${name}'`).join(" and ");
4626
+ return `\`rules['${rule}']\`: squawk reports this rule as ${names}, so a level on '${rule}' would never apply. Write ${names} instead.`;
4627
+ }
4628
+ const near = nearest(rule);
4629
+ return `\`rules['${rule}']\` is not a rule of squawk ${squawkRules.squawk} or of sentinel.` + (near ? ` Did you mean '${near}'?` : "") + ` The names are listed by \`pnpm exec sentinel --inspect --sql --json\`.`;
4630
+ }
4631
+ function nearest(rule) {
4632
+ let best;
4633
+ for (const name of [...squawkRules.rules, ...NOT_SQUAWK_CONFIG]) {
4634
+ const distance = editDistance(rule, name);
4635
+ if (distance <= 3 && (best === void 0 || distance < best.distance)) best = { name, distance };
4636
+ }
4637
+ return best?.name;
4638
+ }
4639
+ function editDistance(a, b) {
4640
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
4641
+ for (let i = 1; i <= a.length; i++) {
4642
+ const current = [i];
4643
+ for (let j = 1; j <= b.length; j++) {
4644
+ current[j] = Math.min(
4645
+ (previous[j] ?? 0) + 1,
4646
+ (current[j - 1] ?? 0) + 1,
4647
+ (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)
4648
+ );
4649
+ }
4650
+ previous = current;
4651
+ }
4652
+ return previous[b.length] ?? 0;
4653
+ }
4654
+
4655
+ // src/roles/sql/configs/resolve.ts
4656
+ async function loadSqlConfig(cwd) {
4657
+ const path2 = join22(cwd, SQL_CONFIG_FILE);
4658
+ if (!existsSync15(path2)) return { config: defineSql(), from: null, unreadable: null };
4659
+ try {
4660
+ const loaded = await import(pathToFileURL2(path2).href);
4661
+ const config = adopt(loaded.default);
4662
+ const problem = configProblem(config);
4663
+ if (problem)
4664
+ return { config: defineSql(), from: null, unreadable: `${SQL_CONFIG_FILE}: ${problem}` };
4665
+ return { config, from: SQL_CONFIG_FILE, unreadable: null };
4666
+ } catch (error) {
4667
+ return {
4668
+ config: defineSql(),
4669
+ from: null,
4670
+ unreadable: `${SQL_CONFIG_FILE}: ${explainUnreadableSqlConfig(error)}`
4671
+ };
4672
+ }
4673
+ }
4674
+ function explainUnreadableSqlConfig(error) {
4675
+ const message = error instanceof Error ? error.message : String(error);
4676
+ const code = error?.code;
4677
+ if (code !== "ERR_PACKAGE_PATH_NOT_EXPORTED" || !message.includes("@hublo/sentinel")) {
4678
+ return message;
4679
+ }
4680
+ return `${message}
4681
+ The @hublo/sentinel installed in this module does not ship the sql role yet. Bump it to a release that does, then run this again.`;
4682
+ }
4683
+ function adopt(exported) {
4684
+ if (exported === null || typeof exported !== "object") return defineSql();
4685
+ if (Array.isArray(exported.moved)) return exported;
4686
+ return defineSql(exported);
4687
+ }
4688
+ function configProblem(config) {
4689
+ return shapeProblem(settingsOf(config), defaults, "") ?? pgVersionProblem(config.pgVersion) ?? rulesProblem(config.rules);
4690
+ }
4691
+ function shapeProblem(value, expected, path2) {
4692
+ const got = `; got ${JSON.stringify(value)}.`;
4693
+ if (Array.isArray(expected)) {
4694
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return null;
4695
+ return `\`${path2}\` must be a list of strings, like ['**/generated/**']${got}`;
4696
+ }
4697
+ if (typeof expected === "boolean" || typeof expected === "string") {
4698
+ if (typeof value === typeof expected) return null;
4699
+ return `\`${path2}\` must be a ${typeof expected}, like ${JSON.stringify(expected)}${got}`;
4700
+ }
4701
+ if (!isPlainObject(value)) return `\`${path2}\` must be an object${got}`;
4702
+ if (path2 === "rules") return null;
4703
+ const known = Object.keys(expected);
4704
+ const named = (key) => path2 ? `${path2}.${key}` : key;
4705
+ for (const [key, inner] of Object.entries(value)) {
4706
+ if (!known.includes(key)) {
4707
+ return `\`${named(key)}\` is not a setting of the sql role, so it would be ignored. The settings here are: ${known.map(named).join(", ")}.`;
4708
+ }
4709
+ const problem = shapeProblem(inner, expected[key], named(key));
4710
+ if (problem) return problem;
4711
+ }
4712
+ return null;
4713
+ }
4714
+ function settingsOf(config) {
4715
+ const { root: _root, moved: _moved, ...settings } = config;
4716
+ return settings;
4717
+ }
4718
+ var PG_VERSION = /^\d+(?:\.\d+){0,2}$/;
4719
+ function pgVersionProblem(pgVersion) {
4720
+ if (typeof pgVersion === "string" && PG_VERSION.test(pgVersion)) return null;
4721
+ return `\`pgVersion\` must be a PostgreSQL version written like '16.8' (major, or major.minor); got ${JSON.stringify(pgVersion)}.`;
4722
+ }
4723
+
4724
+ // src/roles/sql/enum-values.ts
4725
+ function sqlStatements(text) {
4726
+ const statements = [];
4727
+ let current = "";
4728
+ let start = -1;
4729
+ let line = 1;
4730
+ const flush = () => {
4731
+ if (current.trim() !== "") statements.push({ text: current.trim(), line: start });
4732
+ current = "";
4733
+ start = -1;
4734
+ };
4735
+ const begin = () => {
4736
+ if (start === -1) start = line;
4737
+ };
4738
+ let index = 0;
4739
+ while (index < text.length) {
4740
+ const character = text[index];
4741
+ const next = text[index + 1];
4742
+ if (character === "\n") {
4743
+ line++;
4744
+ current += character;
4745
+ index++;
4746
+ continue;
4747
+ }
4748
+ if (character === "-" && next === "-") {
4749
+ const end = text.indexOf("\n", index);
4750
+ index = end === -1 ? text.length : end;
4751
+ current += " ";
4752
+ continue;
4753
+ }
4754
+ if (character === "/" && next === "*") {
4755
+ let depth = 0;
4756
+ let at = index;
4757
+ while (at < text.length) {
4758
+ if (text[at] === "/" && text[at + 1] === "*") {
4759
+ depth++;
4760
+ at += 2;
4761
+ } else if (text[at] === "*" && text[at + 1] === "/") {
4762
+ depth--;
4763
+ at += 2;
4764
+ if (depth === 0) break;
4765
+ } else {
4766
+ if (text[at] === "\n") line++;
4767
+ at++;
4768
+ }
4769
+ }
4770
+ if (depth !== 0) return void 0;
4771
+ index = at;
4772
+ current += " ";
4773
+ continue;
4774
+ }
4775
+ if (character === ";") {
4776
+ flush();
4777
+ index++;
4778
+ continue;
4779
+ }
4780
+ if (character === "'" || character === '"') {
4781
+ begin();
4782
+ const escapes = character === "'" && /[Ee]/.test(text[index - 1] ?? "") && !/[\w$]/.test(text[index - 2] ?? "");
4783
+ let at = index + 1;
4784
+ for (; ; ) {
4785
+ if (at >= text.length) return void 0;
4786
+ const here = text[at];
4787
+ if (escapes && here === "\\") {
4788
+ at += 2;
4789
+ continue;
4790
+ }
4791
+ if (here === character) {
4792
+ if (text[at + 1] === character) {
4793
+ at += 2;
4794
+ continue;
4795
+ }
4796
+ break;
4797
+ }
4798
+ at++;
4799
+ }
4800
+ const quoted = text.slice(index, at + 1);
4801
+ line += quoted.split("\n").length - 1;
4802
+ current += quoted;
4803
+ index = at + 1;
4804
+ continue;
4805
+ }
4806
+ if (character === "$" && !/[\w$]/.test(text[index - 1] ?? "")) {
4807
+ const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(text.slice(index));
4808
+ if (tag !== null) {
4809
+ begin();
4810
+ const close = text.indexOf(tag[0], index + tag[0].length);
4811
+ if (close === -1) return void 0;
4812
+ const body = text.slice(index, close + tag[0].length);
4813
+ line += body.split("\n").length - 1;
4814
+ current += body;
4815
+ index = close + tag[0].length;
4816
+ continue;
4817
+ }
4818
+ }
4819
+ if (!/\s/.test(character)) begin();
4820
+ current += character;
4821
+ index++;
4822
+ }
4823
+ flush();
4824
+ return statements;
4825
+ }
4826
+ var ADD_VALUE = /^ALTER\s+TYPE\s+((?:"(?:[^"]|"")+"|[\w$]+)(?:\s*\.\s*(?:"(?:[^"]|"")+"|[\w$]+))?)\s+ADD\s+VALUE\s+(?:IF\s+NOT\s+EXISTS\s+)?'((?:[^']|'')*)'/i;
4827
+ var ENDS_TRANSACTION = /^(?:COMMIT|END|ROLLBACK|ABORT)\b(?!\s+TO\b)/i;
4828
+ function enumValueFindings(file, text, count) {
4829
+ const statements = sqlStatements(text);
4830
+ if (statements === void 0 || statements.length !== count || count < 2) return [];
4831
+ const findings = [];
4832
+ let added = [];
4833
+ for (const statement of statements) {
4834
+ if (ENDS_TRANSACTION.test(statement.text)) {
4835
+ added = [];
4836
+ continue;
4837
+ }
4838
+ const add2 = ADD_VALUE.exec(statement.text);
4839
+ for (const value of add2 === null ? added : []) {
4840
+ if (!statement.text.includes(`'${value.value.replace(/'/g, "''")}'`)) continue;
4841
+ findings.push(finding2(file, statement.line, value));
4842
+ }
4843
+ if (add2 !== null) {
4844
+ added.push({
4845
+ type: add2[1],
4846
+ value: add2[2].replace(/''/g, "'"),
4847
+ line: statement.line
4848
+ });
4849
+ }
4850
+ }
4851
+ return findings;
4852
+ }
4853
+ function finding2(file, line, value) {
4854
+ return {
4855
+ file,
4856
+ line,
4857
+ column: 1,
4858
+ endLine: line,
4859
+ endColumn: 1,
4860
+ rule: ENUM_VALUE_RULE,
4861
+ squawkLevel: "Warning",
4862
+ message: `'${value.value}' is added to the enum ${value.type} on line ${value.line}, and this statement uses it in the same transaction, if it means that value: Prisma runs a migration of several statements in one transaction, where PostgreSQL refuses a new enum value before it is committed (55P04), so the deploy fails with P3018 and every next one is refused`,
4863
+ note: null,
4864
+ help: "give the ALTER TYPE \u2026 ADD VALUE a migration of its own, before the one that uses the value"
4865
+ };
4866
+ }
4867
+
4580
4868
  // src/roles/sql/history.ts
4581
4869
  import { spawnSync as spawnSync6 } from "node:child_process";
4582
4870
  import { readdirSync as readdirSync3 } from "node:fs";
4583
- import { basename, dirname as dirname2, join as join22, matchesGlob } from "node:path";
4584
- var APPLIED_RULE = "applied-migration-changed";
4871
+ import { basename, dirname as dirname2, join as join23, matchesGlob } from "node:path";
4585
4872
  function appliedMigrationChanges(cwd, sha, settings, nested = []) {
4586
4873
  const diff = git2(cwd, [
4587
4874
  "diff",
@@ -4650,7 +4937,7 @@ function appliedMigrationChanges(cwd, sha, settings, nested = []) {
4650
4937
  }
4651
4938
  const renamed = added.find((other) => !claimed.has(other.path) && same(other));
4652
4939
  if (renamed === void 0) {
4653
- const folderKept = holdsFiles(join22(cwd, dirname2(entry.path)));
4940
+ const folderKept = holdsFiles(join23(cwd, dirname2(entry.path)));
4654
4941
  changes.push({ kind: "deleted", file: entry.path, ...folderKept ? { folderKept } : {} });
4655
4942
  } else {
4656
4943
  claimed.add(renamed.path);
@@ -4765,810 +5052,135 @@ function historyFindings(changes, baseRef2) {
4765
5052
  });
4766
5053
  }
4767
5054
 
4768
- // src/roles/sql/unsafe/unsafe-calls.ts
4769
- import { dirname as dirname3, join as join23 } from "node:path";
4770
- import { parseSync as parseSync3 } from "oxc-parser";
4771
- var UNSAFE_RULE = "unsafe-sql-pasted-value";
4772
- var UNSAFE_METHODS = ["$queryRawUnsafe", "$executeRawUnsafe"];
4773
- var RAW_FRAGMENT_RULE = "unsafe-sql-raw-fragment";
4774
- var BOTH = { methods: true, raw: true };
4775
- var MAX_DEPTH = 12;
4776
- function checkUnsafeCalls(cwd, file, text, readFile, checking = BOTH) {
4777
- const parsed = parse(join23(cwd, file), text);
4778
- if (!parsed.ok) return parsed;
4779
- const findings = [];
4780
- let calls = 0;
4781
- let rawCalls = 0;
4782
- const files = new FileCache(readFile);
4783
- files.set(parsed.file);
4784
- const imports = {
4785
- prisma: prismaNames(parsed.file.bindings),
4786
- prismaNamespaces: prismaNamespacesOf(parsed.file.program),
4787
- unsafeAliases: unsafeAliasesOf(parsed.file.program, parsed.file.bindings),
4788
- ...driversImported(parsed.file.program)
4789
- };
4790
- walk(parsed.file.program, (node) => {
4791
- const call = sqlTextCall(node, imports, text);
4792
- if (call === void 0) return;
4793
- const raw = call.rule === RAW_FRAGMENT_RULE;
4794
- if (raw ? !checking.raw : !checking.methods) return;
4795
- if (call.texts.length === 0) return;
4796
- if (raw) rawCalls++;
4797
- else calls++;
4798
- const context2 = { file: parsed.file, files, depth: 0, local: /* @__PURE__ */ new Map() };
4799
- const pasted = call.texts.flatMap((sql) => unsafeParts(sql, context2));
4800
- const [first] = pasted;
4801
- if (first === void 0) return;
4802
- findings.push(findingOf(file, text, call, first, pasted));
4803
- });
4804
- return { ok: true, calls, rawCalls, findings };
4805
- }
4806
- function parse(path2, text) {
4807
- const { program, errors } = parseSync3(path2, text, { sourceType: "module" });
4808
- if (errors.length > 0) {
4809
- return {
4810
- ok: false,
4811
- reason: `does not parse (${errors[0]?.message ?? "unknown error"}), so its calls are not checked`
4812
- };
4813
- }
4814
- const tree = program;
4815
- return { ok: true, file: { path: path2, text, program: tree, bindings: bindingsOf(tree) } };
4816
- }
4817
- function bindingsOf(program) {
4818
- const bindings = /* @__PURE__ */ new Map();
4819
- const bind = (name, binding) => {
4820
- bindings.set(name, [...bindings.get(name) ?? [], binding]);
4821
- };
4822
- walk(program, (node) => {
4823
- switch (node.type) {
4824
- case "VariableDeclaration": {
4825
- for (const declarator of node.declarations) {
4826
- const id = declarator.id;
4827
- const init = declarator.init;
4828
- if (node.kind === "const" && id.type === "Identifier" && init) {
4829
- bind(id.name, { kind: "const", init });
4830
- } else {
4831
- for (const name of namesIn(id)) bind(name, { kind: "other" });
4832
- }
4833
- }
4834
- return;
4835
- }
4836
- case "ImportDeclaration": {
4837
- if (node.importKind === "type") return;
4838
- for (const specifier of node.specifiers ?? []) {
4839
- const local = specifier.local.name;
4840
- const imported = specifier.imported;
4841
- if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported) {
4842
- const name = imported.name ?? imported.value;
4843
- bind(local, {
4844
- kind: "import",
4845
- source: node.source.value,
4846
- imported: name
4847
- });
4848
- } else if (specifier.type !== "ImportSpecifier") {
4849
- bind(local, { kind: "other" });
4850
- }
4851
- }
4852
- return;
4853
- }
4854
- case "FunctionDeclaration":
4855
- case "FunctionExpression":
4856
- case "ArrowFunctionExpression":
4857
- if (node.id) bind(node.id.name, { kind: "other" });
4858
- for (const param of node.params) {
4859
- for (const name of namesIn(param)) bind(name, { kind: "other" });
4860
- }
4861
- return;
4862
- case "ClassDeclaration":
4863
- case "ClassExpression":
4864
- case "TSEnumDeclaration":
4865
- if (node.id) bind(node.id.name, { kind: "other" });
4866
- return;
4867
- case "CatchClause":
4868
- if (node.param)
4869
- for (const name of namesIn(node.param)) bind(name, { kind: "other" });
4870
- return;
4871
- default:
4872
- return;
4873
- }
5055
+ // src/roles/sql/adapters/squawk/rule-notes.ts
5056
+ var usesConcurrently = (statement) => /\bconcurrently\b/i.test(statement);
5057
+ var toVarcharOrText = (sql) => /\btype\s+(?:varchar|character\s+varying|text)\b/i.test(sql);
5058
+ var PRISMA_TRANSACTION_PROOF = 'Proven on PostgreSQL 16.8 with Prisma 6.19.3 (sentinel #152): a file holding only `CREATE INDEX CONCURRENTLY` applies; the same file with a `SET` before it fails with P3018 / 25001 "CREATE INDEX CONCURRENTLY cannot run inside a transaction block", because Prisma runs a file of several statements inside one transaction (prisma/prisma#22922). Across the monorepo\'s 40 migrations using CONCURRENTLY, every one is alone in its file.';
5059
+ var CONCURRENTLY_ALONE = {
5060
+ short: "Prisma runs a multi-statement file in a transaction, where CONCURRENTLY fails: give the statement its own migration.",
5061
+ note: "Add CONCURRENTLY only to a statement that is alone in its migration. Prisma runs a file of one statement as it is, and a file of several inside one transaction, where PostgreSQL refuses CONCURRENTLY: the deploy stops with P3018 / 25001, nothing of the file is applied, and the next deploy refuses (P3009) until `prisma migrate resolve --rolled-back <migration>`. So move the index into a migration folder of its own, one CONCURRENTLY statement per migration (`prisma migrate dev --create-only` creates one without applying it), and keep the rest of the change in another. A comment line beside the statement is fine.",
5062
+ source: 'Proven on PostgreSQL 16.8 with Prisma 6.19.3 (sentinel #152): a file holding only `DROP INDEX CONCURRENTLY` applies; a file of two `DROP INDEX CONCURRENTLY` fails with P3018 / 25001 "DROP INDEX CONCURRENTLY cannot run inside a transaction block", both indexes still there, the migration recorded as not finished, and the next `migrate deploy` refuses with P3009; a `DROP INDEX` followed by `CREATE INDEX CONCURRENTLY` in one file fails the same way ("CREATE INDEX CONCURRENTLY cannot run inside a transaction block"). The same three statements as three migrations, one with a comment line, apply, and the new index is valid. `--create-only` is listed by `prisma migrate dev --help` in 6.19.3. Prisma wraps a file of several statements in a transaction: prisma/prisma#22922.'
5063
+ };
5064
+ var RULE_NOTES = {
5065
+ "require-lock-timeout": {
5066
+ appliesTo: usesConcurrently,
5067
+ short: "With CONCURRENTLY, add no SET to the file: keep it alone; lock_timeout goes on the deploy job's DATABASE_URL.",
5068
+ note: "If this statement uses CONCURRENTLY, do not add `SET lock_timeout` to this file: with Prisma, a file of two statements runs inside a transaction and CONCURRENTLY then fails. Keep the statement alone in its file. The timeout belongs to the connection `prisma migrate deploy` opens, which is the deploy job, not this file: ask its owners to add `?options=-c%20lock_timeout%3D5s` to its DATABASE_URL, knowing it then applies to every migration that deploy runs. If it fires, Prisma marks the migration as failed and the next deploy stops until the job runs `prisma migrate resolve --rolled-back <migration>`. For any other statement, `SET lock_timeout = '5s';` on the line before it is the fix squawk describes.",
5069
+ source: `${PRISMA_TRANSACTION_PROOF} Also proven: with \`options=-c lock_timeout=2s\` on the URL and the table locked by another session, the lone CONCURRENTLY stops after 2 s with 55P03 "canceling statement due to lock timeout" (without it, it waits for the lock); the option changes nothing when there is no lock; the next deploy refuses with P3009 until \`migrate resolve --rolled-back\`, and then applies. A \`SET lock_timeout\` before an \`ALTER TABLE\` in a two-statement file stops it the same way. That the option holds for every migration of the deploy is how PostgreSQL applies a connection's \`options\`, which set the session's parameters for everything it runs (PostgreSQL documentation, libpq \`options\`).`
5070
+ },
5071
+ "require-statement-timeout": {
5072
+ appliesTo: usesConcurrently,
5073
+ short: "With CONCURRENTLY, add no SET to the file: keep it alone; statement_timeout goes on the deploy job's DATABASE_URL.",
5074
+ note: "If this statement uses CONCURRENTLY, do not add `SET statement_timeout` to this file: with Prisma, a file of two statements runs inside a transaction and CONCURRENTLY then fails. Keep the statement alone in its file. A statement_timeout belongs to the connection the deploy job opens (`?options=-c%20statement_timeout%3D\u2026` in its DATABASE_URL), set by its owners, and then applies to every migration that deploy runs: building an index on a large table takes time, and the timeout stops it.",
5075
+ source: `${PRISMA_TRANSACTION_PROOF} Also proven: with \`options=-c statement_timeout=1s\` on the URL, a migration running \`SELECT pg_sleep(3)\` stops with "canceling statement due to statement timeout". No value is recommended: none was measured on a real table.`
5076
+ },
5077
+ "require-concurrent-index-creation": CONCURRENTLY_ALONE,
5078
+ "require-concurrent-index-deletion": CONCURRENTLY_ALONE,
5079
+ /**
5080
+ * squawk reports this once sentinel reads a file of several statements as Prisma runs it, in a
5081
+ * transaction (`runSquawk`), for CREATE, DROP and REINDEX … CONCURRENTLY and DETACH PARTITION …
5082
+ * CONCURRENTLY (measured on 2.72.0). squawk's words are generic; sentinel's say what happens at
5083
+ * deploy and what to do, the advice of the two rules above.
5084
+ */
5085
+ "ban-concurrent-index-creation-in-transaction": CONCURRENTLY_ALONE,
5086
+ /**
5087
+ * squawk says a change of type rewrites the table. A widening does not, and its risk is the lock
5088
+ * wait, which is a different fix. Héla's decision (2026-11-15): add the note, once proven.
5089
+ */
5090
+ "changing-column-type": {
5091
+ appliesTo: toVarcharOrText,
5092
+ short: "Widening a varchar, or to text, rewrites nothing; only the lock wait remains: put SET lock_timeout before the ALTER.",
5093
+ note: "If the column was a shorter varchar, or a varchar becoming text, PostgreSQL rewrites nothing: the change is immediate whatever the size of the table, and its indexes are kept. It still takes an ACCESS EXCLUSIVE lock, and waits for it behind any transaction open on the table, holding up every query that arrives after it. So the risk is the wait, and a `SET lock_timeout = '\u2026';` before the statement bounds it, as require-lock-timeout says. Any other change of type rewrites the table and rebuilds its indexes under that lock, from UUID or INTEGER to text, or a varchar made shorter: squawk's advice stands for those. The statement does not say what the column was: the migration that created it does.",
5094
+ source: 'Proven on PostgreSQL 16.8 (sentinel #152), on a table of 2 000 000 rows: varchar(20) to varchar(40), then to text, each in under 4 ms, the table and its index keeping their files (`pg_relation_filenode` unchanged), so nothing was rewritten. The widening holds `AccessExclusiveLock` on the table. Behind a transaction holding the table for 5 s, it waited 4.3 s, and a plain SELECT arriving after it waited 3.3 s; with `options=-c lock_timeout=1s` it stopped after 1 s with "canceling statement due to lock timeout" and the SELECT went through at once. On 500 000 rows, UUID to text and varchar(5) to varchar(3) each rewrote the table (new filenode, 0.7 to 0.8 s), the UUID primary key index rebuilt too.'
5095
+ }
5096
+ };
5097
+ function noteFor(rule) {
5098
+ return Object.hasOwn(RULE_NOTES, rule) ? RULE_NOTES[rule] : void 0;
5099
+ }
5100
+ function noteForStatement(rule, sql) {
5101
+ const note = noteFor(rule);
5102
+ if (note === void 0) return null;
5103
+ if (note.appliesTo !== void 0 && sql !== null && !note.appliesTo(sql)) return null;
5104
+ return { short: note.short, note: note.note, source: note.source };
5105
+ }
5106
+
5107
+ // src/roles/sql/report/model.ts
5108
+ var EXCERPT_LINES = 12;
5109
+ function withNotes(findings, textOf, rules = {}) {
5110
+ const lines = /* @__PURE__ */ new Map();
5111
+ const linesOf2 = (file) => {
5112
+ if (!lines.has(file)) lines.set(file, textOf(file)?.split(/\r?\n/));
5113
+ return lines.get(file);
5114
+ };
5115
+ return findings.map((finding3) => {
5116
+ const fileLines = linesOf2(finding3.file);
5117
+ return {
5118
+ ...finding3,
5119
+ level: levelOf(rules, finding3.rule),
5120
+ sentinelNote: noteForStatement(finding3.rule, spanOf(fileLines, finding3)),
5121
+ excerpt: excerptOf(fileLines, finding3)
5122
+ };
4874
5123
  });
4875
- return bindings;
4876
5124
  }
4877
- function namesIn(pattern) {
4878
- if (!pattern) return [];
4879
- switch (pattern.type) {
4880
- case "Identifier":
4881
- return [pattern.name];
4882
- case "ObjectPattern":
4883
- return pattern.properties.flatMap(
4884
- (property) => property.type === "RestElement" ? namesIn(property.argument) : namesIn(property.value)
4885
- );
4886
- case "ArrayPattern":
4887
- return pattern.elements.flatMap((element) => namesIn(element));
4888
- case "AssignmentPattern":
4889
- return namesIn(pattern.left);
4890
- case "RestElement":
4891
- return namesIn(pattern.argument);
4892
- case "TSParameterProperty":
4893
- return namesIn(pattern.parameter);
4894
- default:
4895
- return [];
4896
- }
5125
+ function spanOf(lines, finding3) {
5126
+ if (lines === void 0 || finding3.line < 1 || finding3.endLine > lines.length) return null;
5127
+ if (finding3.endLine < finding3.line) return null;
5128
+ const picked = lines.slice(finding3.line - 1, finding3.endLine);
5129
+ const last = picked.length - 1;
5130
+ return picked.map((text, index) => {
5131
+ const from = index === 0 ? finding3.column - 1 : 0;
5132
+ return index === last ? text.slice(from, finding3.endColumn) : text.slice(from);
5133
+ }).join("\n");
4897
5134
  }
4898
- var FileCache = class {
4899
- constructor(readFile) {
4900
- this.readFile = readFile;
4901
- }
4902
- readFile;
4903
- parsed = /* @__PURE__ */ new Map();
4904
- set(file) {
4905
- this.parsed.set(file.path, file);
4906
- }
4907
- /** The file a relative specifier names from `from`, or null when it cannot be read or parsed. */
4908
- resolve(from, specifier) {
4909
- for (const candidate of candidatesFor(join23(dirname3(from), specifier))) {
4910
- if (this.parsed.has(candidate)) return this.parsed.get(candidate) ?? null;
4911
- const text = this.readFile(candidate);
4912
- if (text === void 0) continue;
4913
- const parsed = parse(candidate, text);
4914
- const file = parsed.ok ? parsed.file : null;
4915
- this.parsed.set(candidate, file);
4916
- return file;
4917
- }
4918
- return null;
5135
+ function excerptOf(lines, finding3) {
5136
+ if (lines === void 0 || finding3.line < 1 || finding3.line > lines.length) return null;
5137
+ const last = Math.min(finding3.endLine, finding3.line + EXCERPT_LINES - 1, lines.length);
5138
+ return lines.slice(finding3.line - 1, last).join("\n");
5139
+ }
5140
+ function byRule(findings) {
5141
+ const groups = /* @__PURE__ */ new Map();
5142
+ for (const finding3 of findings) {
5143
+ if (finding3.rule === SYNTAX_ERROR) continue;
5144
+ groups.set(finding3.rule, [...groups.get(finding3.rule) ?? [], finding3]);
4919
5145
  }
4920
- };
4921
- function candidatesFor(base) {
4922
- const typescript = base.replace(
4923
- /\.(m|c)?js$/,
4924
- (_, kind) => `.${kind ?? ""}ts`
5146
+ return [...groups].map(([rule, list]) => ({ rule, findings: [...list].sort(byPlace) })).sort(
5147
+ (a, b) => errorsFirst(a.findings, b.findings) || b.findings.length - a.findings.length || a.rule.localeCompare(b.rule)
4925
5148
  );
5149
+ }
5150
+ function errorsFirst(a, b) {
5151
+ return Number(b[0]?.level === "error") - Number(a[0]?.level === "error");
5152
+ }
5153
+ function countedFindings(findings) {
4926
5154
  return [
4927
- ...typescript === base ? [] : [typescript],
4928
- base,
4929
- ...RESOLVABLE_EXTENSIONS.map((extension) => `${base}${extension}`),
4930
- ...RESOLVABLE_EXTENSIONS.map((extension) => join23(base, `index${extension}`))
5155
+ ...findings.filter((finding3) => finding3.rule !== SYNTAX_ERROR),
5156
+ ...unparsedMigrations(findings).map(({ first }) => first)
4931
5157
  ];
4932
5158
  }
4933
- var KNOWN_METHODS = /* @__PURE__ */ new Set([...UNSAFE_METHODS, "raw", "join", "query", "unsafe"]);
4934
- function callShape(node, imports) {
4935
- const callee = unwrap(node.callee);
4936
- const args = node.arguments ?? [];
4937
- const alias = (expression) => expression.type === "Identifier" ? imports.unsafeAliases.get(expression.name) : void 0;
4938
- const aliased = alias(callee);
4939
- if (aliased !== void 0) return { name: aliased, object: void 0, args, callee };
4940
- const name = memberName(callee);
4941
- if (name === void 0) return void 0;
4942
- if (name === "call" || name === "apply") {
4943
- const target = unwrap(callee.object);
4944
- const method = alias(target) ?? memberName(target);
4945
- if (method === void 0 || !KNOWN_METHODS.has(method)) return void 0;
4946
- const object = alias(target) === void 0 ? unwrap(target.object) : void 0;
4947
- if (name === "call") return { name: method, object, args: args.slice(1), callee: target };
4948
- const list = args[1] === void 0 ? void 0 : unwrap(args[1]);
4949
- const applied = list === void 0 ? [] : list.type === "ArrayExpression" ? list.elements.filter(
4950
- (item) => item !== null
4951
- ) : [{ type: "SpreadElement", argument: list, start: list.start, end: list.end }];
4952
- return { name: method, object, args: applied, callee: target };
4953
- }
4954
- return { name, object: unwrap(callee.object), args, callee };
4955
- }
4956
- function textsAt(args, from, to = from + 1) {
4957
- const texts = [];
4958
- for (let index = 0; index < Math.min(args.length, to); index++) {
4959
- const argument = args[index];
4960
- if (argument.type === "SpreadElement") {
4961
- texts.push(argument.argument);
4962
- return texts;
4963
- }
4964
- if (index >= from) texts.push(argument);
5159
+ var errorFindings = (findings) => countedFindings(findings).filter((finding3) => finding3.level === "error");
5160
+ function unparsedMigrations(findings) {
5161
+ const byFile2 = /* @__PURE__ */ new Map();
5162
+ for (const finding3 of findings) {
5163
+ if (finding3.rule !== SYNTAX_ERROR) continue;
5164
+ byFile2.set(finding3.file, [...byFile2.get(finding3.file) ?? [], finding3]);
4965
5165
  }
4966
- return texts;
4967
- }
4968
- function unsafeAliasesOf(program, bindings) {
4969
- const isUnsafe = (name) => name !== void 0 && UNSAFE_METHODS.includes(name);
4970
- const declared = /* @__PURE__ */ new Map();
4971
- const alias = (local, method) => {
4972
- declared.set(local, [...declared.get(local) ?? [], method]);
4973
- };
4974
- walk(program, (node) => {
4975
- if (node.type !== "VariableDeclarator" || !node.init) return;
4976
- const id = node.id;
4977
- let init = unwrap(node.init);
4978
- if (id.type === "ObjectPattern") {
4979
- for (const property of id.properties) {
4980
- if (property.type !== "Property" || property.computed) continue;
4981
- const key = property.key.name ?? property.key.value;
4982
- const value = unwrap(property.value);
4983
- const local = value.type === "AssignmentPattern" ? unwrap(value.left) : value;
4984
- if (isUnsafe(key) && local.type === "Identifier") {
4985
- alias(local.name, key);
4986
- }
4987
- }
4988
- return;
4989
- }
4990
- if (id.type !== "Identifier") return;
4991
- if (init.type === "CallExpression" && memberName(unwrap(init.callee)) === "bind") {
4992
- init = unwrap(unwrap(init.callee).object ?? init);
4993
- }
4994
- const method = memberName(init);
4995
- if (isUnsafe(method)) alias(id.name, method);
5166
+ return [...byFile2.values()].map((errors) => {
5167
+ const [first] = [...errors].sort((a, b) => a.line - b.line || a.column - b.column);
5168
+ return { first, more: errors.length - 1 };
4996
5169
  });
4997
- const aliases = /* @__PURE__ */ new Map();
4998
- for (const [local, methods] of declared) {
4999
- const [method] = methods;
5000
- const everyBinding = methods.length === (bindings.get(local)?.length ?? 0);
5001
- if (method !== void 0 && everyBinding && methods.every((other) => other === method))
5002
- aliases.set(local, method);
5003
- }
5004
- return aliases;
5005
5170
  }
5006
- function prismaNamespacesOf(program) {
5007
- const names = /* @__PURE__ */ new Set();
5008
- walk(program, (node) => {
5009
- if (node.type !== "ImportDeclaration" || node.importKind === "type") return;
5010
- const source = node.source.value;
5011
- if (typeof source !== "string" || !source.startsWith("@prisma/")) return;
5012
- for (const specifier of node.specifiers ?? []) {
5013
- if (specifier.type === "ImportNamespaceSpecifier") {
5014
- names.add(specifier.local.name);
5015
- }
5016
- }
5017
- });
5018
- return names;
5171
+ function byPlace(a, b) {
5172
+ return a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column;
5019
5173
  }
5020
- function driversImported(program) {
5021
- const sources = /* @__PURE__ */ new Set();
5022
- walk(program, (node) => {
5023
- if (node.type === "ImportDeclaration") {
5024
- sources.add(node.source.value);
5025
- } else if (node.type === "CallExpression") {
5026
- const callee = node.callee;
5027
- const [first] = node.arguments ?? [];
5028
- if (callee.type === "Identifier" && callee.name === "require" && first?.type === "Literal" && typeof first.value === "string") {
5029
- sources.add(first.value);
5030
- }
5031
- }
5032
- });
5033
- return { pg: sources.has("pg"), postgres: sources.has("postgres") };
5034
- }
5035
- function memberName(callee) {
5036
- if (!MEMBER_TYPES.has(callee.type)) return void 0;
5037
- const property = callee.property;
5038
- if (!callee.computed) return property.name;
5039
- return property.type === "Literal" && typeof property.value === "string" ? property.value : void 0;
5040
- }
5041
- function isPrisma(object, imports) {
5042
- if (object === void 0) return false;
5043
- if (object.type === "Identifier") return imports.prisma.has(object.name);
5044
- if (memberName(object) !== "Prisma") return false;
5045
- const namespace = unwrap(object.object);
5046
- return namespace.type === "Identifier" && imports.prismaNamespaces.has(namespace.name);
5047
- }
5048
- function sqlTextCall(node, imports, text) {
5049
- if (node.type !== "CallExpression") return void 0;
5050
- const shape = callShape(node, imports);
5051
- if (shape === void 0) return void 0;
5052
- const { name, args, callee } = shape;
5053
- const onPrisma = isPrisma(shape.object, imports);
5054
- if (UNSAFE_METHODS.includes(name)) {
5055
- return {
5056
- label: name,
5057
- rule: UNSAFE_RULE,
5058
- texts: textsAt(args, 0),
5059
- help: `pass a value as a parameter (\`$1\` in the text, the value after it), or use the tagged ${name.replace("Unsafe", "")}\`\u2026\`, which binds each \`\${}\`; a table or column name cannot be a parameter: take it from a \`const\` of this file`
5060
- };
5061
- }
5062
- if (onPrisma && name === "raw") {
5063
- return {
5064
- label: "Prisma.raw",
5065
- rule: RAW_FRAGMENT_RULE,
5066
- texts: textsAt(args, 0),
5067
- help: `Prisma.raw puts its text in the query as SQL, never as a parameter: pass a value as \`\${value}\` in Prisma.sql\`\u2026\`, which binds it; for a keyword or a column name, write each choice as a literal, \`order === 'DESC' ? Prisma.raw('DESC') : Prisma.raw('ASC')\`, or take it from a \`const\` of this file`
5068
- };
5069
- }
5070
- if (onPrisma && name === "join") {
5071
- return {
5072
- label: "Prisma.join",
5073
- rule: RAW_FRAGMENT_RULE,
5074
- // The list is bound; the separator, prefix and suffix are SQL text.
5075
- texts: textsAt(args, 1, 4),
5076
- help: `Prisma.join binds the values of its list, but its separator, prefix and suffix are SQL text: write them as literals (\`Prisma.join(conditions, ' AND ')\`)`
5077
- };
5078
- }
5079
- if (shape.object === void 0) return void 0;
5080
- const shown = sourceOf(text, callee);
5081
- if (imports.pg && name === "query") {
5082
- const [first] = textsAt(args, 0);
5083
- const sql = first?.type === "ObjectExpression" ? propertyValue(first, "text") : first;
5084
- return {
5085
- label: `${shown} (pg)`,
5086
- rule: UNSAFE_RULE,
5087
- texts: sql === void 0 ? [] : [sql],
5088
- help: `pass a value as a parameter: \`$1\` in the text, the value in the array after it (\`client.query(text, [value])\`); a table or column name cannot be a parameter: take it from a \`const\` of this file`
5089
- };
5090
- }
5091
- if (imports.postgres && name === "unsafe") {
5092
- return {
5093
- label: `${shown} (postgres)`,
5094
- rule: UNSAFE_RULE,
5095
- texts: textsAt(args, 0),
5096
- help: `use the tagged sql\`\u2026\${value}\u2026\`, which binds each value; for a table or column name, \`sql(name)\` quotes it as an identifier`
5097
- };
5098
- }
5099
- return void 0;
5100
- }
5101
- function propertyValue(object, key) {
5102
- for (const property of object.properties) {
5103
- if (property.type !== "Property" || property.computed) continue;
5104
- const name = property.key.name ?? property.key.value;
5105
- if (name === key) return property.value;
5106
- }
5107
- return void 0;
5108
- }
5109
- function prismaNames(bindings) {
5110
- const names = /* @__PURE__ */ new Set();
5111
- for (const [name, bound] of bindings) {
5112
- const fromPrisma = bound.some(
5113
- (binding) => binding.kind === "import" && binding.imported === "Prisma" && binding.source.startsWith("@prisma/")
5114
- );
5115
- if (fromPrisma) names.add(name);
5116
- }
5117
- return names;
5118
- }
5119
- function unwrap(node) {
5120
- let current = node;
5121
- while ([
5122
- "ParenthesizedExpression",
5123
- "TSAsExpression",
5124
- "TSSatisfiesExpression",
5125
- "TSNonNullExpression",
5126
- "TSTypeAssertion",
5127
- "ChainExpression"
5128
- ].includes(current.type)) {
5129
- current = current.expression;
5130
- }
5131
- return current;
5132
- }
5133
- function unsafeParts(sql, context2) {
5134
- const node = unwrap(sql);
5135
- if (node.type === "TemplateLiteral") {
5136
- return node.expressions.flatMap((part) => unsafeParts(part, context2));
5137
- }
5138
- if (node.type === "BinaryExpression" && node.operator === "+") {
5139
- if (isNumeric(node, context2)) return [];
5140
- return [
5141
- ...unsafeParts(node.left, context2),
5142
- ...unsafeParts(node.right, context2)
5143
- ];
5144
- }
5145
- return isSafe(node, context2) ? [] : [node];
5146
- }
5147
- var NUMERIC_OPERATORS = /* @__PURE__ */ new Set(["-", "*", "/", "%", "**", "|", "&", "^", "<<", ">>", ">>>"]);
5148
- function isSafe(expression, context2) {
5149
- if (context2.depth > MAX_DEPTH) return false;
5150
- const node = unwrap(expression);
5151
- switch (node.type) {
5152
- case "Literal":
5153
- return true;
5154
- case "TemplateLiteral":
5155
- return node.expressions.every((part) => isSafe(part, context2));
5156
- case "BinaryExpression":
5157
- return node.operator === "+" ? isSafe(node.left, context2) && isSafe(node.right, context2) : NUMERIC_OPERATORS.has(node.operator) || // A comparison is a boolean.
5158
- ["==", "!=", "===", "!==", "<", "<=", ">", ">=", "in", "instanceof"].includes(
5159
- node.operator
5160
- );
5161
- case "UnaryExpression":
5162
- return true;
5163
- case "ConditionalExpression":
5164
- return isSafe(node.consequent, context2) && isSafe(node.alternate, context2);
5165
- case "LogicalExpression":
5166
- return isSafe(node.left, context2) && isSafe(node.right, context2);
5167
- case "Identifier":
5168
- return isSafeName(node.name, context2);
5169
- case "CallExpression":
5170
- return isPlaceholderList(node, context2);
5171
- default:
5172
- return false;
5173
- }
5174
- }
5175
- function isNumeric(node, context2) {
5176
- const current = unwrap(node);
5177
- if (current.type === "Literal") return typeof current.value === "number";
5178
- if (current.type === "BinaryExpression") {
5179
- if (NUMERIC_OPERATORS.has(current.operator)) return true;
5180
- if (current.operator === "+") {
5181
- return isNumeric(current.left, context2) && isNumeric(current.right, context2);
5182
- }
5183
- }
5184
- if (current.type === "UnaryExpression")
5185
- return ["-", "+", "~"].includes(current.operator);
5186
- if (current.type === "Identifier") return context2.local.get(current.name) === true;
5187
- return false;
5188
- }
5189
- function isSafeName(name, context2) {
5190
- if (context2.local.has(name)) return context2.local.get(name) === true;
5191
- const bindings = context2.file.bindings.get(name) ?? [];
5192
- if (bindings.length !== 1) return false;
5193
- const [binding] = bindings;
5194
- const deeper = { ...context2, depth: context2.depth + 1, local: /* @__PURE__ */ new Map() };
5195
- if (binding?.kind === "const") return isSafe(binding.init, deeper);
5196
- if (binding?.kind === "import") return isSafeImport(binding.source, binding.imported, deeper);
5197
- return false;
5198
- }
5199
- function isSafeImport(source, imported, context2) {
5200
- if (!source.startsWith(".")) return false;
5201
- const file = context2.files.resolve(context2.file.path, source);
5202
- if (file === null) return false;
5203
- const exported = exportedConst(file, imported);
5204
- return exported !== void 0 && isSafe(exported, { ...context2, file });
5205
- }
5206
- function exportedConst(file, name) {
5207
- for (const statement of file.program.body) {
5208
- if (statement.type !== "ExportNamedDeclaration") continue;
5209
- const declaration = statement.declaration;
5210
- if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const") continue;
5211
- for (const declarator of declaration.declarations) {
5212
- const id = declarator.id;
5213
- if (id.type === "Identifier" && id.name === name && declarator.init)
5214
- return declarator.init;
5215
- }
5216
- }
5217
- return void 0;
5218
- }
5219
- function isPlaceholderList(call, context2) {
5220
- const join43 = unwrap(call.callee);
5221
- if (!MEMBER_TYPES.has(join43.type) || join43.property.name !== "join") return false;
5222
- const separator = call.arguments[0];
5223
- if (separator !== void 0 && !isSafe(separator, context2)) return false;
5224
- const map = unwrap(join43.object);
5225
- if (map.type !== "CallExpression") return false;
5226
- const mapCallee = unwrap(map.callee);
5227
- if (!MEMBER_TYPES.has(mapCallee.type) || mapCallee.property.name !== "map")
5228
- return false;
5229
- const callback = map.arguments[0];
5230
- if (callback === void 0) return false;
5231
- if (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression")
5232
- return false;
5233
- const returned = returnedExpression(callback);
5234
- if (returned === void 0) return false;
5235
- const params = callback.params;
5236
- const local = new Map(context2.local);
5237
- params.forEach((param, position) => {
5238
- for (const name of namesIn(param))
5239
- local.set(name, position === 1 && param.type === "Identifier");
5240
- });
5241
- return isSafe(returned, { ...context2, depth: context2.depth + 1, local });
5242
- }
5243
- function returnedExpression(callback) {
5244
- const body = callback.body;
5245
- if (body.type !== "BlockStatement") return body;
5246
- const statements = body.body;
5247
- const [only] = statements;
5248
- return statements.length === 1 && only?.type === "ReturnStatement" && only.argument ? only.argument : void 0;
5249
- }
5250
- function findingOf(file, text, call, first, pasted) {
5251
- const start = positionOf(text, first.start);
5252
- const end = positionOf(text, Math.max(first.end - 1, first.start));
5253
- const shown = pasted.slice(0, 3).map((part) => codeSpan(sourceOf(text, part)));
5254
- const more = pasted.length > 3 ? ` and ${pasted.length - 3} more` : "";
5255
- const whole = call.texts.some((sql) => unwrap(sql) === first);
5256
- const method = call.label;
5257
- return {
5258
- file,
5259
- line: start.line,
5260
- column: start.column,
5261
- endLine: end.line,
5262
- endColumn: end.column,
5263
- rule: call.rule,
5264
- squawkLevel: "Warning",
5265
- message: whole ? `the SQL text of ${method} is ${shown[0]}, which sentinel cannot show is a constant: whatever was pasted into it, wherever it was built, runs as SQL` : `${shown.join(", ")}${more} ${pasted.length === 1 ? "is" : "are"} pasted into the SQL text of ${method}, and sentinel cannot show ${pasted.length === 1 ? "it is" : "they are"} constant: a quote in ${pasted.length === 1 ? "it" : "them"} would end the string and run the rest as SQL`,
5266
- note: null,
5267
- help: call.help
5268
- };
5269
- }
5270
- function sourceOf(text, node) {
5271
- const source = text.slice(node.start, node.end).replace(/\s+/g, " ");
5272
- return source.length > 60 ? `${source.slice(0, 57)}\u2026` : source;
5273
- }
5274
- function codeSpan(source) {
5275
- return `\`${source.replace(/`/g, "'")}\``;
5276
- }
5277
- function positionOf(text, offset) {
5278
- const before = text.slice(0, offset);
5279
- const lineStart = before.lastIndexOf("\n") + 1;
5280
- return { line: before.split("\n").length, column: offset - lineStart + 1 };
5281
- }
5282
- function readOne(cwd, file, text, readFile, checking) {
5283
- try {
5284
- return checkUnsafeCalls(cwd, file, text, readFile, checking);
5285
- } catch (error) {
5286
- const why = error instanceof RangeError ? "an expression too deeply nested to follow" : error instanceof Error ? error.message : String(error);
5287
- return { ok: false, reason: `could not be checked (${why}), so its calls are not checked` };
5288
- }
5289
- }
5290
- function checkUnsafeFiles(cwd, files, readFile, checking = BOTH) {
5291
- const run = { calls: 0, rawCalls: 0, findings: [], unparsed: [] };
5292
- for (const file of files) {
5293
- const text = readFile(join23(cwd, file));
5294
- if (text === void 0) {
5295
- run.unparsed.push({ file, reason: "could not be read, so its calls are not checked" });
5296
- continue;
5297
- }
5298
- const reading = readOne(cwd, file, text, readFile, checking);
5299
- if (!reading.ok) {
5300
- run.unparsed.push({ file, reason: reading.reason });
5301
- continue;
5302
- }
5303
- run.calls += reading.calls;
5304
- run.rawCalls += reading.rawCalls;
5305
- run.findings.push(...reading.findings);
5306
- }
5307
- return run;
5308
- }
5309
-
5310
- // src/roles/sql/configs/rule-levels.ts
5311
- var SENTINEL_RULES = [UNSAFE_RULE, RAW_FRAGMENT_RULE, APPLIED_RULE];
5312
- var SYNTAX_ERROR = "syntax-error";
5313
- var NOT_SQUAWK_CONFIG = [...SENTINEL_RULES, SYNTAX_ERROR];
5314
- var LEVELS = ["off", "warn", "error"];
5315
- function levelOf(rules, rule) {
5316
- return Object.hasOwn(rules, rule) && rules[rule] === "error" ? "error" : "warn";
5317
- }
5318
- function rulesOff(rules) {
5319
- return Object.keys(rules).filter((rule) => rules[rule] === "off").sort();
5320
- }
5321
- function rulesOn(rules) {
5322
- return Object.keys(rules).filter((rule) => rules[rule] !== "off").sort();
5323
- }
5324
- function rulesProblem(rules) {
5325
- if (rules === null || typeof rules !== "object" || Array.isArray(rules)) {
5326
- return `\`rules\` must be an object of rule names and levels, like { 'ban-drop-column': 'error' }; got ${JSON.stringify(rules)}.`;
5327
- }
5328
- for (const [rule, level] of Object.entries(rules)) {
5329
- const name = nameProblem(rule);
5330
- if (name) return name;
5331
- if (rule === SYNTAX_ERROR && level === "off") {
5332
- return `\`rules['${SYNTAX_ERROR}']\` can be 'warn' or 'error', not 'off': a migration that does not parse is refused by PostgreSQL at deploy, so it is always reported.`;
5333
- }
5334
- if (!LEVELS.includes(level)) {
5335
- return `\`rules['${rule}']\` must be 'off', 'warn' or 'error'; got ${JSON.stringify(level)}.`;
5336
- }
5337
- }
5338
- return null;
5339
- }
5340
- function nameProblem(rule) {
5341
- if (squawkRules.rules.includes(rule) || NOT_SQUAWK_CONFIG.includes(rule)) return null;
5342
- const standsFor = Object.hasOwn(squawkRules.aliases, rule) ? squawkRules.aliases[rule] : void 0;
5343
- if (standsFor !== void 0) {
5344
- const names = standsFor.map((name) => `'${name}'`).join(" and ");
5345
- return `\`rules['${rule}']\`: squawk reports this rule as ${names}, so a level on '${rule}' would never apply. Write ${names} instead.`;
5346
- }
5347
- const near = nearest(rule);
5348
- return `\`rules['${rule}']\` is not a rule of squawk ${squawkRules.squawk} or of sentinel.` + (near ? ` Did you mean '${near}'?` : "") + ` The names are listed by \`pnpm exec sentinel --inspect --sql --json\`.`;
5349
- }
5350
- function nearest(rule) {
5351
- let best;
5352
- for (const name of [...squawkRules.rules, ...NOT_SQUAWK_CONFIG]) {
5353
- const distance = editDistance(rule, name);
5354
- if (distance <= 3 && (best === void 0 || distance < best.distance)) best = { name, distance };
5355
- }
5356
- return best?.name;
5357
- }
5358
- function editDistance(a, b) {
5359
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
5360
- for (let i = 1; i <= a.length; i++) {
5361
- const current = [i];
5362
- for (let j = 1; j <= b.length; j++) {
5363
- current[j] = Math.min(
5364
- (previous[j] ?? 0) + 1,
5365
- (current[j - 1] ?? 0) + 1,
5366
- (previous[j - 1] ?? 0) + (a[i - 1] === b[j - 1] ? 0 : 1)
5367
- );
5368
- }
5369
- previous = current;
5370
- }
5371
- return previous[b.length] ?? 0;
5372
- }
5373
-
5374
- // src/roles/sql/configs/resolve.ts
5375
- async function loadSqlConfig(cwd) {
5376
- const path2 = join24(cwd, SQL_CONFIG_FILE);
5377
- if (!existsSync15(path2)) return { config: defineSql(), from: null, unreadable: null };
5378
- try {
5379
- const loaded = await import(pathToFileURL2(path2).href);
5380
- const config = adopt(loaded.default);
5381
- const problem = configProblem(config);
5382
- if (problem)
5383
- return { config: defineSql(), from: null, unreadable: `${SQL_CONFIG_FILE}: ${problem}` };
5384
- return { config, from: SQL_CONFIG_FILE, unreadable: null };
5385
- } catch (error) {
5386
- return {
5387
- config: defineSql(),
5388
- from: null,
5389
- unreadable: `${SQL_CONFIG_FILE}: ${explainUnreadableSqlConfig(error)}`
5390
- };
5391
- }
5392
- }
5393
- function explainUnreadableSqlConfig(error) {
5394
- const message = error instanceof Error ? error.message : String(error);
5395
- const code = error?.code;
5396
- if (code !== "ERR_PACKAGE_PATH_NOT_EXPORTED" || !message.includes("@hublo/sentinel")) {
5397
- return message;
5398
- }
5399
- return `${message}
5400
- The @hublo/sentinel installed in this module does not ship the sql role yet. Bump it to a release that does, then run this again.`;
5401
- }
5402
- function adopt(exported) {
5403
- if (exported === null || typeof exported !== "object") return defineSql();
5404
- if (Array.isArray(exported.moved)) return exported;
5405
- return defineSql(exported);
5406
- }
5407
- function configProblem(config) {
5408
- return shapeProblem(settingsOf(config), defaults, "") ?? pgVersionProblem(config.pgVersion) ?? rulesProblem(config.rules);
5409
- }
5410
- function shapeProblem(value, expected, path2) {
5411
- const got = `; got ${JSON.stringify(value)}.`;
5412
- if (Array.isArray(expected)) {
5413
- if (Array.isArray(value) && value.every((item) => typeof item === "string")) return null;
5414
- return `\`${path2}\` must be a list of strings, like ['**/generated/**']${got}`;
5415
- }
5416
- if (typeof expected === "boolean" || typeof expected === "string") {
5417
- if (typeof value === typeof expected) return null;
5418
- return `\`${path2}\` must be a ${typeof expected}, like ${JSON.stringify(expected)}${got}`;
5419
- }
5420
- if (!isPlainObject(value)) return `\`${path2}\` must be an object${got}`;
5421
- if (path2 === "rules") return null;
5422
- const known = Object.keys(expected);
5423
- const named = (key) => path2 ? `${path2}.${key}` : key;
5424
- for (const [key, inner] of Object.entries(value)) {
5425
- if (!known.includes(key)) {
5426
- return `\`${named(key)}\` is not a setting of the sql role, so it would be ignored. The settings here are: ${known.map(named).join(", ")}.`;
5427
- }
5428
- const problem = shapeProblem(inner, expected[key], named(key));
5429
- if (problem) return problem;
5430
- }
5431
- return null;
5432
- }
5433
- function settingsOf(config) {
5434
- const { root: _root, moved: _moved, ...settings } = config;
5435
- return settings;
5436
- }
5437
- var PG_VERSION = /^\d+(?:\.\d+){0,2}$/;
5438
- function pgVersionProblem(pgVersion) {
5439
- if (typeof pgVersion === "string" && PG_VERSION.test(pgVersion)) return null;
5440
- return `\`pgVersion\` must be a PostgreSQL version written like '16.8' (major, or major.minor); got ${JSON.stringify(pgVersion)}.`;
5441
- }
5442
-
5443
- // src/roles/sql/adapters/squawk/rule-notes.ts
5444
- var usesConcurrently = (statement) => /\bconcurrently\b/i.test(statement);
5445
- var toVarcharOrText = (sql) => /\btype\s+(?:varchar|character\s+varying|text)\b/i.test(sql);
5446
- var PRISMA_TRANSACTION_PROOF = 'Proven on PostgreSQL 16.8 with Prisma 6.19.3 (sentinel #152): a file holding only `CREATE INDEX CONCURRENTLY` applies; the same file with a `SET` before it fails with P3018 / 25001 "CREATE INDEX CONCURRENTLY cannot run inside a transaction block", because Prisma runs a file of several statements inside one transaction (prisma/prisma#22922). Across the monorepo\'s 40 migrations using CONCURRENTLY, every one is alone in its file.';
5447
- var CONCURRENTLY_ALONE = {
5448
- short: "Prisma runs a multi-statement file in a transaction, where CONCURRENTLY fails: give the statement its own migration.",
5449
- note: "Add CONCURRENTLY only to a statement that is alone in its migration. Prisma runs a file of one statement as it is, and a file of several inside one transaction, where PostgreSQL refuses CONCURRENTLY: the deploy stops with P3018 / 25001, nothing of the file is applied, and the next deploy refuses (P3009) until `prisma migrate resolve --rolled-back <migration>`. So move the index into a migration folder of its own, one CONCURRENTLY statement per migration (`prisma migrate dev --create-only` creates one without applying it), and keep the rest of the change in another. A comment line beside the statement is fine.",
5450
- source: 'Proven on PostgreSQL 16.8 with Prisma 6.19.3 (sentinel #152): a file holding only `DROP INDEX CONCURRENTLY` applies; a file of two `DROP INDEX CONCURRENTLY` fails with P3018 / 25001 "DROP INDEX CONCURRENTLY cannot run inside a transaction block", both indexes still there, the migration recorded as not finished, and the next `migrate deploy` refuses with P3009; a `DROP INDEX` followed by `CREATE INDEX CONCURRENTLY` in one file fails the same way ("CREATE INDEX CONCURRENTLY cannot run inside a transaction block"). The same three statements as three migrations, one with a comment line, apply, and the new index is valid. `--create-only` is listed by `prisma migrate dev --help` in 6.19.3. Prisma wraps a file of several statements in a transaction: prisma/prisma#22922.'
5451
- };
5452
- var RULE_NOTES = {
5453
- "require-lock-timeout": {
5454
- appliesTo: usesConcurrently,
5455
- short: "With CONCURRENTLY, add no SET to the file: keep it alone; lock_timeout goes on the deploy job's DATABASE_URL.",
5456
- note: "If this statement uses CONCURRENTLY, do not add `SET lock_timeout` to this file: with Prisma, a file of two statements runs inside a transaction and CONCURRENTLY then fails. Keep the statement alone in its file. The timeout belongs to the connection `prisma migrate deploy` opens, which is the deploy job, not this file: ask its owners to add `?options=-c%20lock_timeout%3D5s` to its DATABASE_URL, knowing it then applies to every migration that deploy runs. If it fires, Prisma marks the migration as failed and the next deploy stops until the job runs `prisma migrate resolve --rolled-back <migration>`. For any other statement, `SET lock_timeout = '5s';` on the line before it is the fix squawk describes.",
5457
- source: `${PRISMA_TRANSACTION_PROOF} Also proven: with \`options=-c lock_timeout=2s\` on the URL and the table locked by another session, the lone CONCURRENTLY stops after 2 s with 55P03 "canceling statement due to lock timeout" (without it, it waits for the lock); the option changes nothing when there is no lock; the next deploy refuses with P3009 until \`migrate resolve --rolled-back\`, and then applies. A \`SET lock_timeout\` before an \`ALTER TABLE\` in a two-statement file stops it the same way. That the option holds for every migration of the deploy is how PostgreSQL applies a connection's \`options\`, which set the session's parameters for everything it runs (PostgreSQL documentation, libpq \`options\`).`
5458
- },
5459
- "require-statement-timeout": {
5460
- appliesTo: usesConcurrently,
5461
- short: "With CONCURRENTLY, add no SET to the file: keep it alone; statement_timeout goes on the deploy job's DATABASE_URL.",
5462
- note: "If this statement uses CONCURRENTLY, do not add `SET statement_timeout` to this file: with Prisma, a file of two statements runs inside a transaction and CONCURRENTLY then fails. Keep the statement alone in its file. A statement_timeout belongs to the connection the deploy job opens (`?options=-c%20statement_timeout%3D\u2026` in its DATABASE_URL), set by its owners, and then applies to every migration that deploy runs: building an index on a large table takes time, and the timeout stops it.",
5463
- source: `${PRISMA_TRANSACTION_PROOF} Also proven: with \`options=-c statement_timeout=1s\` on the URL, a migration running \`SELECT pg_sleep(3)\` stops with "canceling statement due to statement timeout". No value is recommended: none was measured on a real table.`
5464
- },
5465
- "require-concurrent-index-creation": CONCURRENTLY_ALONE,
5466
- "require-concurrent-index-deletion": CONCURRENTLY_ALONE,
5467
- /**
5468
- * squawk reports this once sentinel reads a file of several statements as Prisma runs it, in a
5469
- * transaction (`runSquawk`), for CREATE, DROP and REINDEX … CONCURRENTLY and DETACH PARTITION …
5470
- * CONCURRENTLY (measured on 2.72.0). squawk's words are generic; sentinel's say what happens at
5471
- * deploy and what to do, the advice of the two rules above.
5472
- */
5473
- "ban-concurrent-index-creation-in-transaction": CONCURRENTLY_ALONE,
5474
- /**
5475
- * squawk says a change of type rewrites the table. A widening does not, and its risk is the lock
5476
- * wait, which is a different fix. Héla's decision (2026-11-15): add the note, once proven.
5477
- */
5478
- "changing-column-type": {
5479
- appliesTo: toVarcharOrText,
5480
- short: "Widening a varchar, or to text, rewrites nothing; only the lock wait remains: put SET lock_timeout before the ALTER.",
5481
- note: "If the column was a shorter varchar, or a varchar becoming text, PostgreSQL rewrites nothing: the change is immediate whatever the size of the table, and its indexes are kept. It still takes an ACCESS EXCLUSIVE lock, and waits for it behind any transaction open on the table, holding up every query that arrives after it. So the risk is the wait, and a `SET lock_timeout = '\u2026';` before the statement bounds it, as require-lock-timeout says. Any other change of type rewrites the table and rebuilds its indexes under that lock, from UUID or INTEGER to text, or a varchar made shorter: squawk's advice stands for those. The statement does not say what the column was: the migration that created it does.",
5482
- source: 'Proven on PostgreSQL 16.8 (sentinel #152), on a table of 2 000 000 rows: varchar(20) to varchar(40), then to text, each in under 4 ms, the table and its index keeping their files (`pg_relation_filenode` unchanged), so nothing was rewritten. The widening holds `AccessExclusiveLock` on the table. Behind a transaction holding the table for 5 s, it waited 4.3 s, and a plain SELECT arriving after it waited 3.3 s; with `options=-c lock_timeout=1s` it stopped after 1 s with "canceling statement due to lock timeout" and the SELECT went through at once. On 500 000 rows, UUID to text and varchar(5) to varchar(3) each rewrote the table (new filenode, 0.7 to 0.8 s), the UUID primary key index rebuilt too.'
5483
- }
5484
- };
5485
- function noteFor(rule) {
5486
- return Object.hasOwn(RULE_NOTES, rule) ? RULE_NOTES[rule] : void 0;
5487
- }
5488
- function noteForStatement(rule, sql) {
5489
- const note = noteFor(rule);
5490
- if (note === void 0) return null;
5491
- if (note.appliesTo !== void 0 && sql !== null && !note.appliesTo(sql)) return null;
5492
- return { short: note.short, note: note.note, source: note.source };
5493
- }
5494
-
5495
- // src/roles/sql/report/model.ts
5496
- var EXCERPT_LINES = 12;
5497
- function withNotes(findings, textOf, rules = {}) {
5498
- const lines = /* @__PURE__ */ new Map();
5499
- const linesOf2 = (file) => {
5500
- if (!lines.has(file)) lines.set(file, textOf(file)?.split(/\r?\n/));
5501
- return lines.get(file);
5502
- };
5503
- return findings.map((finding2) => {
5504
- const fileLines = linesOf2(finding2.file);
5505
- return {
5506
- ...finding2,
5507
- level: levelOf(rules, finding2.rule),
5508
- sentinelNote: noteForStatement(finding2.rule, spanOf(fileLines, finding2)),
5509
- excerpt: excerptOf(fileLines, finding2)
5510
- };
5511
- });
5512
- }
5513
- function spanOf(lines, finding2) {
5514
- if (lines === void 0 || finding2.line < 1 || finding2.endLine > lines.length) return null;
5515
- if (finding2.endLine < finding2.line) return null;
5516
- const picked = lines.slice(finding2.line - 1, finding2.endLine);
5517
- const last = picked.length - 1;
5518
- return picked.map((text, index) => {
5519
- const from = index === 0 ? finding2.column - 1 : 0;
5520
- return index === last ? text.slice(from, finding2.endColumn) : text.slice(from);
5521
- }).join("\n");
5522
- }
5523
- function excerptOf(lines, finding2) {
5524
- if (lines === void 0 || finding2.line < 1 || finding2.line > lines.length) return null;
5525
- const last = Math.min(finding2.endLine, finding2.line + EXCERPT_LINES - 1, lines.length);
5526
- return lines.slice(finding2.line - 1, last).join("\n");
5527
- }
5528
- function byRule(findings) {
5529
- const groups = /* @__PURE__ */ new Map();
5530
- for (const finding2 of findings) {
5531
- if (finding2.rule === SYNTAX_ERROR) continue;
5532
- groups.set(finding2.rule, [...groups.get(finding2.rule) ?? [], finding2]);
5533
- }
5534
- return [...groups].map(([rule, list]) => ({ rule, findings: [...list].sort(byPlace) })).sort(
5535
- (a, b) => errorsFirst(a.findings, b.findings) || b.findings.length - a.findings.length || a.rule.localeCompare(b.rule)
5536
- );
5537
- }
5538
- function errorsFirst(a, b) {
5539
- return Number(b[0]?.level === "error") - Number(a[0]?.level === "error");
5540
- }
5541
- function countedFindings(findings) {
5542
- return [
5543
- ...findings.filter((finding2) => finding2.rule !== SYNTAX_ERROR),
5544
- ...unparsedMigrations(findings).map(({ first }) => first)
5545
- ];
5546
- }
5547
- var errorFindings = (findings) => countedFindings(findings).filter((finding2) => finding2.level === "error");
5548
- function unparsedMigrations(findings) {
5549
- const byFile2 = /* @__PURE__ */ new Map();
5550
- for (const finding2 of findings) {
5551
- if (finding2.rule !== SYNTAX_ERROR) continue;
5552
- byFile2.set(finding2.file, [...byFile2.get(finding2.file) ?? [], finding2]);
5553
- }
5554
- return [...byFile2.values()].map((errors) => {
5555
- const [first] = [...errors].sort((a, b) => a.line - b.line || a.column - b.column);
5556
- return { first, more: errors.length - 1 };
5557
- });
5558
- }
5559
- function byPlace(a, b) {
5560
- return a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column;
5561
- }
5562
- var placeOf = (finding2) => `${finding2.file}:${finding2.line}:${finding2.column}`;
5174
+ var placeOf = (finding3) => `${finding3.file}:${finding3.line}:${finding3.column}`;
5563
5175
 
5564
5176
  // src/roles/sql/report/outputs.ts
5565
5177
  import { existsSync as existsSync16, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2, writeFileSync as writeFileSync6 } from "node:fs";
5566
- import { join as join26 } from "node:path";
5178
+ import { join as join25 } from "node:path";
5567
5179
 
5568
5180
  // src/roles/static-analysis/maintainability/size-rules.ts
5569
5181
  import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync5 } from "node:fs";
5570
5182
  import { tmpdir } from "node:os";
5571
- import { join as join25 } from "node:path";
5183
+ import { join as join24 } from "node:path";
5572
5184
  var GAUGE_THRESHOLDS = {
5573
5185
  // McCabe 1976 says 10, our p90 says 11. The only indicator where two independent candidates agree
5574
5186
  // within one unit, and 94.8% of our functions already sit in the 1-10 band SEI calls low risk.
@@ -5597,7 +5209,7 @@ var GAUGE_THRESHOLDS = {
5597
5209
  "cognitive-complexity": 7
5598
5210
  };
5599
5211
  var COGNITIVE = "cognitive-complexity";
5600
- var cognitivePlugin = () => join25(ownPackageDir(), "plugins", "sonar-cognitive.js");
5212
+ var cognitivePlugin = () => join24(ownPackageDir(), "plugins", "sonar-cognitive.js");
5601
5213
  var CATEGORIES = [
5602
5214
  "correctness",
5603
5215
  "suspicious",
@@ -5629,8 +5241,8 @@ function sizeRulesConfig() {
5629
5241
  };
5630
5242
  }
5631
5243
  function sizeRulesRun(paths2, ignore) {
5632
- const dir = mkdtempSync(join25(tmpdir(), "sentinel-size-"));
5633
- const configPath = join25(dir, "oxlintrc.json");
5244
+ const dir = mkdtempSync(join24(tmpdir(), "sentinel-size-"));
5245
+ const configPath = join24(dir, "oxlintrc.json");
5634
5246
  writeFileSync5(configPath, `${JSON.stringify(sizeRulesConfig(), null, 2)}
5635
5247
  `, "utf8");
5636
5248
  return {
@@ -6155,23 +5767,23 @@ function helpDetails(help, withoutReference) {
6155
5767
  <p class="source">Source: ${prose(help.source)}</p>
6156
5768
  </details>`;
6157
5769
  }
6158
- function secondSide(finding2) {
6159
- if (!finding2.other) return "";
5770
+ function secondSide(finding3) {
5771
+ if (!finding3.other) return "";
6160
5772
  const file = (at) => at.split(":")[0] ?? at;
6161
- const sameFile = file(finding2.other) === file(finding2.path);
5773
+ const sameFile = file(finding3.other) === file(finding3.path);
6162
5774
  const label = sameFile ? "and line" : "and";
6163
- const shownSide = sameFile ? finding2.other.split(":")[1] ?? finding2.other : finding2.other;
5775
+ const shownSide = sameFile ? finding3.other.split(":")[1] ?? finding3.other : finding3.other;
6164
5776
  return ` <span class="unit">${label}</span> <code>${escape(shownSide)}</code>`;
6165
5777
  }
6166
5778
  var HTML_GROUP_LIMIT = 50;
6167
5779
  function listedByMetric(findings) {
6168
5780
  const groups = /* @__PURE__ */ new Map();
6169
- for (const finding2 of findings) {
6170
- const bucket = groups.get(finding2.metric) ?? [];
6171
- bucket.push(finding2);
6172
- groups.set(finding2.metric, bucket);
5781
+ for (const finding3 of findings) {
5782
+ const bucket = groups.get(finding3.metric) ?? [];
5783
+ bucket.push(finding3);
5784
+ groups.set(finding3.metric, bucket);
6173
5785
  }
6174
- const weight = (finding2) => finding2.value ?? finding2.lines ?? 0;
5786
+ const weight = (finding3) => finding3.value ?? finding3.lines ?? 0;
6175
5787
  return new Map(
6176
5788
  [...groups.entries()].map(([metric, all2]) => {
6177
5789
  const sorted = [...all2].sort((left, right) => weight(right) - weight(left));
@@ -6276,8 +5888,8 @@ function renderJson2(report) {
6276
5888
  function renderMarkdown2(report) {
6277
5889
  const version = report.settings.find((setting) => setting.key === "sentinel")?.value;
6278
5890
  const places2 = /* @__PURE__ */ new Map();
6279
- for (const finding2 of report.findings) {
6280
- places2.set(finding2.metric, (places2.get(finding2.metric) ?? 0) + 1);
5891
+ for (const finding3 of report.findings) {
5892
+ places2.set(finding3.metric, (places2.get(finding3.metric) ?? 0) + 1);
6281
5893
  }
6282
5894
  const figureLine = (row) => {
6283
5895
  const help = helpFor(row.metric);
@@ -6331,64 +5943,64 @@ function ruleChip(metric) {
6331
5943
  const threshold = GAUGE_THRESHOLDS[metric];
6332
5944
  return threshold === void 0 ? "" : ` <span class="chip"><code>${escape(metric)}</code> &gt; ${threshold}</span>`;
6333
5945
  }
6334
- function measureOf(finding2) {
6335
- const metric = finding2.metric;
5946
+ function measureOf(finding3) {
5947
+ const metric = finding3.metric;
6336
5948
  const number = (value, unit = "") => `<span class="pmeas">${grouped(value)}${unit === "" ? "" : `<span class="unit">${escape(unit)}</span>`}</span>`;
6337
- if (finding2.value !== void 0) {
6338
- if (GAUGE_THRESHOLDS[metric] !== void 0) return number(finding2.value);
6339
- if (metric.startsWith("complexity")) return number(finding2.value, "complexity");
6340
- if (finding2.dependsOn !== void 0) return number(finding2.value, "imported by");
6341
- if (metric === "cycles") return number(finding2.value, "files in the cycle");
6342
- return number(finding2.value);
5949
+ if (finding3.value !== void 0) {
5950
+ if (GAUGE_THRESHOLDS[metric] !== void 0) return number(finding3.value);
5951
+ if (metric.startsWith("complexity")) return number(finding3.value, "complexity");
5952
+ if (finding3.dependsOn !== void 0) return number(finding3.value, "imported by");
5953
+ if (metric === "cycles") return number(finding3.value, "files in the cycle");
5954
+ return number(finding3.value);
6343
5955
  }
6344
- return finding2.lines === void 0 ? "" : number(finding2.lines, "lines");
5956
+ return finding3.lines === void 0 ? "" : number(finding3.lines, "lines");
6345
5957
  }
6346
- function metaOf(finding2) {
5958
+ function metaOf(finding3) {
6347
5959
  const pairs = [];
6348
5960
  const add2 = (label, value) => {
6349
5961
  pairs.push(`<span class="pair"><span class="k">${escape(label)}</span>${value}</span>`);
6350
5962
  };
6351
- if (finding2.name) {
5963
+ if (finding3.name) {
6352
5964
  add2(
6353
- finding2.metric.startsWith("complexity") ? "function" : "name",
6354
- `<code>${escape(finding2.name)}</code>`
5965
+ finding3.metric.startsWith("complexity") ? "function" : "name",
5966
+ `<code>${escape(finding3.name)}</code>`
6355
5967
  );
6356
5968
  }
6357
- if (finding2.dependsOn !== void 0) add2("depends on", String(finding2.dependsOn));
6358
- if (finding2.instability !== void 0) add2("instability", finding2.instability.toFixed(2));
6359
- if (finding2.centrality !== void 0) add2("centrality", finding2.centrality.toFixed(4));
6360
- if (finding2.lines !== void 0 && finding2.value !== void 0)
6361
- add2("length", `${finding2.lines} lines`);
6362
- if (finding2.confidence !== void 0) add2("confidence", `${finding2.confidence}%`);
6363
- if (finding2.reason) add2("unsure", `<span class="reason">${escape(finding2.reason)}</span>`);
5969
+ if (finding3.dependsOn !== void 0) add2("depends on", String(finding3.dependsOn));
5970
+ if (finding3.instability !== void 0) add2("instability", finding3.instability.toFixed(2));
5971
+ if (finding3.centrality !== void 0) add2("centrality", finding3.centrality.toFixed(4));
5972
+ if (finding3.lines !== void 0 && finding3.value !== void 0)
5973
+ add2("length", `${finding3.lines} lines`);
5974
+ if (finding3.confidence !== void 0) add2("confidence", `${finding3.confidence}%`);
5975
+ if (finding3.reason) add2("unsure", `<span class="reason">${escape(finding3.reason)}</span>`);
6364
5976
  return pairs.length === 0 ? "" : ` <div class="pmeta">${pairs.join("")}</div>
6365
5977
  `;
6366
5978
  }
6367
- function codeSummary(finding2) {
6368
- const count = finding2.excerpt === void 0 ? 0 : finding2.excerpt.split("\n").length;
6369
- if (finding2.metric === "clones" || finding2.metric === "clonesTests") {
6370
- return `${finding2.lines ?? count} duplicated lines`;
5979
+ function codeSummary(finding3) {
5980
+ const count = finding3.excerpt === void 0 ? 0 : finding3.excerpt.split("\n").length;
5981
+ if (finding3.metric === "clones" || finding3.metric === "clonesTests") {
5982
+ return `${finding3.lines ?? count} duplicated lines`;
6371
5983
  }
6372
- if (finding2.excerptFirstLine === 1) return `the first ${count} lines`;
6373
- return `${count} lines from ${finding2.excerptFirstLine ?? "?"}`;
5984
+ if (finding3.excerptFirstLine === 1) return `the first ${count} lines`;
5985
+ return `${count} lines from ${finding3.excerptFirstLine ?? "?"}`;
6374
5986
  }
6375
- function codeBlock(finding2) {
6376
- if (finding2.excerpt === void 0) return "";
6377
- const first = finding2.excerptFirstLine;
6378
- const body = first === void 0 ? escape(finding2.excerpt) : finding2.excerpt.split("\n").map((line, offset) => `<span class="n">${first + offset}</span>${escape(line)}`).join("\n");
5987
+ function codeBlock(finding3) {
5988
+ if (finding3.excerpt === void 0) return "";
5989
+ const first = finding3.excerptFirstLine;
5990
+ const body = first === void 0 ? escape(finding3.excerpt) : finding3.excerpt.split("\n").map((line, offset) => `<span class="n">${first + offset}</span>${escape(line)}`).join("\n");
6379
5991
  return ` <details class="pcode">
6380
- <summary>${escape(codeSummary(finding2))}</summary>
5992
+ <summary>${escape(codeSummary(finding3))}</summary>
6381
5993
  <pre class="code">${body}</pre>
6382
5994
  </details>
6383
5995
  `;
6384
5996
  }
6385
- function placeCard(finding2) {
5997
+ function placeCard(finding3) {
6386
5998
  return ` <div class="pcard">
6387
5999
  <div class="phead">
6388
- <code class="path">${escape(finding2.path)}</code>${secondSide(finding2)}
6389
- <span class="pright">${measureOf(finding2)}${ruleChip(finding2.metric)}</span>
6000
+ <code class="path">${escape(finding3.path)}</code>${secondSide(finding3)}
6001
+ <span class="pright">${measureOf(finding3)}${ruleChip(finding3.metric)}</span>
6390
6002
  </div>
6391
- ${metaOf(finding2)}${codeBlock(finding2)} </div>`;
6003
+ ${metaOf(finding3)}${codeBlock(finding3)} </div>`;
6392
6004
  }
6393
6005
  function placesFor(group) {
6394
6006
  const total = group.listed.length + group.rest;
@@ -6396,7 +6008,7 @@ function placesFor(group) {
6396
6008
  return ` <details class="place">
6397
6009
  <summary>where to look <span class="count">${grouped(total)} ${total === 1 ? "place" : "places"}</span>${capped}</summary>
6398
6010
  <div class="cards">
6399
- ${group.listed.map((finding2) => placeCard(finding2)).join("\n")}
6011
+ ${group.listed.map((finding3) => placeCard(finding3)).join("\n")}
6400
6012
  </div>
6401
6013
  ${group.rest > 0 ? ` <p class="sub">The other ${group.rest} are not on this page. <code>${SCRIPTS2.json}</code> writes all of them, from the same run as this one.</p>` : ""}
6402
6014
  </details>`;
@@ -6453,17 +6065,17 @@ var KIND_UNITS = {
6453
6065
  cycles: "files",
6454
6066
  mostImported: "imported by"
6455
6067
  };
6456
- function findingRow(finding2) {
6457
- const path2 = finding2.path;
6068
+ function findingRow(finding3) {
6069
+ const path2 = finding3.path;
6458
6070
  const cut = path2.lastIndexOf("/");
6459
6071
  const dir = cut === -1 ? "" : path2.slice(0, cut + 1);
6460
6072
  const file = cut === -1 ? path2 : path2.slice(cut + 1);
6461
- const measure = finding2.value ?? finding2.lines;
6462
- const unit = KIND_UNITS[finding2.metric];
6463
- const haystack = [path2, finding2.name, finding2.other].filter(Boolean).join(" ").toLowerCase();
6464
- return ` <tr data-kind="${escape(kindOf(finding2.metric))}" data-find="${escape(haystack)}">
6465
- <td><span class="kind">${escape(kindOf(finding2.metric))}</span></td>
6466
- <td class="where"><span class="dir">${escape(dir)}</span><b>${escape(file)}</b>${finding2.name === void 0 ? "" : `<span class="sym">${escape(finding2.name)}</span>`}${finding2.other === void 0 ? "" : `<span class="sym">&#8596; ${escape(finding2.other)}</span>`}</td>
6073
+ const measure = finding3.value ?? finding3.lines;
6074
+ const unit = KIND_UNITS[finding3.metric];
6075
+ const haystack = [path2, finding3.name, finding3.other].filter(Boolean).join(" ").toLowerCase();
6076
+ return ` <tr data-kind="${escape(kindOf(finding3.metric))}" data-find="${escape(haystack)}">
6077
+ <td><span class="kind">${escape(kindOf(finding3.metric))}</span></td>
6078
+ <td class="where"><span class="dir">${escape(dir)}</span><b>${escape(file)}</b>${finding3.name === void 0 ? "" : `<span class="sym">${escape(finding3.name)}</span>`}${finding3.other === void 0 ? "" : `<span class="sym">&#8596; ${escape(finding3.other)}</span>`}</td>
6467
6079
  <td class="meas">${measure === void 0 ? "" : `<b>${escape(typeof measure === "number" ? grouped(measure) : String(measure))}</b>${unit === void 0 ? "" : `<span>${escape(unit)}</span>`}`}</td>
6468
6080
  </tr>`;
6469
6081
  }
@@ -6473,7 +6085,7 @@ function findingsPanel(report) {
6473
6085
  return ` <p class="read">This run produced no finding to list.</p>`;
6474
6086
  }
6475
6087
  const counts2 = /* @__PURE__ */ new Map();
6476
- for (const finding2 of findings) counts2.set(finding2.metric, (counts2.get(finding2.metric) ?? 0) + 1);
6088
+ for (const finding3 of findings) counts2.set(finding3.metric, (counts2.get(finding3.metric) ?? 0) + 1);
6477
6089
  const chips = [...counts2.entries()].map(
6478
6090
  ([metric, count]) => `<button type="button" class="fchip" data-kind="${escape(kindOf(metric))}">${escape(kindOf(metric))} <span>${grouped(count)}</span></button>`
6479
6091
  ).join("\n ");
@@ -6496,7 +6108,7 @@ function findingsPanel(report) {
6496
6108
  <tr><th scope="col">Kind</th><th scope="col">Where</th><th scope="col" class="meas">Measure</th></tr>
6497
6109
  </thead>
6498
6110
  <tbody>
6499
- ${findings.map((finding2) => findingRow(finding2)).join("\n")}
6111
+ ${findings.map((finding3) => findingRow(finding3)).join("\n")}
6500
6112
  </tbody>
6501
6113
  </table>`;
6502
6114
  }
@@ -6509,7 +6121,7 @@ function summaryParts(report, bold) {
6509
6121
  const withReference = report.rows.filter((row) => row.status !== void 0);
6510
6122
  const above = withReference.filter((row) => row.status === "exceed").length;
6511
6123
  const findings = report.findings ?? [];
6512
- const inTests = findings.filter((finding2) => finding2.metric === "clonesTests").length;
6124
+ const inTests = findings.filter((finding3) => finding3.metric === "clonesTests").length;
6513
6125
  const inProduct = findings.length - inTests;
6514
6126
  const thresholds = withReference.length === 0 ? [] : above === 0 ? [`${bold("No threshold exceeded")}: the measured levels are within the recommended norm`] : [`${bold(`${above} threshold${above === 1 ? "" : "s"} exceeded`)}`];
6515
6127
  return [
@@ -7007,694 +6619,1234 @@ ${places2}
7007
6619
  ...complete.filter((family) => family.label === "Bundle"),
7008
6620
  ...complete.filter((family) => family.label !== "Bundle")
7009
6621
  ];
7010
- const absences = report.notes.length === 0 ? "" : ` <div class="notes"><h2>Not measured</h2>${report.notes.map((note) => `<p>${escape(note)}</p>`).join("")}</div>`;
7011
- const overview = `${ordered.map(
7012
- (family, index) => ` <section class="fam">
7013
- <h2>${escape(family.label)}</h2>
7014
- ${family.rows.map((row) => figureBlock(row, placesByMetric.get(row.metric) ?? "")).join("\n")}${orphansFor(family.label)}${index === 0 ? absences : ""}
7015
- </section>`
7016
- ).join(
7017
- "\n"
7018
- )}${report.picture === void 0 ? "" : `
7019
- <section class="fam">
7020
- <h2>Shape</h2>
7021
- ${report.picture}
7022
- </section>`}`;
7023
- const panels = [
7024
- { label: "Overview", body: overview },
7025
- { label: "Findings", body: findingsPanel(report), count: report.findings?.length ?? 0 },
7026
- {
7027
- label: "Settings",
7028
- count: report.settings.length,
7029
- body: ` <p class="panel-note">The settings these figures were produced with. Two modules measured with
7030
- different settings cannot be compared, which is why they travel with the numbers.</p>
7031
- <table class="settings">
7032
- <thead>
7033
- <tr><th scope="col">Setting</th><th scope="col">Value</th><th scope="col">Origin</th></tr>
7034
- </thead>
7035
- <tbody>
7036
- ${settings}
7037
- </tbody>
7038
- </table>`
7039
- }
6622
+ const absences = report.notes.length === 0 ? "" : ` <div class="notes"><h2>Not measured</h2>${report.notes.map((note) => `<p>${escape(note)}</p>`).join("")}</div>`;
6623
+ const overview = `${ordered.map(
6624
+ (family, index) => ` <section class="fam">
6625
+ <h2>${escape(family.label)}</h2>
6626
+ ${family.rows.map((row) => figureBlock(row, placesByMetric.get(row.metric) ?? "")).join("\n")}${orphansFor(family.label)}${index === 0 ? absences : ""}
6627
+ </section>`
6628
+ ).join(
6629
+ "\n"
6630
+ )}${report.picture === void 0 ? "" : `
6631
+ <section class="fam">
6632
+ <h2>Shape</h2>
6633
+ ${report.picture}
6634
+ </section>`}`;
6635
+ const panels = [
6636
+ { label: "Overview", body: overview },
6637
+ { label: "Findings", body: findingsPanel(report), count: report.findings?.length ?? 0 },
6638
+ {
6639
+ label: "Settings",
6640
+ count: report.settings.length,
6641
+ body: ` <p class="panel-note">The settings these figures were produced with. Two modules measured with
6642
+ different settings cannot be compared, which is why they travel with the numbers.</p>
6643
+ <table class="settings">
6644
+ <thead>
6645
+ <tr><th scope="col">Setting</th><th scope="col">Value</th><th scope="col">Origin</th></tr>
6646
+ </thead>
6647
+ <tbody>
6648
+ ${settings}
6649
+ </tbody>
6650
+ </table>`
6651
+ }
6652
+ ];
6653
+ const tabInputs = panels.map(
6654
+ (panel, index) => ` <input class="tab" type="radio" name="tab" id="tab-${index}"${index === 0 ? " checked" : ""}>`
6655
+ ).join("\n");
6656
+ const tabLabels = panels.map(
6657
+ (panel, index) => ` <label for="tab-${index}" id="tablabel-${index}" aria-controls="panel-${index}">${escape(panel.label)}${panel.count === void 0 ? "" : ` <span class="tabn">${grouped(panel.count)}</span>`}</label>`
6658
+ ).join("\n");
6659
+ const tabPanels = panels.map(
6660
+ (panel, index) => ` <section class="panel" data-tab="${index}" id="panel-${index}" aria-labelledby="tablabel-${index}">
6661
+ ${panel.body}
6662
+ </section>`
6663
+ ).join("\n");
6664
+ const page = `<!DOCTYPE html>
6665
+ <html lang="en">
6666
+ <head>
6667
+ <meta charset="utf-8">
6668
+ <title>Static analysis: ${escape(report.module)}</title>
6669
+ <style>${STYLES.replace("__TAB_RULES__", tabRules(panels.length))}</style>
6670
+ </head>
6671
+ <body>
6672
+ <main>
6673
+ <header>
6674
+ <div class="brand"><b>sentinel</b> <span>static analysis</span><span class="stamp">${report.commit == null ? "" : `commit <code>${escape(report.commit)}</code> &middot; `}${escape(report.passes.join(" / "))}</span></div>
6675
+ <h1>${escape(report.module)}</h1>
6676
+ <p class="lede">${summaryLine(report)}</p>
6677
+ ${populationsLine(report)}
6678
+ </header>
6679
+
6680
+ ${tabInputs}
6681
+ <nav class="tabs" aria-label="Figure families">
6682
+ ${tabLabels}
6683
+ </nav>
6684
+ ${tabPanels}
6685
+ <footer>sentinel static-analysis</footer>
6686
+ </main>
6687
+ <script>${FINDINGS_SCRIPT}</script>
6688
+ </body>
6689
+ </html>
6690
+ `;
6691
+ return page.split("\n").map((line) => line.replace(/[ \t]+$/, "")).join("\n");
6692
+ }
6693
+
6694
+ // src/roles/sql/adapters/squawk/summary.ts
6695
+ var PLAIN = { count: String, name: (name) => name };
6696
+ function checkedCalls({ calls, rawCalls }, rulesOff2, mark = PLAIN) {
6697
+ const methods = !rulesOff2.includes(UNSAFE_RULE);
6698
+ const raw = !rulesOff2.includes(RAW_FRAGMENT_RULE);
6699
+ const text = `${mark.count(calls)} call(s) taking SQL text (${mark.name("$queryRawUnsafe")} / ${mark.name("$executeRawUnsafe")}, ${mark.name("pg")}, ${mark.name("postgres")})`;
6700
+ const fragments = `${mark.count(rawCalls)} Prisma fragment(s) (${mark.name("Prisma.raw")}, ${mark.name("Prisma.join")})`;
6701
+ if (methods && raw) return `${text} and ${fragments}`;
6702
+ return methods ? text : fragments;
6703
+ }
6704
+ var CALLED = "raw SQL ($queryRawUnsafe / $executeRawUnsafe, pg, postgres, Prisma.raw, Prisma.join)";
6705
+ function summariseMigrations(outcome) {
6706
+ return [
6707
+ whatWasRead(outcome),
6708
+ ...codeReadLines(outcome),
6709
+ ...offLines(outcome),
6710
+ ...unreadLines(outcome.unread),
6711
+ ...unparsedLines(outcome.code.unparsed),
6712
+ ...syntaxErrorLines(outcome.findings),
6713
+ ...findingLines(outcome.findings)
6714
+ ];
6715
+ }
6716
+ function whatWasRead({ total, read, base }) {
6717
+ if (total === 0 || base === null) return "no migration in this module.";
6718
+ const against = `compared with ${base.ref} at ${base.commit}`;
6719
+ if (read === 0) {
6720
+ return `no migration added or changed by this branch, ${against}. The ${total} in this module are not read: only what a branch introduces is.`;
6721
+ }
6722
+ const others = total - read;
6723
+ return `read ${read} migration(s) this branch adds or changes, ${against}.` + (others > 0 ? ` The ${others} other(s) in this module are unchanged and not read.` : "");
6724
+ }
6725
+ function offLines({ read, rulesOff: rulesOff2, code }) {
6726
+ if (read === 0 && code.files === 0 || rulesOff2.length === 0) return [];
6727
+ return [
6728
+ `this module turns off ${rulesOff2.length} rule(s) in sql.config.mjs, so they are not checked: ${rulesOff2.join(", ")}.`
6729
+ ];
6730
+ }
6731
+ function codeReadLines({ code, rulesOff: rulesOff2 }) {
6732
+ if (code.files === 0) return [];
6733
+ if (rulesOff2.includes(UNSAFE_RULE) && rulesOff2.includes(RAW_FRAGMENT_RULE)) return [];
6734
+ if (code.read === 0) {
6735
+ return [
6736
+ `${code.files} file(s) call ${CALLED}; none is added or changed by this branch, so none is read.`
6737
+ ];
6738
+ }
6739
+ const others = code.files - code.read;
6740
+ return [
6741
+ `checked ${checkedCalls(code, rulesOff2)} in the ${code.read} file(s) this branch adds or changes.` + (others > 0 ? ` The ${others} other file(s) calling them are unchanged and not read.` : "")
6742
+ ];
6743
+ }
6744
+ function unparsedLines(unparsed) {
6745
+ if (unparsed.length === 0) return [];
6746
+ return [
6747
+ `\u2717 ${unparsed.length} TypeScript file(s) could not be read, so their calls are not checked:`,
6748
+ ...unparsed.map(({ file, reason }) => ` ${file}: ${reason}`)
6749
+ ];
6750
+ }
6751
+ function unreadLines(unread) {
6752
+ if (unread.length === 0) return [];
6753
+ return [
6754
+ `\u2717 ${unread.length} migration(s) could not be opened, so nothing about them is checked:`,
6755
+ ...unread.map(({ file, reason }) => ` ${file}: ${reason}`)
6756
+ ];
6757
+ }
6758
+ function syntaxErrorLines(findings) {
6759
+ const files = unparsedMigrations(findings);
6760
+ if (files.length === 0) return [];
6761
+ return [
6762
+ `\u2717 ${files.length} migration(s) do not parse: squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it too. The first error, the one to fix:`,
6763
+ ...files.map(
6764
+ ({ first, more }) => ` ${first.file}:${first.line}:${first.column} ${first.message}` + (more > 0 ? ` (and ${more} more after it)` : "")
6765
+ )
6766
+ ];
6767
+ }
6768
+ function findingLines(findings) {
6769
+ const counted = countedFindings(findings);
6770
+ const errors = errorFindings(findings);
6771
+ const errorRules = new Set(errors.map((finding3) => finding3.rule));
6772
+ const byRule2 = countByRule(counted).sort(
6773
+ ([a], [b]) => Number(errorRules.has(b)) - Number(errorRules.has(a))
6774
+ );
6775
+ if (byRule2.length === 0) return ["no finding."];
6776
+ const total = counted.length;
6777
+ const width = Math.max(...byRule2.map(([rule]) => rule.length));
6778
+ return [
6779
+ errors.length === 0 ? `${total} finding(s), every one a warning while the role is being adopted:` : `\u2717 ${total} finding(s): ${errors.length} error(s), from the rule(s) this module sets to "error" in sql.config.mjs, which fail this run, and ${total - errors.length} warning(s):`,
6780
+ ...byRule2.flatMap(([rule, count]) => {
6781
+ const note = findings.find(
6782
+ (finding3) => finding3.rule === rule && finding3.sentinelNote
6783
+ )?.sentinelNote;
6784
+ return [
6785
+ ` ${rule.padEnd(width)} ${count}${errorRules.has(rule) ? " error" : ""}`,
6786
+ // The one-sentence form: a console is read a line at a time. The full note and its proof
6787
+ // are in the page, the json and `--inspect`.
6788
+ ...note ? [` sentinel's note: ${note.short}`] : [],
6789
+ // The syntax errors' places are listed above, with the error to fix.
6790
+ ...rule === SYNTAX_ERROR ? [] : placeLines(counted, rule)
6791
+ ];
6792
+ })
7040
6793
  ];
7041
- const tabInputs = panels.map(
7042
- (panel, index) => ` <input class="tab" type="radio" name="tab" id="tab-${index}"${index === 0 ? " checked" : ""}>`
7043
- ).join("\n");
7044
- const tabLabels = panels.map(
7045
- (panel, index) => ` <label for="tab-${index}" id="tablabel-${index}" aria-controls="panel-${index}">${escape(panel.label)}${panel.count === void 0 ? "" : ` <span class="tabn">${grouped(panel.count)}</span>`}</label>`
7046
- ).join("\n");
7047
- const tabPanels = panels.map(
7048
- (panel, index) => ` <section class="panel" data-tab="${index}" id="panel-${index}" aria-labelledby="tablabel-${index}">
7049
- ${panel.body}
7050
- </section>`
7051
- ).join("\n");
7052
- const page = `<!DOCTYPE html>
6794
+ }
6795
+ var CONSOLE_PLACES = 3;
6796
+ function placeLines(findings, rule) {
6797
+ const mine = findings.filter((finding3) => finding3.rule === rule).sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
6798
+ const shown = mine.slice(0, CONSOLE_PLACES).map((finding3) => ` ${finding3.file}:${finding3.line}:${finding3.column}`);
6799
+ const more = mine.length - shown.length;
6800
+ return more > 0 ? [...shown, ` and ${more} more: pnpm run sql:html lists them all`] : shown;
6801
+ }
6802
+ function countByRule(findings) {
6803
+ const counts2 = /* @__PURE__ */ new Map();
6804
+ for (const { rule } of findings) counts2.set(rule, (counts2.get(rule) ?? 0) + 1);
6805
+ return [...counts2].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));
6806
+ }
6807
+
6808
+ // src/roles/sql/report/render-html.ts
6809
+ function renderHtml2(report, now = /* @__PURE__ */ new Date()) {
6810
+ return `<!doctype html>
7053
6811
  <html lang="en">
7054
6812
  <head>
7055
6813
  <meta charset="utf-8">
7056
- <title>Static analysis: ${escape(report.module)}</title>
7057
- <style>${STYLES.replace("__TAB_RULES__", tabRules(panels.length))}</style>
6814
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6815
+ <title>SQL \xB7 ${escape(report.module)}</title>
6816
+ <style>${STYLES2}</style>
7058
6817
  </head>
7059
6818
  <body>
7060
6819
  <main>
7061
6820
  <header>
7062
- <div class="brand"><b>sentinel</b> <span>static analysis</span><span class="stamp">${report.commit == null ? "" : `commit <code>${escape(report.commit)}</code> &middot; `}${escape(report.passes.join(" / "))}</span></div>
6821
+ <p class="eyebrow">sentinel \xB7 sql</p>
7063
6822
  <h1>${escape(report.module)}</h1>
7064
- <p class="lede">${summaryLine(report)}</p>
7065
- ${populationsLine(report)}
6823
+ <p class="meta">${meta(report, now)}</p>
7066
6824
  </header>
6825
+ ${counts(report)}
6826
+ ${offSection(report)}
6827
+ ${unreadSection(report)}
6828
+ ${syntaxSection(report)}
6829
+ ${findingsSection(report)}
6830
+ ${readSection(report)}
6831
+ ${unsafeSection(report)}
6832
+ ${settingsSection(report)}
6833
+ <footer>Only the migrations this branch adds or changes are read. ${errorFindings(report.findings).length === 0 ? "Every finding is a warning while the role is being adopted: nothing here fails the run." : "A rule the module sets to <code>error</code> fails the module's <code>sql</code> run; every other finding is a warning."} squawk's text is squawk's; what is labelled sentinel is sentinel's, with how it was proven.</footer>
6834
+ </main>
6835
+ </body>
6836
+ </html>
6837
+ `;
6838
+ }
6839
+ function meta(report, now) {
6840
+ const parts = [
6841
+ report.base ? `compared with <code>${escape(report.base.ref)}</code> at <code>${escape(report.base.commit)}</code>` : "no migration to compare",
6842
+ report.commit ? `commit <code>${escape(report.commit)}</code>` : null,
6843
+ `sentinel ${escape(report.sentinel)}`,
6844
+ `generated ${escape(now.toISOString().slice(0, 16).replace("T", " "))} UTC`
6845
+ ];
6846
+ return parts.filter((part) => part !== null).join(" \xB7 ");
6847
+ }
6848
+ function counts(report) {
6849
+ const syntax = unparsedMigrations(report.findings).length;
6850
+ const cell2 = (value, label, alarm = false) => `<div class="count${alarm && value > 0 ? " alarm" : ""}"><b>${grouped(value)}</b><span>${label}</span></div>`;
6851
+ const errors = errorFindings(report.findings).length;
6852
+ return `<section class="counts">
6853
+ ${cell2(report.read.length, `read, of ${grouped(report.migrations)} in the module`)}
6854
+ ${cell2(countedFindings(report.findings).length, errors === 0 ? "findings, all warnings" : "findings")}
6855
+ ${errors === 0 ? "" : cell2(errors, "errors, from rules set to error", true)}
6856
+ ${cell2(report.unread.length, "could not be opened", true)}
6857
+ ${cell2(syntax, "do not parse", true)}
6858
+ ${cell2(report.unsafe.files.length, "files with a raw SQL call")}
6859
+ </section>`;
6860
+ }
6861
+ function offSection(report) {
6862
+ if (report.read.length === 0 && report.unsafe.files.length === 0 || report.rulesOff.length === 0)
6863
+ return "";
6864
+ const names = report.rulesOff.map((rule) => `<code>${escape(rule)}</code>`).join(", ");
6865
+ return `<section><p class="quiet">Turned off by this module, so not checked: ${names}.</p></section>`;
6866
+ }
6867
+ function unreadSection(report) {
6868
+ if (report.unread.length === 0) return "";
6869
+ const items = report.unread.map(({ file, reason }) => `<li><code>${escape(file)}</code>: ${escape(reason)}</li>`).join("\n");
6870
+ return `<section class="alarm-box">
6871
+ <h2>Could not be opened</h2>
6872
+ <p>Nothing about these migrations is checked.</p>
6873
+ <ul>${items}</ul>
6874
+ </section>`;
6875
+ }
6876
+ function syntaxSection(report) {
6877
+ const files = unparsedMigrations(report.findings);
6878
+ if (files.length === 0) return "";
6879
+ return `<section class="alarm-box">
6880
+ <h2>Migrations that do not parse</h2>
6881
+ <p>squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it
6882
+ too. The first error of each file is the one to fix; the ones after it follow from it.</p>
6883
+ ${files.map(
6884
+ ({ first, more }) => place(first, more > 0 ? `${first.message} (and ${more} more after it)` : first.message)
6885
+ ).join("\n")}
6886
+ </section>`;
6887
+ }
6888
+ function findingsSection(report) {
6889
+ const groups = byRule(report.findings);
6890
+ if (groups.length === 0) {
6891
+ const why = report.read.length === 0 ? "No migration was read, so there is nothing to find." : "squawk read every migration listed below and found nothing.";
6892
+ return `<section><h2>Findings</h2><p class="quiet">${why}</p></section>`;
6893
+ }
6894
+ return `<section>
6895
+ <h2>Findings, by rule</h2>
6896
+ ${groups.map(ruleBlock).join("\n")}
6897
+ </section>`;
6898
+ }
6899
+ function ruleBlock({ rule, findings }) {
6900
+ const [first] = findings;
6901
+ if (first === void 0) return "";
6902
+ const note = findings.find((finding3) => finding3.sentinelNote !== null)?.sentinelNote ?? null;
6903
+ return `<article class="rule">
6904
+ <div class="rule-head"><code class="name">${escape(rule)}</code>${first.level === "error" ? '<span class="level">error</span>' : ""}<span class="n">${grouped(findings.length)}</span></div>
6905
+ <p class="squawk"><span class="who">${SENTINEL_RULES.includes(rule) ? "sentinel" : "squawk"}</span> ${prose2(first.message)}${first.help ? `. <b>Fix:</b> ${prose2(first.help)}` : ""}.</p>${note ? `
6906
+ <div class="note">
6907
+ <p><span class="who">sentinel</span> ${prose2(note.short)}</p>
6908
+ <details><summary>The full note, and how it was proven</summary>
6909
+ <p>${prose2(note.note)}</p>
6910
+ <p class="source">${prose2(note.source)}</p>
6911
+ </details>
6912
+ </div>` : ""}
6913
+ ${places(findings)}
6914
+ </article>`;
6915
+ }
6916
+ var OPEN_PLACES = 5;
6917
+ function places(findings) {
6918
+ const said = findings[0]?.message;
6919
+ const folded = findings.slice(OPEN_PLACES);
6920
+ const more = folded.length === 0 ? "" : `<details class="more"><summary>${grouped(folded.length)} more place(s)</summary>${byFile(folded, said)}</details>`;
6921
+ return `${byFile(findings.slice(0, OPEN_PLACES), said)}${more}`;
6922
+ }
6923
+ function byFile(findings, said) {
6924
+ const files = /* @__PURE__ */ new Map();
6925
+ for (const finding3 of findings) {
6926
+ files.set(finding3.file, [...files.get(finding3.file) ?? [], finding3]);
6927
+ }
6928
+ return [...files].map(
6929
+ ([file, list]) => `<p class="file"><code>${escape(file)}</code></p>${list.map(
6930
+ (finding3) => place(finding3, void 0, finding3.message === said ? void 0 : finding3.message)
6931
+ ).join("")}`
6932
+ ).join("");
6933
+ }
6934
+ function place(finding3, message, own) {
6935
+ const code = finding3.excerpt === null ? "" : `<pre><code>${escape(finding3.excerpt)}</code></pre>`;
6936
+ const where = message === void 0 ? `line ${finding3.line}:${finding3.column}` + (own === void 0 ? "" : ` <span class="said">${prose2(own)}</span>`) : `<code>${escape(placeOf(finding3))}</code> <span class="said">${prose2(message)}</span>`;
6937
+ return `<div class="place"><p class="where">${where}</p>${code}</div>`;
6938
+ }
6939
+ function prose2(text) {
6940
+ return escape(text).replace(/`([^`]+)`/g, "<code>$1</code>");
6941
+ }
6942
+ function readSection(report) {
6943
+ if (report.read.length === 0) return "";
6944
+ return `<section>
6945
+ <details><summary>The ${grouped(report.read.length)} migration(s) read</summary>
6946
+ <ul>${report.read.map((file) => `<li><code>${escape(file)}</code></li>`).join("")}</ul>
6947
+ </details>
6948
+ </section>`;
6949
+ }
6950
+ function unsafeSection(report) {
6951
+ const { files, read, unparsed } = report.unsafe;
6952
+ const methods = "raw SQL (<code>$queryRawUnsafe</code> / <code>$executeRawUnsafe</code>, <code>pg</code>, <code>postgres</code>, <code>Prisma.raw</code>, <code>Prisma.join</code>)";
6953
+ const checked = checkedCalls(report.unsafe, report.rulesOff, {
6954
+ count: grouped,
6955
+ name: (name) => `<code>${escape(name)}</code>`
6956
+ });
6957
+ const lead = files.length === 0 ? `No ${methods} call in ${grouped(report.unsafe.codeFiles)} TypeScript file(s).` : read.length === 0 ? `${grouped(files.length)} file(s) call ${methods}; none is added or changed by this branch, so none is read.` : `${checked} checked in the ${grouped(read.length)} file(s) this branch adds or changes, out of ${grouped(files.length)} calling them. Their findings are under <code>unsafe-sql-pasted-value</code> and <code>unsafe-sql-raw-fragment</code> above.`;
6958
+ const list = read.length === 0 ? "" : `<ul>${read.map((file) => `<li><code>${escape(file)}</code></li>`).join("")}</ul>`;
6959
+ const broken = unparsed.length === 0 ? "" : `<div class="alarm-box"><h2>Could not be read</h2><p>Nothing in these files is checked.</p><ul>${unparsed.map(({ file, reason }) => `<li><code>${escape(file)}</code>: ${escape(reason)}</li>`).join("")}</ul></div>`;
6960
+ return `<section><h2>Raw SQL in code</h2><p>${lead}</p>${list}${broken}</section>`;
6961
+ }
6962
+ function settingsSection(report) {
6963
+ const rows = report.settings.map(
6964
+ (setting) => `<tr><th scope="row"><code>${escape(setting.key)}</code></th><td><code>${escape(setting.value)}</code></td><td>${setting.moved ? '<span class="moved">overridden by this module</span>' : '<span class="quiet">the role&rsquo;s value</span>'}</td></tr>`
6965
+ ).join("\n");
6966
+ return `<section><details><summary>Settings this run used</summary>
6967
+ <table>${rows}</table>
6968
+ </details></section>`;
6969
+ }
6970
+ var STYLES2 = `
6971
+ :root {
6972
+ color-scheme: light dark;
6973
+ --page: #faf7f1; --surface: #ffffff; --ink: #23091c; --ink-soft: #4a3344; --label: #6f5a67;
6974
+ --rule: #e1dcd0; --brand: #491b3c; --brand-bg: #f3e9ee; --moved: #a3341f; --over: #a3341f;
6975
+ --note: #fdf6ee; --radius: 10px;
6976
+ }
6977
+ @media (prefers-color-scheme: dark) {
6978
+ :root {
6979
+ --page: #23091c; --surface: #2f1128; --ink: #faf7f1; --ink-soft: #d8c6d1; --label: #b298ab;
6980
+ --rule: #45253d; --brand: #ffab93; --brand-bg: #3a1830; --moved: #ef8f78; --over: #ef8f78;
6981
+ --note: #2f1128;
6982
+ }
6983
+ }
6984
+ * { box-sizing: border-box; }
6985
+ body { margin: 0; background: var(--page); color: var(--ink);
6986
+ font: 15px/1.6 'Brand Sans', Inter, ui-sans-serif, system-ui, sans-serif; }
6987
+ main { max-width: 960px; margin: 0 auto; padding: 32px 16px 48px; }
6988
+ code, pre { font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
6989
+ .eyebrow { margin: 0; color: var(--label); text-transform: uppercase; letter-spacing: .08em; font-size: 12px; }
6990
+ h1 { margin: 4px 0; font-size: 26px; overflow-wrap: anywhere; }
6991
+ h2 { font-size: 18px; margin: 0 0 12px; }
6992
+ .meta { margin: 0; color: var(--label); overflow-wrap: anywhere; }
6993
+ section { margin-top: 24px; }
6994
+ .counts { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
6995
+ .count { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius); padding: 12px 14px; }
6996
+ .count b { display: block; font-size: 22px; }
6997
+ .count span { color: var(--label); font-size: 13px; }
6998
+ .count.alarm { border-color: var(--over); }
6999
+ .count.alarm b { color: var(--over); }
7000
+ .alarm-box { border: 1px solid var(--over); border-radius: var(--radius); padding: 14px 16px; background: var(--surface); }
7001
+ .alarm-box h2 { color: var(--over); }
7002
+ .rule { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius); padding: 14px 16px; margin-bottom: 14px; }
7003
+ .rule-head { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
7004
+ .rule-head .name { font-size: 15px; font-weight: 600; color: var(--brand); overflow-wrap: anywhere; }
7005
+ .rule-head .n { color: var(--label); }
7006
+ .rule-head .level { color: var(--over); font-weight: 600; margin-right: auto; margin-left: 8px; }
7007
+ .who { display: inline-block; font-size: 11px; text-transform: uppercase; letter-spacing: .06em;
7008
+ padding: 1px 6px; border-radius: 4px; background: var(--brand-bg); color: var(--brand); margin-right: 6px; }
7009
+ .squawk { color: var(--ink-soft); }
7010
+ .note { background: var(--note); border-radius: 8px; padding: 8px 12px; margin: 8px 0; }
7011
+ .note p { margin: 4px 0; }
7012
+ .source { color: var(--label); font-size: 13px; }
7013
+ details summary { cursor: pointer; color: var(--brand); }
7014
+ .place { border-top: 1px solid var(--rule); padding-top: 8px; margin-top: 8px; }
7015
+ .where { margin: 0 0 4px; overflow-wrap: anywhere; color: var(--label); font-size: 13px; }
7016
+ .file { margin: 12px 0 0; overflow-wrap: anywhere; font-weight: 600; }
7017
+ .more { margin-top: 10px; }
7018
+ .said { color: var(--ink-soft); }
7019
+ pre { margin: 0; padding: 8px 10px; background: var(--page); border-radius: 6px; overflow-x: auto; }
7020
+ .quiet { color: var(--label); }
7021
+ .moved { color: var(--moved); }
7022
+ table { border-collapse: collapse; width: 100%; margin-top: 8px; }
7023
+ th, td { text-align: left; padding: 6px 8px; border-top: 1px solid var(--rule); vertical-align: top; overflow-wrap: anywhere; }
7024
+ ul { padding-left: 20px; }
7025
+ footer { margin-top: 32px; color: var(--label); font-size: 13px; }
7026
+ `;
7067
7027
 
7068
- ${tabInputs}
7069
- <nav class="tabs" aria-label="Figure families">
7070
- ${tabLabels}
7071
- </nav>
7072
- ${tabPanels}
7073
- <footer>sentinel static-analysis</footer>
7074
- </main>
7075
- <script>${FINDINGS_SCRIPT}</script>
7076
- </body>
7077
- </html>
7028
+ // src/roles/sql/report/render-json.ts
7029
+ var JSON_SCHEMA_VERSION2 = 1;
7030
+ function renderJson3(report, now = /* @__PURE__ */ new Date()) {
7031
+ const envelope = {
7032
+ schemaVersion: JSON_SCHEMA_VERSION2,
7033
+ generatedAt: now.toISOString(),
7034
+ ...report,
7035
+ findings: countedAsEverywhere(report.findings),
7036
+ // `origin/main@abc1234`, the form the `--json` row carries, beside the parts.
7037
+ comparedWith: report.base ? `${report.base.ref}@${report.base.commit}` : null
7038
+ };
7039
+ return `${JSON.stringify(envelope, null, 2)}
7078
7040
  `;
7079
- return page.split("\n").map((line) => line.replace(/[ \t]+$/, "")).join("\n");
7080
7041
  }
7081
-
7082
- // src/roles/sql/adapters/squawk/summary.ts
7083
- var PLAIN = { count: String, name: (name) => name };
7084
- function checkedCalls({ calls, rawCalls }, rulesOff2, mark = PLAIN) {
7085
- const methods = !rulesOff2.includes(UNSAFE_RULE);
7086
- const raw = !rulesOff2.includes(RAW_FRAGMENT_RULE);
7087
- const text = `${mark.count(calls)} call(s) taking SQL text (${mark.name("$queryRawUnsafe")} / ${mark.name("$executeRawUnsafe")}, ${mark.name("pg")}, ${mark.name("postgres")})`;
7088
- const fragments = `${mark.count(rawCalls)} Prisma fragment(s) (${mark.name("Prisma.raw")}, ${mark.name("Prisma.join")})`;
7089
- if (methods && raw) return `${text} and ${fragments}`;
7090
- return methods ? text : fragments;
7042
+ function countedAsEverywhere(findings) {
7043
+ const firsts = new Map(unparsedMigrations(findings).map(({ first, more }) => [first, more]));
7044
+ return findings.flatMap((finding3) => {
7045
+ if (finding3.rule !== SYNTAX_ERROR) return [finding3];
7046
+ const more = firsts.get(finding3);
7047
+ return more === void 0 ? [] : [{ ...finding3, parserMessagesAfter: more }];
7048
+ });
7091
7049
  }
7092
- var CALLED = "raw SQL ($queryRawUnsafe / $executeRawUnsafe, pg, postgres, Prisma.raw, Prisma.join)";
7093
- function summariseMigrations(outcome) {
7050
+
7051
+ // src/roles/sql/report/render-markdown.ts
7052
+ var PLACES_PER_RULE = 3;
7053
+ function renderMarkdown3(report) {
7094
7054
  return [
7095
- whatWasRead(outcome),
7096
- ...codeReadLines(outcome),
7097
- ...offLines(outcome),
7098
- ...unreadLines(outcome.unread),
7099
- ...unparsedLines(outcome.code.unparsed),
7100
- ...syntaxErrorLines(outcome.findings),
7101
- ...findingLines(outcome.findings)
7102
- ];
7055
+ `#### \`${report.module}\``,
7056
+ "",
7057
+ headline2(report),
7058
+ ...offBlock(report),
7059
+ ...unreadBlock(report),
7060
+ ...syntaxBlock(report),
7061
+ ...unsafeBlock(report),
7062
+ ...ruleBlocks(report),
7063
+ "",
7064
+ `<sub>Only the migrations this branch adds or changes are read. ${levelsLine(report)} Every place, with the SQL behind it and sentinel's full notes, is in the \`sql.html\` this run keeps. Measured by sentinel ${report.sentinel}.</sub>`,
7065
+ ""
7066
+ ].join("\n");
7103
7067
  }
7104
- function whatWasRead({ total, read, base }) {
7105
- if (total === 0 || base === null) return "no migration in this module.";
7106
- const against = `compared with ${base.ref} at ${base.commit}`;
7107
- if (read === 0) {
7108
- return `no migration added or changed by this branch, ${against}. The ${total} in this module are not read: only what a branch introduces is.`;
7068
+ function headline2(report) {
7069
+ if (report.base === null) return "No migration and no raw SQL call in this module.";
7070
+ const against = `compared with \`${report.base.ref}\` at \`${report.base.commit}\``;
7071
+ const migrations = report.read.length;
7072
+ const files = report.unsafe.read.length;
7073
+ if (migrations === 0 && files === 0) {
7074
+ return `No migration or raw SQL call added or changed by this branch, ${against}: nothing to check.`;
7109
7075
  }
7110
- const others = total - read;
7111
- return `read ${read} migration(s) this branch adds or changes, ${against}.` + (others > 0 ? ` The ${others} other(s) in this module are unchanged and not read.` : "");
7112
- }
7113
- function offLines({ read, rulesOff: rulesOff2, code }) {
7114
- if (read === 0 && code.files === 0 || rulesOff2.length === 0) return [];
7115
- return [
7116
- `this module turns off ${rulesOff2.length} rule(s) in sql.config.mjs, so they are not checked: ${rulesOff2.join(", ")}.`
7076
+ const counts2 = (count, what, noun) => `**${count}** ${what} ${noun}${count === 1 ? "" : "s"}`;
7077
+ const calls = [
7078
+ ...report.rulesOff.includes(UNSAFE_RULE) ? [] : [counts2(report.unsafe.calls, "raw SQL", "call")],
7079
+ ...report.rulesOff.includes(RAW_FRAGMENT_RULE) ? [] : [counts2(report.unsafe.rawCalls, "Prisma", "fragment")]
7117
7080
  ];
7118
- }
7119
- function codeReadLines({ code, rulesOff: rulesOff2 }) {
7120
- if (code.files === 0) return [];
7121
- if (rulesOff2.includes(UNSAFE_RULE) && rulesOff2.includes(RAW_FRAGMENT_RULE)) return [];
7122
- if (code.read === 0) {
7123
- return [
7124
- `${code.files} file(s) call ${CALLED}; none is added or changed by this branch, so none is read.`
7125
- ];
7126
- }
7127
- const others = code.files - code.read;
7128
- return [
7129
- `checked ${checkedCalls(code, rulesOff2)} in the ${code.read} file(s) this branch adds or changes.` + (others > 0 ? ` The ${others} other file(s) calling them are unchanged and not read.` : "")
7081
+ const items = [
7082
+ ...migrations > 0 ? [`**${migrations}** migration${migrations === 1 ? "" : "s"}`] : [],
7083
+ ...files > 0 ? calls : []
7130
7084
  ];
7085
+ const where = files > 0 ? ` in ${files} file${files === 1 ? "" : "s"}` : "";
7086
+ const read = items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}${where}` : `${items.join("")}${where}`;
7087
+ const findings = countedFindings(report.findings).length;
7088
+ const errors = errorFindings(report.findings).length;
7089
+ const counted = `**${findings} finding${findings === 1 ? "" : "s"}**`;
7090
+ const found = findings === 0 ? "no finding" : errors === 0 ? `${counted}, every one a warning` : `${counted}: \u2717 **${errors} error${errors === 1 ? "" : "s"}**, from rules this module sets to \`error\`, and ${findings - errors} warning${findings - errors === 1 ? "" : "s"}`;
7091
+ return `Read ${read} this branch adds or changes, ${against}: ${found}.`;
7131
7092
  }
7132
- function unparsedLines(unparsed) {
7133
- if (unparsed.length === 0) return [];
7093
+ function levelsLine(report) {
7094
+ return errorFindings(report.findings).length === 0 ? "Every finding is a warning while the role is being adopted: nothing here fails the run." : "A rule the module sets to `error` fails the module's `sql` run; every other finding is a warning.";
7095
+ }
7096
+ function offBlock(report) {
7097
+ if (report.read.length === 0 && report.unsafe.files.length === 0 || report.rulesOff.length === 0)
7098
+ return [];
7134
7099
  return [
7135
- `\u2717 ${unparsed.length} TypeScript file(s) could not be read, so their calls are not checked:`,
7136
- ...unparsed.map(({ file, reason }) => ` ${file}: ${reason}`)
7100
+ "",
7101
+ `Turned off by this module, so not checked: ${report.rulesOff.map((rule) => `\`${rule}\``).join(", ")}.`
7137
7102
  ];
7138
7103
  }
7139
- function unreadLines(unread) {
7140
- if (unread.length === 0) return [];
7104
+ function unreadBlock(report) {
7105
+ if (report.unread.length === 0) return [];
7141
7106
  return [
7142
- `\u2717 ${unread.length} migration(s) could not be opened, so nothing about them is checked:`,
7143
- ...unread.map(({ file, reason }) => ` ${file}: ${reason}`)
7107
+ "",
7108
+ `\u2717 **${report.unread.length} migration(s) could not be opened**, so nothing in them is checked:`,
7109
+ ...report.unread.map(({ file, reason }) => `- \`${file}\`: ${reason}`)
7144
7110
  ];
7145
7111
  }
7146
- function syntaxErrorLines(findings) {
7147
- const files = unparsedMigrations(findings);
7112
+ function syntaxBlock(report) {
7113
+ const files = unparsedMigrations(report.findings);
7148
7114
  if (files.length === 0) return [];
7149
7115
  return [
7150
- `\u2717 ${files.length} migration(s) do not parse: squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it too. The first error, the one to fix:`,
7116
+ "",
7117
+ `\u2717 **${files.length} migration${files.length === 1 ? " does" : "s do"} not parse**: squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it too. The first error, the one to fix:`,
7151
7118
  ...files.map(
7152
- ({ first, more }) => ` ${first.file}:${first.line}:${first.column} ${first.message}` + (more > 0 ? ` (and ${more} more after it)` : "")
7119
+ ({ first, more }) => `- \`${placeOf(first)}\` ${first.message}` + (more > 0 ? ` (and ${more} more after it, which follow from it)` : "")
7153
7120
  )
7154
7121
  ];
7155
7122
  }
7156
- function findingLines(findings) {
7157
- const counted = countedFindings(findings);
7158
- const errors = errorFindings(findings);
7159
- const errorRules = new Set(errors.map((finding2) => finding2.rule));
7160
- const byRule2 = countByRule(counted).sort(
7161
- ([a], [b]) => Number(errorRules.has(b)) - Number(errorRules.has(a))
7162
- );
7163
- if (byRule2.length === 0) return ["no finding."];
7164
- const total = counted.length;
7165
- const width = Math.max(...byRule2.map(([rule]) => rule.length));
7123
+ function ruleBlocks(report) {
7124
+ return byRule(report.findings).flatMap(({ rule, findings }) => {
7125
+ const [first] = findings;
7126
+ if (first === void 0) return [];
7127
+ const more = findings.length - Math.min(findings.length, PLACES_PER_RULE);
7128
+ const places2 = placesText(findings.slice(0, PLACES_PER_RULE)) + (more > 0 ? ` and ${more} more` : "");
7129
+ const note = findings.find((finding3) => finding3.sentinelNote !== null)?.sentinelNote;
7130
+ return [
7131
+ "",
7132
+ `**${rule}**${first.level === "error" ? " \u2717 error" : ""} \xB7 ${findings.length} \xB7 ${places2}`,
7133
+ // sentinel's own rules speak as sentinel: their words are not squawk's.
7134
+ `> ${SENTINEL_RULES.includes(rule) ? "sentinel" : "squawk"}: ${first.message}${first.help ? `. Fix: ${first.help}` : ""}.`,
7135
+ ...note ? [`> **sentinel:** ${note.short}`] : []
7136
+ ];
7137
+ });
7138
+ }
7139
+ function placesText(findings) {
7140
+ const byFile2 = /* @__PURE__ */ new Map();
7141
+ for (const finding3 of findings)
7142
+ byFile2.set(finding3.file, [...byFile2.get(finding3.file) ?? [], finding3.line]);
7143
+ return [...byFile2].map(([file, lines]) => `\`${file}\` line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`).join("; ");
7144
+ }
7145
+ function unsafeBlock(report) {
7146
+ const { unparsed } = report.unsafe;
7147
+ if (unparsed.length === 0) return [];
7166
7148
  return [
7167
- errors.length === 0 ? `${total} finding(s), every one a warning while the role is being adopted:` : `\u2717 ${total} finding(s): ${errors.length} error(s), from the rule(s) this module sets to "error" in sql.config.mjs, which fail this run, and ${total - errors.length} warning(s):`,
7168
- ...byRule2.flatMap(([rule, count]) => {
7169
- const note = findings.find(
7170
- (finding2) => finding2.rule === rule && finding2.sentinelNote
7171
- )?.sentinelNote;
7172
- return [
7173
- ` ${rule.padEnd(width)} ${count}${errorRules.has(rule) ? " error" : ""}`,
7174
- // The one-sentence form: a console is read a line at a time. The full note and its proof
7175
- // are in the page, the json and `--inspect`.
7176
- ...note ? [` sentinel's note: ${note.short}`] : [],
7177
- // The syntax errors' places are listed above, with the error to fix.
7178
- ...rule === SYNTAX_ERROR ? [] : placeLines(counted, rule)
7179
- ];
7180
- })
7149
+ "",
7150
+ `\u2717 **${unparsed.length} TypeScript file(s) could not be read**, so their raw SQL calls are not checked:`,
7151
+ ...unparsed.map(({ file, reason }) => `- \`${file}\`: ${reason}`)
7181
7152
  ];
7182
7153
  }
7183
- var CONSOLE_PLACES = 3;
7184
- function placeLines(findings, rule) {
7185
- const mine = findings.filter((finding2) => finding2.rule === rule).sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.column - b.column);
7186
- const shown = mine.slice(0, CONSOLE_PLACES).map((finding2) => ` ${finding2.file}:${finding2.line}:${finding2.column}`);
7187
- const more = mine.length - shown.length;
7188
- return more > 0 ? [...shown, ` and ${more} more: pnpm run sql:html lists them all`] : shown;
7154
+
7155
+ // src/roles/sql/report/outputs.ts
7156
+ var SHAPE_FILE2 = {
7157
+ json: `${TARGET}.json`,
7158
+ html: `${TARGET}.html`,
7159
+ markdown: `${TARGET}.md`
7160
+ };
7161
+ function shapesOf2(output) {
7162
+ const asked = (output ?? "console").split(",").map((one) => one.trim()).filter((one) => one !== "");
7163
+ const shapes = [...new Set(asked)];
7164
+ const unknown = shapes.filter((one) => !OUTPUT_SHAPES.includes(one));
7165
+ if (shapes.length === 0 || unknown.length > 0) {
7166
+ return {
7167
+ ok: false,
7168
+ reason: `unknown --output "${output ?? ""}" (known: ${OUTPUT_SHAPES.join(", ")}; several at once with a comma).`
7169
+ };
7170
+ }
7171
+ return { ok: true, shapes };
7172
+ }
7173
+ var writesFiles = (shapes) => shapes.some((shape) => shape !== "console");
7174
+ function writeOutputs(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
7175
+ if (!writesFiles(shapes)) return [];
7176
+ removeOutputs(cwd, shapes);
7177
+ mkdirSync2(join25(cwd, REPORT_DIR), { recursive: true });
7178
+ const written = [];
7179
+ for (const shape of shapes) {
7180
+ if (shape === "console") continue;
7181
+ const path2 = join25(REPORT_DIR, SHAPE_FILE2[shape]);
7182
+ writeFileSync6(join25(cwd, path2), render(report, shape, now));
7183
+ written.push(path2);
7184
+ }
7185
+ return written;
7186
+ }
7187
+ function removeOutputs(cwd, keeping = []) {
7188
+ for (const [shape, name] of Object.entries(SHAPE_FILE2)) {
7189
+ if (keeping.includes(shape)) continue;
7190
+ const path2 = join25(cwd, REPORT_DIR, name);
7191
+ if (existsSync16(path2)) unlinkSync2(path2);
7192
+ }
7189
7193
  }
7190
- function countByRule(findings) {
7191
- const counts2 = /* @__PURE__ */ new Map();
7192
- for (const { rule } of findings) counts2.set(rule, (counts2.get(rule) ?? 0) + 1);
7193
- return [...counts2].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));
7194
+ function render(report, shape, now) {
7195
+ if (shape === "json") return renderJson3(report, now);
7196
+ if (shape === "html") return renderHtml2(report, now);
7197
+ return renderMarkdown3(report);
7194
7198
  }
7195
7199
 
7196
- // src/roles/sql/report/render-html.ts
7197
- function renderHtml2(report, now = /* @__PURE__ */ new Date()) {
7198
- return `<!doctype html>
7199
- <html lang="en">
7200
- <head>
7201
- <meta charset="utf-8">
7202
- <meta name="viewport" content="width=device-width, initial-scale=1">
7203
- <title>SQL \xB7 ${escape(report.module)}</title>
7204
- <style>${STYLES2}</style>
7205
- </head>
7206
- <body>
7207
- <main>
7208
- <header>
7209
- <p class="eyebrow">sentinel \xB7 sql</p>
7210
- <h1>${escape(report.module)}</h1>
7211
- <p class="meta">${meta(report, now)}</p>
7212
- </header>
7213
- ${counts(report)}
7214
- ${offSection(report)}
7215
- ${unreadSection(report)}
7216
- ${syntaxSection(report)}
7217
- ${findingsSection(report)}
7218
- ${readSection(report)}
7219
- ${unsafeSection(report)}
7220
- ${settingsSection(report)}
7221
- <footer>Only the migrations this branch adds or changes are read. ${errorFindings(report.findings).length === 0 ? "Every finding is a warning while the role is being adopted: nothing here fails the run." : "A rule the module sets to <code>error</code> fails the module's <code>sql</code> run; every other finding is a warning."} squawk's text is squawk's; what is labelled sentinel is sentinel's, with how it was proven.</footer>
7222
- </main>
7223
- </body>
7224
- </html>
7225
- `;
7226
- }
7227
- function meta(report, now) {
7228
- const parts = [
7229
- report.base ? `compared with <code>${escape(report.base.ref)}</code> at <code>${escape(report.base.commit)}</code>` : "no migration to compare",
7230
- report.commit ? `commit <code>${escape(report.commit)}</code>` : null,
7231
- `sentinel ${escape(report.sentinel)}`,
7232
- `generated ${escape(now.toISOString().slice(0, 16).replace("T", " "))} UTC`
7233
- ];
7234
- return parts.filter((part) => part !== null).join(" \xB7 ");
7200
+ // src/roles/sql/sources.ts
7201
+ import { existsSync as existsSync17, readFileSync as readFileSync16, realpathSync as realpathSync2 } from "node:fs";
7202
+ import { dirname as dirname3, join as join26, relative as relative4, resolve as resolve3, sep } from "node:path";
7203
+ import { globSync } from "tinyglobby";
7204
+ var WALK = { onlyFiles: true, dot: false, followSymbolicLinks: false };
7205
+ var ADOPTION_FILE = "sql.config.mjs";
7206
+ function adoptedInnerModules(cwd, nested) {
7207
+ return (nested ?? adoptedInnerDirs(cwd)).map((dir) => `${dir}/**`);
7235
7208
  }
7236
- function counts(report) {
7237
- const syntax = unparsedMigrations(report.findings).length;
7238
- const cell2 = (value, label, alarm = false) => `<div class="count${alarm && value > 0 ? " alarm" : ""}"><b>${grouped(value)}</b><span>${label}</span></div>`;
7239
- const errors = errorFindings(report.findings).length;
7240
- return `<section class="counts">
7241
- ${cell2(report.read.length, `read, of ${grouped(report.migrations)} in the module`)}
7242
- ${cell2(countedFindings(report.findings).length, errors === 0 ? "findings, all warnings" : "findings")}
7243
- ${errors === 0 ? "" : cell2(errors, "errors, from rules set to error", true)}
7244
- ${cell2(report.unread.length, "could not be opened", true)}
7245
- ${cell2(syntax, "do not parse", true)}
7246
- ${cell2(report.unsafe.files.length, "files with a raw SQL call")}
7247
- </section>`;
7209
+ function adoptedInnerDirs(cwd) {
7210
+ return globSync([`**/${ADOPTION_FILE}`], {
7211
+ ...WALK,
7212
+ cwd,
7213
+ ignore: ["**/node_modules/**"]
7214
+ }).map((file) => file.slice(0, -ADOPTION_FILE.length - 1)).filter((dir) => dir !== "");
7248
7215
  }
7249
- function offSection(report) {
7250
- if (report.read.length === 0 && report.unsafe.files.length === 0 || report.rulesOff.length === 0)
7251
- return "";
7252
- const names = report.rulesOff.map((rule) => `<code>${escape(rule)}</code>`).join(", ");
7253
- return `<section><p class="quiet">Turned off by this module, so not checked: ${names}.</p></section>`;
7216
+ function migrationFiles(cwd, settings, nested) {
7217
+ return globSync(settings.migrations.include, {
7218
+ ...WALK,
7219
+ cwd,
7220
+ ignore: [
7221
+ ...settings.migrations.exclude,
7222
+ ...settings.ignore,
7223
+ ...adoptedInnerModules(cwd, nested)
7224
+ ]
7225
+ }).sort();
7254
7226
  }
7255
- function unreadSection(report) {
7256
- if (report.unread.length === 0) return "";
7257
- const items = report.unread.map(({ file, reason }) => `<li><code>${escape(file)}</code>: ${escape(reason)}</li>`).join("\n");
7258
- return `<section class="alarm-box">
7259
- <h2>Could not be opened</h2>
7260
- <p>Nothing about these migrations is checked.</p>
7261
- <ul>${items}</ul>
7262
- </section>`;
7227
+ function codeFiles(cwd, settings, nested) {
7228
+ return globSync(["**/*.{ts,mts,cts}"], {
7229
+ ...WALK,
7230
+ cwd,
7231
+ ignore: [
7232
+ "**/*.d.{ts,mts,cts}",
7233
+ ...settings.ignore,
7234
+ ...settings.unsafe.includeTests ? [] : settings.unsafe.tests,
7235
+ ...adoptedInnerModules(cwd, nested)
7236
+ ]
7237
+ }).sort();
7263
7238
  }
7264
- function syntaxSection(report) {
7265
- const files = unparsedMigrations(report.findings);
7266
- if (files.length === 0) return "";
7267
- return `<section class="alarm-box">
7268
- <h2>Migrations that do not parse</h2>
7269
- <p>squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it
7270
- too. The first error of each file is the one to fix; the ones after it follow from it.</p>
7271
- ${files.map(
7272
- ({ first, more }) => place(first, more > 0 ? `${first.message} (and ${more} more after it)` : first.message)
7273
- ).join("\n")}
7274
- </section>`;
7239
+ var UNSAFE_CALL = /\$(?:queryRaw|executeRaw)Unsafe\b/;
7240
+ var PRISMA_IMPORT = /from\s*['"]@prisma\//;
7241
+ var RAW_CALL = /\.raw\s*\(/;
7242
+ var PRISMA_ALIAS = /\bPrisma\s+as\s+([A-Za-z_$][\w$]*)/g;
7243
+ function callsPrismaJoin(text) {
7244
+ const names = ["Prisma", ...[...text.matchAll(PRISMA_ALIAS)].map((match) => match[1] ?? "")];
7245
+ return names.some(
7246
+ (name) => new RegExp(`(?<![\\w$])${name.replace(/\$/g, "\\$")}\\.join\\s*\\(`).test(text)
7247
+ );
7275
7248
  }
7276
- function findingsSection(report) {
7277
- const groups = byRule(report.findings);
7278
- if (groups.length === 0) {
7279
- const why = report.read.length === 0 ? "No migration was read, so there is nothing to find." : "squawk read every migration listed below and found nothing.";
7280
- return `<section><h2>Findings</h2><p class="quiet">${why}</p></section>`;
7249
+ var PG_IMPORT = /from\s*['"]pg['"]|require\(\s*['"]pg['"]\s*\)/;
7250
+ var PG_CALL = /\.query\s*\(/;
7251
+ var POSTGRES_IMPORT = /from\s*['"]postgres['"]|require\(\s*['"]postgres['"]\s*\)/;
7252
+ var POSTGRES_CALL = /\.unsafe\s*\(/;
7253
+ function callsUnsafe(cwd, file) {
7254
+ try {
7255
+ const text = readFileSync16(join26(cwd, file), "utf8");
7256
+ return UNSAFE_CALL.test(text) || PRISMA_IMPORT.test(text) && (RAW_CALL.test(text) || callsPrismaJoin(text)) || PG_IMPORT.test(text) && PG_CALL.test(text) || POSTGRES_IMPORT.test(text) && POSTGRES_CALL.test(text);
7257
+ } catch {
7258
+ return false;
7281
7259
  }
7282
- return `<section>
7283
- <h2>Findings, by rule</h2>
7284
- ${groups.map(ruleBlock).join("\n")}
7285
- </section>`;
7286
7260
  }
7287
- function ruleBlock({ rule, findings }) {
7288
- const [first] = findings;
7289
- if (first === void 0) return "";
7290
- const note = findings.find((finding2) => finding2.sentinelNote !== null)?.sentinelNote ?? null;
7291
- return `<article class="rule">
7292
- <div class="rule-head"><code class="name">${escape(rule)}</code>${first.level === "error" ? '<span class="level">error</span>' : ""}<span class="n">${grouped(findings.length)}</span></div>
7293
- <p class="squawk"><span class="who">${SENTINEL_RULES.includes(rule) ? "sentinel" : "squawk"}</span> ${prose2(first.message)}${first.help ? `. <b>Fix:</b> ${prose2(first.help)}` : ""}.</p>${note ? `
7294
- <div class="note">
7295
- <p><span class="who">sentinel</span> ${prose2(note.short)}</p>
7296
- <details><summary>The full note, and how it was proven</summary>
7297
- <p>${prose2(note.note)}</p>
7298
- <p class="source">${prose2(note.source)}</p>
7299
- </details>
7300
- </div>` : ""}
7301
- ${places(findings)}
7302
- </article>`;
7261
+ function filesWithUnsafeCalls(cwd, files) {
7262
+ return files.filter((file) => callsUnsafe(cwd, file));
7303
7263
  }
7304
- var OPEN_PLACES = 5;
7305
- function places(findings) {
7306
- const said = findings[0]?.message;
7307
- const folded = findings.slice(OPEN_PLACES);
7308
- const more = folded.length === 0 ? "" : `<details class="more"><summary>${grouped(folded.length)} more place(s)</summary>${byFile(folded, said)}</details>`;
7309
- return `${byFile(findings.slice(0, OPEN_PLACES), said)}${more}`;
7264
+ function holdsSql(cwd, settings) {
7265
+ if (migrationFiles(cwd, settings).length > 0) return true;
7266
+ return codeFiles(cwd, settings).some((file) => callsUnsafe(cwd, file));
7310
7267
  }
7311
- function byFile(findings, said) {
7312
- const files = /* @__PURE__ */ new Map();
7313
- for (const finding2 of findings) {
7314
- files.set(finding2.file, [...files.get(finding2.file) ?? [], finding2]);
7268
+ function rawSqlInParent(cwd) {
7269
+ let here;
7270
+ try {
7271
+ here = realpathSync2(cwd);
7272
+ } catch {
7273
+ return void 0;
7315
7274
  }
7316
- return [...files].map(
7317
- ([file, list]) => `<p class="file"><code>${escape(file)}</code></p>${list.map(
7318
- (finding2) => place(finding2, void 0, finding2.message === said ? void 0 : finding2.message)
7319
- ).join("")}`
7320
- ).join("");
7321
- }
7322
- function place(finding2, message, own) {
7323
- const code = finding2.excerpt === null ? "" : `<pre><code>${escape(finding2.excerpt)}</code></pre>`;
7324
- const where = message === void 0 ? `line ${finding2.line}:${finding2.column}` + (own === void 0 ? "" : ` <span class="said">${prose2(own)}</span>`) : `<code>${escape(placeOf(finding2))}</code> <span class="said">${prose2(message)}</span>`;
7325
- return `<div class="place"><p class="where">${where}</p>${code}</div>`;
7326
- }
7327
- function prose2(text) {
7328
- return escape(text).replace(/`([^`]+)`/g, "<code>$1</code>");
7275
+ const stop = findWorkspaceRoot(here) ?? findRepositoryRoot(here);
7276
+ if (stop === void 0 || dirname3(here) === here) return void 0;
7277
+ const parent = findModuleRoot(dirname3(here), stop);
7278
+ if (parent === void 0 || existsSync17(join26(parent, ADOPTION_FILE))) return void 0;
7279
+ const mine = `${relative4(parent, here).split(sep).join("/")}/`;
7280
+ const files = filesWithUnsafeCalls(
7281
+ parent,
7282
+ codeFiles(parent, defaults).filter((file) => !file.startsWith(mine))
7283
+ );
7284
+ if (files.length === 0) return void 0;
7285
+ return { dir: relative4(here, parent).split(sep).join("/"), files };
7329
7286
  }
7330
- function readSection(report) {
7331
- if (report.read.length === 0) return "";
7332
- return `<section>
7333
- <details><summary>The ${grouped(report.read.length)} migration(s) read</summary>
7334
- <ul>${report.read.map((file) => `<li><code>${escape(file)}</code></li>`).join("")}</ul>
7335
- </details>
7336
- </section>`;
7287
+ function migrationsInNested(cwd, settings = defaults, nested = adoptedInnerDirs(cwd)) {
7288
+ const out = [];
7289
+ for (const dir of nested) {
7290
+ const count = migrationFiles(join26(cwd, dir), defaults).length;
7291
+ if (count > 0) out.push({ dir, count, adopted: true });
7292
+ }
7293
+ const root = resolve3(cwd);
7294
+ const owner = /* @__PURE__ */ new Map();
7295
+ const counts2 = /* @__PURE__ */ new Map();
7296
+ for (const file of migrationFiles(cwd, settings, nested)) {
7297
+ const folder = dirname3(join26(root, file));
7298
+ if (!owner.has(folder)) {
7299
+ const project = findModuleRoot(folder, root);
7300
+ owner.set(
7301
+ folder,
7302
+ project === void 0 ? void 0 : relative4(root, project).split(sep).join("/")
7303
+ );
7304
+ }
7305
+ const dir = owner.get(folder);
7306
+ if (dir !== void 0 && dir !== "") counts2.set(dir, (counts2.get(dir) ?? 0) + 1);
7307
+ }
7308
+ for (const [dir, count] of counts2) out.push({ dir, count, adopted: false });
7309
+ return out.sort((a, b) => a.dir.localeCompare(b.dir));
7337
7310
  }
7338
- function unsafeSection(report) {
7339
- const { files, read, unparsed } = report.unsafe;
7340
- const methods = "raw SQL (<code>$queryRawUnsafe</code> / <code>$executeRawUnsafe</code>, <code>pg</code>, <code>postgres</code>, <code>Prisma.raw</code>, <code>Prisma.join</code>)";
7341
- const checked = checkedCalls(report.unsafe, report.rulesOff, {
7342
- count: grouped,
7343
- name: (name) => `<code>${escape(name)}</code>`
7311
+
7312
+ // src/roles/sql/unsafe/unsafe-calls.ts
7313
+ import { dirname as dirname4, join as join27 } from "node:path";
7314
+ import { parseSync as parseSync3 } from "oxc-parser";
7315
+ var UNSAFE_METHODS = ["$queryRawUnsafe", "$executeRawUnsafe"];
7316
+ var BOTH = { methods: true, raw: true };
7317
+ var MAX_DEPTH = 12;
7318
+ function checkUnsafeCalls(cwd, file, text, readFile, checking = BOTH) {
7319
+ const parsed = parse(join27(cwd, file), text);
7320
+ if (!parsed.ok) return parsed;
7321
+ const findings = [];
7322
+ let calls = 0;
7323
+ let rawCalls = 0;
7324
+ const files = new FileCache(readFile);
7325
+ files.set(parsed.file);
7326
+ const imports = {
7327
+ prisma: prismaNames(parsed.file.bindings),
7328
+ prismaNamespaces: prismaNamespacesOf(parsed.file.program),
7329
+ unsafeAliases: unsafeAliasesOf(parsed.file.program, parsed.file.bindings),
7330
+ ...driversImported(parsed.file.program)
7331
+ };
7332
+ walk(parsed.file.program, (node) => {
7333
+ const call = sqlTextCall(node, imports, text);
7334
+ if (call === void 0) return;
7335
+ const raw = call.rule === RAW_FRAGMENT_RULE;
7336
+ if (raw ? !checking.raw : !checking.methods) return;
7337
+ if (call.texts.length === 0) return;
7338
+ if (raw) rawCalls++;
7339
+ else calls++;
7340
+ const context2 = { file: parsed.file, files, depth: 0, local: /* @__PURE__ */ new Map() };
7341
+ const pasted = call.texts.flatMap((sql) => unsafeParts(sql, context2));
7342
+ const [first] = pasted;
7343
+ if (first === void 0) return;
7344
+ findings.push(findingOf(file, text, call, first, pasted));
7344
7345
  });
7345
- const lead = files.length === 0 ? `No ${methods} call in ${grouped(report.unsafe.codeFiles)} TypeScript file(s).` : read.length === 0 ? `${grouped(files.length)} file(s) call ${methods}; none is added or changed by this branch, so none is read.` : `${checked} checked in the ${grouped(read.length)} file(s) this branch adds or changes, out of ${grouped(files.length)} calling them. Their findings are under <code>unsafe-sql-pasted-value</code> and <code>unsafe-sql-raw-fragment</code> above.`;
7346
- const list = read.length === 0 ? "" : `<ul>${read.map((file) => `<li><code>${escape(file)}</code></li>`).join("")}</ul>`;
7347
- const broken = unparsed.length === 0 ? "" : `<div class="alarm-box"><h2>Could not be read</h2><p>Nothing in these files is checked.</p><ul>${unparsed.map(({ file, reason }) => `<li><code>${escape(file)}</code>: ${escape(reason)}</li>`).join("")}</ul></div>`;
7348
- return `<section><h2>Raw SQL in code</h2><p>${lead}</p>${list}${broken}</section>`;
7349
- }
7350
- function settingsSection(report) {
7351
- const rows = report.settings.map(
7352
- (setting) => `<tr><th scope="row"><code>${escape(setting.key)}</code></th><td><code>${escape(setting.value)}</code></td><td>${setting.moved ? '<span class="moved">overridden by this module</span>' : '<span class="quiet">the role&rsquo;s value</span>'}</td></tr>`
7353
- ).join("\n");
7354
- return `<section><details><summary>Settings this run used</summary>
7355
- <table>${rows}</table>
7356
- </details></section>`;
7346
+ return { ok: true, calls, rawCalls, findings };
7357
7347
  }
7358
- var STYLES2 = `
7359
- :root {
7360
- color-scheme: light dark;
7361
- --page: #faf7f1; --surface: #ffffff; --ink: #23091c; --ink-soft: #4a3344; --label: #6f5a67;
7362
- --rule: #e1dcd0; --brand: #491b3c; --brand-bg: #f3e9ee; --moved: #a3341f; --over: #a3341f;
7363
- --note: #fdf6ee; --radius: 10px;
7364
- }
7365
- @media (prefers-color-scheme: dark) {
7366
- :root {
7367
- --page: #23091c; --surface: #2f1128; --ink: #faf7f1; --ink-soft: #d8c6d1; --label: #b298ab;
7368
- --rule: #45253d; --brand: #ffab93; --brand-bg: #3a1830; --moved: #ef8f78; --over: #ef8f78;
7369
- --note: #2f1128;
7370
- }
7348
+ function parse(path2, text) {
7349
+ const { program, errors } = parseSync3(path2, text, { sourceType: "module" });
7350
+ if (errors.length > 0) {
7351
+ return {
7352
+ ok: false,
7353
+ reason: `does not parse (${errors[0]?.message ?? "unknown error"}), so its calls are not checked`
7354
+ };
7371
7355
  }
7372
- * { box-sizing: border-box; }
7373
- body { margin: 0; background: var(--page); color: var(--ink);
7374
- font: 15px/1.6 'Brand Sans', Inter, ui-sans-serif, system-ui, sans-serif; }
7375
- main { max-width: 960px; margin: 0 auto; padding: 32px 16px 48px; }
7376
- code, pre { font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
7377
- .eyebrow { margin: 0; color: var(--label); text-transform: uppercase; letter-spacing: .08em; font-size: 12px; }
7378
- h1 { margin: 4px 0; font-size: 26px; overflow-wrap: anywhere; }
7379
- h2 { font-size: 18px; margin: 0 0 12px; }
7380
- .meta { margin: 0; color: var(--label); overflow-wrap: anywhere; }
7381
- section { margin-top: 24px; }
7382
- .counts { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; }
7383
- .count { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius); padding: 12px 14px; }
7384
- .count b { display: block; font-size: 22px; }
7385
- .count span { color: var(--label); font-size: 13px; }
7386
- .count.alarm { border-color: var(--over); }
7387
- .count.alarm b { color: var(--over); }
7388
- .alarm-box { border: 1px solid var(--over); border-radius: var(--radius); padding: 14px 16px; background: var(--surface); }
7389
- .alarm-box h2 { color: var(--over); }
7390
- .rule { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius); padding: 14px 16px; margin-bottom: 14px; }
7391
- .rule-head { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
7392
- .rule-head .name { font-size: 15px; font-weight: 600; color: var(--brand); overflow-wrap: anywhere; }
7393
- .rule-head .n { color: var(--label); }
7394
- .rule-head .level { color: var(--over); font-weight: 600; margin-right: auto; margin-left: 8px; }
7395
- .who { display: inline-block; font-size: 11px; text-transform: uppercase; letter-spacing: .06em;
7396
- padding: 1px 6px; border-radius: 4px; background: var(--brand-bg); color: var(--brand); margin-right: 6px; }
7397
- .squawk { color: var(--ink-soft); }
7398
- .note { background: var(--note); border-radius: 8px; padding: 8px 12px; margin: 8px 0; }
7399
- .note p { margin: 4px 0; }
7400
- .source { color: var(--label); font-size: 13px; }
7401
- details summary { cursor: pointer; color: var(--brand); }
7402
- .place { border-top: 1px solid var(--rule); padding-top: 8px; margin-top: 8px; }
7403
- .where { margin: 0 0 4px; overflow-wrap: anywhere; color: var(--label); font-size: 13px; }
7404
- .file { margin: 12px 0 0; overflow-wrap: anywhere; font-weight: 600; }
7405
- .more { margin-top: 10px; }
7406
- .said { color: var(--ink-soft); }
7407
- pre { margin: 0; padding: 8px 10px; background: var(--page); border-radius: 6px; overflow-x: auto; }
7408
- .quiet { color: var(--label); }
7409
- .moved { color: var(--moved); }
7410
- table { border-collapse: collapse; width: 100%; margin-top: 8px; }
7411
- th, td { text-align: left; padding: 6px 8px; border-top: 1px solid var(--rule); vertical-align: top; overflow-wrap: anywhere; }
7412
- ul { padding-left: 20px; }
7413
- footer { margin-top: 32px; color: var(--label); font-size: 13px; }
7414
- `;
7415
-
7416
- // src/roles/sql/report/render-json.ts
7417
- var JSON_SCHEMA_VERSION2 = 1;
7418
- function renderJson3(report, now = /* @__PURE__ */ new Date()) {
7419
- const envelope = {
7420
- schemaVersion: JSON_SCHEMA_VERSION2,
7421
- generatedAt: now.toISOString(),
7422
- ...report,
7423
- findings: countedAsEverywhere(report.findings),
7424
- // `origin/main@abc1234`, the form the `--json` row carries, beside the parts.
7425
- comparedWith: report.base ? `${report.base.ref}@${report.base.commit}` : null
7426
- };
7427
- return `${JSON.stringify(envelope, null, 2)}
7428
- `;
7356
+ const tree = program;
7357
+ return { ok: true, file: { path: path2, text, program: tree, bindings: bindingsOf(tree) } };
7429
7358
  }
7430
- function countedAsEverywhere(findings) {
7431
- const firsts = new Map(unparsedMigrations(findings).map(({ first, more }) => [first, more]));
7432
- return findings.flatMap((finding2) => {
7433
- if (finding2.rule !== SYNTAX_ERROR) return [finding2];
7434
- const more = firsts.get(finding2);
7435
- return more === void 0 ? [] : [{ ...finding2, parserMessagesAfter: more }];
7359
+ function bindingsOf(program) {
7360
+ const bindings = /* @__PURE__ */ new Map();
7361
+ const bind = (name, binding) => {
7362
+ bindings.set(name, [...bindings.get(name) ?? [], binding]);
7363
+ };
7364
+ walk(program, (node) => {
7365
+ switch (node.type) {
7366
+ case "VariableDeclaration": {
7367
+ for (const declarator of node.declarations) {
7368
+ const id = declarator.id;
7369
+ const init = declarator.init;
7370
+ if (node.kind === "const" && id.type === "Identifier" && init) {
7371
+ bind(id.name, { kind: "const", init });
7372
+ } else {
7373
+ for (const name of namesIn(id)) bind(name, { kind: "other" });
7374
+ }
7375
+ }
7376
+ return;
7377
+ }
7378
+ case "ImportDeclaration": {
7379
+ if (node.importKind === "type") return;
7380
+ for (const specifier of node.specifiers ?? []) {
7381
+ const local = specifier.local.name;
7382
+ const imported = specifier.imported;
7383
+ if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imported) {
7384
+ const name = imported.name ?? imported.value;
7385
+ bind(local, {
7386
+ kind: "import",
7387
+ source: node.source.value,
7388
+ imported: name
7389
+ });
7390
+ } else if (specifier.type !== "ImportSpecifier") {
7391
+ bind(local, { kind: "other" });
7392
+ }
7393
+ }
7394
+ return;
7395
+ }
7396
+ case "FunctionDeclaration":
7397
+ case "FunctionExpression":
7398
+ case "ArrowFunctionExpression":
7399
+ if (node.id) bind(node.id.name, { kind: "other" });
7400
+ for (const param of node.params) {
7401
+ for (const name of namesIn(param)) bind(name, { kind: "other" });
7402
+ }
7403
+ return;
7404
+ case "ClassDeclaration":
7405
+ case "ClassExpression":
7406
+ case "TSEnumDeclaration":
7407
+ if (node.id) bind(node.id.name, { kind: "other" });
7408
+ return;
7409
+ case "CatchClause":
7410
+ if (node.param)
7411
+ for (const name of namesIn(node.param)) bind(name, { kind: "other" });
7412
+ return;
7413
+ default:
7414
+ return;
7415
+ }
7436
7416
  });
7417
+ return bindings;
7437
7418
  }
7438
-
7439
- // src/roles/sql/report/render-markdown.ts
7440
- var PLACES_PER_RULE = 3;
7441
- function renderMarkdown3(report) {
7442
- return [
7443
- `#### \`${report.module}\``,
7444
- "",
7445
- headline2(report),
7446
- ...offBlock(report),
7447
- ...unreadBlock(report),
7448
- ...syntaxBlock(report),
7449
- ...unsafeBlock(report),
7450
- ...ruleBlocks(report),
7451
- "",
7452
- `<sub>Only the migrations this branch adds or changes are read. ${levelsLine(report)} Every place, with the SQL behind it and sentinel's full notes, is in the \`sql.html\` this run keeps. Measured by sentinel ${report.sentinel}.</sub>`,
7453
- ""
7454
- ].join("\n");
7419
+ function namesIn(pattern) {
7420
+ if (!pattern) return [];
7421
+ switch (pattern.type) {
7422
+ case "Identifier":
7423
+ return [pattern.name];
7424
+ case "ObjectPattern":
7425
+ return pattern.properties.flatMap(
7426
+ (property) => property.type === "RestElement" ? namesIn(property.argument) : namesIn(property.value)
7427
+ );
7428
+ case "ArrayPattern":
7429
+ return pattern.elements.flatMap((element) => namesIn(element));
7430
+ case "AssignmentPattern":
7431
+ return namesIn(pattern.left);
7432
+ case "RestElement":
7433
+ return namesIn(pattern.argument);
7434
+ case "TSParameterProperty":
7435
+ return namesIn(pattern.parameter);
7436
+ default:
7437
+ return [];
7438
+ }
7455
7439
  }
7456
- function headline2(report) {
7457
- if (report.base === null) return "No migration and no raw SQL call in this module.";
7458
- const against = `compared with \`${report.base.ref}\` at \`${report.base.commit}\``;
7459
- const migrations = report.read.length;
7460
- const files = report.unsafe.read.length;
7461
- if (migrations === 0 && files === 0) {
7462
- return `No migration or raw SQL call added or changed by this branch, ${against}: nothing to check.`;
7440
+ var FileCache = class {
7441
+ constructor(readFile) {
7442
+ this.readFile = readFile;
7463
7443
  }
7464
- const counts2 = (count, what, noun) => `**${count}** ${what} ${noun}${count === 1 ? "" : "s"}`;
7465
- const calls = [
7466
- ...report.rulesOff.includes(UNSAFE_RULE) ? [] : [counts2(report.unsafe.calls, "raw SQL", "call")],
7467
- ...report.rulesOff.includes(RAW_FRAGMENT_RULE) ? [] : [counts2(report.unsafe.rawCalls, "Prisma", "fragment")]
7468
- ];
7469
- const items = [
7470
- ...migrations > 0 ? [`**${migrations}** migration${migrations === 1 ? "" : "s"}`] : [],
7471
- ...files > 0 ? calls : []
7444
+ readFile;
7445
+ parsed = /* @__PURE__ */ new Map();
7446
+ set(file) {
7447
+ this.parsed.set(file.path, file);
7448
+ }
7449
+ /** The file a relative specifier names from `from`, or null when it cannot be read or parsed. */
7450
+ resolve(from, specifier) {
7451
+ for (const candidate of candidatesFor(join27(dirname4(from), specifier))) {
7452
+ if (this.parsed.has(candidate)) return this.parsed.get(candidate) ?? null;
7453
+ const text = this.readFile(candidate);
7454
+ if (text === void 0) continue;
7455
+ const parsed = parse(candidate, text);
7456
+ const file = parsed.ok ? parsed.file : null;
7457
+ this.parsed.set(candidate, file);
7458
+ return file;
7459
+ }
7460
+ return null;
7461
+ }
7462
+ };
7463
+ function candidatesFor(base) {
7464
+ const typescript = base.replace(
7465
+ /\.(m|c)?js$/,
7466
+ (_, kind) => `.${kind ?? ""}ts`
7467
+ );
7468
+ return [
7469
+ ...typescript === base ? [] : [typescript],
7470
+ base,
7471
+ ...RESOLVABLE_EXTENSIONS.map((extension) => `${base}${extension}`),
7472
+ ...RESOLVABLE_EXTENSIONS.map((extension) => join27(base, `index${extension}`))
7472
7473
  ];
7473
- const where = files > 0 ? ` in ${files} file${files === 1 ? "" : "s"}` : "";
7474
- const read = items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}${where}` : `${items.join("")}${where}`;
7475
- const findings = countedFindings(report.findings).length;
7476
- const errors = errorFindings(report.findings).length;
7477
- const counted = `**${findings} finding${findings === 1 ? "" : "s"}**`;
7478
- const found = findings === 0 ? "no finding" : errors === 0 ? `${counted}, every one a warning` : `${counted}: \u2717 **${errors} error${errors === 1 ? "" : "s"}**, from rules this module sets to \`error\`, and ${findings - errors} warning${findings - errors === 1 ? "" : "s"}`;
7479
- return `Read ${read} this branch adds or changes, ${against}: ${found}.`;
7480
7474
  }
7481
- function levelsLine(report) {
7482
- return errorFindings(report.findings).length === 0 ? "Every finding is a warning while the role is being adopted: nothing here fails the run." : "A rule the module sets to `error` fails the module's `sql` run; every other finding is a warning.";
7475
+ var KNOWN_METHODS = /* @__PURE__ */ new Set([...UNSAFE_METHODS, "raw", "join", "query", "unsafe"]);
7476
+ function callShape(node, imports) {
7477
+ const callee = unwrap(node.callee);
7478
+ const args = node.arguments ?? [];
7479
+ const alias = (expression) => expression.type === "Identifier" ? imports.unsafeAliases.get(expression.name) : void 0;
7480
+ const aliased = alias(callee);
7481
+ if (aliased !== void 0) return { name: aliased, object: void 0, args, callee };
7482
+ const name = memberName(callee);
7483
+ if (name === void 0) return void 0;
7484
+ if (name === "call" || name === "apply") {
7485
+ const target = unwrap(callee.object);
7486
+ const method = alias(target) ?? memberName(target);
7487
+ if (method === void 0 || !KNOWN_METHODS.has(method)) return void 0;
7488
+ const object = alias(target) === void 0 ? unwrap(target.object) : void 0;
7489
+ if (name === "call") return { name: method, object, args: args.slice(1), callee: target };
7490
+ const list = args[1] === void 0 ? void 0 : unwrap(args[1]);
7491
+ const applied = list === void 0 ? [] : list.type === "ArrayExpression" ? list.elements.filter(
7492
+ (item) => item !== null
7493
+ ) : [{ type: "SpreadElement", argument: list, start: list.start, end: list.end }];
7494
+ return { name: method, object, args: applied, callee: target };
7495
+ }
7496
+ return { name, object: unwrap(callee.object), args, callee };
7483
7497
  }
7484
- function offBlock(report) {
7485
- if (report.read.length === 0 && report.unsafe.files.length === 0 || report.rulesOff.length === 0)
7486
- return [];
7487
- return [
7488
- "",
7489
- `Turned off by this module, so not checked: ${report.rulesOff.map((rule) => `\`${rule}\``).join(", ")}.`
7490
- ];
7498
+ function textsAt(args, from, to = from + 1) {
7499
+ const texts = [];
7500
+ for (let index = 0; index < Math.min(args.length, to); index++) {
7501
+ const argument = args[index];
7502
+ if (argument.type === "SpreadElement") {
7503
+ texts.push(argument.argument);
7504
+ return texts;
7505
+ }
7506
+ if (index >= from) texts.push(argument);
7507
+ }
7508
+ return texts;
7491
7509
  }
7492
- function unreadBlock(report) {
7493
- if (report.unread.length === 0) return [];
7494
- return [
7495
- "",
7496
- `\u2717 **${report.unread.length} migration(s) could not be opened**, so nothing in them is checked:`,
7497
- ...report.unread.map(({ file, reason }) => `- \`${file}\`: ${reason}`)
7498
- ];
7510
+ function unsafeAliasesOf(program, bindings) {
7511
+ const isUnsafe = (name) => name !== void 0 && UNSAFE_METHODS.includes(name);
7512
+ const declared = /* @__PURE__ */ new Map();
7513
+ const alias = (local, method) => {
7514
+ declared.set(local, [...declared.get(local) ?? [], method]);
7515
+ };
7516
+ walk(program, (node) => {
7517
+ if (node.type !== "VariableDeclarator" || !node.init) return;
7518
+ const id = node.id;
7519
+ let init = unwrap(node.init);
7520
+ if (id.type === "ObjectPattern") {
7521
+ for (const property of id.properties) {
7522
+ if (property.type !== "Property" || property.computed) continue;
7523
+ const key = property.key.name ?? property.key.value;
7524
+ const value = unwrap(property.value);
7525
+ const local = value.type === "AssignmentPattern" ? unwrap(value.left) : value;
7526
+ if (isUnsafe(key) && local.type === "Identifier") {
7527
+ alias(local.name, key);
7528
+ }
7529
+ }
7530
+ return;
7531
+ }
7532
+ if (id.type !== "Identifier") return;
7533
+ if (init.type === "CallExpression" && memberName(unwrap(init.callee)) === "bind") {
7534
+ init = unwrap(unwrap(init.callee).object ?? init);
7535
+ }
7536
+ const method = memberName(init);
7537
+ if (isUnsafe(method)) alias(id.name, method);
7538
+ });
7539
+ const aliases = /* @__PURE__ */ new Map();
7540
+ for (const [local, methods] of declared) {
7541
+ const [method] = methods;
7542
+ const everyBinding = methods.length === (bindings.get(local)?.length ?? 0);
7543
+ if (method !== void 0 && everyBinding && methods.every((other) => other === method))
7544
+ aliases.set(local, method);
7545
+ }
7546
+ return aliases;
7499
7547
  }
7500
- function syntaxBlock(report) {
7501
- const files = unparsedMigrations(report.findings);
7502
- if (files.length === 0) return [];
7503
- return [
7504
- "",
7505
- `\u2717 **${files.length} migration${files.length === 1 ? " does" : "s do"} not parse**: squawk could not read the SQL, so no other rule checked it, and PostgreSQL will refuse it too. The first error, the one to fix:`,
7506
- ...files.map(
7507
- ({ first, more }) => `- \`${placeOf(first)}\` ${first.message}` + (more > 0 ? ` (and ${more} more after it, which follow from it)` : "")
7508
- )
7509
- ];
7548
+ function prismaNamespacesOf(program) {
7549
+ const names = /* @__PURE__ */ new Set();
7550
+ walk(program, (node) => {
7551
+ if (node.type !== "ImportDeclaration" || node.importKind === "type") return;
7552
+ const source = node.source.value;
7553
+ if (typeof source !== "string" || !source.startsWith("@prisma/")) return;
7554
+ for (const specifier of node.specifiers ?? []) {
7555
+ if (specifier.type === "ImportNamespaceSpecifier") {
7556
+ names.add(specifier.local.name);
7557
+ }
7558
+ }
7559
+ });
7560
+ return names;
7510
7561
  }
7511
- function ruleBlocks(report) {
7512
- return byRule(report.findings).flatMap(({ rule, findings }) => {
7513
- const [first] = findings;
7514
- if (first === void 0) return [];
7515
- const more = findings.length - Math.min(findings.length, PLACES_PER_RULE);
7516
- const places2 = placesText(findings.slice(0, PLACES_PER_RULE)) + (more > 0 ? ` and ${more} more` : "");
7517
- const note = findings.find((finding2) => finding2.sentinelNote !== null)?.sentinelNote;
7518
- return [
7519
- "",
7520
- `**${rule}**${first.level === "error" ? " \u2717 error" : ""} \xB7 ${findings.length} \xB7 ${places2}`,
7521
- // sentinel's own rules speak as sentinel: their words are not squawk's.
7522
- `> ${SENTINEL_RULES.includes(rule) ? "sentinel" : "squawk"}: ${first.message}${first.help ? `. Fix: ${first.help}` : ""}.`,
7523
- ...note ? [`> **sentinel:** ${note.short}`] : []
7524
- ];
7562
+ function driversImported(program) {
7563
+ const sources = /* @__PURE__ */ new Set();
7564
+ walk(program, (node) => {
7565
+ if (node.type === "ImportDeclaration") {
7566
+ sources.add(node.source.value);
7567
+ } else if (node.type === "CallExpression") {
7568
+ const callee = node.callee;
7569
+ const [first] = node.arguments ?? [];
7570
+ if (callee.type === "Identifier" && callee.name === "require" && first?.type === "Literal" && typeof first.value === "string") {
7571
+ sources.add(first.value);
7572
+ }
7573
+ }
7525
7574
  });
7575
+ return { pg: sources.has("pg"), postgres: sources.has("postgres") };
7526
7576
  }
7527
- function placesText(findings) {
7528
- const byFile2 = /* @__PURE__ */ new Map();
7529
- for (const finding2 of findings)
7530
- byFile2.set(finding2.file, [...byFile2.get(finding2.file) ?? [], finding2.line]);
7531
- return [...byFile2].map(([file, lines]) => `\`${file}\` line${lines.length === 1 ? "" : "s"} ${lines.join(", ")}`).join("; ");
7577
+ function memberName(callee) {
7578
+ if (!MEMBER_TYPES.has(callee.type)) return void 0;
7579
+ const property = callee.property;
7580
+ if (!callee.computed) return property.name;
7581
+ return property.type === "Literal" && typeof property.value === "string" ? property.value : void 0;
7532
7582
  }
7533
- function unsafeBlock(report) {
7534
- const { unparsed } = report.unsafe;
7535
- if (unparsed.length === 0) return [];
7536
- return [
7537
- "",
7538
- `\u2717 **${unparsed.length} TypeScript file(s) could not be read**, so their raw SQL calls are not checked:`,
7539
- ...unparsed.map(({ file, reason }) => `- \`${file}\`: ${reason}`)
7540
- ];
7583
+ function isPrisma(object, imports) {
7584
+ if (object === void 0) return false;
7585
+ if (object.type === "Identifier") return imports.prisma.has(object.name);
7586
+ if (memberName(object) !== "Prisma") return false;
7587
+ const namespace = unwrap(object.object);
7588
+ return namespace.type === "Identifier" && imports.prismaNamespaces.has(namespace.name);
7541
7589
  }
7542
-
7543
- // src/roles/sql/report/outputs.ts
7544
- var SHAPE_FILE2 = {
7545
- json: `${TARGET}.json`,
7546
- html: `${TARGET}.html`,
7547
- markdown: `${TARGET}.md`
7548
- };
7549
- function shapesOf2(output) {
7550
- const asked = (output ?? "console").split(",").map((one) => one.trim()).filter((one) => one !== "");
7551
- const shapes = [...new Set(asked)];
7552
- const unknown = shapes.filter((one) => !OUTPUT_SHAPES.includes(one));
7553
- if (shapes.length === 0 || unknown.length > 0) {
7590
+ function sqlTextCall(node, imports, text) {
7591
+ if (node.type !== "CallExpression") return void 0;
7592
+ const shape = callShape(node, imports);
7593
+ if (shape === void 0) return void 0;
7594
+ const { name, args, callee } = shape;
7595
+ const onPrisma = isPrisma(shape.object, imports);
7596
+ if (UNSAFE_METHODS.includes(name)) {
7554
7597
  return {
7555
- ok: false,
7556
- reason: `unknown --output "${output ?? ""}" (known: ${OUTPUT_SHAPES.join(", ")}; several at once with a comma).`
7598
+ label: name,
7599
+ rule: UNSAFE_RULE,
7600
+ texts: textsAt(args, 0),
7601
+ help: `pass a value as a parameter (\`$1\` in the text, the value after it), or use the tagged ${name.replace("Unsafe", "")}\`\u2026\`, which binds each \`\${}\`; a table or column name cannot be a parameter: take it from a \`const\` of this file`
7602
+ };
7603
+ }
7604
+ if (onPrisma && name === "raw") {
7605
+ return {
7606
+ label: "Prisma.raw",
7607
+ rule: RAW_FRAGMENT_RULE,
7608
+ texts: textsAt(args, 0),
7609
+ help: `Prisma.raw puts its text in the query as SQL, never as a parameter: pass a value as \`\${value}\` in Prisma.sql\`\u2026\`, which binds it; for a keyword or a column name, write each choice as a literal, \`order === 'DESC' ? Prisma.raw('DESC') : Prisma.raw('ASC')\`, or take it from a \`const\` of this file`
7610
+ };
7611
+ }
7612
+ if (onPrisma && name === "join") {
7613
+ return {
7614
+ label: "Prisma.join",
7615
+ rule: RAW_FRAGMENT_RULE,
7616
+ // The list is bound; the separator, prefix and suffix are SQL text.
7617
+ texts: textsAt(args, 1, 4),
7618
+ help: `Prisma.join binds the values of its list, but its separator, prefix and suffix are SQL text: write them as literals (\`Prisma.join(conditions, ' AND ')\`)`
7619
+ };
7620
+ }
7621
+ if (shape.object === void 0) return void 0;
7622
+ const shown = sourceOf(text, callee);
7623
+ if (imports.pg && name === "query") {
7624
+ const [first] = textsAt(args, 0);
7625
+ const sql = first?.type === "ObjectExpression" ? propertyValue(first, "text") : first;
7626
+ return {
7627
+ label: `${shown} (pg)`,
7628
+ rule: UNSAFE_RULE,
7629
+ texts: sql === void 0 ? [] : [sql],
7630
+ help: `pass a value as a parameter: \`$1\` in the text, the value in the array after it (\`client.query(text, [value])\`); a table or column name cannot be a parameter: take it from a \`const\` of this file`
7631
+ };
7632
+ }
7633
+ if (imports.postgres && name === "unsafe") {
7634
+ return {
7635
+ label: `${shown} (postgres)`,
7636
+ rule: UNSAFE_RULE,
7637
+ texts: textsAt(args, 0),
7638
+ help: `use the tagged sql\`\u2026\${value}\u2026\`, which binds each value; for a table or column name, \`sql(name)\` quotes it as an identifier`
7557
7639
  };
7558
7640
  }
7559
- return { ok: true, shapes };
7641
+ return void 0;
7642
+ }
7643
+ function propertyValue(object, key) {
7644
+ for (const property of object.properties) {
7645
+ if (property.type !== "Property" || property.computed) continue;
7646
+ const name = property.key.name ?? property.key.value;
7647
+ if (name === key) return property.value;
7648
+ }
7649
+ return void 0;
7650
+ }
7651
+ function prismaNames(bindings) {
7652
+ const names = /* @__PURE__ */ new Set();
7653
+ for (const [name, bound] of bindings) {
7654
+ const fromPrisma = bound.some(
7655
+ (binding) => binding.kind === "import" && binding.imported === "Prisma" && binding.source.startsWith("@prisma/")
7656
+ );
7657
+ if (fromPrisma) names.add(name);
7658
+ }
7659
+ return names;
7660
+ }
7661
+ function unwrap(node) {
7662
+ let current = node;
7663
+ while ([
7664
+ "ParenthesizedExpression",
7665
+ "TSAsExpression",
7666
+ "TSSatisfiesExpression",
7667
+ "TSNonNullExpression",
7668
+ "TSTypeAssertion",
7669
+ "ChainExpression"
7670
+ ].includes(current.type)) {
7671
+ current = current.expression;
7672
+ }
7673
+ return current;
7674
+ }
7675
+ function unsafeParts(sql, context2) {
7676
+ const node = unwrap(sql);
7677
+ if (node.type === "TemplateLiteral") {
7678
+ return node.expressions.flatMap((part) => unsafeParts(part, context2));
7679
+ }
7680
+ if (node.type === "BinaryExpression" && node.operator === "+") {
7681
+ if (isNumeric(node, context2)) return [];
7682
+ return [
7683
+ ...unsafeParts(node.left, context2),
7684
+ ...unsafeParts(node.right, context2)
7685
+ ];
7686
+ }
7687
+ return isSafe(node, context2) ? [] : [node];
7560
7688
  }
7561
- var writesFiles = (shapes) => shapes.some((shape) => shape !== "console");
7562
- function writeOutputs(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
7563
- if (!writesFiles(shapes)) return [];
7564
- removeOutputs(cwd, shapes);
7565
- mkdirSync2(join26(cwd, REPORT_DIR), { recursive: true });
7566
- const written = [];
7567
- for (const shape of shapes) {
7568
- if (shape === "console") continue;
7569
- const path2 = join26(REPORT_DIR, SHAPE_FILE2[shape]);
7570
- writeFileSync6(join26(cwd, path2), render(report, shape, now));
7571
- written.push(path2);
7689
+ var NUMERIC_OPERATORS = /* @__PURE__ */ new Set(["-", "*", "/", "%", "**", "|", "&", "^", "<<", ">>", ">>>"]);
7690
+ function isSafe(expression, context2) {
7691
+ if (context2.depth > MAX_DEPTH) return false;
7692
+ const node = unwrap(expression);
7693
+ switch (node.type) {
7694
+ case "Literal":
7695
+ return true;
7696
+ case "TemplateLiteral":
7697
+ return node.expressions.every((part) => isSafe(part, context2));
7698
+ case "BinaryExpression":
7699
+ return node.operator === "+" ? isSafe(node.left, context2) && isSafe(node.right, context2) : NUMERIC_OPERATORS.has(node.operator) || // A comparison is a boolean.
7700
+ ["==", "!=", "===", "!==", "<", "<=", ">", ">=", "in", "instanceof"].includes(
7701
+ node.operator
7702
+ );
7703
+ case "UnaryExpression":
7704
+ return true;
7705
+ case "ConditionalExpression":
7706
+ return isSafe(node.consequent, context2) && isSafe(node.alternate, context2);
7707
+ case "LogicalExpression":
7708
+ return isSafe(node.left, context2) && isSafe(node.right, context2);
7709
+ case "Identifier":
7710
+ return isSafeName(node.name, context2);
7711
+ case "CallExpression":
7712
+ return isPlaceholderList(node, context2);
7713
+ default:
7714
+ return false;
7572
7715
  }
7573
- return written;
7574
7716
  }
7575
- function removeOutputs(cwd, keeping = []) {
7576
- for (const [shape, name] of Object.entries(SHAPE_FILE2)) {
7577
- if (keeping.includes(shape)) continue;
7578
- const path2 = join26(cwd, REPORT_DIR, name);
7579
- if (existsSync16(path2)) unlinkSync2(path2);
7717
+ function isNumeric(node, context2) {
7718
+ const current = unwrap(node);
7719
+ if (current.type === "Literal") return typeof current.value === "number";
7720
+ if (current.type === "BinaryExpression") {
7721
+ if (NUMERIC_OPERATORS.has(current.operator)) return true;
7722
+ if (current.operator === "+") {
7723
+ return isNumeric(current.left, context2) && isNumeric(current.right, context2);
7724
+ }
7580
7725
  }
7726
+ if (current.type === "UnaryExpression")
7727
+ return ["-", "+", "~"].includes(current.operator);
7728
+ if (current.type === "Identifier") return context2.local.get(current.name) === true;
7729
+ return false;
7581
7730
  }
7582
- function render(report, shape, now) {
7583
- if (shape === "json") return renderJson3(report, now);
7584
- if (shape === "html") return renderHtml2(report, now);
7585
- return renderMarkdown3(report);
7731
+ function isSafeName(name, context2) {
7732
+ if (context2.local.has(name)) return context2.local.get(name) === true;
7733
+ const bindings = context2.file.bindings.get(name) ?? [];
7734
+ if (bindings.length !== 1) return false;
7735
+ const [binding] = bindings;
7736
+ const deeper = { ...context2, depth: context2.depth + 1, local: /* @__PURE__ */ new Map() };
7737
+ if (binding?.kind === "const") return isSafe(binding.init, deeper);
7738
+ if (binding?.kind === "import") return isSafeImport(binding.source, binding.imported, deeper);
7739
+ return false;
7586
7740
  }
7587
-
7588
- // src/roles/sql/sources.ts
7589
- import { existsSync as existsSync17, readFileSync as readFileSync16, realpathSync as realpathSync2 } from "node:fs";
7590
- import { dirname as dirname4, join as join27, relative as relative4, resolve as resolve3, sep } from "node:path";
7591
- import { globSync } from "tinyglobby";
7592
- var WALK = { onlyFiles: true, dot: false, followSymbolicLinks: false };
7593
- var ADOPTION_FILE = "sql.config.mjs";
7594
- function adoptedInnerModules(cwd, nested) {
7595
- return (nested ?? adoptedInnerDirs(cwd)).map((dir) => `${dir}/**`);
7741
+ function isSafeImport(source, imported, context2) {
7742
+ if (!source.startsWith(".")) return false;
7743
+ const file = context2.files.resolve(context2.file.path, source);
7744
+ if (file === null) return false;
7745
+ const exported = exportedConst(file, imported);
7746
+ return exported !== void 0 && isSafe(exported, { ...context2, file });
7596
7747
  }
7597
- function adoptedInnerDirs(cwd) {
7598
- return globSync([`**/${ADOPTION_FILE}`], {
7599
- ...WALK,
7600
- cwd,
7601
- ignore: ["**/node_modules/**"]
7602
- }).map((file) => file.slice(0, -ADOPTION_FILE.length - 1)).filter((dir) => dir !== "");
7748
+ function exportedConst(file, name) {
7749
+ for (const statement of file.program.body) {
7750
+ if (statement.type !== "ExportNamedDeclaration") continue;
7751
+ const declaration = statement.declaration;
7752
+ if (declaration?.type !== "VariableDeclaration" || declaration.kind !== "const") continue;
7753
+ for (const declarator of declaration.declarations) {
7754
+ const id = declarator.id;
7755
+ if (id.type === "Identifier" && id.name === name && declarator.init)
7756
+ return declarator.init;
7757
+ }
7758
+ }
7759
+ return void 0;
7603
7760
  }
7604
- function migrationFiles(cwd, settings, nested) {
7605
- return globSync(settings.migrations.include, {
7606
- ...WALK,
7607
- cwd,
7608
- ignore: [
7609
- ...settings.migrations.exclude,
7610
- ...settings.ignore,
7611
- ...adoptedInnerModules(cwd, nested)
7612
- ]
7613
- }).sort();
7761
+ function isPlaceholderList(call, context2) {
7762
+ const join43 = unwrap(call.callee);
7763
+ if (!MEMBER_TYPES.has(join43.type) || join43.property.name !== "join") return false;
7764
+ const separator = call.arguments[0];
7765
+ if (separator !== void 0 && !isSafe(separator, context2)) return false;
7766
+ const map = unwrap(join43.object);
7767
+ if (map.type !== "CallExpression") return false;
7768
+ const mapCallee = unwrap(map.callee);
7769
+ if (!MEMBER_TYPES.has(mapCallee.type) || mapCallee.property.name !== "map")
7770
+ return false;
7771
+ const callback = map.arguments[0];
7772
+ if (callback === void 0) return false;
7773
+ if (callback.type !== "ArrowFunctionExpression" && callback.type !== "FunctionExpression")
7774
+ return false;
7775
+ const returned = returnedExpression(callback);
7776
+ if (returned === void 0) return false;
7777
+ const params = callback.params;
7778
+ const local = new Map(context2.local);
7779
+ params.forEach((param, position) => {
7780
+ for (const name of namesIn(param))
7781
+ local.set(name, position === 1 && param.type === "Identifier");
7782
+ });
7783
+ return isSafe(returned, { ...context2, depth: context2.depth + 1, local });
7614
7784
  }
7615
- function codeFiles(cwd, settings, nested) {
7616
- return globSync(["**/*.{ts,mts,cts}"], {
7617
- ...WALK,
7618
- cwd,
7619
- ignore: [
7620
- "**/*.d.{ts,mts,cts}",
7621
- ...settings.ignore,
7622
- ...settings.unsafe.includeTests ? [] : settings.unsafe.tests,
7623
- ...adoptedInnerModules(cwd, nested)
7624
- ]
7625
- }).sort();
7785
+ function returnedExpression(callback) {
7786
+ const body = callback.body;
7787
+ if (body.type !== "BlockStatement") return body;
7788
+ const statements = body.body;
7789
+ const [only] = statements;
7790
+ return statements.length === 1 && only?.type === "ReturnStatement" && only.argument ? only.argument : void 0;
7626
7791
  }
7627
- var UNSAFE_CALL = /\$(?:queryRaw|executeRaw)Unsafe\b/;
7628
- var PRISMA_IMPORT = /from\s*['"]@prisma\//;
7629
- var RAW_CALL = /\.raw\s*\(/;
7630
- var PRISMA_ALIAS = /\bPrisma\s+as\s+([A-Za-z_$][\w$]*)/g;
7631
- function callsPrismaJoin(text) {
7632
- const names = ["Prisma", ...[...text.matchAll(PRISMA_ALIAS)].map((match) => match[1] ?? "")];
7633
- return names.some(
7634
- (name) => new RegExp(`(?<![\\w$])${name.replace(/\$/g, "\\$")}\\.join\\s*\\(`).test(text)
7635
- );
7792
+ function findingOf(file, text, call, first, pasted) {
7793
+ const start = positionOf(text, first.start);
7794
+ const end = positionOf(text, Math.max(first.end - 1, first.start));
7795
+ const shown = pasted.slice(0, 3).map((part) => codeSpan(sourceOf(text, part)));
7796
+ const more = pasted.length > 3 ? ` and ${pasted.length - 3} more` : "";
7797
+ const whole = call.texts.some((sql) => unwrap(sql) === first);
7798
+ const method = call.label;
7799
+ return {
7800
+ file,
7801
+ line: start.line,
7802
+ column: start.column,
7803
+ endLine: end.line,
7804
+ endColumn: end.column,
7805
+ rule: call.rule,
7806
+ squawkLevel: "Warning",
7807
+ message: whole ? `the SQL text of ${method} is ${shown[0]}, which sentinel cannot show is a constant: whatever was pasted into it, wherever it was built, runs as SQL` : `${shown.join(", ")}${more} ${pasted.length === 1 ? "is" : "are"} pasted into the SQL text of ${method}, and sentinel cannot show ${pasted.length === 1 ? "it is" : "they are"} constant: a quote in ${pasted.length === 1 ? "it" : "them"} would end the string and run the rest as SQL`,
7808
+ note: null,
7809
+ help: call.help
7810
+ };
7636
7811
  }
7637
- var PG_IMPORT = /from\s*['"]pg['"]|require\(\s*['"]pg['"]\s*\)/;
7638
- var PG_CALL = /\.query\s*\(/;
7639
- var POSTGRES_IMPORT = /from\s*['"]postgres['"]|require\(\s*['"]postgres['"]\s*\)/;
7640
- var POSTGRES_CALL = /\.unsafe\s*\(/;
7641
- function callsUnsafe(cwd, file) {
7642
- try {
7643
- const text = readFileSync16(join27(cwd, file), "utf8");
7644
- return UNSAFE_CALL.test(text) || PRISMA_IMPORT.test(text) && (RAW_CALL.test(text) || callsPrismaJoin(text)) || PG_IMPORT.test(text) && PG_CALL.test(text) || POSTGRES_IMPORT.test(text) && POSTGRES_CALL.test(text);
7645
- } catch {
7646
- return false;
7647
- }
7812
+ function sourceOf(text, node) {
7813
+ const source = text.slice(node.start, node.end).replace(/\s+/g, " ");
7814
+ return source.length > 60 ? `${source.slice(0, 57)}\u2026` : source;
7648
7815
  }
7649
- function filesWithUnsafeCalls(cwd, files) {
7650
- return files.filter((file) => callsUnsafe(cwd, file));
7816
+ function codeSpan(source) {
7817
+ return `\`${source.replace(/`/g, "'")}\``;
7651
7818
  }
7652
- function holdsSql(cwd, settings) {
7653
- if (migrationFiles(cwd, settings).length > 0) return true;
7654
- return codeFiles(cwd, settings).some((file) => callsUnsafe(cwd, file));
7819
+ function positionOf(text, offset) {
7820
+ const before = text.slice(0, offset);
7821
+ const lineStart = before.lastIndexOf("\n") + 1;
7822
+ return { line: before.split("\n").length, column: offset - lineStart + 1 };
7655
7823
  }
7656
- function rawSqlInParent(cwd) {
7657
- let here;
7824
+ function readOne(cwd, file, text, readFile, checking) {
7658
7825
  try {
7659
- here = realpathSync2(cwd);
7660
- } catch {
7661
- return void 0;
7826
+ return checkUnsafeCalls(cwd, file, text, readFile, checking);
7827
+ } catch (error) {
7828
+ const why = error instanceof RangeError ? "an expression too deeply nested to follow" : error instanceof Error ? error.message : String(error);
7829
+ return { ok: false, reason: `could not be checked (${why}), so its calls are not checked` };
7662
7830
  }
7663
- const stop = findWorkspaceRoot(here) ?? findRepositoryRoot(here);
7664
- if (stop === void 0 || dirname4(here) === here) return void 0;
7665
- const parent = findModuleRoot(dirname4(here), stop);
7666
- if (parent === void 0 || existsSync17(join27(parent, ADOPTION_FILE))) return void 0;
7667
- const mine = `${relative4(parent, here).split(sep).join("/")}/`;
7668
- const files = filesWithUnsafeCalls(
7669
- parent,
7670
- codeFiles(parent, defaults).filter((file) => !file.startsWith(mine))
7671
- );
7672
- if (files.length === 0) return void 0;
7673
- return { dir: relative4(here, parent).split(sep).join("/"), files };
7674
7831
  }
7675
- function migrationsInNested(cwd, settings = defaults, nested = adoptedInnerDirs(cwd)) {
7676
- const out = [];
7677
- for (const dir of nested) {
7678
- const count = migrationFiles(join27(cwd, dir), defaults).length;
7679
- if (count > 0) out.push({ dir, count, adopted: true });
7680
- }
7681
- const root = resolve3(cwd);
7682
- const owner = /* @__PURE__ */ new Map();
7683
- const counts2 = /* @__PURE__ */ new Map();
7684
- for (const file of migrationFiles(cwd, settings, nested)) {
7685
- const folder = dirname4(join27(root, file));
7686
- if (!owner.has(folder)) {
7687
- const project = findModuleRoot(folder, root);
7688
- owner.set(
7689
- folder,
7690
- project === void 0 ? void 0 : relative4(root, project).split(sep).join("/")
7691
- );
7832
+ function checkUnsafeFiles(cwd, files, readFile, checking = BOTH) {
7833
+ const run = { calls: 0, rawCalls: 0, findings: [], unparsed: [] };
7834
+ for (const file of files) {
7835
+ const text = readFile(join27(cwd, file));
7836
+ if (text === void 0) {
7837
+ run.unparsed.push({ file, reason: "could not be read, so its calls are not checked" });
7838
+ continue;
7692
7839
  }
7693
- const dir = owner.get(folder);
7694
- if (dir !== void 0 && dir !== "") counts2.set(dir, (counts2.get(dir) ?? 0) + 1);
7840
+ const reading = readOne(cwd, file, text, readFile, checking);
7841
+ if (!reading.ok) {
7842
+ run.unparsed.push({ file, reason: reading.reason });
7843
+ continue;
7844
+ }
7845
+ run.calls += reading.calls;
7846
+ run.rawCalls += reading.rawCalls;
7847
+ run.findings.push(...reading.findings);
7695
7848
  }
7696
- for (const [dir, count] of counts2) out.push({ dir, count, adopted: false });
7697
- return out.sort((a, b) => a.dir.localeCompare(b.dir));
7849
+ return run;
7698
7850
  }
7699
7851
 
7700
7852
  // src/roles/sql/adapters/squawk/resolve-squawk.ts
@@ -7845,18 +7997,19 @@ function runSquawk(invocation, files) {
7845
7997
  if (!reading.ok) return reading;
7846
7998
  findings.push(
7847
7999
  ...reading.findings.filter(
7848
- (finding2) => !(inTransaction && finding2.rule === NESTING && quietNesting(finding2.file))
8000
+ (finding3) => !(inTransaction && finding3.rule === NESTING && quietNesting(finding3.file))
7849
8001
  )
7850
8002
  );
7851
8003
  }
7852
8004
  }
7853
8005
  const quietTimeouts = quietTimeoutFiles(invocation, readable, statements, wrapped);
7854
8006
  const kept = findings.filter(
7855
- (finding2) => !(TIMEOUTS.has(finding2.rule) && quietTimeouts.has(finding2.file))
8007
+ (finding3) => !(TIMEOUTS.has(finding3.rule) && quietTimeouts.has(finding3.file))
7856
8008
  );
7857
8009
  const order = new Map(readable.map((file, index) => [file, index]));
7858
8010
  kept.sort((a, b) => (order.get(a.file) ?? 0) - (order.get(b.file) ?? 0));
7859
- return { ok: true, findings: kept, unread };
8011
+ const statementCounts = new Map([...statements].map(([file, read]) => [file, read.count]));
8012
+ return { ok: true, findings: kept, unread, statementCounts };
7860
8013
  }
7861
8014
  function quietTimeoutFiles(invocation, readable, statements, wrapped) {
7862
8015
  const texts = /* @__PURE__ */ new Map();
@@ -7880,8 +8033,8 @@ function indexesOnExistingTables(invocation, files) {
7880
8033
  for (const batch of batches(files)) {
7881
8034
  const reading = runBatch({ ...invocation, configPath }, batch, true);
7882
8035
  if (!reading.ok) return void 0;
7883
- for (const finding2 of reading.findings)
7884
- if (INDEX_ON_EXISTING.has(finding2.rule)) found.add(finding2.file);
8036
+ for (const finding3 of reading.findings)
8037
+ if (INDEX_ON_EXISTING.has(finding3.rule)) found.add(finding3.file);
7885
8038
  }
7886
8039
  return found;
7887
8040
  } finally {
@@ -8052,7 +8205,7 @@ function runBatch(invocation, batch, inTransaction = false) {
8052
8205
  }
8053
8206
  function onlyWhatWasAsked(findings, batch) {
8054
8207
  const asked = new Set(batch);
8055
- const stray = findings.find((finding2) => !asked.has(finding2.file));
8208
+ const stray = findings.find((finding3) => !asked.has(finding3.file));
8056
8209
  if (stray === void 0) return { ok: true, findings };
8057
8210
  return {
8058
8211
  ok: false,
@@ -8247,7 +8400,12 @@ var SquawkAdapter = class extends BaseAdapter {
8247
8400
  const unsafeOff = !checking.methods && !checking.raw;
8248
8401
  const unsafe = unsafeOff ? { calls: 0, rawCalls: 0, findings: [], unparsed: [] } : checkUnsafeFiles(ctx.cwd, code, readAbsolute, checking);
8249
8402
  const findings = withNotes(
8250
- [...history.findings, ...run.findings, ...unsafe.findings],
8403
+ [
8404
+ ...history.findings,
8405
+ ...run.findings,
8406
+ ...enumFindings(ctx.cwd, config, read, run),
8407
+ ...unsafe.findings
8408
+ ],
8251
8409
  (file) => readText2(ctx.cwd, file),
8252
8410
  config.rules
8253
8411
  );
@@ -8415,6 +8573,14 @@ function appliedChanges(cwd, config, base, nested) {
8415
8573
  if (!reading.ok) return reading;
8416
8574
  return { ok: true, findings: historyFindings(reading.changes, base.ref) };
8417
8575
  }
8576
+ function enumFindings(cwd, config, files, run) {
8577
+ if (config.rules[ENUM_VALUE_RULE] === "off") return [];
8578
+ return files.flatMap((file) => {
8579
+ const count = run.statementCounts?.get(file);
8580
+ const text = count === void 0 ? void 0 : readText2(cwd, file);
8581
+ return count === void 0 || text === void 0 ? [] : enumValueFindings(file, text, count);
8582
+ });
8583
+ }
8418
8584
  function whatTheModuleHolds(cwd, config) {
8419
8585
  const nested = adoptedInnerDirs(cwd);
8420
8586
  const code = codeFiles(cwd, config, nested);
@@ -9191,16 +9357,16 @@ function declarationOf(lines, name) {
9191
9357
  }
9192
9358
  return hits.length === 1 ? hits[0] : void 0;
9193
9359
  }
9194
- function windowFor(finding2, lines) {
9195
- const { line } = pointOf(finding2.path);
9360
+ function windowFor(finding3, lines) {
9361
+ const { line } = pointOf(finding3.path);
9196
9362
  const head = () => ({
9197
9363
  firstLine: 1,
9198
9364
  text: lines.slice(0, WINDOW.lines).join("\n")
9199
9365
  });
9200
- if (WHOLE_FILE.has(finding2.metric) || SHOWS_THE_HEAD.has(finding2.metric)) return head();
9201
- const at = line ?? (finding2.name ? declarationOf(lines, finding2.name) : void 0);
9366
+ if (WHOLE_FILE.has(finding3.metric) || SHOWS_THE_HEAD.has(finding3.metric)) return head();
9367
+ const at = line ?? (finding3.name ? declarationOf(lines, finding3.name) : void 0);
9202
9368
  if (at === void 0) return void 0;
9203
- const nests = NESTS_UPWARD.has(finding2.metric);
9369
+ const nests = NESTS_UPWARD.has(finding3.metric);
9204
9370
  const from = nests ? Math.max(1, at - WINDOW.nesting.before) : at;
9205
9371
  const to = Math.min(lines.length, nests ? at + WINDOW.nesting.after : at + WINDOW.lines - 1);
9206
9372
  if (from > lines.length) return void 0;
@@ -9209,18 +9375,18 @@ function windowFor(finding2, lines) {
9209
9375
  function withExcerpts(report, cwd) {
9210
9376
  const wanted = /* @__PURE__ */ new Set();
9211
9377
  for (const group of listedByMetric(report.findings).values()) {
9212
- for (const finding2 of group.listed) {
9213
- if (finding2.excerpt === void 0) wanted.add(finding2);
9378
+ for (const finding3 of group.listed) {
9379
+ if (finding3.excerpt === void 0) wanted.add(finding3);
9214
9380
  }
9215
9381
  }
9216
9382
  if (wanted.size === 0) return report;
9217
9383
  const cache = /* @__PURE__ */ new Map();
9218
- const findings = report.findings.map((finding2) => {
9219
- if (!wanted.has(finding2)) return finding2;
9220
- const lines = linesOf(cache, cwd, pointOf(finding2.path).file);
9221
- if (lines === void 0) return finding2;
9222
- const found = windowFor(finding2, lines);
9223
- return found === void 0 ? finding2 : { ...finding2, excerpt: found.text, excerptFirstLine: found.firstLine };
9384
+ const findings = report.findings.map((finding3) => {
9385
+ if (!wanted.has(finding3)) return finding3;
9386
+ const lines = linesOf(cache, cwd, pointOf(finding3.path).file);
9387
+ if (lines === void 0) return finding3;
9388
+ const found = windowFor(finding3, lines);
9389
+ return found === void 0 ? finding3 : { ...finding3, excerpt: found.text, excerptFirstLine: found.firstLine };
9224
9390
  });
9225
9391
  return { ...report, findings };
9226
9392
  }
@@ -10237,8 +10403,8 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
10237
10403
  return { kind: "no-entry-point", files: statistics.files ?? 0 };
10238
10404
  }
10239
10405
  const byCategory = {};
10240
- for (const finding2 of parsed?.findings ?? []) {
10241
- const category = finding2.category ?? "unknown";
10406
+ for (const finding3 of parsed?.findings ?? []) {
10407
+ const category = finding3.category ?? "unknown";
10242
10408
  byCategory[category] = (byCategory[category] ?? 0) + 1;
10243
10409
  }
10244
10410
  return { kind: "figures", statistics, byCategory, findings: parsed?.findings ?? [] };
@@ -10325,7 +10491,7 @@ function placesToLook(product, tests, dead, complexity, graph, size, outsideTest
10325
10491
  const toolTestOnlyPaths = new Set(
10326
10492
  dead.kind === "figures" ? dead.findings.filter((f) => f.category === "unused-file" && f.reasons?.includes("used-only-by-tests")).map((f) => f.path ?? "").filter(Boolean) : []
10327
10493
  );
10328
- const metricOf = (finding2) => finding2.category === "unused-file" && finding2.reasons?.includes("used-only-by-tests") === true ? "usedOnlyByTests" : deadMetric[finding2.category ?? ""] ?? "deadLinesPercent";
10494
+ const metricOf = (finding3) => finding3.category === "unused-file" && finding3.reasons?.includes("used-only-by-tests") === true ? "usedOnlyByTests" : deadMetric[finding3.category ?? ""] ?? "deadLinesPercent";
10329
10495
  const weight = (f) => f.value ?? f.lines ?? 0;
10330
10496
  const inOrder = (all2) => [...all2].sort(
10331
10497
  (left, right) => left.metric.localeCompare(right.metric) || weight(right) - weight(left) || left.path.localeCompare(right.path) || (left.other ?? "").localeCompare(right.other ?? "")
@@ -10340,14 +10506,14 @@ function placesToLook(product, tests, dead, complexity, graph, size, outsideTest
10340
10506
  name: fn.name,
10341
10507
  value: fn.complexity
10342
10508
  })),
10343
- ...dead.kind === "figures" && !unreadable ? dead.findings.map((finding2) => ({
10344
- metric: metricOf(finding2),
10345
- path: finding2.path ?? "(unknown)",
10346
- ...finding2.name ? { name: finding2.name } : {},
10347
- ...finding2.lines === void 0 ? {} : { lines: finding2.lines },
10348
- ...finding2.confidence === void 0 ? {} : { confidence: finding2.confidence },
10349
- ...finding2.reasons?.length ? { reason: finding2.reasons.join(", ") } : {},
10350
- ...finding2.message ? { message: finding2.message } : {}
10509
+ ...dead.kind === "figures" && !unreadable ? dead.findings.map((finding3) => ({
10510
+ metric: metricOf(finding3),
10511
+ path: finding3.path ?? "(unknown)",
10512
+ ...finding3.name ? { name: finding3.name } : {},
10513
+ ...finding3.lines === void 0 ? {} : { lines: finding3.lines },
10514
+ ...finding3.confidence === void 0 ? {} : { confidence: finding3.confidence },
10515
+ ...finding3.reasons?.length ? { reason: finding3.reasons.join(", ") } : {},
10516
+ ...finding3.message ? { message: finding3.message } : {}
10351
10517
  })) : [],
10352
10518
  /*
10353
10519
  * The files the workspace index found, which the tool cannot see.
@@ -10588,8 +10754,8 @@ function assembleReport({
10588
10754
  }
10589
10755
  const toolTestOnly = new Set(
10590
10756
  dead.kind === "figures" ? dead.findings.filter(
10591
- (finding2) => finding2.category === "unused-file" && finding2.reasons?.includes("used-only-by-tests") === true
10592
- ).map((finding2) => finding2.path ?? "").filter(Boolean) : []
10757
+ (finding3) => finding3.category === "unused-file" && finding3.reasons?.includes("used-only-by-tests") === true
10758
+ ).map((finding3) => finding3.path ?? "").filter(Boolean) : []
10593
10759
  );
10594
10760
  if (dead.kind === "figures" && !unreadable) {
10595
10761
  const stats = dead.statistics;