@hublo/sentinel 1.7.0-alpha.37 → 1.7.0-alpha.39

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.
@@ -145,7 +145,7 @@ import {
145
145
  defineSql,
146
146
  squawkRules,
147
147
  withDefaults
148
- } from "./chunk-5KNSTZ7F.js";
148
+ } from "./chunk-GYDS3OMU.js";
149
149
  import {
150
150
  CODE_CHURN_CONFIG_FILE,
151
151
  REPORT_DIR as REPORT_DIR2,
@@ -901,9 +901,9 @@ function buildConsumerIndex(workspaceRoot, moduleRoots) {
901
901
  const importer = line.slice(0, first).split(sep).join("/");
902
902
  const specifier = line.slice(second + 1);
903
903
  let target;
904
- const relative12 = /^from '((?:\.\.\/)+[^']+)'$/.exec(specifier)?.[1];
905
- if (relative12) {
906
- target = resolveRelative(importer, relative12, workspaceRoot);
904
+ const relative13 = /^from '((?:\.\.\/)+[^']+)'$/.exec(specifier)?.[1];
905
+ if (relative13) {
906
+ target = resolveRelative(importer, relative13, workspaceRoot);
907
907
  } else {
908
908
  const table = tableFor(importer);
909
909
  let seen = seenByTable.get(table);
@@ -4499,10 +4499,10 @@ function matchedNothingLines(report) {
4499
4499
  return lines;
4500
4500
  }
4501
4501
  function unresolvedSentence(unresolved) {
4502
- const relative12 = unresolved.filter((entry) => entry.specifier.startsWith(".")).length;
4503
- const aliases = unresolved.length - relative12;
4502
+ const relative13 = unresolved.filter((entry) => entry.specifier.startsWith(".")).length;
4503
+ const aliases = unresolved.length - relative13;
4504
4504
  const parts = [
4505
- ...relative12 > 0 ? [`${relative12} relative`] : [],
4505
+ ...relative13 > 0 ? [`${relative13} relative`] : [],
4506
4506
  ...aliases > 0 ? [`${aliases} that look like an alias`] : []
4507
4507
  ];
4508
4508
  return `${unresolved.length} import(s) resolve to nothing (${parts.join(", ")}), so no rule saw them`;
@@ -6753,11 +6753,11 @@ import { tmpdir as tmpdir2 } from "node:os";
6753
6753
  import { join as join16 } from "node:path";
6754
6754
  var OWN_ARTEFACTS = [`**/${STATIC_CONFIG_FILE}`, `**/${REPORT_DIR}/**`];
6755
6755
  function testGlobs(config) {
6756
- const relative12 = config.duplication.tests;
6756
+ const relative13 = config.duplication.tests;
6757
6757
  return {
6758
- ignore: relative12.map((glob) => `**/${glob}`),
6758
+ ignore: relative13.map((glob) => `**/${glob}`),
6759
6759
  // A one-item brace group is avoided rather than trusted: nothing guarantees `{x}` expands.
6760
- pattern: relative12.length === 1 ? `**/${relative12[0]}` : `**/{${relative12.join(",")}}`
6760
+ pattern: relative13.length === 1 ? `**/${relative13[0]}` : `**/{${relative13.join(",")}}`
6761
6761
  };
6762
6762
  }
6763
6763
  function exclusions(config, scope = "tests") {
@@ -13267,18 +13267,18 @@ function runsOfScreen(runs, screen) {
13267
13267
  var presentValues = (list, metric) => list.map((run) => run.metrics[metric]).filter((entry) => entry !== null);
13268
13268
  var isRelativeMetric = (metric) => metric !== "cls";
13269
13269
  function metricFigures(metric, screenRuns) {
13270
- const relative12 = isRelativeMetric(metric);
13270
+ const relative13 = isRelativeMetric(metric);
13271
13271
  const gaps = screenRuns.baseAgainPairs.filter(([first, again]) => first.metrics[metric] !== null && again.metrics[metric] !== null).map(([first, again]) => {
13272
13272
  const firstValue = first.metrics[metric];
13273
13273
  const againValue = again.metrics[metric];
13274
- return relative12 ? Math.abs(againValue / firstValue - 1) : Math.abs(againValue - firstValue);
13274
+ return relative13 ? Math.abs(againValue / firstValue - 1) : Math.abs(againValue - firstValue);
13275
13275
  });
13276
13276
  const baseMedian = median(presentValues(screenRuns.base, metric));
13277
13277
  const headMedian = median(presentValues(screenRuns.head, metric));
13278
13278
  return {
13279
13279
  base: baseMedian,
13280
13280
  head: headMedian,
13281
- delta: relative12 ? headMedian / baseMedian - 1 : headMedian - baseMedian,
13281
+ delta: relative13 ? headMedian / baseMedian - 1 : headMedian - baseMedian,
13282
13282
  noise: gaps.length ? p90(gaps) : null
13283
13283
  };
13284
13284
  }
@@ -14126,8 +14126,8 @@ function registerRuntimeAnalysis() {
14126
14126
 
14127
14127
  // src/roles/sql/adapters/squawk/squawk.adapter.ts
14128
14128
  import { spawnSync as spawnSync16 } from "node:child_process";
14129
- import { existsSync as existsSync40, readFileSync as readFileSync35 } from "node:fs";
14130
- import { join as join60 } from "node:path";
14129
+ import { existsSync as existsSync40, readFileSync as readFileSync36 } from "node:fs";
14130
+ import { join as join62 } from "node:path";
14131
14131
 
14132
14132
  // src/roles/sql/configs/resolve.ts
14133
14133
  import { existsSync as existsSync37 } from "node:fs";
@@ -14157,6 +14157,20 @@ var TEMPLATE_RULES = [
14157
14157
  LIKE_WILDCARD_RULE,
14158
14158
  ...TEMPLATE_OPT_IN
14159
14159
  ];
14160
+ var ORM_FILTER_INDEX_RULE = "prisma-filter-without-index";
14161
+ var ORM_FK_INDEX_RULE = "prisma-foreign-key-without-index";
14162
+ var ORM_QUERY_LOOP_RULE = "prisma-query-in-loop";
14163
+ var ORM_WRITE_LOOP_RULE = "prisma-write-in-loop";
14164
+ var ORM_NEW_CLIENT_RULE = "prisma-new-client";
14165
+ var ORM_MODEL_NAMING_RULE = "prisma-model-naming";
14166
+ var ORM_RULES = [
14167
+ ORM_FILTER_INDEX_RULE,
14168
+ ORM_FK_INDEX_RULE,
14169
+ ORM_QUERY_LOOP_RULE,
14170
+ ORM_WRITE_LOOP_RULE,
14171
+ ORM_NEW_CLIENT_RULE,
14172
+ ORM_MODEL_NAMING_RULE
14173
+ ];
14160
14174
 
14161
14175
  // src/roles/sql/configs/rule-levels.ts
14162
14176
  var SENTINEL_RULES = [
@@ -14165,7 +14179,8 @@ var SENTINEL_RULES = [
14165
14179
  APPLIED_RULE,
14166
14180
  ENUM_VALUE_RULE,
14167
14181
  FOLDER_RULE,
14168
- ...TEMPLATE_RULES
14182
+ ...TEMPLATE_RULES,
14183
+ ...ORM_RULES
14169
14184
  ];
14170
14185
  var SYNTAX_ERROR = "syntax-error";
14171
14186
  var NOT_SQUAWK_CONFIG = [...SENTINEL_RULES, SYNTAX_ERROR];
@@ -14269,6 +14284,7 @@ function configProblem(config) {
14269
14284
  }
14270
14285
  function shapeProblem(value, expected, path2) {
14271
14286
  const got = `; got ${JSON.stringify(value)}.`;
14287
+ if (path2 === "orm.perRowWrites") return perRowWritesProblem(value, got);
14272
14288
  if (Array.isArray(expected)) {
14273
14289
  if (Array.isArray(value) && value.every((item) => typeof item === "string")) return null;
14274
14290
  return `\`${path2}\` must be a list of strings, like ['**/generated/**']${got}`;
@@ -14290,6 +14306,22 @@ function shapeProblem(value, expected, path2) {
14290
14306
  }
14291
14307
  return null;
14292
14308
  }
14309
+ var WRITTEN_CALL = /^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*$/;
14310
+ function perRowWritesProblem(value, got) {
14311
+ const shape = "`orm.perRowWrites` must be a list of { file, call, reason }, like [{ file: 'src/x.repository.ts', call: 'jobBoard.upsert', reason: 'one row per board, a handful' }]";
14312
+ if (!Array.isArray(value)) return `${shape}${got}`;
14313
+ for (const entry of value) {
14314
+ const keys = isPlainObject(entry) ? Object.keys(entry).sort().join(",") : "";
14315
+ const fields = entry;
14316
+ const texts = ["file", "call", "reason"].every(
14317
+ (key) => typeof fields[key] === "string" && fields[key].trim() !== ""
14318
+ );
14319
+ if (keys !== "call,file,reason" || !texts || !WRITTEN_CALL.test(fields.call)) {
14320
+ return `${shape}; got ${JSON.stringify(entry)}.`;
14321
+ }
14322
+ }
14323
+ return null;
14324
+ }
14293
14325
  function settingsOf2(config) {
14294
14326
  const { root: _root, moved: _moved, ...settings } = config;
14295
14327
  return settings;
@@ -14580,6 +14612,13 @@ function git4(cwd, args) {
14580
14612
  };
14581
14613
  return { ok: true, out: run.stdout };
14582
14614
  }
14615
+ function textAtCommit(cwd, sha, file) {
14616
+ const listed = git4(cwd, ["ls-tree", "--name-only", sha, "--", file]);
14617
+ if (!listed.ok) return void 0;
14618
+ if (listed.out.trim() === "") return "";
14619
+ const shown = git4(cwd, ["show", `${sha}:./${file}`]);
14620
+ return shown.ok ? shown.out : void 0;
14621
+ }
14583
14622
  function insideRepository(cwd) {
14584
14623
  const run = git4(cwd, ["rev-parse", "--is-inside-work-tree"]);
14585
14624
  return run.ok && run.out.trim() === "true";
@@ -14673,10 +14712,14 @@ function folderFindings(folders) {
14673
14712
  });
14674
14713
  }
14675
14714
 
14676
- // src/roles/sql/raw/check-templates.ts
14715
+ // src/roles/sql/orm/check-orm.ts
14677
14716
  import { join as join54 } from "node:path";
14678
14717
  import { parseSync as parseSync9 } from "oxc-parser";
14679
14718
 
14719
+ // src/roles/sql/unsafe/unsafe-calls.ts
14720
+ import { dirname as dirname9, join as join53 } from "node:path";
14721
+ import { parseSync as parseSync7 } from "oxc-parser";
14722
+
14680
14723
  // src/roles/sql/prisma-imports.ts
14681
14724
  function prismaImportsOf(program) {
14682
14725
  const imports = { names: /* @__PURE__ */ new Set(), namespaces: /* @__PURE__ */ new Set() };
@@ -14725,8 +14768,6 @@ function unwrap(node) {
14725
14768
  }
14726
14769
 
14727
14770
  // src/roles/sql/unsafe/unsafe-calls.ts
14728
- import { dirname as dirname9, join as join53 } from "node:path";
14729
- import { parseSync as parseSync7 } from "oxc-parser";
14730
14771
  var UNSAFE_METHODS = ["$queryRawUnsafe", "$executeRawUnsafe"];
14731
14772
  var BOTH = { methods: true, raw: true };
14732
14773
  var MAX_DEPTH = 12;
@@ -14902,10 +14943,10 @@ function callShape(node, imports) {
14902
14943
  const object = alias(target) === void 0 ? unwrap(target.object) : void 0;
14903
14944
  if (name === "call") return { name: method, object, args: args.slice(1), callee: target };
14904
14945
  const list = args[1] === void 0 ? void 0 : unwrap(args[1]);
14905
- const applied2 = list === void 0 ? [] : list.type === "ArrayExpression" ? list.elements.filter(
14946
+ const applied3 = list === void 0 ? [] : list.type === "ArrayExpression" ? list.elements.filter(
14906
14947
  (item) => item !== null
14907
14948
  ) : [{ type: "SpreadElement", argument: list, start: list.start, end: list.end }];
14908
- return { name: method, object, args: applied2, callee: target };
14949
+ return { name: method, object, args: applied3, callee: target };
14909
14950
  }
14910
14951
  return { name, object: unwrap(callee.object), args, callee };
14911
14952
  }
@@ -15122,11 +15163,11 @@ function exportedConst(file, name) {
15122
15163
  return void 0;
15123
15164
  }
15124
15165
  function isPlaceholderList(call, context2) {
15125
- const join69 = unwrap(call.callee);
15126
- if (!MEMBER_TYPES.has(join69.type) || join69.property.name !== "join") return false;
15166
+ const join71 = unwrap(call.callee);
15167
+ if (!MEMBER_TYPES.has(join71.type) || join71.property.name !== "join") return false;
15127
15168
  const separator = call.arguments[0];
15128
15169
  if (separator !== void 0 && !isSafe(separator, context2)) return false;
15129
- const map = unwrap(join69.object);
15170
+ const map = unwrap(join71.object);
15130
15171
  if (map.type !== "CallExpression") return false;
15131
15172
  const mapCallee = unwrap(map.callee);
15132
15173
  if (!MEMBER_TYPES.has(mapCallee.type) || mapCallee.property.name !== "map")
@@ -15229,43 +15270,6 @@ function findingOf2({ file, text }, rule, { offset, message }) {
15229
15270
  };
15230
15271
  }
15231
15272
 
15232
- // src/roles/sql/raw/joined-text.ts
15233
- function joined(parts, fill) {
15234
- const text = { sql: "", pieces: [] };
15235
- parts.forEach((part, index) => {
15236
- if (index > 0) {
15237
- text.pieces.push({ at: text.sql.length, part, fill: true });
15238
- text.sql += fill(index);
15239
- }
15240
- text.pieces.push({ at: text.sql.length, part, fill: false });
15241
- text.sql += part.text;
15242
- });
15243
- return text;
15244
- }
15245
- function fileOffsetOf(text, index) {
15246
- const piece = [...text.pieces].reverse().find((candidate) => candidate.at <= index);
15247
- if (piece === void 0) return text.pieces[0]?.part.start ?? 0;
15248
- if (piece.fill) return piece.part.start - 1;
15249
- const inPart = index - piece.at;
15250
- switch (piece.part.placing) {
15251
- case "exact":
15252
- return piece.part.start + inPart;
15253
- case "crlf":
15254
- return piece.part.start + sourceIndexAfterCrlf(piece.part.source, inPart);
15255
- case "start":
15256
- return piece.part.start;
15257
- }
15258
- }
15259
- function sourceIndexAfterCrlf(source2, index) {
15260
- let read2 = 0;
15261
- for (let at = 0; at < source2.length; at++) {
15262
- if (source2[at] === "\r" && source2[at + 1] === "\n") continue;
15263
- if (read2 === index) return at;
15264
- read2++;
15265
- }
15266
- return source2.length;
15267
- }
15268
-
15269
15273
  // src/roles/sql/raw/sql-parser.ts
15270
15274
  import { loadModule, parseSync as parseSync8 } from "libpg-query";
15271
15275
  var loading;
@@ -15314,157 +15318,199 @@ function pushInReverse(stack, children) {
15314
15318
  for (let index = children.length - 1; index >= 0; index--) stack.push(children[index]);
15315
15319
  }
15316
15320
 
15317
- // src/roles/sql/raw/read-template.ts
15318
- var WRAPS = [
15319
- ["statement", "", ""],
15320
- ["expression", "SELECT ", ""],
15321
- ["predicate", "SELECT 1 WHERE ", ""],
15322
- ["from-item", "SELECT 1 FROM ", ""],
15323
- ["after-from", "SELECT 1 FROM t ", ""],
15324
- ["select-list", "SELECT ", " FROM t"],
15325
- ["order-by", "SELECT 1 FROM t ORDER BY ", ""],
15326
- ["set-list", "UPDATE t SET ", ""],
15327
- ["values", "INSERT INTO t VALUES ", ""],
15328
- ["cte", "WITH ", " SELECT 1"],
15329
- ["and-tail", "SELECT 1 FROM t WHERE true ", ""],
15330
- ["comma-tail", "SELECT 1 ", " FROM t"]
15331
- ];
15332
- var FILLS = [
15333
- ["value", (n) => `$${n}`],
15334
- ["identifier", (n) => `__p${n}`],
15335
- ["nothing", () => ""],
15336
- ["list", (n) => `($${n})`]
15337
- ];
15338
- function readTemplate(template) {
15339
- if (template.parts.every((part) => part.text.trim() === "")) return { kind: "empty" };
15340
- let firstError;
15341
- for (const [fillName, fill] of FILLS) {
15342
- const text = joined(template.parts, fill);
15343
- for (const [wrap, before, after] of WRAPS) {
15344
- const parsed2 = parseSql(`${before}${text.sql}${after}`);
15345
- if (parsed2.ok) {
15346
- return {
15347
- kind: "read",
15348
- reading: readingOf(
15349
- parsed2.statements,
15350
- { wrap, before, fill: fillName, values: template.values },
15351
- text
15352
- )
15353
- };
15354
- }
15355
- firstError ??= parsed2.message;
15321
+ // src/roles/sql/orm/loops.ts
15322
+ var ITERATING = /* @__PURE__ */ new Set(["map", "forEach", "flatMap", "reduce", "filter", "some", "every"]);
15323
+ function walkWithAncestors(program, visit2) {
15324
+ const ancestors = [];
15325
+ const descend = (value) => {
15326
+ if (value === null || typeof value !== "object") return;
15327
+ if (Array.isArray(value)) {
15328
+ for (const item of value) descend(item);
15329
+ return;
15356
15330
  }
15331
+ const node = value;
15332
+ if (typeof node.type !== "string") return;
15333
+ visit2(node, ancestors);
15334
+ ancestors.push(node);
15335
+ for (const [key, child] of Object.entries(node)) if (key !== "parent") descend(child);
15336
+ ancestors.pop();
15337
+ };
15338
+ descend(program);
15339
+ }
15340
+ function loopAround(ancestors, node, text) {
15341
+ const chain = [...ancestors, node];
15342
+ for (let i = chain.length - 2; i >= 0; i--) {
15343
+ const loop = loopOf(chain[i], chain[i + 1], text);
15344
+ if (loop !== void 0) return loop;
15357
15345
  }
15358
- return { kind: "unread", reason: `PostgreSQL's parser does not read it alone (${firstError})` };
15346
+ return void 0;
15359
15347
  }
15360
- function readingOf(statements, {
15361
- wrap,
15362
- before,
15363
- fill,
15364
- values
15365
- }, text) {
15366
- const wrapped = `${before}${text.sql}`;
15367
- const indexIn = (location) => indexOfByte(wrapped, location) - before.length;
15368
- return {
15369
- statements,
15370
- wrap,
15371
- fill,
15372
- own: (location) => {
15373
- const index = indexIn(location);
15374
- return index >= 0 && index < text.sql.length;
15375
- },
15376
- fileOffset: (location) => fileOffsetOf(text, indexIn(location)),
15377
- valueStart: (n) => fill === "value" ? values[n - 1] : void 0
15348
+ function loopOf(candidate, child, text) {
15349
+ const source2 = (n) => {
15350
+ const at = n;
15351
+ return typeof at?.start === "number" && typeof at.end === "number" ? text.slice(at.start, at.end) : "";
15378
15352
  };
15353
+ const body = (n) => slicedConsts(n, text);
15354
+ switch (candidate.type) {
15355
+ case "ForOfStatement":
15356
+ case "ForInStatement":
15357
+ if (child === candidate.right) return void 0;
15358
+ return {
15359
+ walks: source2(candidate.right),
15360
+ vars: union(namesOf(candidate.left), body(candidate.body))
15361
+ };
15362
+ case "ForStatement":
15363
+ if (child === candidate.init) return void 0;
15364
+ return {
15365
+ walks: `${source2(candidate.test)} ${source2(candidate.update)}`,
15366
+ vars: union(namesOf(candidate.init), body(candidate.body))
15367
+ };
15368
+ case "WhileStatement":
15369
+ case "DoWhileStatement":
15370
+ return { walks: `while ${source2(candidate.test)}`, vars: body(candidate.body) };
15371
+ default:
15372
+ return iteratingCall(candidate, child, source2);
15373
+ }
15379
15374
  }
15380
-
15381
- // src/roles/sql/raw/template-rule.ts
15382
- var NO_CONTEXT = {
15383
- trigramIndexes: () => [],
15384
- indexesFrom: () => ({ read: [], empty: [] })
15385
- };
15386
-
15387
- // src/roles/sql/raw/value-starts.ts
15388
- var MAX_DEPTH2 = 8;
15389
- function valueStart(node, bindings, depth = 0) {
15390
- if (depth > MAX_DEPTH2) return void 0;
15391
- const current = unwrap(node);
15392
- const deeper = (next) => valueStart(next, bindings, depth + 1);
15393
- switch (current.type) {
15394
- case "Literal":
15395
- return typeof current.value === "string" ? current.value : void 0;
15396
- case "TemplateLiteral":
15397
- return templateStart(current, deeper);
15398
- case "BinaryExpression":
15399
- return current.operator === "+" ? sumStart(current, deeper) : void 0;
15375
+ function iteratingCall(candidate, child, source2) {
15376
+ if (candidate.type !== "CallExpression") return void 0;
15377
+ const callee = candidate.callee;
15378
+ const method = callee?.property?.name;
15379
+ if (callee?.type !== "MemberExpression" || typeof method !== "string" || !ITERATING.has(method)) {
15380
+ return void 0;
15381
+ }
15382
+ if (!(candidate.arguments ?? []).includes(child)) return void 0;
15383
+ const params = (child.params ?? []).flatMap((p) => [...namesOf(p)]);
15384
+ return { walks: source2(callee.object), vars: new Set(params) };
15385
+ }
15386
+ function namesOf(pattern) {
15387
+ const p = pattern;
15388
+ if (p === void 0 || p === null) return /* @__PURE__ */ new Set();
15389
+ switch (p.type) {
15400
15390
  case "Identifier":
15401
- return nameStart(current.name, bindings, deeper);
15391
+ return /* @__PURE__ */ new Set([p.name]);
15392
+ case "VariableDeclaration":
15393
+ return union(...(p.declarations ?? []).map((d) => namesOf(d.id)));
15394
+ case "ObjectPattern":
15395
+ return union(
15396
+ ...(p.properties ?? []).map((q) => namesOf(q.value ?? q.argument))
15397
+ );
15398
+ case "ArrayPattern":
15399
+ return union(...(p.elements ?? []).map((e) => namesOf(e)));
15400
+ case "AssignmentPattern":
15401
+ return namesOf(p.left);
15402
+ case "RestElement":
15403
+ return namesOf(p.argument);
15402
15404
  default:
15403
- return void 0;
15405
+ return /* @__PURE__ */ new Set();
15404
15406
  }
15405
15407
  }
15406
- function templateStart(node, deeper) {
15407
- const [first] = node.quasis;
15408
- const value = first?.value;
15409
- const text = value?.cooked ?? value?.raw;
15410
- if (text === void 0) return void 0;
15411
- const [expression] = node.expressions;
15412
- if (text !== "" || expression === void 0) return text;
15413
- return deeper(expression);
15414
- }
15415
- function sumStart(node, deeper) {
15416
- const left = deeper(node.left);
15417
- if (left !== "") return left;
15418
- return deeper(node.right);
15408
+ function slicedConsts(body, text) {
15409
+ const statements = (body?.type === "BlockStatement" ? body.body : []) ?? [];
15410
+ const names = /* @__PURE__ */ new Set();
15411
+ for (const statement of statements) {
15412
+ if (statement.type !== "VariableDeclaration") continue;
15413
+ for (const declarator of statement.declarations ?? []) {
15414
+ const init = declarator.init;
15415
+ const source2 = init?.start === void 0 ? "" : text.slice(init.start, init.end);
15416
+ if (/\.slice\(|chunk/i.test(source2))
15417
+ for (const name of namesOf(declarator.id)) names.add(name);
15418
+ }
15419
+ }
15420
+ return names;
15419
15421
  }
15420
- function nameStart(name, bindings, deeper) {
15421
- const found = bindings.get(name) ?? [];
15422
- const [binding] = found;
15423
- if (found.length !== 1 || binding?.kind !== "const") return void 0;
15424
- return deeper(binding.init);
15422
+ function union(...sets) {
15423
+ return new Set(sets.flatMap((set) => [...set]));
15425
15424
  }
15426
15425
 
15427
- // src/roles/sql/raw/templates.ts
15428
- function sqlTemplatesOf(program, prisma, fileText) {
15429
- const templates = [];
15430
- let bindings;
15431
- const bindingsOnce = () => {
15432
- bindings ??= bindingsOf(program);
15433
- return bindings;
15434
- };
15435
- walk(program, (node) => {
15436
- if (node.type !== "TaggedTemplateExpression") return;
15437
- const tag = tagOf(node.tag, prisma);
15438
- if (tag === void 0) return;
15439
- const quasis = node.quasi.quasis;
15440
- const parts = quasis.map((element) => partOf(element, fileText));
15441
- const expressions = node.quasi.expressions;
15442
- const values = expressions.map((expression) => valueStart(expression, bindingsOnce()));
15443
- templates.push({ tag, parts, values, start: node.start });
15426
+ // src/roles/sql/orm/prisma-calls.ts
15427
+ var READ_OPERATIONS = [
15428
+ "findMany",
15429
+ "findFirst",
15430
+ "findFirstOrThrow",
15431
+ "findUnique",
15432
+ "findUniqueOrThrow"
15433
+ ];
15434
+ var WRITE_OPERATIONS = [
15435
+ "create",
15436
+ "createMany",
15437
+ "createManyAndReturn",
15438
+ "update",
15439
+ "updateMany",
15440
+ "updateManyAndReturn",
15441
+ "upsert",
15442
+ "delete",
15443
+ "deleteMany"
15444
+ ];
15445
+ var ORM_OPERATIONS = [...READ_OPERATIONS, ...WRITE_OPERATIONS];
15446
+ var CLIENT_NAME = /^(?:tx|txHost|trx|transaction)$|database|db|prisma|replica|pgclient/i;
15447
+ function prismaCallsOf(program, operations, text) {
15448
+ const wanted = new Set(operations);
15449
+ const calls = [];
15450
+ walkWithAncestors(program, (node, ancestors) => {
15451
+ const call = node.type === "CallExpression" ? callOf(node, wanted) : void 0;
15452
+ if (call) calls.push({ ...call, loop: loopAround(ancestors, node, text) });
15444
15453
  });
15445
- return templates;
15454
+ return calls;
15455
+ }
15456
+ function callOf(node, wanted) {
15457
+ const parts = partsOf(unwrap(node.callee));
15458
+ if (parts === void 0 || !wanted.has(parts.operation)) return void 0;
15459
+ if (!CLIENT_NAME.test(clientName(parts.member))) return void 0;
15460
+ const [first] = node.arguments ?? [];
15461
+ const args = first === void 0 ? void 0 : unwrap(first);
15462
+ return {
15463
+ model: parts.model,
15464
+ operation: parts.operation,
15465
+ start: node.start,
15466
+ args: args?.type === "ObjectExpression" ? args : void 0
15467
+ };
15446
15468
  }
15447
- function tagOf(tag, prisma) {
15448
- const member = unwrap(tag);
15449
- const name = memberName(member);
15450
- if (name === "$queryRaw" || name === "$executeRaw") return name;
15451
- if (name === "sql" && isPrismaObject(unwrap(member.object), prisma))
15452
- return "Prisma.sql";
15453
- return void 0;
15469
+ function partsOf(callee) {
15470
+ if (callee.type !== "MemberExpression" || callee.computed) return void 0;
15471
+ const operation = callee.property?.name;
15472
+ const member = unwrap(callee.object);
15473
+ if (typeof operation !== "string" || member.type !== "MemberExpression" || member.computed) {
15474
+ return void 0;
15475
+ }
15476
+ const model = member.property?.name;
15477
+ return typeof model === "string" ? { operation, model, member } : void 0;
15454
15478
  }
15455
- function partOf(element, fileText) {
15456
- const value = element.value;
15457
- const text = value.cooked ?? value.raw;
15458
- const start = element.start + 1;
15459
- const source2 = fileText.slice(start, element.end - (element.tail ? 1 : 2));
15460
- const placing = source2 === text ? "exact" : source2.replace(/\r\n/g, "\n") === text ? "crlf" : "start";
15461
- return { text, start, placing, source: source2 };
15479
+ function clientName(model) {
15480
+ let object = unwrap(model.object);
15481
+ while (object.type === "MemberExpression") {
15482
+ const inner = unwrap(object.object);
15483
+ if (inner.type === "ThisExpression") return object.property?.name ?? "";
15484
+ object = inner;
15485
+ }
15486
+ return object.type === "Identifier" ? object.name : "";
15487
+ }
15488
+ function propertyOf(object, key) {
15489
+ if (object?.type !== "ObjectExpression") return void 0;
15490
+ const found = object.properties.find(
15491
+ (p) => p.type === "Property" && !p.computed && keyName(p) === key
15492
+ );
15493
+ return found === void 0 ? void 0 : unwrap(found.value);
15494
+ }
15495
+ function keysOf(object) {
15496
+ if (object?.type !== "ObjectExpression") return { keys: [], spread: object !== void 0 };
15497
+ const properties = object.properties;
15498
+ return {
15499
+ keys: properties.flatMap(
15500
+ (p) => p.type === "Property" && !p.computed ? [keyName(p)].filter((k) => k !== "") : []
15501
+ ),
15502
+ spread: properties.some((p) => p.type === "SpreadElement")
15503
+ };
15504
+ }
15505
+ function keyName(property) {
15506
+ const key = property.key;
15507
+ return key.name ?? key.value ?? "";
15462
15508
  }
15463
15509
 
15464
- // src/roles/sql/raw/check-templates.ts
15465
- async function checkSqlTemplates(cwd, files, readFile, { rules, context: context2 = NO_CONTEXT }) {
15466
- const run = { templates: 0, read: 0, unread: [], unparsed: [], findings: [] };
15467
- if (files.length === 0) return run;
15510
+ // src/roles/sql/orm/check-orm.ts
15511
+ async function checkOrmCalls(cwd, files, readFile, { rules, context: context2 }) {
15512
+ const run = { calls: 0, writes: 0, schemas: [], unparsed: [], findings: [] };
15513
+ if (rules.length === 0 || files.length === 0) return run;
15468
15514
  const loaded2 = await parserLoaded();
15469
15515
  if (!loaded2.ok) {
15470
15516
  for (const file of files) run.unparsed.push({ file, reason: loaded2.reason });
@@ -15473,13 +15519,66 @@ async function checkSqlTemplates(cwd, files, readFile, { rules, context: context
15473
15519
  for (const file of files) {
15474
15520
  const text = readFile(join54(cwd, file));
15475
15521
  if (text === void 0) {
15476
- run.unparsed.push({ file, reason: "could not be read, so its SQL templates are not read" });
15522
+ run.unparsed.push({ file, reason: "could not be read, so its Prisma calls are not read" });
15477
15523
  continue;
15478
15524
  }
15479
- checkFile({ file, text, rules, context: context2 }, run);
15525
+ checkFile({ file, text }, rules, context2, run);
15480
15526
  }
15527
+ if (run.calls + run.writes > 0) run.schemas = context2.schemas();
15481
15528
  return run;
15482
15529
  }
15530
+ function checkFile(input, rules, context2, run) {
15531
+ const parsed2 = programOf(input);
15532
+ if (!parsed2.ok) {
15533
+ run.unparsed.push({
15534
+ file: input.file,
15535
+ reason: `${parsed2.why}, so its Prisma calls are not read`
15536
+ });
15537
+ return;
15538
+ }
15539
+ for (const rule of rules) {
15540
+ for (const { offset, message } of fileFindingsOf(rule, parsed2.program, input.file, context2)) {
15541
+ run.findings.push(findingOf2(input, rule, { offset, message }));
15542
+ }
15543
+ }
15544
+ for (const call of prismaCallsOf(parsed2.program, ORM_OPERATIONS, input.text)) {
15545
+ if (READ_OPERATIONS.includes(call.operation)) run.calls++;
15546
+ else run.writes++;
15547
+ for (const rule of rules) {
15548
+ const message = messageOf(rule, call, context2, input.file);
15549
+ if (message !== void 0)
15550
+ run.findings.push(findingOf2(input, rule, { offset: call.start, message }));
15551
+ }
15552
+ }
15553
+ }
15554
+ function programOf(input) {
15555
+ try {
15556
+ const parsed2 = parseSync9(input.file, input.text, { sourceType: "module" });
15557
+ if (parsed2.errors.length > 0) {
15558
+ return { ok: false, why: `does not parse (${parsed2.errors[0]?.message ?? "unknown error"})` };
15559
+ }
15560
+ return { ok: true, program: parsed2.program };
15561
+ } catch (error) {
15562
+ return {
15563
+ ok: false,
15564
+ why: `could not be read (${error instanceof Error ? error.message : String(error)})`
15565
+ };
15566
+ }
15567
+ }
15568
+ function messageOf(rule, call, context2, file) {
15569
+ try {
15570
+ return rule.check(call, context2, file);
15571
+ } catch {
15572
+ return void 0;
15573
+ }
15574
+ }
15575
+ function fileFindingsOf(rule, program, file, context2) {
15576
+ try {
15577
+ return rule.checkFile?.(program, file, context2) ?? [];
15578
+ } catch {
15579
+ return [];
15580
+ }
15581
+ }
15483
15582
  async function parserLoaded() {
15484
15583
  try {
15485
15584
  await loadSqlParser();
@@ -15488,65 +15587,19 @@ async function parserLoaded() {
15488
15587
  const why = error instanceof Error ? error.message : String(error);
15489
15588
  return {
15490
15589
  ok: false,
15491
- reason: `PostgreSQL's parser could not be loaded (${why}), so its SQL templates are not read`
15590
+ reason: `PostgreSQL's parser could not be loaded (${why}), so its Prisma calls are not read`
15492
15591
  };
15493
15592
  }
15494
15593
  }
15495
- function checkFile(input, run) {
15496
- const { file, text } = input;
15497
- try {
15498
- const { program, errors } = parseSync9(file, text, { sourceType: "module" });
15499
- if (errors.length > 0) {
15500
- const reason = `does not parse (${errors[0]?.message ?? "unknown error"})`;
15501
- run.unparsed.push({ file, reason: `${reason}, so its SQL templates are not read` });
15502
- return;
15503
- }
15504
- const tree = program;
15505
- for (const template of sqlTemplatesOf(tree, prismaImportsOf(tree), text)) {
15506
- checkTemplate(input, template, run);
15507
- }
15508
- } catch (error) {
15509
- const why = error instanceof Error ? error.message : String(error);
15510
- run.unparsed.push({
15511
- file,
15512
- reason: `could not be read (${why}), so its SQL templates are not read`
15513
- });
15514
- }
15515
- }
15516
- function checkTemplate(input, template, run) {
15517
- const { line } = positionOf(input.text, template.start);
15518
- let result;
15519
- try {
15520
- result = readTemplate(template);
15521
- } catch (error) {
15522
- run.templates++;
15523
- run.unread.push({ file: input.file, line, reason: `could not be read (${messageOf(error)})` });
15524
- return;
15525
- }
15526
- if (result.kind === "empty") return;
15527
- run.templates++;
15528
- if (result.kind === "unread") {
15529
- run.unread.push({ file: input.file, line, reason: result.reason });
15530
- return;
15531
- }
15532
- run.read++;
15533
- for (const rule of input.rules) checkRule(input, rule, result.reading, run);
15534
- }
15535
- function checkRule(input, rule, reading, run) {
15536
- let hits;
15537
- try {
15538
- hits = rule.check(reading, input.context);
15539
- } catch {
15540
- return;
15541
- }
15542
- for (const hit of hits) {
15543
- const offset = reading.fileOffset(hit.location);
15544
- run.findings.push(findingOf2(input, rule, { offset, message: hit.message }));
15545
- }
15546
- }
15547
- function messageOf(error) {
15548
- return error instanceof Error ? error.message : String(error);
15549
- }
15594
+
15595
+ // src/roles/sql/orm/orm-context.ts
15596
+ import { readdirSync as readdirSync12, readFileSync as readFileSync33 } from "node:fs";
15597
+ import { dirname as dirname10, join as join56, relative as relative10 } from "node:path";
15598
+ import { globSync as globSync4 } from "tinyglobby";
15599
+
15600
+ // src/roles/sql/trigram-indexes.ts
15601
+ import { readdirSync as readdirSync11, readFileSync as readFileSync32 } from "node:fs";
15602
+ import { join as join55 } from "node:path";
15550
15603
 
15551
15604
  // src/roles/sql/raw/rules/pg-tree.ts
15552
15605
  function bodyOf(node, kind) {
@@ -15621,9 +15674,9 @@ var MAX_KEY_DEPTH = 32;
15621
15674
  function expressionKey(node, depth = 0) {
15622
15675
  if (depth > MAX_KEY_DEPTH || node === null || typeof node !== "object") return void 0;
15623
15676
  const [kind] = Object.keys(node);
15624
- const keyOf = kind === void 0 ? void 0 : KEYS.get(kind);
15677
+ const keyOf2 = kind === void 0 ? void 0 : KEYS.get(kind);
15625
15678
  const body = kind === void 0 ? void 0 : bodyOf(node, kind);
15626
- return keyOf && body ? keyOf(body, depth + 1) : void 0;
15679
+ return keyOf2 && body ? keyOf2(body, depth + 1) : void 0;
15627
15680
  }
15628
15681
  function columnKey(column) {
15629
15682
  const name = columnNames(column).at(-1);
@@ -15635,47 +15688,906 @@ function callKey(call, depth) {
15635
15688
  if (name === void 0 || args.some((arg) => arg === void 0)) return void 0;
15636
15689
  return `${name}(${args.join(", ")})`;
15637
15690
  }
15638
- function castKey(cast, depth) {
15639
- const inner = expressionKey(cast.arg, depth);
15640
- const type2 = lastName(cast.typeName?.names);
15641
- return inner === void 0 || type2 === void 0 ? void 0 : `${inner}::${type2}`;
15691
+ function castKey(cast, depth) {
15692
+ const inner = expressionKey(cast.arg, depth);
15693
+ const type2 = lastName(cast.typeName?.names);
15694
+ return inner === void 0 || type2 === void 0 ? void 0 : `${inner}::${type2}`;
15695
+ }
15696
+ function operationKey(operation, depth) {
15697
+ if (operation.kind !== "AEXPR_OP") return void 0;
15698
+ const operator = lastName(operation.name);
15699
+ const left = expressionKey(operation.lexpr, depth);
15700
+ const right = expressionKey(operation.rexpr, depth);
15701
+ if (operator === void 0 || left === void 0 || right === void 0) return void 0;
15702
+ return `${left} ${operator} ${right}`;
15703
+ }
15704
+ function constantKey(constant) {
15705
+ if (constant.isnull === true) return "null";
15706
+ const text = bodyOf(constant, "sval")?.sval;
15707
+ if (typeof text === "string") return `'${text}'`;
15708
+ for (const [kind, zero] of [
15709
+ ["ival", "0"],
15710
+ ["fval", "0"],
15711
+ ["boolval", "false"]
15712
+ ]) {
15713
+ const body = bodyOf(constant, kind);
15714
+ if (body) return body[kind] === void 0 ? zero : String(body[kind]);
15715
+ }
15716
+ return void 0;
15717
+ }
15718
+ var KEYS = /* @__PURE__ */ new Map([
15719
+ ["ColumnRef", columnKey],
15720
+ ["FuncCall", callKey],
15721
+ ["TypeCast", castKey],
15722
+ ["A_Const", constantKey],
15723
+ ["A_Expr", operationKey]
15724
+ ]);
15725
+ function qualifiersUnder(node) {
15726
+ const qualifiers = /* @__PURE__ */ new Set();
15727
+ for (const names of columnsUnder(node)) {
15728
+ const qualifier = names.at(-2);
15729
+ if (qualifier !== void 0) qualifiers.add(qualifier);
15730
+ }
15731
+ return qualifiers;
15732
+ }
15733
+
15734
+ // src/roles/sql/trigram-indexes.ts
15735
+ var TRIGRAM_CLASSES = /* @__PURE__ */ new Set(["gin_trgm_ops", "gist_trgm_ops"]);
15736
+ function trigramContext(cwd, own, indexesFrom) {
15737
+ let loaded2;
15738
+ const once = () => {
15739
+ loaded2 ??= readIndexes(cwd, own, indexesFrom);
15740
+ return loaded2;
15741
+ };
15742
+ return { trigramIndexes: () => once().indexes, indexesFrom: () => once().folders };
15743
+ }
15744
+ function readIndexes(cwd, own, indexesFrom) {
15745
+ const read2 = [];
15746
+ const empty = [];
15747
+ const shared = indexesFrom.flatMap((folder) => {
15748
+ const migrations = migrationsIn(join55(cwd, folder)).flatMap(
15749
+ (name) => migrationText(cwd, `${folder}/${name}/migration.sql`)
15750
+ );
15751
+ (migrations.length > 0 ? read2 : empty).push(folder);
15752
+ return migrations;
15753
+ });
15754
+ const ownMigrations = own.flatMap((file) => migrationText(cwd, file));
15755
+ return { indexes: trigramIndexesOf([...ownMigrations, ...shared]), folders: { read: read2, empty } };
15756
+ }
15757
+ function migrationsIn(directory) {
15758
+ try {
15759
+ return readdirSync11(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
15760
+ } catch {
15761
+ return [];
15762
+ }
15763
+ }
15764
+ function migrationText(cwd, file) {
15765
+ try {
15766
+ return [{ file, text: readFileSync32(join55(cwd, file), "utf8") }];
15767
+ } catch {
15768
+ return [];
15769
+ }
15770
+ }
15771
+ function trigramIndexesOf(migrations) {
15772
+ let indexes = [];
15773
+ for (const { file, text } of migrations) {
15774
+ const parsed2 = parseSql(text);
15775
+ if (!parsed2.ok) continue;
15776
+ for (const statement of parsed2.statements) indexes = applied(indexes, statement, file);
15777
+ }
15778
+ return indexes;
15779
+ }
15780
+ function applied(indexes, statement, file) {
15781
+ const created = bodyOf(statement, "IndexStmt");
15782
+ if (created) return [...indexes, ...indexesOf(created, file)];
15783
+ const dropped = bodyOf(statement, "DropStmt");
15784
+ if (dropped) return withoutDropped(indexes, dropped);
15785
+ const renamed4 = bodyOf(statement, "RenameStmt");
15786
+ if (renamed4) return withRenamed(indexes, renamed4);
15787
+ return indexes;
15788
+ }
15789
+ function indexesOf(index, file) {
15790
+ const table = index.relation?.relname;
15791
+ if (typeof table !== "string") return [];
15792
+ const name = typeof index.idxname === "string" ? index.idxname : void 0;
15793
+ return (index.indexParams ?? []).flatMap((param) => {
15794
+ const element = bodyOf(param, "IndexElem");
15795
+ if (!element || !isTrigram(element)) return [];
15796
+ const expression = typeof element.name === "string" ? element.name : expressionKey(element.expr);
15797
+ return expression === void 0 ? [] : [{ name, table, expression, file }];
15798
+ });
15799
+ }
15800
+ function isTrigram(element) {
15801
+ const name = lastName(element.opclass);
15802
+ return name !== void 0 && TRIGRAM_CLASSES.has(name);
15803
+ }
15804
+ function withoutDropped(indexes, drop) {
15805
+ const names = (drop.objects ?? []).flatMap((object) => {
15806
+ const last = lastName(bodyOf(object, "List")?.items);
15807
+ return last === void 0 ? [] : [last];
15808
+ });
15809
+ if (drop.removeType === "OBJECT_INDEX")
15810
+ return indexes.filter((index) => !names.includes(index.name ?? ""));
15811
+ if (drop.removeType === "OBJECT_TABLE")
15812
+ return indexes.filter((index) => !names.includes(index.table));
15813
+ return indexes;
15814
+ }
15815
+ function withRenamed(indexes, rename) {
15816
+ const from = rename.relation?.relname;
15817
+ const to = rename.newname;
15818
+ if (typeof from !== "string" || typeof to !== "string") return indexes;
15819
+ if (rename.renameType === "OBJECT_INDEX")
15820
+ return indexes.map((index) => index.name === from ? { ...index, name: to } : index);
15821
+ if (rename.renameType === "OBJECT_TABLE")
15822
+ return indexes.map((index) => index.table === from ? { ...index, table: to } : index);
15823
+ if (rename.renameType === "OBJECT_COLUMN") {
15824
+ return indexes.map(
15825
+ (index) => index.table === from && index.expression === rename.subname ? { ...index, expression: to } : index
15826
+ );
15827
+ }
15828
+ return indexes;
15829
+ }
15830
+
15831
+ // src/roles/sql/orm/migration-indexes.ts
15832
+ function indexColumnsOf(migrations) {
15833
+ let indexes = [];
15834
+ for (const { text } of migrations) {
15835
+ const parsed2 = parseSql(text);
15836
+ if (!parsed2.ok) continue;
15837
+ for (const statement of parsed2.statements) indexes = applied2(indexes, statement);
15838
+ }
15839
+ const columns = /* @__PURE__ */ new Map();
15840
+ for (const { table, column } of indexes) {
15841
+ columns.set(table, /* @__PURE__ */ new Set([...columns.get(table) ?? [], column]));
15842
+ }
15843
+ return columns;
15844
+ }
15845
+ function applied2(indexes, statement) {
15846
+ const index = bodyOf(statement, "IndexStmt");
15847
+ if (index) return [...indexes, ...createdIndex(index)];
15848
+ const table = bodyOf(statement, "CreateStmt");
15849
+ if (table) return [...indexes, ...tableConstraints(table)];
15850
+ const alter = bodyOf(statement, "AlterTableStmt");
15851
+ if (alter) return [...indexes, ...addedConstraints(alter)];
15852
+ const drop = bodyOf(statement, "DropStmt");
15853
+ if (drop) return withoutDropped(indexes, drop);
15854
+ const rename = bodyOf(statement, "RenameStmt");
15855
+ if (rename) return withRenamed2(indexes, rename);
15856
+ return indexes;
15857
+ }
15858
+ function createdIndex(index) {
15859
+ const table = relationName(index.relation);
15860
+ const column = firstColumn(index.indexParams);
15861
+ if (table === void 0 || column === void 0) return [];
15862
+ return [{ name: typeof index.idxname === "string" ? index.idxname : void 0, table, column }];
15863
+ }
15864
+ function tableConstraints(create) {
15865
+ const table = relationName(create.relation);
15866
+ if (table === void 0) return [];
15867
+ return (create.tableElts ?? []).flatMap((element) => {
15868
+ const constraint = bodyOf(element, "Constraint");
15869
+ if (constraint) return constraintIndex(table, constraint, void 0);
15870
+ const column = bodyOf(element, "ColumnDef");
15871
+ const name = column?.colname;
15872
+ if (typeof name !== "string") return [];
15873
+ return (column?.constraints ?? []).flatMap((inner) => {
15874
+ const c = bodyOf(inner, "Constraint");
15875
+ return c ? constraintIndex(table, c, name) : [];
15876
+ });
15877
+ });
15878
+ }
15879
+ function addedConstraints(alter) {
15880
+ const table = relationName(alter.relation);
15881
+ if (table === void 0) return [];
15882
+ return (alter.cmds ?? []).flatMap((command2) => {
15883
+ const constraint = bodyOf(bodyOf(command2, "AlterTableCmd")?.def, "Constraint");
15884
+ return constraint ? constraintIndex(table, constraint, void 0) : [];
15885
+ });
15886
+ }
15887
+ function constraintIndex(table, constraint, column) {
15888
+ const name = typeof constraint.conname === "string" ? constraint.conname : void 0;
15889
+ if (constraint.contype === "CONSTR_PRIMARY" || constraint.contype === "CONSTR_UNIQUE") {
15890
+ const first = column ?? firstColumn(constraint.keys);
15891
+ return first === void 0 ? [] : [{ name, table, column: first }];
15892
+ }
15893
+ if (constraint.contype === "CONSTR_EXCLUSION") {
15894
+ const firstExclusion = bodyOf(constraint.exclusions?.[0], "List");
15895
+ const first = firstColumn(firstExclusion?.items);
15896
+ return first === void 0 ? [] : [{ name, table, column: first }];
15897
+ }
15898
+ return [];
15899
+ }
15900
+ function withRenamed2(indexes, rename) {
15901
+ const from = relationName(rename.relation);
15902
+ const to = rename.newname;
15903
+ if (from === void 0 || typeof to !== "string") return indexes;
15904
+ switch (rename.renameType) {
15905
+ case "OBJECT_TABLE":
15906
+ return indexes.map((i) => i.table === from ? { ...i, table: to } : i);
15907
+ case "OBJECT_COLUMN":
15908
+ return indexes.map(
15909
+ (i) => i.table === from && i.column === rename.subname ? { ...i, column: to } : i
15910
+ );
15911
+ case "OBJECT_INDEX":
15912
+ return indexes.map((i) => i.name === from ? { ...i, name: to } : i);
15913
+ default:
15914
+ return indexes;
15915
+ }
15916
+ }
15917
+ function relationName(relation) {
15918
+ const name = relation?.relname;
15919
+ return typeof name === "string" ? name : void 0;
15920
+ }
15921
+ function firstColumn(list) {
15922
+ const first = list?.[0];
15923
+ const element = bodyOf(first, "IndexElem");
15924
+ if (typeof element?.name === "string") return element.name;
15925
+ const text = bodyOf(first, "String")?.sval;
15926
+ return typeof text === "string" ? text : void 0;
15927
+ }
15928
+
15929
+ // src/roles/sql/orm/prisma-schema.ts
15930
+ var MODEL = /^model\s+(\w+)\s*\{([\s\S]*?)^\}/gm;
15931
+ var PROVIDER = /datasource\s+\w+\s*\{[^}]*?provider\s*=\s*"(\w+)"/s;
15932
+ var FIELD = /^(\w+)\s+(\w+)/;
15933
+ var MAP = /@map\(\s*"([^"]+)"/;
15934
+ var TABLE = /^\s*@@map\(\s*"([^"]+)"/m;
15935
+ var RELATION_FK = /@relation\([^)]*fields:\s*\[\s*(\w+)/;
15936
+ var BLOCK_INDEX = /^@@(?:index|unique|id)\(\s*(?:fields:\s*)?\[\s*(\w+)/;
15937
+ var COMPOUND = /^@@(?:unique|id)\(\s*(?:fields:\s*)?\[([^\]]+)\](?:.*?\bname:\s*"(\w+)")?/;
15938
+ function readPrismaSchema(text) {
15939
+ return {
15940
+ provider: PROVIDER.exec(text)?.[1] ?? "unknown",
15941
+ models: [...text.matchAll(MODEL)].map(([, name = "", body = ""]) => modelOf(name, body))
15942
+ };
15943
+ }
15944
+ function modelOf(name, body) {
15945
+ const model = {
15946
+ name,
15947
+ table: TABLE.exec(body)?.[1] ?? name,
15948
+ fields: /* @__PURE__ */ new Map(),
15949
+ foreignKeys: /* @__PURE__ */ new Map(),
15950
+ indexed: /* @__PURE__ */ new Set(),
15951
+ compoundKeys: /* @__PURE__ */ new Set()
15952
+ };
15953
+ for (const raw of body.split("\n")) {
15954
+ const line = raw.trim();
15955
+ if (line === "" || line.startsWith("//")) continue;
15956
+ if (line.startsWith("@@")) blockAttribute(model, line);
15957
+ else fieldLine(model, line);
15958
+ }
15959
+ return model;
15960
+ }
15961
+ function fieldLine(model, line) {
15962
+ const field = FIELD.exec(line);
15963
+ if (!field) return;
15964
+ const [, name = "", type2 = ""] = field;
15965
+ model.fields.set(name, { column: MAP.exec(line)?.[1] ?? name, type: type2 });
15966
+ if (/@id\b|@unique\b/.test(line)) model.indexed.add(name);
15967
+ const fk = RELATION_FK.exec(line)?.[1];
15968
+ if (fk) model.foreignKeys.set(name, fk);
15969
+ }
15970
+ function blockAttribute(model, line) {
15971
+ const first = BLOCK_INDEX.exec(line)?.[1];
15972
+ if (first) model.indexed.add(first);
15973
+ const compound = COMPOUND.exec(line);
15974
+ if (!compound) return;
15975
+ const [, fields = "", given] = compound;
15976
+ model.compoundKeys.add(
15977
+ fields.split(",").map((part) => part.trim().split(/[\s(]/)[0]).join("_")
15978
+ );
15979
+ if (given) model.compoundKeys.add(given);
15980
+ }
15981
+ var clientNameOf = (model) => model.name.charAt(0).toLowerCase() + model.name.slice(1);
15982
+
15983
+ // src/roles/sql/orm/orm-context.ts
15984
+ var NO_SCHEMA = "no Prisma schema on PostgreSQL was read, so these calls are not judged: a module that queries another module's database names that database's migrations in `migrations.indexesFrom` (its schema is read beside them).";
15985
+ function ormContext(cwd, settings) {
15986
+ let read2;
15987
+ const models = () => {
15988
+ read2 ??= readModels(cwd, settings);
15989
+ return read2;
15990
+ };
15991
+ return {
15992
+ modelOf: (name) => {
15993
+ const found = models().judged.get(name) ?? [];
15994
+ return found.length === 1 ? found[0] : void 0;
15995
+ },
15996
+ isPostgreSqlModel: (name) => models().postgres.has(name) && !models().others.has(name),
15997
+ referenceTables: new Set(settings.referenceTables),
15998
+ perRowWrites: settings.perRowWrites ?? [],
15999
+ scripts: settings.scripts ?? [],
16000
+ schemas: () => models().schemas
16001
+ };
16002
+ }
16003
+ function readModels(cwd, settings) {
16004
+ const schemas = [
16005
+ ...globSync4(["**/*.prisma"], {
16006
+ cwd,
16007
+ ignore: [...settings.ignore],
16008
+ onlyFiles: true,
16009
+ dot: false,
16010
+ followSymbolicLinks: false
16011
+ }),
16012
+ ...settings.indexesFrom.flatMap(
16013
+ (folder) => prismaFilesIn(join56(cwd, dirname10(folder))).map((file) => relative10(cwd, file))
16014
+ )
16015
+ ];
16016
+ const judged = /* @__PURE__ */ new Map();
16017
+ const postgres = /* @__PURE__ */ new Set();
16018
+ const others = /* @__PURE__ */ new Set();
16019
+ const read2 = [];
16020
+ for (const schema of new Set(schemas)) {
16021
+ const text = readText(join56(cwd, schema));
16022
+ if (text === void 0) continue;
16023
+ const parsed2 = readPrismaSchema(text);
16024
+ const declared = parsed2.provider === "postgresql" ? postgres : others;
16025
+ for (const model of parsed2.models) declared.add(clientNameOf(model));
16026
+ if (parsed2.provider !== "postgresql") continue;
16027
+ read2.push(schema);
16028
+ for (const one of judgedOf(cwd, schema, parsed2)) {
16029
+ const name = clientNameOf(one.model);
16030
+ judged.set(name, [...judged.get(name) ?? [], one]);
16031
+ }
16032
+ }
16033
+ return { judged, postgres, others, schemas: read2.sort() };
16034
+ }
16035
+ function judgedModelsOf(cwd, schema) {
16036
+ const text = readText(join56(cwd, schema));
16037
+ return text === void 0 ? [] : judgedOf(cwd, schema, readPrismaSchema(text));
16038
+ }
16039
+ function judgedOf(cwd, schema, parsed2) {
16040
+ const migrations = join56(cwd, dirname10(schema), "migrations");
16041
+ const folders = migrationsIn(migrations);
16042
+ if (parsed2.provider !== "postgresql" || folders.length === 0) return [];
16043
+ const indexes = indexColumnsOf(
16044
+ folders.flatMap((folder) => {
16045
+ const sql = readText(join56(migrations, folder, "migration.sql"));
16046
+ return sql === void 0 ? [] : [{ text: sql }];
16047
+ })
16048
+ );
16049
+ const modelNames = new Set(parsed2.models.map((model) => model.name));
16050
+ return parsed2.models.map((model) => ({ model, indexes, schema, modelNames }));
16051
+ }
16052
+ function prismaFilesIn(directory) {
16053
+ try {
16054
+ return readdirSync12(directory).filter((name) => name.endsWith(".prisma")).map((name) => join56(directory, name));
16055
+ } catch {
16056
+ return [];
16057
+ }
16058
+ }
16059
+ function readText(path2) {
16060
+ try {
16061
+ return readFileSync33(path2, "utf8");
16062
+ } catch {
16063
+ return void 0;
16064
+ }
16065
+ }
16066
+
16067
+ // src/roles/sql/orm/rules/filter-without-index.ts
16068
+ var NOT_JUDGED = /* @__PURE__ */ new Set([
16069
+ "some",
16070
+ "every",
16071
+ "none",
16072
+ "is",
16073
+ "isNot",
16074
+ "contains",
16075
+ "startsWith",
16076
+ "endsWith",
16077
+ "search"
16078
+ ]);
16079
+ var COMBINATORS = /* @__PURE__ */ new Set(["AND", "OR", "NOT"]);
16080
+ var filterWithoutIndex = {
16081
+ name: ORM_FILTER_INDEX_RULE,
16082
+ help: 'index the column in the schema (`@@index([field])`) and its migration, or name the table in `orm.referenceTables` when it is a small reference table; Prisma\'s guide: "index fields used in where"',
16083
+ check: (call, context2) => {
16084
+ if (!READ_OPERATIONS.includes(call.operation)) return void 0;
16085
+ const judged = context2.modelOf(call.model);
16086
+ if (judged === void 0 || context2.referenceTables.has(judged.model.table)) return void 0;
16087
+ const columns = unindexedColumns(propertyOf(call.args, "where"), judged);
16088
+ if (columns === void 0) return void 0;
16089
+ return messageOf2(call, judged, columns);
16090
+ }
16091
+ };
16092
+ function unindexedColumns(where, judged) {
16093
+ if (where === void 0) return void 0;
16094
+ const { keys, spread } = keysOf(where);
16095
+ const filtered = keys.filter((key) => !COMBINATORS.has(key));
16096
+ if (spread || filtered.length === 0) return void 0;
16097
+ const columns = [];
16098
+ for (const key of filtered) {
16099
+ const column = columnOf(key, where, judged);
16100
+ if (column === void 0 || isIndexed(column, judged)) return void 0;
16101
+ columns.push(column.column);
16102
+ }
16103
+ return columns;
16104
+ }
16105
+ function columnOf(key, where, { model, modelNames }) {
16106
+ if (model.compoundKeys.has(key)) return void 0;
16107
+ if (readsAnotherTable(propertyOf(where, key))) return void 0;
16108
+ const scalar = model.foreignKeys.get(key) ?? key;
16109
+ const field = model.fields.get(scalar);
16110
+ if (field === void 0 || scalar === key && modelNames.has(field.type)) return void 0;
16111
+ return { field: scalar, column: field.column };
16112
+ }
16113
+ function readsAnotherTable(value) {
16114
+ if (value?.type === "ArrayExpression") {
16115
+ return (value.elements ?? []).some(
16116
+ (element) => readsAnotherTable(element)
16117
+ );
16118
+ }
16119
+ if (value?.type !== "ObjectExpression") return false;
16120
+ return value.properties.some((p) => {
16121
+ if (p.type !== "Property") return true;
16122
+ const key = p.key.name ?? p.key.value;
16123
+ return NOT_JUDGED.has(key) || readsAnotherTable(p.value);
16124
+ });
16125
+ }
16126
+ function isIndexed({ field, column }, judged) {
16127
+ return judged.model.indexed.has(field) || (judged.indexes.get(judged.model.table)?.has(column) ?? false);
16128
+ }
16129
+ function messageOf2(call, judged, columns) {
16130
+ const named = columns.map((column) => `\`${column}\``).join(", ");
16131
+ return `this ${call.operation} on ${call.model} filters on ${named} of \`${judged.model.table}\`, and no index of the schema or of the migrations read (\`${judged.schema}\`) starts with ${columns.length === 1 ? "that column" : "any of them"}: PostgreSQL reads every row of the table. An index created outside the migrations is not seen, and sentinel cannot know the size of a table`;
16132
+ }
16133
+
16134
+ // src/roles/sql/orm/rules/new-client.ts
16135
+ import { matchesGlob as matchesGlob2 } from "node:path";
16136
+ var newClient = {
16137
+ name: ORM_NEW_CLIENT_RULE,
16138
+ help: "inject the module's database service (the one that extends PrismaClient); a one-off script belongs in a folder that `orm.scripts` names",
16139
+ check: () => void 0,
16140
+ checkFile: (program, file, context2) => {
16141
+ if (context2.scripts.some((pattern) => matchesGlob2(file, pattern))) return [];
16142
+ const found = [];
16143
+ walkWithAncestors(program, (node) => {
16144
+ if (node.type === "NewExpression" && namesPrismaClient(node.callee)) {
16145
+ found.push({
16146
+ offset: node.start,
16147
+ message: "this code creates its own PrismaClient: each one opens its own pool of connections to the database, beside the one the module shares"
16148
+ });
16149
+ }
16150
+ });
16151
+ return found;
16152
+ }
16153
+ };
16154
+ function namesPrismaClient(callee) {
16155
+ if (callee?.type === "Identifier") return callee.name === "PrismaClient";
16156
+ return callee?.type === "MemberExpression" && callee.property?.name === "PrismaClient";
16157
+ }
16158
+
16159
+ // src/roles/sql/orm/batches.ts
16160
+ var BATCHES = /chunk|batch|slice\(|group|frontier|\bpage/i;
16161
+ var SET_KEYS = /* @__PURE__ */ new Set(["in", "notIn", "OR", "AND"]);
16162
+ var KEYSET = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
16163
+ function runsPerBatch(call, loop) {
16164
+ if (BATCHES.test(loop.walks)) return true;
16165
+ const where = propertyOf(call.args, "where");
16166
+ if (readsAsSet(where, loop.vars)) return true;
16167
+ return propertyOf(call.args, "take") !== void 0 && (propertyOf(call.args, "cursor") !== void 0 || comparesKeyset(where));
16168
+ }
16169
+ function readsAsSet(node, vars) {
16170
+ if (node === null || typeof node !== "object") return false;
16171
+ if (Array.isArray(node)) return node.some((item) => readsAsSet(item, vars));
16172
+ const n = node;
16173
+ if (n.type === "Property" && SET_KEYS.has(keyOf(n)) && rootsAt(n.value, vars)) {
16174
+ return true;
16175
+ }
16176
+ return Object.entries(n).some(
16177
+ ([key, child]) => key !== "parent" && typeof child === "object" && readsAsSet(child, vars)
16178
+ );
16179
+ }
16180
+ function rootsAt(value, vars) {
16181
+ let node = value;
16182
+ while (node?.type === "MemberExpression") node = node.object;
16183
+ return node?.type === "Identifier" && vars.has(node.name);
16184
+ }
16185
+ function comparesKeyset(where) {
16186
+ if (where?.type !== "ObjectExpression") return false;
16187
+ return where.properties.some((p) => {
16188
+ const value = p.value;
16189
+ return value?.type === "ObjectExpression" && value.properties.some((q) => KEYSET.has(keyOf(q)));
16190
+ });
16191
+ }
16192
+ function keyOf(property) {
16193
+ const key = property.key;
16194
+ return key?.name ?? key?.value ?? "";
16195
+ }
16196
+ function shortly(text) {
16197
+ const line = text.replace(/\s+/g, " ").trim();
16198
+ return line.length > 60 ? `${line.slice(0, 57)}...` : line;
16199
+ }
16200
+
16201
+ // src/roles/sql/orm/rules/query-in-loop.ts
16202
+ var queryInLoop = {
16203
+ name: ORM_QUERY_LOOP_RULE,
16204
+ help: "read the elements in one query: one `findMany` with `where: { id: { in: ids } }`, or an `include` on the query that gave the list; Prisma's guide: avoid N+1 queries",
16205
+ check: (call, context2) => {
16206
+ if (!READ_OPERATIONS.includes(call.operation) || call.loop === void 0) return void 0;
16207
+ if (!context2.isPostgreSqlModel(call.model)) return void 0;
16208
+ if (runsPerBatch(call, call.loop)) return void 0;
16209
+ return `this ${call.operation} on ${call.model} runs once per element of \`${shortly(call.loop.walks)}\`: the number of queries grows with the data`;
16210
+ }
16211
+ };
16212
+
16213
+ // src/roles/sql/orm/rules/write-in-loop.ts
16214
+ var writeInLoop = {
16215
+ name: ORM_WRITE_LOOP_RULE,
16216
+ help: "write the set in one statement: `createMany`, `updateMany` or `deleteMany` with the list; when one write per row is wanted, name it in `orm.perRowWrites` with its reason",
16217
+ check: (call, context2, file) => {
16218
+ if (!WRITE_OPERATIONS.includes(call.operation) || call.loop === void 0) return void 0;
16219
+ if (!context2.isPostgreSqlModel(call.model) || isNamed(call, context2, file)) return void 0;
16220
+ if (runsPerBatch(call, call.loop)) return void 0;
16221
+ return `this ${call.operation} on ${call.model} runs once per element of \`${shortly(call.loop.walks)}\`: one statement per row, the number of writes grows with the data`;
16222
+ }
16223
+ };
16224
+ function isNamed(call, context2, file) {
16225
+ const written = `${call.model}.${call.operation}`;
16226
+ return context2.perRowWrites.some((entry) => entry.file === file && entry.call === written);
16227
+ }
16228
+
16229
+ // src/roles/sql/orm/orm-rules.ts
16230
+ var ALL_ORM_RULES = [
16231
+ filterWithoutIndex,
16232
+ queryInLoop,
16233
+ writeInLoop,
16234
+ newClient
16235
+ ];
16236
+ function ormRules(rules) {
16237
+ return ALL_ORM_RULES.filter((rule) => rules[rule.name] !== "off");
16238
+ }
16239
+
16240
+ // src/roles/sql/orm/rules/foreign-key-without-index.ts
16241
+ var foreignKeyWithoutIndex = {
16242
+ name: ORM_FK_INDEX_RULE,
16243
+ help: "index the foreign key in the schema (`@@index([field])`) and in a new migration; Prisma's guide: index the relation scalar fields"
16244
+ };
16245
+ function foreignKeyFindings(cwd, changes) {
16246
+ return changes.flatMap((change) => {
16247
+ const before = new Map(readPrismaSchema(change.base).models.map((model) => [model.name, model]));
16248
+ return judgedModelsOf(cwd, change.file).flatMap(
16249
+ (judged) => addedForeignKeys(judged.model, before.get(judged.model.name)).filter(([, scalar]) => !isIndexed2(judged, scalar)).map(([relation, scalar]) => findingOn(change, judged, relation, scalar))
16250
+ );
16251
+ });
16252
+ }
16253
+ function addedForeignKeys(model, base) {
16254
+ const said = /* @__PURE__ */ new Set();
16255
+ return [...model.foreignKeys].filter(([relation, scalar]) => {
16256
+ if (base?.foreignKeys.get(relation) === scalar || said.has(scalar)) return false;
16257
+ said.add(scalar);
16258
+ return true;
16259
+ });
16260
+ }
16261
+ function isIndexed2(judged, scalar) {
16262
+ const column = judged.model.fields.get(scalar)?.column ?? scalar;
16263
+ return judged.model.indexed.has(scalar) || (judged.indexes.get(judged.model.table)?.has(column) ?? false);
16264
+ }
16265
+ function findingOn(change, judged, relation, scalar) {
16266
+ const { model } = judged;
16267
+ const column = model.fields.get(scalar)?.column ?? scalar;
16268
+ const target = model.fields.get(relation)?.type ?? "the row it points at";
16269
+ const message = `the relation \`${relation}\` of ${model.name} adds the foreign key \`${column}\` (\`${scalar}\`), and no index of the schema or of the migrations read starts with it: PostgreSQL does not create one for a foreign key, so a join or a filter on it, and every delete of a ${target}, read every row of \`${model.table}\``;
16270
+ return findingOf2(change, foreignKeyWithoutIndex, {
16271
+ offset: offsetOf(change.text, model.name, relation),
16272
+ message
16273
+ });
16274
+ }
16275
+ function offsetOf(text, model, relation) {
16276
+ const start = new RegExp(`^model\\s+${model}\\s*\\{`, "m").exec(text)?.index ?? 0;
16277
+ const field = new RegExp(`^\\s*${relation}\\s`, "m").exec(text.slice(start));
16278
+ return field === null ? start : start + field.index + (field[0].length - field[0].trimStart().length);
16279
+ }
16280
+
16281
+ // src/roles/sql/orm/rules/model-naming.ts
16282
+ var modelNaming = {
16283
+ name: ORM_MODEL_NAMING_RULE,
16284
+ help: 'name the model in PascalCase and in the singular, and map its table with `@@map`; Prisma\'s guide: `model User { ... @@map("users") }`'
16285
+ };
16286
+ var PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
16287
+ var READS_PLURAL = /[^s]s$/;
16288
+ var SINGULAR_ENDINGS = /(?:ss|us|is|ness)$/;
16289
+ function modelNamingFindings(changes) {
16290
+ return changes.flatMap((change) => {
16291
+ const now = readPrismaSchema(change.text);
16292
+ if (now.provider !== "postgresql") return [];
16293
+ const before = new Set(readPrismaSchema(change.base).models.map((model) => model.name));
16294
+ return now.models.filter((model) => !before.has(model.name)).flatMap((model) => {
16295
+ const problem = problemOf(model.name);
16296
+ return problem === void 0 ? [] : [
16297
+ findingOf2(change, modelNaming, {
16298
+ offset: offsetOf2(change.text, model.name),
16299
+ message: problem
16300
+ })
16301
+ ];
16302
+ });
16303
+ });
16304
+ }
16305
+ function problemOf(name) {
16306
+ if (!PASCAL_CASE.test(name)) {
16307
+ return `the model \`${name}\` this branch adds is not in PascalCase: the client reads it as \`${name}\`, unlike the other models`;
16308
+ }
16309
+ if (READS_PLURAL.test(name) && !SINGULAR_ENDINGS.test(name)) {
16310
+ return `the model \`${name}\` this branch adds reads as a plural: a model names one row, and the client reads \`${name[0]?.toLowerCase()}${name.slice(1)}.findMany()\` for a list of them`;
16311
+ }
16312
+ return void 0;
16313
+ }
16314
+ function offsetOf2(text, name) {
16315
+ return new RegExp(`^model\\s+${name}\\s*\\{`, "m").exec(text)?.index ?? 0;
16316
+ }
16317
+
16318
+ // src/roles/sql/raw/check-templates.ts
16319
+ import { join as join57 } from "node:path";
16320
+ import { parseSync as parseSync10 } from "oxc-parser";
16321
+
16322
+ // src/roles/sql/raw/joined-text.ts
16323
+ function joined(parts, fill) {
16324
+ const text = { sql: "", pieces: [] };
16325
+ parts.forEach((part, index) => {
16326
+ if (index > 0) {
16327
+ text.pieces.push({ at: text.sql.length, part, fill: true });
16328
+ text.sql += fill(index);
16329
+ }
16330
+ text.pieces.push({ at: text.sql.length, part, fill: false });
16331
+ text.sql += part.text;
16332
+ });
16333
+ return text;
16334
+ }
16335
+ function fileOffsetOf(text, index) {
16336
+ const piece = [...text.pieces].reverse().find((candidate) => candidate.at <= index);
16337
+ if (piece === void 0) return text.pieces[0]?.part.start ?? 0;
16338
+ if (piece.fill) return piece.part.start - 1;
16339
+ const inPart = index - piece.at;
16340
+ switch (piece.part.placing) {
16341
+ case "exact":
16342
+ return piece.part.start + inPart;
16343
+ case "crlf":
16344
+ return piece.part.start + sourceIndexAfterCrlf(piece.part.source, inPart);
16345
+ case "start":
16346
+ return piece.part.start;
16347
+ }
16348
+ }
16349
+ function sourceIndexAfterCrlf(source2, index) {
16350
+ let read2 = 0;
16351
+ for (let at = 0; at < source2.length; at++) {
16352
+ if (source2[at] === "\r" && source2[at + 1] === "\n") continue;
16353
+ if (read2 === index) return at;
16354
+ read2++;
16355
+ }
16356
+ return source2.length;
16357
+ }
16358
+
16359
+ // src/roles/sql/raw/read-template.ts
16360
+ var WRAPS = [
16361
+ ["statement", "", ""],
16362
+ ["expression", "SELECT ", ""],
16363
+ ["predicate", "SELECT 1 WHERE ", ""],
16364
+ ["from-item", "SELECT 1 FROM ", ""],
16365
+ ["after-from", "SELECT 1 FROM t ", ""],
16366
+ ["select-list", "SELECT ", " FROM t"],
16367
+ ["order-by", "SELECT 1 FROM t ORDER BY ", ""],
16368
+ ["set-list", "UPDATE t SET ", ""],
16369
+ ["values", "INSERT INTO t VALUES ", ""],
16370
+ ["cte", "WITH ", " SELECT 1"],
16371
+ ["and-tail", "SELECT 1 FROM t WHERE true ", ""],
16372
+ ["comma-tail", "SELECT 1 ", " FROM t"]
16373
+ ];
16374
+ var FILLS = [
16375
+ ["value", (n) => `$${n}`],
16376
+ ["identifier", (n) => `__p${n}`],
16377
+ ["nothing", () => ""],
16378
+ ["list", (n) => `($${n})`]
16379
+ ];
16380
+ function readTemplate(template) {
16381
+ if (template.parts.every((part) => part.text.trim() === "")) return { kind: "empty" };
16382
+ let firstError;
16383
+ for (const [fillName, fill] of FILLS) {
16384
+ const text = joined(template.parts, fill);
16385
+ for (const [wrap, before, after] of WRAPS) {
16386
+ const parsed2 = parseSql(`${before}${text.sql}${after}`);
16387
+ if (parsed2.ok) {
16388
+ return {
16389
+ kind: "read",
16390
+ reading: readingOf(
16391
+ parsed2.statements,
16392
+ { wrap, before, fill: fillName, values: template.values },
16393
+ text
16394
+ )
16395
+ };
16396
+ }
16397
+ firstError ??= parsed2.message;
16398
+ }
16399
+ }
16400
+ return { kind: "unread", reason: `PostgreSQL's parser does not read it alone (${firstError})` };
16401
+ }
16402
+ function readingOf(statements, {
16403
+ wrap,
16404
+ before,
16405
+ fill,
16406
+ values
16407
+ }, text) {
16408
+ const wrapped = `${before}${text.sql}`;
16409
+ const indexIn = (location) => indexOfByte(wrapped, location) - before.length;
16410
+ return {
16411
+ statements,
16412
+ wrap,
16413
+ fill,
16414
+ own: (location) => {
16415
+ const index = indexIn(location);
16416
+ return index >= 0 && index < text.sql.length;
16417
+ },
16418
+ fileOffset: (location) => fileOffsetOf(text, indexIn(location)),
16419
+ valueStart: (n) => fill === "value" ? values[n - 1] : void 0
16420
+ };
16421
+ }
16422
+
16423
+ // src/roles/sql/raw/template-rule.ts
16424
+ var NO_CONTEXT = {
16425
+ trigramIndexes: () => [],
16426
+ indexesFrom: () => ({ read: [], empty: [] })
16427
+ };
16428
+
16429
+ // src/roles/sql/raw/value-starts.ts
16430
+ var MAX_DEPTH2 = 8;
16431
+ function valueStart(node, bindings, depth = 0) {
16432
+ if (depth > MAX_DEPTH2) return void 0;
16433
+ const current = unwrap(node);
16434
+ const deeper = (next) => valueStart(next, bindings, depth + 1);
16435
+ switch (current.type) {
16436
+ case "Literal":
16437
+ return typeof current.value === "string" ? current.value : void 0;
16438
+ case "TemplateLiteral":
16439
+ return templateStart(current, deeper);
16440
+ case "BinaryExpression":
16441
+ return current.operator === "+" ? sumStart(current, deeper) : void 0;
16442
+ case "Identifier":
16443
+ return nameStart(current.name, bindings, deeper);
16444
+ default:
16445
+ return void 0;
16446
+ }
16447
+ }
16448
+ function templateStart(node, deeper) {
16449
+ const [first] = node.quasis;
16450
+ const value = first?.value;
16451
+ const text = value?.cooked ?? value?.raw;
16452
+ if (text === void 0) return void 0;
16453
+ const [expression] = node.expressions;
16454
+ if (text !== "" || expression === void 0) return text;
16455
+ return deeper(expression);
16456
+ }
16457
+ function sumStart(node, deeper) {
16458
+ const left = deeper(node.left);
16459
+ if (left !== "") return left;
16460
+ return deeper(node.right);
16461
+ }
16462
+ function nameStart(name, bindings, deeper) {
16463
+ const found = bindings.get(name) ?? [];
16464
+ const [binding] = found;
16465
+ if (found.length !== 1 || binding?.kind !== "const") return void 0;
16466
+ return deeper(binding.init);
16467
+ }
16468
+
16469
+ // src/roles/sql/raw/templates.ts
16470
+ function sqlTemplatesOf(program, prisma, fileText) {
16471
+ const templates = [];
16472
+ let bindings;
16473
+ const bindingsOnce = () => {
16474
+ bindings ??= bindingsOf(program);
16475
+ return bindings;
16476
+ };
16477
+ walk(program, (node) => {
16478
+ if (node.type !== "TaggedTemplateExpression") return;
16479
+ const tag = tagOf(node.tag, prisma);
16480
+ if (tag === void 0) return;
16481
+ const quasis = node.quasi.quasis;
16482
+ const parts = quasis.map((element) => partOf(element, fileText));
16483
+ const expressions = node.quasi.expressions;
16484
+ const values = expressions.map((expression) => valueStart(expression, bindingsOnce()));
16485
+ templates.push({ tag, parts, values, start: node.start });
16486
+ });
16487
+ return templates;
16488
+ }
16489
+ function tagOf(tag, prisma) {
16490
+ const member = unwrap(tag);
16491
+ const name = memberName(member);
16492
+ if (name === "$queryRaw" || name === "$executeRaw") return name;
16493
+ if (name === "sql" && isPrismaObject(unwrap(member.object), prisma))
16494
+ return "Prisma.sql";
16495
+ return void 0;
16496
+ }
16497
+ function partOf(element, fileText) {
16498
+ const value = element.value;
16499
+ const text = value.cooked ?? value.raw;
16500
+ const start = element.start + 1;
16501
+ const source2 = fileText.slice(start, element.end - (element.tail ? 1 : 2));
16502
+ const placing = source2 === text ? "exact" : source2.replace(/\r\n/g, "\n") === text ? "crlf" : "start";
16503
+ return { text, start, placing, source: source2 };
16504
+ }
16505
+
16506
+ // src/roles/sql/raw/check-templates.ts
16507
+ async function checkSqlTemplates(cwd, files, readFile, { rules, context: context2 = NO_CONTEXT }) {
16508
+ const run = { templates: 0, read: 0, unread: [], unparsed: [], findings: [] };
16509
+ if (files.length === 0) return run;
16510
+ const loaded2 = await parserLoaded2();
16511
+ if (!loaded2.ok) {
16512
+ for (const file of files) run.unparsed.push({ file, reason: loaded2.reason });
16513
+ return run;
16514
+ }
16515
+ for (const file of files) {
16516
+ const text = readFile(join57(cwd, file));
16517
+ if (text === void 0) {
16518
+ run.unparsed.push({ file, reason: "could not be read, so its SQL templates are not read" });
16519
+ continue;
16520
+ }
16521
+ checkFile2({ file, text, rules, context: context2 }, run);
16522
+ }
16523
+ return run;
15642
16524
  }
15643
- function operationKey(operation, depth) {
15644
- if (operation.kind !== "AEXPR_OP") return void 0;
15645
- const operator = lastName(operation.name);
15646
- const left = expressionKey(operation.lexpr, depth);
15647
- const right = expressionKey(operation.rexpr, depth);
15648
- if (operator === void 0 || left === void 0 || right === void 0) return void 0;
15649
- return `${left} ${operator} ${right}`;
16525
+ async function parserLoaded2() {
16526
+ try {
16527
+ await loadSqlParser();
16528
+ return { ok: true };
16529
+ } catch (error) {
16530
+ const why = error instanceof Error ? error.message : String(error);
16531
+ return {
16532
+ ok: false,
16533
+ reason: `PostgreSQL's parser could not be loaded (${why}), so its SQL templates are not read`
16534
+ };
16535
+ }
15650
16536
  }
15651
- function constantKey(constant) {
15652
- if (constant.isnull === true) return "null";
15653
- const text = bodyOf(constant, "sval")?.sval;
15654
- if (typeof text === "string") return `'${text}'`;
15655
- for (const [kind, zero] of [
15656
- ["ival", "0"],
15657
- ["fval", "0"],
15658
- ["boolval", "false"]
15659
- ]) {
15660
- const body = bodyOf(constant, kind);
15661
- if (body) return body[kind] === void 0 ? zero : String(body[kind]);
16537
+ function checkFile2(input, run) {
16538
+ const { file, text } = input;
16539
+ try {
16540
+ const { program, errors } = parseSync10(file, text, { sourceType: "module" });
16541
+ if (errors.length > 0) {
16542
+ const reason = `does not parse (${errors[0]?.message ?? "unknown error"})`;
16543
+ run.unparsed.push({ file, reason: `${reason}, so its SQL templates are not read` });
16544
+ return;
16545
+ }
16546
+ const tree = program;
16547
+ for (const template of sqlTemplatesOf(tree, prismaImportsOf(tree), text)) {
16548
+ checkTemplate(input, template, run);
16549
+ }
16550
+ } catch (error) {
16551
+ const why = error instanceof Error ? error.message : String(error);
16552
+ run.unparsed.push({
16553
+ file,
16554
+ reason: `could not be read (${why}), so its SQL templates are not read`
16555
+ });
15662
16556
  }
15663
- return void 0;
15664
16557
  }
15665
- var KEYS = /* @__PURE__ */ new Map([
15666
- ["ColumnRef", columnKey],
15667
- ["FuncCall", callKey],
15668
- ["TypeCast", castKey],
15669
- ["A_Const", constantKey],
15670
- ["A_Expr", operationKey]
15671
- ]);
15672
- function qualifiersUnder(node) {
15673
- const qualifiers = /* @__PURE__ */ new Set();
15674
- for (const names of columnsUnder(node)) {
15675
- const qualifier = names.at(-2);
15676
- if (qualifier !== void 0) qualifiers.add(qualifier);
16558
+ function checkTemplate(input, template, run) {
16559
+ const { line } = positionOf(input.text, template.start);
16560
+ let result;
16561
+ try {
16562
+ result = readTemplate(template);
16563
+ } catch (error) {
16564
+ run.templates++;
16565
+ run.unread.push({ file: input.file, line, reason: `could not be read (${messageOf3(error)})` });
16566
+ return;
15677
16567
  }
15678
- return qualifiers;
16568
+ if (result.kind === "empty") return;
16569
+ run.templates++;
16570
+ if (result.kind === "unread") {
16571
+ run.unread.push({ file: input.file, line, reason: result.reason });
16572
+ return;
16573
+ }
16574
+ run.read++;
16575
+ for (const rule of input.rules) checkRule(input, rule, result.reading, run);
16576
+ }
16577
+ function checkRule(input, rule, reading, run) {
16578
+ let hits;
16579
+ try {
16580
+ hits = rule.check(reading, input.context);
16581
+ } catch {
16582
+ return;
16583
+ }
16584
+ for (const hit of hits) {
16585
+ const offset = reading.fileOffset(hit.location);
16586
+ run.findings.push(findingOf2(input, rule, { offset, message: hit.message }));
16587
+ }
16588
+ }
16589
+ function messageOf3(error) {
16590
+ return error instanceof Error ? error.message : String(error);
15679
16591
  }
15680
16592
 
15681
16593
  // src/roles/sql/raw/rules/exists-union-correlated-outside.ts
@@ -15683,11 +16595,11 @@ var existsUnionCorrelatedOutside = {
15683
16595
  name: EXISTS_UNION_RULE,
15684
16596
  help: "repeat the correlation inside each branch of the union (`WHERE a.profile_id = np.id` in every SELECT), or write one EXISTS per branch joined by OR, so PostgreSQL filters each branch with its own index",
15685
16597
  check: (reading) => existsSublinks(reading).flatMap(({ location, select }) => {
15686
- const union = unionFilteredOutside(select);
15687
- return union === void 0 ? [] : [
16598
+ const union2 = unionFilteredOutside(select);
16599
+ return union2 === void 0 ? [] : [
15688
16600
  {
15689
16601
  location,
15690
- message: `this EXISTS reads the UNION \`${union.alias}\` and filters it only outside the union (\`${union.filter}\`): PostgreSQL cannot push that filter into the branches, so it builds the whole union for every outer row. This is the shape of the 19 May incident`
16602
+ message: `this EXISTS reads the UNION \`${union2.alias}\` and filters it only outside the union (\`${union2.filter}\`): PostgreSQL cannot push that filter into the branches, so it builds the whole union for every outer row. This is the shape of the 19 May incident`
15691
16603
  }
15692
16604
  ];
15693
16605
  })
@@ -15706,8 +16618,8 @@ function existsSublinks(reading) {
15706
16618
  return found;
15707
16619
  }
15708
16620
  function unionFilteredOutside(select) {
15709
- for (const { alias, union } of derivedUnions(select)) {
15710
- if (setBranches(union).some(isCorrelated)) continue;
16621
+ for (const { alias, union: union2 } of derivedUnions(select)) {
16622
+ if (setBranches(union2).some(isCorrelated)) continue;
15711
16623
  const filter = columnsUnder(select.whereClause).find(
15712
16624
  (names) => names.length === 2 && names[0] === alias
15713
16625
  );
@@ -15718,9 +16630,9 @@ function unionFilteredOutside(select) {
15718
16630
  function* derivedUnions(select) {
15719
16631
  for (const node of pgNodes(select.fromClause)) {
15720
16632
  const derived = bodyOf(node, "RangeSubselect");
15721
- const union = bodyOf(derived?.subquery, "SelectStmt");
16633
+ const union2 = bodyOf(derived?.subquery, "SelectStmt");
15722
16634
  const alias = derived ? aliasOf(derived) : void 0;
15723
- if (union?.op === "SETOP_UNION" && alias !== void 0) yield { alias, union };
16635
+ if (union2?.op === "SETOP_UNION" && alias !== void 0) yield { alias, union: union2 };
15724
16636
  }
15725
16637
  }
15726
16638
  function isCorrelated(branch) {
@@ -16146,7 +17058,7 @@ function levelCounts(findings) {
16146
17058
  function plural2(count, noun, many = `${noun}s`) {
16147
17059
  return `${count} ${count === 1 ? noun : many}`;
16148
17060
  }
16149
- function problemOf(finding3) {
17061
+ function problemOf2(finding3) {
16150
17062
  const own = SENTINEL_RULES.includes(finding3.rule);
16151
17063
  return sentence(finding3.message) + (!own && finding3.help ? ` Fix: ${endOf(finding3.help)}` : "");
16152
17064
  }
@@ -16179,7 +17091,7 @@ var placeOf = (finding3) => `${finding3.file}:${finding3.line}:${finding3.column
16179
17091
 
16180
17092
  // src/roles/sql/report/outputs.ts
16181
17093
  import { existsSync as existsSync38, mkdirSync as mkdirSync10, unlinkSync as unlinkSync3, writeFileSync as writeFileSync13 } from "node:fs";
16182
- import { join as join55 } from "node:path";
17094
+ import { join as join58 } from "node:path";
16183
17095
 
16184
17096
  // src/roles/sql/report/render-html.ts
16185
17097
  var PAGE_SIZE2 = 50;
@@ -16221,7 +17133,7 @@ function findingsOf(report, side) {
16221
17133
  (finding3) => finding3.rule !== SYNTAX_ERROR && isMigration(finding3.file) === (side === "migrations")
16222
17134
  );
16223
17135
  }
16224
- var isMigration = (file) => file.endsWith(".sql");
17136
+ var isMigration = (file) => file.endsWith(".sql") || file.endsWith(".prisma");
16225
17137
  function migrationsCount(report) {
16226
17138
  return countedFindings(report.findings).filter((finding3) => isMigration(finding3.file)).length;
16227
17139
  }
@@ -16256,7 +17168,10 @@ function readCard(report) {
16256
17168
  const parts = [
16257
17169
  report.read.length > 0 ? plural2(report.read.length, "migration") : null,
16258
17170
  report.unsafe.read.length > 0 ? `${plural2(report.unsafe.read.length, "file")} with raw SQL calls` : null,
16259
- report.templates.templates > 0 ? plural2(report.templates.templates, "SQL template") : null
17171
+ report.templates.templates > 0 ? plural2(report.templates.templates, "SQL template") : null,
17172
+ (report.orm?.calls ?? 0) > 0 ? plural2(report.orm?.calls ?? 0, "Prisma read") : null,
17173
+ (report.orm?.writes ?? 0) > 0 ? plural2(report.orm?.writes ?? 0, "Prisma write") : null,
17174
+ (report.schemaChanges?.length ?? 0) > 0 ? plural2(report.schemaChanges?.length ?? 0, "Prisma schema") : null
16260
17175
  ].filter((part) => part !== null);
16261
17176
  const notRead = notReadCount(report);
16262
17177
  return `<div class="kpi${notRead > 0 ? " band-above" : ""}">
@@ -16266,7 +17181,7 @@ function readCard(report) {
16266
17181
  </div>`;
16267
17182
  }
16268
17183
  function notReadCount(report) {
16269
- return report.unread.length + unparsedMigrations(report.findings).length + report.unsafe.unparsed.length + report.templates.unread.length + report.templates.unparsed.length;
17184
+ return report.unread.length + unparsedMigrations(report.findings).length + report.unsafe.unparsed.length + report.templates.unread.length + report.templates.unparsed.length + (report.orm?.unparsed.length ?? 0);
16270
17185
  }
16271
17186
  function toolsCard(report) {
16272
17187
  const counted = countedFindings(report.findings);
@@ -16286,15 +17201,15 @@ function toolsCard(report) {
16286
17201
  </div>`;
16287
17202
  }
16288
17203
  function codePanel(report, findings) {
16289
- const readAny = report.unsafe.read.length > 0 || report.templates.read.length > 0;
17204
+ const readAny = report.unsafe.read.length > 0 || report.templates.read.length > 0 || (report.orm?.read.length ?? 0) > 0;
16290
17205
  const empty = readAny ? "No finding in the SQL in code this branch adds or changes." : "This branch adds or changes no raw SQL call and no SQL template.";
16291
17206
  return `${unparsedBox(
16292
17207
  "These TypeScript files could not be read, so nothing in them is checked.",
16293
- [...report.unsafe.unparsed, ...report.templates.unparsed]
17208
+ [...report.unsafe.unparsed, ...report.templates.unparsed, ...report.orm?.unparsed ?? []]
16294
17209
  )}
16295
17210
  ${findingsTable("code", findings, empty)}
16296
17211
  <h2>What was read</h2>
16297
- <div class="card">${unsafeLine(report)}${templatesLine(report)}</div>`;
17212
+ <div class="card">${unsafeLine(report)}${templatesLine(report)}${ormLine(report)}</div>`;
16298
17213
  }
16299
17214
  function migrationsPanel(report, findings) {
16300
17215
  if (report.migrations === 0) return '<p class="empty">This module holds no migration.</p>';
@@ -16379,7 +17294,7 @@ function tagsOf(finding3) {
16379
17294
  }
16380
17295
  function rowOf(finding3, fullNoteShown) {
16381
17296
  const who = SENTINEL_RULES.includes(finding3.rule) ? "sentinel" : "squawk";
16382
- const problem = problemOf(finding3);
17297
+ const problem = problemOf2(finding3);
16383
17298
  const find = `${finding3.file} ${finding3.rule} ${problem}`.toLowerCase();
16384
17299
  const level = finding3.level === "error" ? '<span class="level-error">error</span>' : "warning";
16385
17300
  const details2 = detailsOf(finding3, fullNoteShown);
@@ -16454,6 +17369,19 @@ function templatesLine(report) {
16454
17369
  );
16455
17370
  return notRead.length === 0 ? `${lead}${fileList(read2)}` : `${lead}<details><summary>${grouped(notRead.length)} not read alone, so no rule checked them</summary><ul>${notRead.join("")}</ul></details>${fileList(read2)}`;
16456
17371
  }
17372
+ function ormLine(report) {
17373
+ const orm = report.orm;
17374
+ if (orm === void 0 || orm.files.length === 0) return "";
17375
+ if (orm.read.length === 0) {
17376
+ return `<p><b>Prisma reads.</b> ${plural2(orm.files.length, "file")} of the module ${orm.files.length === 1 ? "makes" : "make"} Prisma Client reads; none is added or changed by this branch, so none is read.</p>`;
17377
+ }
17378
+ const writes = orm.writes > 0 ? ` and ${plural2(orm.writes, "write")} (<code>create</code>, <code>update</code>, <code>upsert</code>, <code>delete</code>)` : "";
17379
+ return `<p><b>Prisma calls.</b> ${plural2(orm.calls, "Prisma Client read")} (<code>findMany</code>, <code>findFirst</code>, <code>findUnique</code>)${writes} in the ${plural2(orm.read.length, "file")} this branch adds or changes, against the module's Prisma schemas and the indexes their migrations create.</p>${noSchema(orm)}${fileList(orm.read)}`;
17380
+ }
17381
+ function noSchema(orm) {
17382
+ if (orm.calls + orm.writes === 0 || orm.schemas === void 0 || orm.schemas.length > 0) return "";
17383
+ return `<p class="note">${prose2(NO_SCHEMA)}</p>`;
17384
+ }
16457
17385
  function fileList(files) {
16458
17386
  if (files.length === 0) return "";
16459
17387
  return `<details><summary>${files.length === 1 ? "The file" : `The ${grouped(files.length)} files`}</summary><ul>${files.map((file) => `<li><code>${escape(file)}</code></li>`).join("")}</ul></details>`;
@@ -16528,6 +17456,7 @@ function renderMarkdown5(report) {
16528
17456
  ...syntaxBlock(report),
16529
17457
  ...unsafeBlock(report),
16530
17458
  ...templatesLine2(report),
17459
+ ...noSchemaLine(report),
16531
17460
  ...fileBlocks(report),
16532
17461
  "",
16533
17462
  `<sub>Every place, with the SQL behind it and sentinel's notes, is in the \`sql.html\` this run keeps. Measured by sentinel ${report.sentinel}.</sub>`,
@@ -16540,7 +17469,10 @@ function headline4(report) {
16540
17469
  const migrations = report.read.length;
16541
17470
  const files = report.unsafe.read.length;
16542
17471
  const templates = report.templates.read.length > 0 ? report.templates.templates : 0;
16543
- if (migrations === 0 && files === 0 && templates === 0) {
17472
+ const ormCalls = report.orm !== void 0 && report.orm.read.length > 0 ? report.orm.calls : 0;
17473
+ const ormWrites = report.orm !== void 0 && report.orm.read.length > 0 ? report.orm.writes : 0;
17474
+ const schemas = report.schemaChanges?.length ?? 0;
17475
+ if (migrations === 0 && files === 0 && templates === 0 && ormCalls === 0 && ormWrites === 0 && schemas === 0) {
16544
17476
  return `No migration or raw SQL call added or changed by this branch, ${against}: nothing to check.`;
16545
17477
  }
16546
17478
  const counts = (count, what, noun) => `**${count}** ${what} ${noun}${count === 1 ? "" : "s"}`;
@@ -16551,9 +17483,16 @@ function headline4(report) {
16551
17483
  const items = [
16552
17484
  ...migrations > 0 ? [`**${migrations}** migration${migrations === 1 ? "" : "s"}`] : [],
16553
17485
  ...files > 0 ? calls : [],
16554
- ...templates > 0 ? [counts(templates, "SQL", "template")] : []
17486
+ ...templates > 0 ? [counts(templates, "SQL", "template")] : [],
17487
+ ...ormCalls > 0 ? [counts(ormCalls, "Prisma", "read")] : [],
17488
+ ...ormWrites > 0 ? [counts(ormWrites, "Prisma", "write")] : [],
17489
+ ...schemas > 0 ? [counts(schemas, "Prisma", "schema")] : []
16555
17490
  ];
16556
- const codeFiles2 = (/* @__PURE__ */ new Set([...report.unsafe.read, ...report.templates.read])).size;
17491
+ const codeFiles2 = (/* @__PURE__ */ new Set([
17492
+ ...report.unsafe.read,
17493
+ ...report.templates.read,
17494
+ ...report.orm?.read ?? []
17495
+ ])).size;
16557
17496
  const where = codeFiles2 > 0 ? ` in ${codeFiles2} file${codeFiles2 === 1 ? "" : "s"}` : "";
16558
17497
  const read2 = items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}${where}` : `${items.join("")}${where}`;
16559
17498
  const findings = countedFindings(report.findings).length;
@@ -16563,7 +17502,7 @@ function headline4(report) {
16563
17502
  return `Read ${read2} this branch adds or changes, ${against}: ${found}.`;
16564
17503
  }
16565
17504
  function readAnything(report) {
16566
- return report.read.length > 0 || report.unsafe.read.length > 0 || report.templates.read.length > 0;
17505
+ return report.read.length > 0 || report.unsafe.read.length > 0 || report.templates.read.length > 0 || (report.orm?.read.length ?? 0) > 0 || (report.schemaChanges?.length ?? 0) > 0;
16567
17506
  }
16568
17507
  function fileBlocks(report) {
16569
17508
  const findings = report.findings.filter((finding3) => finding3.rule !== SYNTAX_ERROR);
@@ -16596,7 +17535,7 @@ function fileBlocks(report) {
16596
17535
  }
16597
17536
  function rowOf2(finding3) {
16598
17537
  const level = finding3.level === "error" ? "\u2717 error" : "warn";
16599
- return `| ${finding3.line} | ${level} | \`${finding3.rule}\` | ${cell3(problemOf(finding3))} |`;
17538
+ return `| ${finding3.line} | ${level} | \`${finding3.rule}\` | ${cell3(problemOf2(finding3))} |`;
16600
17539
  }
16601
17540
  function cell3(text) {
16602
17541
  return text.replace(/\|/g, "\\|").replace(/\s*\n\s*/g, " ");
@@ -16628,6 +17567,12 @@ function syntaxBlock(report) {
16628
17567
  )
16629
17568
  ];
16630
17569
  }
17570
+ function noSchemaLine(report) {
17571
+ const orm = report.orm;
17572
+ if (orm === void 0 || orm.calls + orm.writes === 0 || orm.schemas === void 0 || orm.schemas.length > 0)
17573
+ return [];
17574
+ return ["", `\u26A0\uFE0F **Prisma calls not judged**: ${NO_SCHEMA}`];
17575
+ }
16631
17576
  function templatesLine2(report) {
16632
17577
  const { read: read2, templates, parsed: parsed2, unread, unparsed } = report.templates;
16633
17578
  if (read2.length === 0) return [];
@@ -16675,12 +17620,12 @@ var writesFiles2 = (shapes) => shapes.some((shape) => shape !== "console");
16675
17620
  function writeOutputs2(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
16676
17621
  if (!writesFiles2(shapes)) return [];
16677
17622
  removeOutputs2(cwd, shapes);
16678
- mkdirSync10(join55(cwd, REPORT_DIR3), { recursive: true });
17623
+ mkdirSync10(join58(cwd, REPORT_DIR3), { recursive: true });
16679
17624
  const written = [];
16680
17625
  for (const shape of shapes) {
16681
17626
  if (shape === "console") continue;
16682
- const path2 = join55(REPORT_DIR3, SHAPE_FILE3[shape]);
16683
- writeFileSync13(join55(cwd, path2), render2(report, shape, now));
17627
+ const path2 = join58(REPORT_DIR3, SHAPE_FILE3[shape]);
17628
+ writeFileSync13(join58(cwd, path2), render2(report, shape, now));
16684
17629
  written.push(path2);
16685
17630
  }
16686
17631
  return written;
@@ -16688,7 +17633,7 @@ function writeOutputs2(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
16688
17633
  function removeOutputs2(cwd, keeping = []) {
16689
17634
  for (const [shape, name] of Object.entries(SHAPE_FILE3)) {
16690
17635
  if (keeping.includes(shape)) continue;
16691
- const path2 = join55(cwd, REPORT_DIR3, name);
17636
+ const path2 = join58(cwd, REPORT_DIR3, name);
16692
17637
  if (existsSync38(path2)) unlinkSync3(path2);
16693
17638
  }
16694
17639
  }
@@ -16699,23 +17644,23 @@ function render2(report, shape, now) {
16699
17644
  }
16700
17645
 
16701
17646
  // src/roles/sql/sources.ts
16702
- import { existsSync as existsSync39, readFileSync as readFileSync32, realpathSync as realpathSync2 } from "node:fs";
16703
- import { dirname as dirname10, join as join56, relative as relative10, resolve as resolve9, sep as sep6 } from "node:path";
16704
- import { globSync as globSync4 } from "tinyglobby";
17647
+ import { existsSync as existsSync39, readFileSync as readFileSync34, realpathSync as realpathSync2 } from "node:fs";
17648
+ import { dirname as dirname11, join as join59, matchesGlob as matchesGlob3, relative as relative11, resolve as resolve9, sep as sep6 } from "node:path";
17649
+ import { globSync as globSync5 } from "tinyglobby";
16705
17650
  var WALK2 = { onlyFiles: true, dot: false, followSymbolicLinks: false };
16706
17651
  var ADOPTION_FILE = "sql.config.mjs";
16707
17652
  function adoptedInnerModules(cwd, nested) {
16708
17653
  return (nested ?? adoptedInnerDirs(cwd)).map((dir) => `${dir}/**`);
16709
17654
  }
16710
17655
  function adoptedInnerDirs(cwd) {
16711
- return globSync4([`**/${ADOPTION_FILE}`], {
17656
+ return globSync5([`**/${ADOPTION_FILE}`], {
16712
17657
  ...WALK2,
16713
17658
  cwd,
16714
17659
  ignore: ["**/node_modules/**"]
16715
17660
  }).map((file) => file.slice(0, -ADOPTION_FILE.length - 1)).filter((dir) => dir !== "");
16716
17661
  }
16717
17662
  function migrationFiles(cwd, settings, nested) {
16718
- return globSync4(settings.migrations.include, {
17663
+ return globSync5(settings.migrations.include, {
16719
17664
  ...WALK2,
16720
17665
  cwd,
16721
17666
  ignore: [
@@ -16726,16 +17671,16 @@ function migrationFiles(cwd, settings, nested) {
16726
17671
  }).sort();
16727
17672
  }
16728
17673
  function migrationRoots(cwd, settings, migrations, nested) {
16729
- const locks = globSync4(["**/migration_lock.toml"], {
17674
+ const locks = globSync5(["**/migration_lock.toml"], {
16730
17675
  ...WALK2,
16731
17676
  cwd,
16732
17677
  ignore: ["**/node_modules/**", ...settings.ignore, ...adoptedInnerModules(cwd, nested)]
16733
- }).map((file) => dirname10(file));
16734
- const holding = migrations.map((file) => dirname10(dirname10(file)));
17678
+ }).map((file) => dirname11(file));
17679
+ const holding = migrations.map((file) => dirname11(dirname11(file)));
16735
17680
  return [.../* @__PURE__ */ new Set([...locks, ...holding])].sort();
16736
17681
  }
16737
17682
  function codeFiles(cwd, settings, nested) {
16738
- return globSync4(["**/*.{ts,mts,cts}"], {
17683
+ return globSync5(["**/*.{ts,mts,cts}"], {
16739
17684
  ...WALK2,
16740
17685
  cwd,
16741
17686
  ignore: [
@@ -16746,6 +17691,13 @@ function codeFiles(cwd, settings, nested) {
16746
17691
  ]
16747
17692
  }).sort();
16748
17693
  }
17694
+ function prismaSchemaFiles(cwd, settings, nested) {
17695
+ return globSync5(["**/*.prisma"], {
17696
+ ...WALK2,
17697
+ cwd,
17698
+ ignore: [...settings.ignore, ...adoptedInnerModules(cwd, nested)]
17699
+ }).sort();
17700
+ }
16749
17701
  var UNSAFE_CALL = /\$(?:queryRaw|executeRaw)Unsafe\b/;
16750
17702
  var PRISMA_IMPORT = /from\s*['"]@prisma\//;
16751
17703
  var RAW_CALL = /\.raw\s*\(/;
@@ -16765,7 +17717,7 @@ function callsUnsafe(text) {
16765
17717
  }
16766
17718
  function fileMatches(cwd, file, test) {
16767
17719
  try {
16768
- return test(readFileSync32(join56(cwd, file), "utf8"));
17720
+ return test(readFileSync34(join59(cwd, file), "utf8"));
16769
17721
  } catch {
16770
17722
  return false;
16771
17723
  }
@@ -16775,17 +17727,21 @@ var SQL_TEMPLATE = /\.sql\s*`/;
16775
17727
  function holdsSqlTemplate(text) {
16776
17728
  return PRISMA_TEMPLATE.test(text) || PRISMA_IMPORT.test(text) && SQL_TEMPLATE.test(text);
16777
17729
  }
16778
- function filesWithSql(cwd, files) {
16779
- const found = { unsafe: [], templates: [] };
17730
+ var PRISMA_CALL = /\.(?:find(?:Many|First|Unique)(?:OrThrow)?|create(?:Many(?:AndReturn)?)?|update(?:Many(?:AndReturn)?)?|upsert|delete(?:Many)?)\s*\(|new\s+(?:\w+\.)?PrismaClient\b/;
17731
+ function filesWithSql(cwd, files, tests = []) {
17732
+ const found = { unsafe: [], templates: [], orm: [] };
16780
17733
  for (const file of files) {
16781
17734
  let text;
16782
17735
  try {
16783
- text = readFileSync32(join56(cwd, file), "utf8");
17736
+ text = readFileSync34(join59(cwd, file), "utf8");
16784
17737
  } catch {
16785
17738
  continue;
16786
17739
  }
16787
17740
  if (callsUnsafe(text)) found.unsafe.push(file);
16788
17741
  if (holdsSqlTemplate(text)) found.templates.push(file);
17742
+ if (PRISMA_CALL.test(text) && !tests.some((pattern) => matchesGlob3(file, pattern))) {
17743
+ found.orm.push(file);
17744
+ }
16789
17745
  }
16790
17746
  return found;
16791
17747
  }
@@ -16806,33 +17762,33 @@ function rawSqlInParent(cwd) {
16806
17762
  return void 0;
16807
17763
  }
16808
17764
  const stop = findWorkspaceRoot(here) ?? findRepositoryRoot(here);
16809
- if (stop === void 0 || dirname10(here) === here) return void 0;
16810
- const parent = findModuleRoot(dirname10(here), stop);
16811
- if (parent === void 0 || existsSync39(join56(parent, ADOPTION_FILE))) return void 0;
16812
- const mine = `${relative10(parent, here).split(sep6).join("/")}/`;
17765
+ if (stop === void 0 || dirname11(here) === here) return void 0;
17766
+ const parent = findModuleRoot(dirname11(here), stop);
17767
+ if (parent === void 0 || existsSync39(join59(parent, ADOPTION_FILE))) return void 0;
17768
+ const mine = `${relative11(parent, here).split(sep6).join("/")}/`;
16813
17769
  const files = filesWithUnsafeCalls(
16814
17770
  parent,
16815
17771
  codeFiles(parent, defaults4).filter((file) => !file.startsWith(mine))
16816
17772
  );
16817
17773
  if (files.length === 0) return void 0;
16818
- return { dir: relative10(here, parent).split(sep6).join("/"), files };
17774
+ return { dir: relative11(here, parent).split(sep6).join("/"), files };
16819
17775
  }
16820
17776
  function migrationsInNested(cwd, settings = defaults4, nested = adoptedInnerDirs(cwd)) {
16821
17777
  const out = [];
16822
17778
  for (const dir of nested) {
16823
- const count = migrationFiles(join56(cwd, dir), defaults4).length;
17779
+ const count = migrationFiles(join59(cwd, dir), defaults4).length;
16824
17780
  if (count > 0) out.push({ dir, count, adopted: true });
16825
17781
  }
16826
17782
  const root = resolve9(cwd);
16827
17783
  const owner = /* @__PURE__ */ new Map();
16828
17784
  const counts = /* @__PURE__ */ new Map();
16829
17785
  for (const file of migrationFiles(cwd, settings, nested)) {
16830
- const folder = dirname10(join56(root, file));
17786
+ const folder = dirname11(join59(root, file));
16831
17787
  if (!owner.has(folder)) {
16832
17788
  const project = findModuleRoot(folder, root);
16833
17789
  owner.set(
16834
17790
  folder,
16835
- project === void 0 ? void 0 : relative10(root, project).split(sep6).join("/")
17791
+ project === void 0 ? void 0 : relative11(root, project).split(sep6).join("/")
16836
17792
  );
16837
17793
  }
16838
17794
  const dir = owner.get(folder);
@@ -16842,105 +17798,6 @@ function migrationsInNested(cwd, settings = defaults4, nested = adoptedInnerDirs
16842
17798
  return out.sort((a, b) => a.dir.localeCompare(b.dir));
16843
17799
  }
16844
17800
 
16845
- // src/roles/sql/trigram-indexes.ts
16846
- import { readdirSync as readdirSync11, readFileSync as readFileSync33 } from "node:fs";
16847
- import { join as join57 } from "node:path";
16848
- var TRIGRAM_CLASSES = /* @__PURE__ */ new Set(["gin_trgm_ops", "gist_trgm_ops"]);
16849
- function trigramContext(cwd, own, indexesFrom) {
16850
- let loaded2;
16851
- const once = () => {
16852
- loaded2 ??= readIndexes(cwd, own, indexesFrom);
16853
- return loaded2;
16854
- };
16855
- return { trigramIndexes: () => once().indexes, indexesFrom: () => once().folders };
16856
- }
16857
- function readIndexes(cwd, own, indexesFrom) {
16858
- const read2 = [];
16859
- const empty = [];
16860
- const shared = indexesFrom.flatMap((folder) => {
16861
- const migrations = migrationsIn(join57(cwd, folder)).flatMap(
16862
- (name) => migrationText(cwd, `${folder}/${name}/migration.sql`)
16863
- );
16864
- (migrations.length > 0 ? read2 : empty).push(folder);
16865
- return migrations;
16866
- });
16867
- const ownMigrations = own.flatMap((file) => migrationText(cwd, file));
16868
- return { indexes: trigramIndexesOf([...ownMigrations, ...shared]), folders: { read: read2, empty } };
16869
- }
16870
- function migrationsIn(directory) {
16871
- try {
16872
- return readdirSync11(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
16873
- } catch {
16874
- return [];
16875
- }
16876
- }
16877
- function migrationText(cwd, file) {
16878
- try {
16879
- return [{ file, text: readFileSync33(join57(cwd, file), "utf8") }];
16880
- } catch {
16881
- return [];
16882
- }
16883
- }
16884
- function trigramIndexesOf(migrations) {
16885
- let indexes = [];
16886
- for (const { file, text } of migrations) {
16887
- const parsed2 = parseSql(text);
16888
- if (!parsed2.ok) continue;
16889
- for (const statement of parsed2.statements) indexes = applied(indexes, statement, file);
16890
- }
16891
- return indexes;
16892
- }
16893
- function applied(indexes, statement, file) {
16894
- const created = bodyOf(statement, "IndexStmt");
16895
- if (created) return [...indexes, ...indexesOf(created, file)];
16896
- const dropped = bodyOf(statement, "DropStmt");
16897
- if (dropped) return withoutDropped(indexes, dropped);
16898
- const renamed4 = bodyOf(statement, "RenameStmt");
16899
- if (renamed4) return withRenamed(indexes, renamed4);
16900
- return indexes;
16901
- }
16902
- function indexesOf(index, file) {
16903
- const table = index.relation?.relname;
16904
- if (typeof table !== "string") return [];
16905
- const name = typeof index.idxname === "string" ? index.idxname : void 0;
16906
- return (index.indexParams ?? []).flatMap((param) => {
16907
- const element = bodyOf(param, "IndexElem");
16908
- if (!element || !isTrigram(element)) return [];
16909
- const expression = typeof element.name === "string" ? element.name : expressionKey(element.expr);
16910
- return expression === void 0 ? [] : [{ name, table, expression, file }];
16911
- });
16912
- }
16913
- function isTrigram(element) {
16914
- const name = lastName(element.opclass);
16915
- return name !== void 0 && TRIGRAM_CLASSES.has(name);
16916
- }
16917
- function withoutDropped(indexes, drop) {
16918
- const names = (drop.objects ?? []).flatMap((object) => {
16919
- const last = lastName(bodyOf(object, "List")?.items);
16920
- return last === void 0 ? [] : [last];
16921
- });
16922
- if (drop.removeType === "OBJECT_INDEX")
16923
- return indexes.filter((index) => !names.includes(index.name ?? ""));
16924
- if (drop.removeType === "OBJECT_TABLE")
16925
- return indexes.filter((index) => !names.includes(index.table));
16926
- return indexes;
16927
- }
16928
- function withRenamed(indexes, rename) {
16929
- const from = rename.relation?.relname;
16930
- const to = rename.newname;
16931
- if (typeof from !== "string" || typeof to !== "string") return indexes;
16932
- if (rename.renameType === "OBJECT_INDEX")
16933
- return indexes.map((index) => index.name === from ? { ...index, name: to } : index);
16934
- if (rename.renameType === "OBJECT_TABLE")
16935
- return indexes.map((index) => index.table === from ? { ...index, table: to } : index);
16936
- if (rename.renameType === "OBJECT_COLUMN") {
16937
- return indexes.map(
16938
- (index) => index.table === from && index.expression === rename.subname ? { ...index, expression: to } : index
16939
- );
16940
- }
16941
- return indexes;
16942
- }
16943
-
16944
17801
  // src/roles/sql/adapters/squawk/resolve-squawk.ts
16945
17802
  function resolveSquawk(cwd) {
16946
17803
  return resolveBin(cwd, "squawk") ?? binFromOwnInstall("squawk-cli", "squawk");
@@ -16951,9 +17808,9 @@ function squawkNotFound(cwd) {
16951
17808
 
16952
17809
  // src/roles/sql/adapters/squawk/run-squawk.ts
16953
17810
  import { spawnSync as spawnSync15 } from "node:child_process";
16954
- import { mkdtempSync as mkdtempSync4, readFileSync as readFileSync34, rmSync as rmSync8, writeFileSync as writeFileSync15 } from "node:fs";
17811
+ import { mkdtempSync as mkdtempSync4, readFileSync as readFileSync35, rmSync as rmSync8, writeFileSync as writeFileSync15 } from "node:fs";
16955
17812
  import { tmpdir as tmpdir4 } from "node:os";
16956
- import { join as join59 } from "node:path";
17813
+ import { join as join61 } from "node:path";
16957
17814
 
16958
17815
  // src/roles/sql/adapters/squawk/read-output.ts
16959
17816
  function readSquawkOutput(stdout, stderr) {
@@ -17011,7 +17868,7 @@ function toFinding(entry) {
17011
17868
  // src/roles/sql/adapters/squawk/squawk-config.ts
17012
17869
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync7, writeFileSync as writeFileSync14 } from "node:fs";
17013
17870
  import { tmpdir as tmpdir3 } from "node:os";
17014
- import { join as join58 } from "node:path";
17871
+ import { join as join60 } from "node:path";
17015
17872
  function squawkToml(settings) {
17016
17873
  const squawks = (rule) => !NOT_SQUAWK_CONFIG.includes(rule);
17017
17874
  const off = rulesOff(settings.rules ?? {}).filter(squawks);
@@ -17025,9 +17882,9 @@ function squawkToml(settings) {
17025
17882
  ].join("\n");
17026
17883
  }
17027
17884
  function withSquawkConfig(settings, use) {
17028
- const dir = mkdtempSync3(join58(tmpdir3(), "sentinel-squawk-"));
17885
+ const dir = mkdtempSync3(join60(tmpdir3(), "sentinel-squawk-"));
17029
17886
  try {
17030
- const configPath = join58(dir, "squawk.toml");
17887
+ const configPath = join60(dir, "squawk.toml");
17031
17888
  writeFileSync14(configPath, squawkToml(settings));
17032
17889
  return use(configPath);
17033
17890
  } finally {
@@ -17108,7 +17965,7 @@ function quietTimeoutFiles(invocation, readable, statements, wrapped) {
17108
17965
  for (const file of readable) {
17109
17966
  const read2 = statements.get(file);
17110
17967
  if (read2 === void 0 || !wrapped(file)) continue;
17111
- const text = readText(invocation.cwd, file);
17968
+ const text = readText2(invocation.cwd, file);
17112
17969
  if (text !== void 0 && onlyBuildsNewTables(read2.types, text, false)) texts.set(file, text);
17113
17970
  }
17114
17971
  if (texts.size === 0) return /* @__PURE__ */ new Set();
@@ -17117,9 +17974,9 @@ function quietTimeoutFiles(invocation, readable, statements, wrapped) {
17117
17974
  return new Set([...texts.keys()].filter((file) => !onExisting.has(file)));
17118
17975
  }
17119
17976
  function indexesOnExistingTables(invocation, files) {
17120
- const dir = mkdtempSync4(join59(tmpdir4(), "sentinel-squawk-"));
17977
+ const dir = mkdtempSync4(join61(tmpdir4(), "sentinel-squawk-"));
17121
17978
  try {
17122
- const configPath = join59(dir, "squawk.toml");
17979
+ const configPath = join61(dir, "squawk.toml");
17123
17980
  writeFileSync15(configPath, DEFAULT_SQUAWK_TOML);
17124
17981
  const found = /* @__PURE__ */ new Set();
17125
17982
  for (const batch of batches(files)) {
@@ -17133,9 +17990,9 @@ function indexesOnExistingTables(invocation, files) {
17133
17990
  rmSync8(dir, { recursive: true, force: true });
17134
17991
  }
17135
17992
  }
17136
- function readText(cwd, file) {
17993
+ function readText2(cwd, file) {
17137
17994
  try {
17138
- return readFileSync34(join59(cwd, file), "utf8");
17995
+ return readFileSync35(join61(cwd, file), "utf8");
17139
17996
  } catch {
17140
17997
  return void 0;
17141
17998
  }
@@ -17217,7 +18074,7 @@ function openable(cwd, files) {
17217
18074
  const utf8 = new TextDecoder("utf-8", { fatal: true });
17218
18075
  for (const file of files) {
17219
18076
  try {
17220
- utf8.decode(readFileSync34(join59(cwd, file)));
18077
+ utf8.decode(readFileSync35(join61(cwd, file)));
17221
18078
  readable.push(file);
17222
18079
  } catch (error) {
17223
18080
  unread.push({ file, reason: unreadReason(error) });
@@ -17321,6 +18178,7 @@ function summariseMigrations(outcome) {
17321
18178
  whatWasRead(outcome),
17322
18179
  ...codeReadLines(outcome),
17323
18180
  ...templateLines(outcome.templates),
18181
+ ...ormLines(outcome.orm),
17324
18182
  ...offLines(outcome),
17325
18183
  ...unreadLines(outcome.unread),
17326
18184
  ...unparsedLines(outcome.code.unparsed),
@@ -17356,6 +18214,19 @@ function codeReadLines({ code, rulesOff: rulesOff2 }) {
17356
18214
  `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.` : "")
17357
18215
  ];
17358
18216
  }
18217
+ function ormLines(orm) {
18218
+ if (orm === void 0 || orm.files === 0) return [];
18219
+ if (orm.read === 0) {
18220
+ return [
18221
+ `${orm.files} file(s) make Prisma Client calls; none is added or changed by this branch, so none is read.`
18222
+ ];
18223
+ }
18224
+ return [
18225
+ `read ${orm.calls} Prisma Client read(s) (findMany, findFirst, findUnique) and ${orm.writes} write(s) (create, update, upsert, delete) in the ${orm.read} file(s) this branch adds or changes.`,
18226
+ ...orm.calls + orm.writes > 0 && orm.schemas.length === 0 ? [` ${NO_SCHEMA}`] : [],
18227
+ ...orm.unparsed.map(({ file, reason }) => ` ${file}: ${reason}`)
18228
+ ];
18229
+ }
17359
18230
  var TEMPLATE_PLACES = 3;
17360
18231
  var TEMPLATE_TAGS = "$queryRaw, $executeRaw, Prisma.sql";
17361
18232
  function templateLines(templates) {
@@ -17512,7 +18383,7 @@ var SquawkAdapter = class extends BaseAdapter {
17512
18383
  skipped: `no migration (${defaults4.migrations.include.join(", ")}) and no raw SQL call in this module: nothing for the ${TARGET3} role to read.`
17513
18384
  };
17514
18385
  }
17515
- const hasConfig = existsSync40(join60(context2.cwd, SQL_CONFIG_FILE));
18386
+ const hasConfig = existsSync40(join62(context2.cwd, SQL_CONFIG_FILE));
17516
18387
  const declared = moduleScripts(context2.cwd);
17517
18388
  const missingScripts = Object.keys(scripts2()).filter((name) => !(name in declared));
17518
18389
  return {
@@ -17613,7 +18484,7 @@ var SquawkAdapter = class extends BaseAdapter {
17613
18484
  const reading = whatTheModuleHolds(ctx.cwd, config);
17614
18485
  const selection = branchFiles(ctx.cwd, reading);
17615
18486
  if (!selection.ok) return failing(selection.reason, countsOf(reading));
17616
- const { read: read2, base, code, templateCode } = selection;
18487
+ const { read: read2, base, code, templateCode, ormCode, schemaCode } = selection;
17617
18488
  const run = this.checkMigrations(ctx.cwd, config, read2);
17618
18489
  if (!run.ok) return failing(run.reason, countsOf(reading));
17619
18490
  const history = appliedChanges(ctx.cwd, config, base ?? selection.quietBase, reading.nested);
@@ -17623,6 +18494,16 @@ var SquawkAdapter = class extends BaseAdapter {
17623
18494
  rules: templateRules(config.rules),
17624
18495
  context: trigramContext(ctx.cwd, reading.migrations, config.migrations.indexesFrom)
17625
18496
  });
18497
+ const orm = await checkOrmCalls(ctx.cwd, ormCode, readAbsolute, {
18498
+ rules: ormRules(config.rules),
18499
+ context: ormContext(ctx.cwd, {
18500
+ indexesFrom: config.migrations.indexesFrom,
18501
+ referenceTables: config.orm.referenceTables,
18502
+ perRowWrites: config.orm.perRowWrites,
18503
+ scripts: config.orm.scripts,
18504
+ ignore: config.ignore
18505
+ })
18506
+ });
17626
18507
  const findings = withNotes(
17627
18508
  [
17628
18509
  ...history.findings,
@@ -17630,9 +18511,11 @@ var SquawkAdapter = class extends BaseAdapter {
17630
18511
  ...run.findings,
17631
18512
  ...enumFindings(ctx.cwd, config, read2, run),
17632
18513
  ...unsafe.findings,
17633
- ...templates.findings
18514
+ ...templates.findings,
18515
+ ...orm.findings,
18516
+ ...await schemaFindings(ctx.cwd, config, schemaCode, base)
17634
18517
  ],
17635
- (file) => readText2(ctx.cwd, file),
18518
+ (file) => readText3(ctx.cwd, file),
17636
18519
  config.rules
17637
18520
  );
17638
18521
  const outcome = {
@@ -17649,12 +18532,20 @@ var SquawkAdapter = class extends BaseAdapter {
17649
18532
  rawCalls: unsafe.rawCalls,
17650
18533
  unparsed: unsafe.unparsed
17651
18534
  },
17652
- templates: templatesOutcome(reading, templateCode, templates)
18535
+ templates: templatesOutcome(reading, templateCode, templates),
18536
+ orm: {
18537
+ files: reading.orm.length,
18538
+ read: ormCode.length,
18539
+ calls: orm.calls,
18540
+ writes: orm.writes,
18541
+ schemas: orm.schemas,
18542
+ unparsed: orm.unparsed
18543
+ }
17653
18544
  };
17654
18545
  if (mode.speaking) {
17655
18546
  for (const line of describeRun(outcome, reading, config, selection.quietNote)) this.say(line);
17656
18547
  for (const dir of reading.nested) {
17657
- const count = migrationFiles(join60(ctx.cwd, dir), defaults4).length;
18548
+ const count = migrationFiles(join62(ctx.cwd, dir), defaults4).length;
17658
18549
  if (count > 0)
17659
18550
  this.say(
17660
18551
  `the ${count} migration(s) under ${dir} are reported by that project, which adopted the role itself.`
@@ -17666,7 +18557,7 @@ var SquawkAdapter = class extends BaseAdapter {
17666
18557
  reportOf(
17667
18558
  ctx,
17668
18559
  config,
17669
- { reading, read: read2, code: unsafeOff ? [] : code, templateCode },
18560
+ { reading, read: read2, code: unsafeOff ? [] : code, templateCode, ormCode, schemaCode },
17670
18561
  {
17671
18562
  outcome,
17672
18563
  findings
@@ -17732,7 +18623,7 @@ var SquawkAdapter = class extends BaseAdapter {
17732
18623
  const expected = Object.keys(scripts2());
17733
18624
  const missing = expected.filter((name) => !(name in declared));
17734
18625
  const adopted = missing.length < expected.length;
17735
- const hasConfig = existsSync40(join60(ctx.cwd, SQL_CONFIG_FILE));
18626
+ const hasConfig = existsSync40(join62(ctx.cwd, SQL_CONFIG_FILE));
17736
18627
  return {
17737
18628
  adopted,
17738
18629
  preset: adopted ? ctx.preset : null,
@@ -17776,7 +18667,7 @@ function formatterReason(pass) {
17776
18667
  return ` (${said.length > 200 ? `${said.slice(0, 197)}\u2026` : said})`;
17777
18668
  }
17778
18669
  function describeRun(outcome, reading, config, quietNote = null) {
17779
- const holdsCode = reading.unsafeFiles > 0 || reading.templates.length > 0;
18670
+ const holdsCode = reading.unsafeFiles > 0 || reading.templates.length > 0 || reading.orm.length > 0;
17780
18671
  if (outcome.total === 0 && !holdsCode && outcome.findings.length === 0) {
17781
18672
  return [
17782
18673
  `nothing to read here: no migration (${config.migrations.include.join(", ")}) and no raw SQL call in ${reading.codeFiles} TypeScript file(s).`,
@@ -17786,10 +18677,18 @@ function describeRun(outcome, reading, config, quietNote = null) {
17786
18677
  return summariseMigrations(outcome);
17787
18678
  }
17788
18679
  function branchFiles(cwd, reading) {
17789
- const { migrations, unsafe, templates } = reading;
17790
- if (migrations.length === 0 && unsafe.length === 0 && templates.length === 0) {
18680
+ const { migrations, unsafe, templates, orm, schemas } = reading;
18681
+ if (migrations.length === 0 && unsafe.length === 0 && templates.length === 0 && orm.length === 0 && schemas.length === 0) {
17791
18682
  const quiet = branchChanges(cwd, process.env, "migrations and raw SQL calls");
17792
- const none = { ok: true, read: [], code: [], templateCode: [], base: null };
18683
+ const none = {
18684
+ ok: true,
18685
+ read: [],
18686
+ code: [],
18687
+ templateCode: [],
18688
+ ormCode: [],
18689
+ schemaCode: [],
18690
+ base: null
18691
+ };
17793
18692
  if (quiet.ok) return { ...none, quietBase: quiet.base, quietNote: null };
17794
18693
  const quietNote = insideRepository(cwd) ? `the migrations this branch deletes were not looked for: ${quiet.reason}` : null;
17795
18694
  return { ...none, quietBase: null, quietNote };
@@ -17802,6 +18701,8 @@ function branchFiles(cwd, reading) {
17802
18701
  read: changed(migrations),
17803
18702
  code: changed(unsafe),
17804
18703
  templateCode: changed(templates),
18704
+ ormCode: changed(orm),
18705
+ schemaCode: changed(schemas),
17805
18706
  base: changes.base,
17806
18707
  quietBase: null,
17807
18708
  quietNote: null
@@ -17822,6 +18723,21 @@ function appliedChanges(cwd, config, base, nested) {
17822
18723
  if (!reading.ok) return reading;
17823
18724
  return { ok: true, findings: historyFindings(reading.changes, base.ref) };
17824
18725
  }
18726
+ async function schemaFindings(cwd, config, schemas, base) {
18727
+ const foreignKeys = config.rules[ORM_FK_INDEX_RULE] !== "off";
18728
+ const naming = config.rules[ORM_MODEL_NAMING_RULE] !== "off";
18729
+ if (base === null || schemas.length === 0 || !(foreignKeys || naming)) return [];
18730
+ const changes = schemas.flatMap((file) => {
18731
+ const text = readText3(cwd, file);
18732
+ const before = textAtCommit(cwd, base.sha, file);
18733
+ return text === void 0 || before === void 0 ? [] : [{ file, text, base: before }];
18734
+ });
18735
+ const indexed = foreignKeys && (await parserLoaded()).ok;
18736
+ return [
18737
+ ...indexed ? foreignKeyFindings(cwd, changes) : [],
18738
+ ...naming ? modelNamingFindings(changes) : []
18739
+ ];
18740
+ }
17825
18741
  function missingFiles(cwd, config, reading, said) {
17826
18742
  if (config.rules[FOLDER_RULE] === "off") return [];
17827
18743
  const already = new Set(said.map((finding3) => finding3.file));
@@ -17834,20 +18750,22 @@ function enumFindings(cwd, config, files, run) {
17834
18750
  if (config.rules[ENUM_VALUE_RULE] === "off") return [];
17835
18751
  return files.flatMap((file) => {
17836
18752
  const count = run.statementCounts?.get(file);
17837
- const text = count === void 0 ? void 0 : readText2(cwd, file);
18753
+ const text = count === void 0 ? void 0 : readText3(cwd, file);
17838
18754
  return count === void 0 || text === void 0 ? [] : enumValueFindings(file, text, count);
17839
18755
  });
17840
18756
  }
17841
18757
  function whatTheModuleHolds(cwd, config) {
17842
18758
  const nested = adoptedInnerDirs(cwd);
17843
18759
  const code = codeFiles(cwd, config, nested);
17844
- const { unsafe, templates } = filesWithSql(cwd, code);
18760
+ const { unsafe, templates, orm } = filesWithSql(cwd, code, config.unsafe.tests);
17845
18761
  return {
17846
18762
  migrations: migrationFiles(cwd, config, nested),
17847
18763
  codeFiles: code.length,
17848
18764
  unsafe,
17849
18765
  unsafeFiles: unsafe.length,
17850
18766
  templates,
18767
+ orm,
18768
+ schemas: prismaSchemaFiles(cwd, config, nested),
17851
18769
  nested
17852
18770
  };
17853
18771
  }
@@ -17901,7 +18819,7 @@ function metricsOf(outcome) {
17901
18819
  };
17902
18820
  }
17903
18821
  function reportOf(ctx, config, files, result) {
17904
- const { reading, read: read2, code, templateCode } = files;
18822
+ const { reading, read: read2, code, templateCode, ormCode, schemaCode } = files;
17905
18823
  const { outcome, findings } = result;
17906
18824
  return {
17907
18825
  module: ctx.module,
@@ -17929,19 +18847,28 @@ function reportOf(ctx, config, files, result) {
17929
18847
  unread: [...outcome.templates.unread],
17930
18848
  unparsed: [...outcome.templates.unparsed]
17931
18849
  },
18850
+ orm: {
18851
+ files: reading.orm,
18852
+ read: [...ormCode],
18853
+ calls: outcome.orm?.calls ?? 0,
18854
+ writes: outcome.orm?.writes ?? 0,
18855
+ schemas: [...outcome.orm?.schemas ?? []],
18856
+ unparsed: [...outcome.orm?.unparsed ?? []]
18857
+ },
18858
+ schemaChanges: [...schemaCode],
17932
18859
  settings: settingsList2(config)
17933
18860
  };
17934
18861
  }
17935
18862
  function readAbsolute(path2) {
17936
18863
  try {
17937
- return readFileSync35(path2, "utf8");
18864
+ return readFileSync36(path2, "utf8");
17938
18865
  } catch {
17939
18866
  return void 0;
17940
18867
  }
17941
18868
  }
17942
- function readText2(cwd, file) {
18869
+ function readText3(cwd, file) {
17943
18870
  try {
17944
- return readFileSync35(join60(cwd, file), "utf8");
18871
+ return readFileSync36(join62(cwd, file), "utf8");
17945
18872
  } catch {
17946
18873
  return void 0;
17947
18874
  }
@@ -17986,9 +18913,9 @@ function registerSql() {
17986
18913
 
17987
18914
  // src/roles/static-analysis/adapters/jscpd/jscpd.adapter.ts
17988
18915
  import { spawnSync as spawnSync18 } from "node:child_process";
17989
- import { existsSync as existsSync44, mkdirSync as mkdirSync12, readFileSync as readFileSync39, unlinkSync as unlinkSync4, writeFileSync as writeFileSync17 } from "node:fs";
17990
- import { join as join65, relative as relative11, sep as sep7 } from "node:path";
17991
- import { globSync as globSync8 } from "tinyglobby";
18916
+ import { existsSync as existsSync44, mkdirSync as mkdirSync12, readFileSync as readFileSync40, unlinkSync as unlinkSync4, writeFileSync as writeFileSync17 } from "node:fs";
18917
+ import { join as join67, relative as relative12, sep as sep7 } from "node:path";
18918
+ import { globSync as globSync9 } from "tinyglobby";
17992
18919
 
17993
18920
  // src/roles/static-analysis/bundle/budgets.ts
17994
18921
  var TRANSFER_REFERENCES = {
@@ -18016,31 +18943,31 @@ function bandFor(valueKb, referenceKb) {
18016
18943
  }
18017
18944
 
18018
18945
  // src/roles/static-analysis/bundle/scan.ts
18019
- import { existsSync as existsSync42, readFileSync as readFileSync37 } from "node:fs";
18020
- import { basename as basename4, join as join62 } from "node:path";
18946
+ import { existsSync as existsSync42, readFileSync as readFileSync38 } from "node:fs";
18947
+ import { basename as basename4, join as join64 } from "node:path";
18021
18948
  import { pathToFileURL as pathToFileURL7 } from "node:url";
18022
18949
  import { gzipSync } from "node:zlib";
18023
- import { globSync as globSync6 } from "tinyglobby";
18950
+ import { globSync as globSync7 } from "tinyglobby";
18024
18951
 
18025
18952
  // src/roles/static-analysis/bundle/find-build.ts
18026
- import { existsSync as existsSync41, readFileSync as readFileSync36, statSync as statSync8 } from "node:fs";
18027
- import { join as join61 } from "node:path";
18028
- import { globSync as globSync5 } from "tinyglobby";
18953
+ import { existsSync as existsSync41, readFileSync as readFileSync37, statSync as statSync8 } from "node:fs";
18954
+ import { join as join63 } from "node:path";
18955
+ import { globSync as globSync6 } from "tinyglobby";
18029
18956
  var MANIFEST_GLOB = "server/_tanstack-start-manifest*.mjs";
18030
18957
  function candidateDirs(cwd) {
18031
18958
  const declared = readProjectPackageJson(cwd).nx?.targets?.build?.["outputs"];
18032
- const fromDeclaration = Array.isArray(declared) ? declared.filter((token) => typeof token === "string").map((token) => join61(cwd, token.replace(/^\{projectRoot\}\//, ""))) : [];
18033
- return [...fromDeclaration, join61(cwd, ".output"), join61(cwd, "dist"), join61(cwd, "build")];
18959
+ const fromDeclaration = Array.isArray(declared) ? declared.filter((token) => typeof token === "string").map((token) => join63(cwd, token.replace(/^\{projectRoot\}\//, ""))) : [];
18960
+ return [...fromDeclaration, join63(cwd, ".output"), join63(cwd, "dist"), join63(cwd, "build")];
18034
18961
  }
18035
18962
  function findBuildOutput(cwd) {
18036
18963
  const lookedIn = [];
18037
18964
  for (const dir of candidateDirs(cwd)) {
18038
18965
  lookedIn.push(dir);
18039
18966
  if (!existsSync41(dir)) continue;
18040
- const found = globSync5(MANIFEST_GLOB, { cwd: dir, absolute: true, dot: false });
18967
+ const found = globSync6(MANIFEST_GLOB, { cwd: dir, absolute: true, dot: false });
18041
18968
  if (found.length === 0) continue;
18042
18969
  const manifestPath = found[0];
18043
- const publicDir = join61(dir, "public");
18970
+ const publicDir = join63(dir, "public");
18044
18971
  if (!existsSync41(publicDir)) continue;
18045
18972
  return { manifestPath, publicDir, ...dateOf(dir, manifestPath) };
18046
18973
  }
@@ -18063,10 +18990,10 @@ function findBuildOutput(cwd) {
18063
18990
  };
18064
18991
  }
18065
18992
  function dateOf(dir, manifestPath) {
18066
- const record = join61(dir, "nitro.json");
18993
+ const record = join63(dir, "nitro.json");
18067
18994
  if (existsSync41(record)) {
18068
18995
  try {
18069
- const parsed2 = JSON.parse(readFileSync36(record, "utf8"));
18996
+ const parsed2 = JSON.parse(readFileSync37(record, "utf8"));
18070
18997
  if (typeof parsed2.date === "string") {
18071
18998
  const date = new Date(parsed2.date);
18072
18999
  if (!Number.isNaN(date.getTime())) return { builtAt: date, builtAtFrom: "build record" };
@@ -18092,9 +19019,9 @@ function kindOf3(path2) {
18092
19019
  return "other";
18093
19020
  }
18094
19021
  function resolveAnnounced(publicDir, announced) {
18095
- const direct = join62(publicDir, announced);
19022
+ const direct = join64(publicDir, announced);
18096
19023
  if (existsSync42(direct)) return direct;
18097
- const stripped = join62(publicDir, announced.replace(/^\/[^/]+\//, "/"));
19024
+ const stripped = join64(publicDir, announced.replace(/^\/[^/]+\//, "/"));
18098
19025
  return existsSync42(stripped) ? stripped : void 0;
18099
19026
  }
18100
19027
  function emptyWeight() {
@@ -18131,7 +19058,7 @@ async function scanBundle(cwd) {
18131
19058
  unresolved.push(announced);
18132
19059
  measured.set(announced, void 0);
18133
19060
  } else {
18134
- const buffer = readFileSync37(path2);
19061
+ const buffer = readFileSync38(path2);
18135
19062
  measured.set(announced, {
18136
19063
  parsed: buffer.length,
18137
19064
  transfer: gzipSync(buffer, { level: 9 }).length
@@ -18211,14 +19138,14 @@ function scanDynamicLayer(publicDir, references) {
18211
19138
  const referenced = new Set([...references].map((announced) => basename4(announced)));
18212
19139
  const groups = /* @__PURE__ */ new Map();
18213
19140
  const all2 = emptyWeight();
18214
- for (const path2 of globSync6("assets/*.{js,mjs,cjs}", {
19141
+ for (const path2 of globSync7("assets/*.{js,mjs,cjs}", {
18215
19142
  cwd: publicDir,
18216
19143
  absolute: true,
18217
19144
  dot: false
18218
19145
  })) {
18219
19146
  const name = basename4(path2);
18220
19147
  if (referenced.has(name)) continue;
18221
- const buffer = readFileSync37(path2);
19148
+ const buffer = readFileSync38(path2);
18222
19149
  const size = { parsed: buffer.length, transfer: gzipSync(buffer, { level: 9 }).length };
18223
19150
  add(all2, size);
18224
19151
  const group = groupOf(name);
@@ -18279,7 +19206,7 @@ function collectComplexity() {
18279
19206
 
18280
19207
  // src/roles/static-analysis/coverage.ts
18281
19208
  import path from "node:path";
18282
- import { globSync as globSync7 } from "tinyglobby";
19209
+ import { globSync as globSync8 } from "tinyglobby";
18283
19210
  var UNREADABLE_EXTENSIONS = [".svelte", ".vue", ".astro"];
18284
19211
  function hasUnreadableCode(coverage) {
18285
19212
  return coverage.unread > 0;
@@ -18289,9 +19216,9 @@ function coverageOf(cwd, config) {
18289
19216
  const readable = extensionsOf(config.languages).map((extension) => extension.slice(1)).join(",");
18290
19217
  const roots = measuredRoots(cwd);
18291
19218
  const under2 = (extensions) => roots.map((root) => root === "." ? `**/*.{${extensions}}` : `${root}/**/*.{${extensions}}`);
18292
- const read2 = readable ? globSync7(under2(readable), { cwd, ignore, dot: false }).length : 0;
19219
+ const read2 = readable ? globSync8(under2(readable), { cwd, ignore, dot: false }).length : 0;
18293
19220
  const unreadable = UNREADABLE_EXTENSIONS.map((extension) => extension.slice(1)).join(",");
18294
- const found = globSync7(under2(unreadable), { cwd, ignore, dot: false });
19221
+ const found = globSync8(under2(unreadable), { cwd, ignore, dot: false });
18295
19222
  const total = read2 + found.length;
18296
19223
  return {
18297
19224
  read: read2,
@@ -18310,7 +19237,7 @@ function unreadableNote(coverage) {
18310
19237
  import { spawnSync as spawnSync17 } from "node:child_process";
18311
19238
  import { existsSync as existsSync43, mkdirSync as mkdirSync11, mkdtempSync as mkdtempSync5, rmSync as rmSync9, writeFileSync as writeFileSync16 } from "node:fs";
18312
19239
  import { tmpdir as tmpdir5 } from "node:os";
18313
- import { join as join63 } from "node:path";
19240
+ import { join as join65 } from "node:path";
18314
19241
  var ROOT_FILES = ["nx.json", "tsconfig.base.json"];
18315
19242
  function git5(cwd, args) {
18316
19243
  const run = spawnSync17("git", args, { cwd, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
@@ -18336,9 +19263,9 @@ function checkoutModuleAt(workspaceRoot, modulePath, sha) {
18336
19263
  if (!listed.ok) return { ok: false, reason: `git could not list the base: ${listed.said}` };
18337
19264
  const present = new Set(listed.out.split("\n").filter((line) => line !== ""));
18338
19265
  const existed = present.has(modulePath);
18339
- const root = mkdtempSync5(join63(tmpdir5(), "sentinel-static-base-"));
19266
+ const root = mkdtempSync5(join65(tmpdir5(), "sentinel-static-base-"));
18340
19267
  const dispose = () => rmSync9(root, { recursive: true, force: true });
18341
- const moduleDir = join63(root, modulePath);
19268
+ const moduleDir = join65(root, modulePath);
18342
19269
  mkdirSync11(moduleDir, { recursive: true });
18343
19270
  const paths2 = [
18344
19271
  ...ROOT_FILES.filter((file) => present.has(file)),
@@ -18365,7 +19292,7 @@ function checkoutModuleAt(workspaceRoot, modulePath, sha) {
18365
19292
  };
18366
19293
  }
18367
19294
  }
18368
- if (!existsSync43(join63(root, "nx.json"))) writeFileSync16(join63(root, "nx.json"), "{}\n");
19295
+ if (!existsSync43(join65(root, "nx.json"))) writeFileSync16(join65(root, "nx.json"), "{}\n");
18369
19296
  return { ok: true, moduleDir, existed, dispose };
18370
19297
  }
18371
19298
 
@@ -18462,21 +19389,21 @@ function comparePlaces(branch, base, renames) {
18462
19389
  }
18463
19390
 
18464
19391
  // src/roles/static-analysis/excerpt.ts
18465
- import { readFileSync as readFileSync38 } from "node:fs";
18466
- import { join as join64 } from "node:path";
19392
+ import { readFileSync as readFileSync39 } from "node:fs";
19393
+ import { join as join66 } from "node:path";
18467
19394
  var WINDOW = { lines: 10, nesting: { before: 3, after: 6 } };
18468
19395
  var NESTS_UPWARD = /* @__PURE__ */ new Set(["max-depth", "max-nested-callbacks"]);
18469
19396
  var SHOWS_THE_HEAD = /* @__PURE__ */ new Set(["max-lines"]);
18470
19397
  var WHOLE_FILE = /* @__PURE__ */ new Set(["unusedFiles", "usedOnlyByTests"]);
18471
- function linesOf(cache, cwd, relative12) {
18472
- if (cache.has(relative12)) return cache.get(relative12);
19398
+ function linesOf(cache, cwd, relative13) {
19399
+ if (cache.has(relative13)) return cache.get(relative13);
18473
19400
  let lines;
18474
19401
  try {
18475
- lines = readFileSync38(join64(cwd, relative12), "utf8").split("\n");
19402
+ lines = readFileSync39(join66(cwd, relative13), "utf8").split("\n");
18476
19403
  } catch {
18477
19404
  lines = void 0;
18478
19405
  }
18479
- cache.set(relative12, lines);
19406
+ cache.set(relative13, lines);
18480
19407
  return lines;
18481
19408
  }
18482
19409
  function pointOf(path2) {
@@ -18790,7 +19717,7 @@ var JscpdAdapter = class extends BaseAdapter {
18790
19717
  operations: [
18791
19718
  // `write` and not `merge-json`: this file is code, and the engine's in-place merge is for
18792
19719
  // JSON. A re-init therefore RESTORES the stub, so an existing one is left alone below.
18793
- ...existsSync44(join65(context2.cwd, STATIC_CONFIG_FILE)) ? [] : [{ kind: "write", path: STATIC_CONFIG_FILE, contents: configStub5() }],
19720
+ ...existsSync44(join67(context2.cwd, STATIC_CONFIG_FILE)) ? [] : [{ kind: "write", path: STATIC_CONFIG_FILE, contents: configStub5() }],
18794
19721
  manifestOperation(context2.cwd, scripts3()),
18795
19722
  ...nxTargetOperations({ cwd: context2.cwd, targets: targets3() })
18796
19723
  // The report directory is ignored ONCE at the workspace root, by `--init`'s workspace prep,
@@ -19012,7 +19939,7 @@ var JscpdAdapter = class extends BaseAdapter {
19012
19939
  const declared = moduleScripts(ctx.cwd);
19013
19940
  const missing = Object.keys(scripts3()).filter((name) => !(name in declared));
19014
19941
  const adopted = missing.length < Object.keys(scripts3()).length;
19015
- const hasConfig = existsSync44(join65(ctx.cwd, STATIC_CONFIG_FILE));
19942
+ const hasConfig = existsSync44(join67(ctx.cwd, STATIC_CONFIG_FILE));
19016
19943
  return {
19017
19944
  adopted,
19018
19945
  preset: adopted ? ctx.preset : null,
@@ -19104,7 +20031,7 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19104
20031
  try {
19105
20032
  const ran = runTool(jscpd, args, cwd, "dead-code");
19106
20033
  if (ran.kind !== "ran") return ran;
19107
- const path2 = join65(rawReportDir, RAW_REPORT["dead-code"]);
20034
+ const path2 = join67(rawReportDir, RAW_REPORT["dead-code"]);
19108
20035
  if (!existsSync44(path2)) {
19109
20036
  process.stderr.write(
19110
20037
  `sentinel static-analysis(jscpd): the dead-code pass wrote no ${RAW_REPORT["dead-code"]}
@@ -19112,7 +20039,7 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19112
20039
  );
19113
20040
  return { kind: "failed", code: 1 };
19114
20041
  }
19115
- const parsed2 = safeParseDeadCode(readFileSync39(path2, "utf8"));
20042
+ const parsed2 = safeParseDeadCode(readFileSync40(path2, "utf8"));
19116
20043
  const statistics = parsed2?.statistics;
19117
20044
  if (!statistics) {
19118
20045
  process.stderr.write(
@@ -19135,11 +20062,11 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19135
20062
  }
19136
20063
  }
19137
20064
  function moduleRelative(name, roots, cwd) {
19138
- if (existsSync44(join65(cwd, name))) return name;
20065
+ if (existsSync44(join67(cwd, name))) return name;
19139
20066
  for (const root of roots) {
19140
20067
  if (root === ".") continue;
19141
20068
  const candidate = `${root}/${name}`;
19142
- if (existsSync44(join65(cwd, candidate))) return candidate;
20069
+ if (existsSync44(join67(cwd, candidate))) return candidate;
19143
20070
  }
19144
20071
  return name;
19145
20072
  }
@@ -19148,8 +20075,8 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19148
20075
  try {
19149
20076
  const ran = runTool(jscpd, args, cwd, scope);
19150
20077
  if (ran.kind !== "ran") return ran;
19151
- const path2 = join65(rawReportDir, RAW_REPORT.duplication);
19152
- const parsed2 = existsSync44(path2) ? safeParse(readFileSync39(path2, "utf8")) : void 0;
20078
+ const path2 = join67(rawReportDir, RAW_REPORT.duplication);
20079
+ const parsed2 = existsSync44(path2) ? safeParse(readFileSync40(path2, "utf8")) : void 0;
19153
20080
  const total = parsed2?.statistics?.total;
19154
20081
  if (!total) {
19155
20082
  process.stderr.write(
@@ -19159,7 +20086,7 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19159
20086
  return { kind: "failed", code: 1 };
19160
20087
  }
19161
20088
  const seen = /* @__PURE__ */ new Map();
19162
- const relative12 = (name) => {
20089
+ const relative13 = (name) => {
19163
20090
  if (name === void 0) return void 0;
19164
20091
  const hit = seen.get(name);
19165
20092
  if (hit !== void 0) return hit;
@@ -19173,8 +20100,8 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19173
20100
  formats: parsed2?.statistics?.formats ?? {},
19174
20101
  duplicates: (parsed2?.duplicates ?? []).map((entry) => ({
19175
20102
  ...entry,
19176
- ...entry.firstFile ? { firstFile: { ...entry.firstFile, name: relative12(entry.firstFile.name) } } : {},
19177
- ...entry.secondFile ? { secondFile: { ...entry.secondFile, name: relative12(entry.secondFile.name) } } : {}
20103
+ ...entry.firstFile ? { firstFile: { ...entry.firstFile, name: relative13(entry.firstFile.name) } } : {},
20104
+ ...entry.secondFile ? { secondFile: { ...entry.secondFile, name: relative13(entry.secondFile.name) } } : {}
19178
20105
  }))
19179
20106
  };
19180
20107
  } finally {
@@ -19408,7 +20335,7 @@ async function deltaAgainstBase(inputs, branch) {
19408
20335
  });
19409
20336
  const workspaceRoot = workspaceRootFrom(ctx.cwd);
19410
20337
  if (workspaceRoot === void 0) return unavailable("the module is not inside a workspace");
19411
- const modulePath = relative11(workspaceRoot, ctx.cwd).split(sep7).join("/");
20338
+ const modulePath = relative12(workspaceRoot, ctx.cwd).split(sep7).join("/");
19412
20339
  const moved = branchRenames(ctx.cwd, changes.base.sha);
19413
20340
  if (!moved.ok) return unavailable(moved.reason);
19414
20341
  const checkout = checkoutModuleAt(workspaceRoot, modulePath, changes.base.sha);
@@ -19437,9 +20364,9 @@ function moduleRenames(cwd, renames) {
19437
20364
  function moduleRootsOf(workspaceRoot) {
19438
20365
  const roots = [];
19439
20366
  for (const area of ["apps", "libs"]) {
19440
- const base = join65(workspaceRoot, area);
20367
+ const base = join67(workspaceRoot, area);
19441
20368
  if (!existsSync44(base)) continue;
19442
- for (const entry of globSync8([`${area}/**/package.json`, `${area}/**/project.json`], {
20369
+ for (const entry of globSync9([`${area}/**/package.json`, `${area}/**/project.json`], {
19443
20370
  cwd: workspaceRoot,
19444
20371
  ignore: ["**/node_modules/**"],
19445
20372
  dot: false
@@ -19780,7 +20707,7 @@ var PICTURE_FILE = `${TARGET}-graph.svg`;
19780
20707
  function clearStaleOutputs(cwd, keeping) {
19781
20708
  for (const name of [...Object.values(SHAPE_FILE4), PICTURE_FILE]) {
19782
20709
  if (keeping.has(name)) continue;
19783
- const path2 = join65(cwd, REPORT_DIR, name);
20710
+ const path2 = join67(cwd, REPORT_DIR, name);
19784
20711
  if (existsSync44(path2)) unlinkSync4(path2);
19785
20712
  }
19786
20713
  }
@@ -19799,11 +20726,11 @@ function drawsPicture(graph, coverage) {
19799
20726
  async function emit(report, shape, cwd, graph, coverage) {
19800
20727
  if (shape === "console") return [];
19801
20728
  const detailed = shape === "markdown" ? report : withExcerpts(report, cwd);
19802
- mkdirSync12(join65(cwd, REPORT_DIR), { recursive: true });
20729
+ mkdirSync12(join67(cwd, REPORT_DIR), { recursive: true });
19803
20730
  const written = [];
19804
20731
  if (shape === "html" && drawsPicture(graph, coverage)) {
19805
20732
  const drawn = layOut(graph.graph, graph.communityOf);
19806
- const path2 = join65(cwd, REPORT_DIR, PICTURE_FILE);
20733
+ const path2 = join67(cwd, REPORT_DIR, PICTURE_FILE);
19807
20734
  await writeGraphPicture(drawn, path2);
19808
20735
  written.push(`${REPORT_DIR}/${PICTURE_FILE}`);
19809
20736
  detailed.picture = buildExplorer(drawn, graph.communityOf).markup;
@@ -19811,7 +20738,7 @@ async function emit(report, shape, cwd, graph, coverage) {
19811
20738
  const RENDER = { json: renderJson, html: renderHtml, markdown: renderMarkdown };
19812
20739
  const name = SHAPE_FILE4[shape] ?? `${TARGET}.${shape}`;
19813
20740
  const body = RENDER[shape](detailed);
19814
- writeFileSync17(join65(cwd, REPORT_DIR, name), body, "utf8");
20741
+ writeFileSync17(join67(cwd, REPORT_DIR, name), body, "utf8");
19815
20742
  written.unshift(`${REPORT_DIR}/${name}`);
19816
20743
  return written;
19817
20744
  }
@@ -19845,9 +20772,9 @@ function registerTest() {
19845
20772
 
19846
20773
  // src/roles/typescript/adapters/tsc/tsc.adapter.ts
19847
20774
  import { spawnSync as spawnSync19 } from "node:child_process";
19848
- import { existsSync as existsSync45, readdirSync as readdirSync12, readFileSync as readFileSync41 } from "node:fs";
20775
+ import { existsSync as existsSync45, readdirSync as readdirSync13, readFileSync as readFileSync42 } from "node:fs";
19849
20776
  import { createRequire } from "node:module";
19850
- import { join as join67 } from "node:path";
20777
+ import { join as join69 } from "node:path";
19851
20778
 
19852
20779
  // src/roles/typescript/config-policy.ts
19853
20780
  var PERMITTED_COMPILER_OPTIONS = [
@@ -19901,11 +20828,11 @@ function standardOverrides(compilerOptions, preset) {
19901
20828
  }
19902
20829
  function legacyCompromises(compilerOptions, preset) {
19903
20830
  const stack = preset !== void 0 && hasShippedPreset(preset) ? tsPresetFor(preset).compilerOptions : {};
19904
- const applied2 = appliedOptions({ compilerOptions: stack });
20831
+ const applied3 = appliedOptions({ compilerOptions: stack });
19905
20832
  return Object.entries(tsLegacyLayer().compilerOptions).filter(
19906
20833
  ([key]) => !(key in stack) && !(compilerOptions !== void 0 && key in compilerOptions)
19907
20834
  ).map(([key, value]) => {
19908
- const standard = applied2.has(key) ? JSON.parse(applied2.get(key) ?? "null") : null;
20835
+ const standard = applied3.has(key) ? JSON.parse(applied3.get(key) ?? "null") : null;
19909
20836
  return {
19910
20837
  rule: key,
19911
20838
  value,
@@ -19960,8 +20887,8 @@ function readTsconfigAdoption(cwd) {
19960
20887
  }
19961
20888
 
19962
20889
  // src/roles/typescript/adapters/tsc/plan.ts
19963
- import { readFileSync as readFileSync40 } from "node:fs";
19964
- import { join as join66 } from "node:path";
20890
+ import { readFileSync as readFileSync41 } from "node:fs";
20891
+ import { join as join68 } from "node:path";
19965
20892
 
19966
20893
  // src/roles/typescript/typecheck-script.ts
19967
20894
  var SENTINEL_TYPECHECK_COMMAND = "sentinel --run --typescript";
@@ -20056,7 +20983,7 @@ function planAdoption(context2) {
20056
20983
  };
20057
20984
  }
20058
20985
  const existing = parseJsonc(
20059
- readFileSync40(join66(context2.cwd, target.path), "utf8"),
20986
+ readFileSync41(join68(context2.cwd, target.path), "utf8"),
20060
20987
  target.path
20061
20988
  );
20062
20989
  const extendsChain = composeExtends(existing.extends, preset);
@@ -20116,10 +21043,10 @@ var PHASED_STRICTNESS_WARNING = `sentinel typescript: phase 1 (non-breaking) \u2
20116
21043
  var TSCONFIG_FILE = /^tsconfig.*\.json$/;
20117
21044
  function configStateOf(reason, moduleDir) {
20118
21045
  if (reason !== "extends-base") return reason;
20119
- const onBase = readdirSync12(moduleDir).filter((name) => TSCONFIG_FILE.test(name)).some((name) => {
21046
+ const onBase = readdirSync13(moduleDir).filter((name) => TSCONFIG_FILE.test(name)).some((name) => {
20120
21047
  try {
20121
21048
  const config = parseJsonc(
20122
- readFileSync41(join67(moduleDir, name), "utf8"),
21049
+ readFileSync42(join69(moduleDir, name), "utf8"),
20123
21050
  name
20124
21051
  );
20125
21052
  return extendsList(config).some(isBaseEntry);
@@ -20210,7 +21137,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20210
21137
  let chain;
20211
21138
  try {
20212
21139
  const parsed2 = parseJsonc(
20213
- readFileSync41(join67(cwd, target.path), "utf8"),
21140
+ readFileSync42(join69(cwd, target.path), "utf8"),
20214
21141
  target.path
20215
21142
  );
20216
21143
  chain = parsed2.extends;
@@ -20223,7 +21150,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20223
21150
  );
20224
21151
  if (preset === void 0) return void 0;
20225
21152
  try {
20226
- createRequire(join67(cwd, "noop.js")).resolve(preset);
21153
+ createRequire(join69(cwd, "noop.js")).resolve(preset);
20227
21154
  return void 0;
20228
21155
  } catch {
20229
21156
  return preset;
@@ -20319,7 +21246,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20319
21246
  referencedProjects(cwd, config) {
20320
21247
  try {
20321
21248
  const parsed2 = parseJsonc(
20322
- readFileSync41(join67(cwd, config), "utf8"),
21249
+ readFileSync42(join69(cwd, config), "utf8"),
20323
21250
  config
20324
21251
  );
20325
21252
  const referenced = (parsed2.references ?? []).map((reference) => reference.path).filter((path2) => typeof path2 === "string" && path2.length > 0);
@@ -20335,7 +21262,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20335
21262
  * check.
20336
21263
  */
20337
21264
  typecheckTarget(cwd) {
20338
- if (existsSync45(join67(cwd, "tsconfig.json"))) return "tsconfig.json";
21265
+ if (existsSync45(join69(cwd, "tsconfig.json"))) return "tsconfig.json";
20339
21266
  const target = resolveTsconfigTarget(cwd);
20340
21267
  return target.reason === "none" ? null : target.path;
20341
21268
  }
@@ -20348,7 +21275,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20348
21275
  const target = resolveTsconfigTarget(ctx.cwd);
20349
21276
  const { preset } = readTsconfigAdoption(ctx.cwd);
20350
21277
  const stack = preset === null ? void 0 : preset.slice(preset.lastIndexOf("/") + 1);
20351
- const config = this.readConfig(join67(ctx.cwd, target.path));
21278
+ const config = this.readConfig(join69(ctx.cwd, target.path));
20352
21279
  const options = config?.compilerOptions;
20353
21280
  const overrides = standardOverrides(options, stack);
20354
21281
  const legacy = config !== void 0 && extendsList(config).some(isLegacyEntry) ? legacyCompromises(options, stack) : [];
@@ -20366,7 +21293,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20366
21293
  readConfig(file) {
20367
21294
  if (!existsSync45(file)) return void 0;
20368
21295
  try {
20369
- return parseJsonc(readFileSync41(file, "utf8"), file);
21296
+ return parseJsonc(readFileSync42(file, "utf8"), file);
20370
21297
  } catch {
20371
21298
  return void 0;
20372
21299
  }
@@ -20563,7 +21490,7 @@ function replaceLines(current, replacements) {
20563
21490
  }
20564
21491
 
20565
21492
  // src/core/apply-plan.ts
20566
- import { existsSync as existsSync46, readFileSync as readFileSync42, renameSync as renameSync2, rmSync as rmSync10, writeFileSync as writeFileSync18 } from "node:fs";
21493
+ import { existsSync as existsSync46, readFileSync as readFileSync43, renameSync as renameSync2, rmSync as rmSync10, writeFileSync as writeFileSync18 } from "node:fs";
20567
21494
  import { resolve as resolve10, sep as sep8 } from "node:path";
20568
21495
  import { applyEdits, findNodeAtLocation, modify, parseTree } from "jsonc-parser";
20569
21496
  function resolveWithinRoot(cwd, relativePath) {
@@ -20575,7 +21502,7 @@ function resolveWithinRoot(cwd, relativePath) {
20575
21502
  return absolutePath;
20576
21503
  }
20577
21504
  function readIfExists(absolutePath) {
20578
- return existsSync46(absolutePath) ? readFileSync42(absolutePath, "utf8") : void 0;
21505
+ return existsSync46(absolutePath) ? readFileSync43(absolutePath, "utf8") : void 0;
20579
21506
  }
20580
21507
  function* leaves(value, prefix = []) {
20581
21508
  for (const [key, keyValue] of Object.entries(value)) {
@@ -20693,8 +21620,8 @@ function applyPlan(cwd, plan3) {
20693
21620
  }
20694
21621
 
20695
21622
  // src/core/config/preset-evidence.ts
20696
- import { existsSync as existsSync47, readdirSync as readdirSync13, readFileSync as readFileSync43 } from "node:fs";
20697
- import { join as join68 } from "node:path";
21623
+ import { existsSync as existsSync47, readdirSync as readdirSync14, readFileSync as readFileSync44 } from "node:fs";
21624
+ import { join as join70 } from "node:path";
20698
21625
  var PATH_SIGNALS = [
20699
21626
  {
20700
21627
  preset: "nest",
@@ -20722,18 +21649,18 @@ function sourceImports(cwd, pattern) {
20722
21649
  const dir = stack.pop();
20723
21650
  let entries;
20724
21651
  try {
20725
- entries = readdirSync13(dir, { withFileTypes: true });
21652
+ entries = readdirSync14(dir, { withFileTypes: true });
20726
21653
  } catch {
20727
21654
  continue;
20728
21655
  }
20729
21656
  for (const entry of entries) {
20730
21657
  if (entry.isDirectory()) {
20731
- if (!NOT_SCANNED.has(entry.name)) stack.push(join68(dir, entry.name));
21658
+ if (!NOT_SCANNED.has(entry.name)) stack.push(join70(dir, entry.name));
20732
21659
  continue;
20733
21660
  }
20734
21661
  if (!SOURCE_FILE.test(entry.name)) continue;
20735
21662
  try {
20736
- if (pattern.test(readFileSync43(join68(dir, entry.name), "utf8"))) return true;
21663
+ if (pattern.test(readFileSync44(join70(dir, entry.name), "utf8"))) return true;
20737
21664
  } catch {
20738
21665
  continue;
20739
21666
  }
@@ -20742,11 +21669,11 @@ function sourceImports(cwd, pattern) {
20742
21669
  return false;
20743
21670
  }
20744
21671
  function dependencyNames(cwd) {
20745
- const path2 = join68(cwd, "package.json");
21672
+ const path2 = join70(cwd, "package.json");
20746
21673
  if (!existsSync47(path2)) return [];
20747
21674
  try {
20748
21675
  const manifest = parseJsonc(
20749
- readFileSync43(path2, "utf8"),
21676
+ readFileSync44(path2, "utf8"),
20750
21677
  path2
20751
21678
  );
20752
21679
  return [
@@ -20761,7 +21688,7 @@ var REACT_TYPESCRIPT_PRESET = "@hublo/sentinel/typescript/react";
20761
21688
  function reactTsconfigEvidence(cwd) {
20762
21689
  let entries;
20763
21690
  try {
20764
- entries = readdirSync13(cwd).filter(
21691
+ entries = readdirSync14(cwd).filter(
20765
21692
  (name) => name.startsWith("tsconfig") && name.endsWith(".json")
20766
21693
  );
20767
21694
  } catch {
@@ -20769,7 +21696,7 @@ function reactTsconfigEvidence(cwd) {
20769
21696
  }
20770
21697
  for (const name of entries) {
20771
21698
  try {
20772
- const config = parseJsonc(readFileSync43(join68(cwd, name), "utf8"), name);
21699
+ const config = parseJsonc(readFileSync44(join70(cwd, name), "utf8"), name);
20773
21700
  if (config.compilerOptions?.jsx !== void 0) return 'its tsconfig sets "jsx"';
20774
21701
  const extended = Array.isArray(config.extends) ? config.extends : config.extends === void 0 ? [] : [config.extends];
20775
21702
  if (extended.some((entry) => entry === REACT_TYPESCRIPT_PRESET)) {