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

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-NYNS4TLN.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, 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,65 @@ 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
  }
15481
15527
  return run;
15482
15528
  }
15529
+ function checkFile(input, rules, context2, run) {
15530
+ const parsed2 = programOf(input);
15531
+ if (!parsed2.ok) {
15532
+ run.unparsed.push({
15533
+ file: input.file,
15534
+ reason: `${parsed2.why}, so its Prisma calls are not read`
15535
+ });
15536
+ return;
15537
+ }
15538
+ for (const rule of rules) {
15539
+ for (const { offset, message } of fileFindingsOf(rule, parsed2.program, input.file, context2)) {
15540
+ run.findings.push(findingOf2(input, rule, { offset, message }));
15541
+ }
15542
+ }
15543
+ for (const call of prismaCallsOf(parsed2.program, ORM_OPERATIONS, input.text)) {
15544
+ if (READ_OPERATIONS.includes(call.operation)) run.calls++;
15545
+ else run.writes++;
15546
+ for (const rule of rules) {
15547
+ const message = messageOf(rule, call, context2, input.file);
15548
+ if (message !== void 0)
15549
+ run.findings.push(findingOf2(input, rule, { offset: call.start, message }));
15550
+ }
15551
+ }
15552
+ }
15553
+ function programOf(input) {
15554
+ try {
15555
+ const parsed2 = parseSync9(input.file, input.text, { sourceType: "module" });
15556
+ if (parsed2.errors.length > 0) {
15557
+ return { ok: false, why: `does not parse (${parsed2.errors[0]?.message ?? "unknown error"})` };
15558
+ }
15559
+ return { ok: true, program: parsed2.program };
15560
+ } catch (error) {
15561
+ return {
15562
+ ok: false,
15563
+ why: `could not be read (${error instanceof Error ? error.message : String(error)})`
15564
+ };
15565
+ }
15566
+ }
15567
+ function messageOf(rule, call, context2, file) {
15568
+ try {
15569
+ return rule.check(call, context2, file);
15570
+ } catch {
15571
+ return void 0;
15572
+ }
15573
+ }
15574
+ function fileFindingsOf(rule, program, file, context2) {
15575
+ try {
15576
+ return rule.checkFile?.(program, file, context2) ?? [];
15577
+ } catch {
15578
+ return [];
15579
+ }
15580
+ }
15483
15581
  async function parserLoaded() {
15484
15582
  try {
15485
15583
  await loadSqlParser();
@@ -15488,65 +15586,19 @@ async function parserLoaded() {
15488
15586
  const why = error instanceof Error ? error.message : String(error);
15489
15587
  return {
15490
15588
  ok: false,
15491
- reason: `PostgreSQL's parser could not be loaded (${why}), so its SQL templates are not read`
15589
+ reason: `PostgreSQL's parser could not be loaded (${why}), so its Prisma calls are not read`
15492
15590
  };
15493
15591
  }
15494
15592
  }
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
- }
15593
+
15594
+ // src/roles/sql/orm/orm-context.ts
15595
+ import { readdirSync as readdirSync12, readFileSync as readFileSync33 } from "node:fs";
15596
+ import { dirname as dirname10, join as join56, relative as relative10 } from "node:path";
15597
+ import { globSync as globSync4 } from "tinyglobby";
15598
+
15599
+ // src/roles/sql/trigram-indexes.ts
15600
+ import { readdirSync as readdirSync11, readFileSync as readFileSync32 } from "node:fs";
15601
+ import { join as join55 } from "node:path";
15550
15602
 
15551
15603
  // src/roles/sql/raw/rules/pg-tree.ts
15552
15604
  function bodyOf(node, kind) {
@@ -15621,61 +15673,916 @@ var MAX_KEY_DEPTH = 32;
15621
15673
  function expressionKey(node, depth = 0) {
15622
15674
  if (depth > MAX_KEY_DEPTH || node === null || typeof node !== "object") return void 0;
15623
15675
  const [kind] = Object.keys(node);
15624
- const keyOf = kind === void 0 ? void 0 : KEYS.get(kind);
15676
+ const keyOf2 = kind === void 0 ? void 0 : KEYS.get(kind);
15625
15677
  const body = kind === void 0 ? void 0 : bodyOf(node, kind);
15626
- return keyOf && body ? keyOf(body, depth + 1) : void 0;
15678
+ return keyOf2 && body ? keyOf2(body, depth + 1) : void 0;
15627
15679
  }
15628
15680
  function columnKey(column) {
15629
15681
  const name = columnNames(column).at(-1);
15630
15682
  return name === void 0 || name === "*" || name === "" ? void 0 : name;
15631
15683
  }
15632
- function callKey(call, depth) {
15633
- const name = lastName(call.funcname);
15634
- const args = (call.args ?? []).map((arg) => expressionKey(arg, depth));
15635
- if (name === void 0 || args.some((arg) => arg === void 0)) return void 0;
15636
- return `${name}(${args.join(", ")})`;
15684
+ function callKey(call, depth) {
15685
+ const name = lastName(call.funcname);
15686
+ const args = (call.args ?? []).map((arg) => expressionKey(arg, depth));
15687
+ if (name === void 0 || args.some((arg) => arg === void 0)) return void 0;
15688
+ return `${name}(${args.join(", ")})`;
15689
+ }
15690
+ function castKey(cast, depth) {
15691
+ const inner = expressionKey(cast.arg, depth);
15692
+ const type2 = lastName(cast.typeName?.names);
15693
+ return inner === void 0 || type2 === void 0 ? void 0 : `${inner}::${type2}`;
15694
+ }
15695
+ function operationKey(operation, depth) {
15696
+ if (operation.kind !== "AEXPR_OP") return void 0;
15697
+ const operator = lastName(operation.name);
15698
+ const left = expressionKey(operation.lexpr, depth);
15699
+ const right = expressionKey(operation.rexpr, depth);
15700
+ if (operator === void 0 || left === void 0 || right === void 0) return void 0;
15701
+ return `${left} ${operator} ${right}`;
15702
+ }
15703
+ function constantKey(constant) {
15704
+ if (constant.isnull === true) return "null";
15705
+ const text = bodyOf(constant, "sval")?.sval;
15706
+ if (typeof text === "string") return `'${text}'`;
15707
+ for (const [kind, zero] of [
15708
+ ["ival", "0"],
15709
+ ["fval", "0"],
15710
+ ["boolval", "false"]
15711
+ ]) {
15712
+ const body = bodyOf(constant, kind);
15713
+ if (body) return body[kind] === void 0 ? zero : String(body[kind]);
15714
+ }
15715
+ return void 0;
15716
+ }
15717
+ var KEYS = /* @__PURE__ */ new Map([
15718
+ ["ColumnRef", columnKey],
15719
+ ["FuncCall", callKey],
15720
+ ["TypeCast", castKey],
15721
+ ["A_Const", constantKey],
15722
+ ["A_Expr", operationKey]
15723
+ ]);
15724
+ function qualifiersUnder(node) {
15725
+ const qualifiers = /* @__PURE__ */ new Set();
15726
+ for (const names of columnsUnder(node)) {
15727
+ const qualifier = names.at(-2);
15728
+ if (qualifier !== void 0) qualifiers.add(qualifier);
15729
+ }
15730
+ return qualifiers;
15731
+ }
15732
+
15733
+ // src/roles/sql/trigram-indexes.ts
15734
+ var TRIGRAM_CLASSES = /* @__PURE__ */ new Set(["gin_trgm_ops", "gist_trgm_ops"]);
15735
+ function trigramContext(cwd, own, indexesFrom) {
15736
+ let loaded2;
15737
+ const once = () => {
15738
+ loaded2 ??= readIndexes(cwd, own, indexesFrom);
15739
+ return loaded2;
15740
+ };
15741
+ return { trigramIndexes: () => once().indexes, indexesFrom: () => once().folders };
15742
+ }
15743
+ function readIndexes(cwd, own, indexesFrom) {
15744
+ const read2 = [];
15745
+ const empty = [];
15746
+ const shared = indexesFrom.flatMap((folder) => {
15747
+ const migrations = migrationsIn(join55(cwd, folder)).flatMap(
15748
+ (name) => migrationText(cwd, `${folder}/${name}/migration.sql`)
15749
+ );
15750
+ (migrations.length > 0 ? read2 : empty).push(folder);
15751
+ return migrations;
15752
+ });
15753
+ const ownMigrations = own.flatMap((file) => migrationText(cwd, file));
15754
+ return { indexes: trigramIndexesOf([...ownMigrations, ...shared]), folders: { read: read2, empty } };
15755
+ }
15756
+ function migrationsIn(directory) {
15757
+ try {
15758
+ return readdirSync11(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort();
15759
+ } catch {
15760
+ return [];
15761
+ }
15762
+ }
15763
+ function migrationText(cwd, file) {
15764
+ try {
15765
+ return [{ file, text: readFileSync32(join55(cwd, file), "utf8") }];
15766
+ } catch {
15767
+ return [];
15768
+ }
15769
+ }
15770
+ function trigramIndexesOf(migrations) {
15771
+ let indexes = [];
15772
+ for (const { file, text } of migrations) {
15773
+ const parsed2 = parseSql(text);
15774
+ if (!parsed2.ok) continue;
15775
+ for (const statement of parsed2.statements) indexes = applied(indexes, statement, file);
15776
+ }
15777
+ return indexes;
15778
+ }
15779
+ function applied(indexes, statement, file) {
15780
+ const created = bodyOf(statement, "IndexStmt");
15781
+ if (created) return [...indexes, ...indexesOf(created, file)];
15782
+ const dropped = bodyOf(statement, "DropStmt");
15783
+ if (dropped) return withoutDropped(indexes, dropped);
15784
+ const renamed4 = bodyOf(statement, "RenameStmt");
15785
+ if (renamed4) return withRenamed(indexes, renamed4);
15786
+ return indexes;
15787
+ }
15788
+ function indexesOf(index, file) {
15789
+ const table = index.relation?.relname;
15790
+ if (typeof table !== "string") return [];
15791
+ const name = typeof index.idxname === "string" ? index.idxname : void 0;
15792
+ return (index.indexParams ?? []).flatMap((param) => {
15793
+ const element = bodyOf(param, "IndexElem");
15794
+ if (!element || !isTrigram(element)) return [];
15795
+ const expression = typeof element.name === "string" ? element.name : expressionKey(element.expr);
15796
+ return expression === void 0 ? [] : [{ name, table, expression, file }];
15797
+ });
15798
+ }
15799
+ function isTrigram(element) {
15800
+ const name = lastName(element.opclass);
15801
+ return name !== void 0 && TRIGRAM_CLASSES.has(name);
15802
+ }
15803
+ function withoutDropped(indexes, drop) {
15804
+ const names = (drop.objects ?? []).flatMap((object) => {
15805
+ const last = lastName(bodyOf(object, "List")?.items);
15806
+ return last === void 0 ? [] : [last];
15807
+ });
15808
+ if (drop.removeType === "OBJECT_INDEX")
15809
+ return indexes.filter((index) => !names.includes(index.name ?? ""));
15810
+ if (drop.removeType === "OBJECT_TABLE")
15811
+ return indexes.filter((index) => !names.includes(index.table));
15812
+ return indexes;
15813
+ }
15814
+ function withRenamed(indexes, rename) {
15815
+ const from = rename.relation?.relname;
15816
+ const to = rename.newname;
15817
+ if (typeof from !== "string" || typeof to !== "string") return indexes;
15818
+ if (rename.renameType === "OBJECT_INDEX")
15819
+ return indexes.map((index) => index.name === from ? { ...index, name: to } : index);
15820
+ if (rename.renameType === "OBJECT_TABLE")
15821
+ return indexes.map((index) => index.table === from ? { ...index, table: to } : index);
15822
+ if (rename.renameType === "OBJECT_COLUMN") {
15823
+ return indexes.map(
15824
+ (index) => index.table === from && index.expression === rename.subname ? { ...index, expression: to } : index
15825
+ );
15826
+ }
15827
+ return indexes;
15828
+ }
15829
+
15830
+ // src/roles/sql/orm/migration-indexes.ts
15831
+ function indexColumnsOf(migrations) {
15832
+ let indexes = [];
15833
+ for (const { text } of migrations) {
15834
+ const parsed2 = parseSql(text);
15835
+ if (!parsed2.ok) continue;
15836
+ for (const statement of parsed2.statements) indexes = applied2(indexes, statement);
15837
+ }
15838
+ const columns = /* @__PURE__ */ new Map();
15839
+ for (const { table, column } of indexes) {
15840
+ columns.set(table, /* @__PURE__ */ new Set([...columns.get(table) ?? [], column]));
15841
+ }
15842
+ return columns;
15843
+ }
15844
+ function applied2(indexes, statement) {
15845
+ const index = bodyOf(statement, "IndexStmt");
15846
+ if (index) return [...indexes, ...createdIndex(index)];
15847
+ const table = bodyOf(statement, "CreateStmt");
15848
+ if (table) return [...indexes, ...tableConstraints(table)];
15849
+ const alter = bodyOf(statement, "AlterTableStmt");
15850
+ if (alter) return [...indexes, ...addedConstraints(alter)];
15851
+ const drop = bodyOf(statement, "DropStmt");
15852
+ if (drop) return withoutDropped(indexes, drop);
15853
+ const rename = bodyOf(statement, "RenameStmt");
15854
+ if (rename) return withRenamed2(indexes, rename);
15855
+ return indexes;
15856
+ }
15857
+ function createdIndex(index) {
15858
+ const table = relationName(index.relation);
15859
+ const column = firstColumn(index.indexParams);
15860
+ if (table === void 0 || column === void 0) return [];
15861
+ return [{ name: typeof index.idxname === "string" ? index.idxname : void 0, table, column }];
15862
+ }
15863
+ function tableConstraints(create) {
15864
+ const table = relationName(create.relation);
15865
+ if (table === void 0) return [];
15866
+ return (create.tableElts ?? []).flatMap((element) => {
15867
+ const constraint = bodyOf(element, "Constraint");
15868
+ if (constraint) return constraintIndex(table, constraint, void 0);
15869
+ const column = bodyOf(element, "ColumnDef");
15870
+ const name = column?.colname;
15871
+ if (typeof name !== "string") return [];
15872
+ return (column?.constraints ?? []).flatMap((inner) => {
15873
+ const c = bodyOf(inner, "Constraint");
15874
+ return c ? constraintIndex(table, c, name) : [];
15875
+ });
15876
+ });
15877
+ }
15878
+ function addedConstraints(alter) {
15879
+ const table = relationName(alter.relation);
15880
+ if (table === void 0) return [];
15881
+ return (alter.cmds ?? []).flatMap((command2) => {
15882
+ const constraint = bodyOf(bodyOf(command2, "AlterTableCmd")?.def, "Constraint");
15883
+ return constraint ? constraintIndex(table, constraint, void 0) : [];
15884
+ });
15885
+ }
15886
+ function constraintIndex(table, constraint, column) {
15887
+ const name = typeof constraint.conname === "string" ? constraint.conname : void 0;
15888
+ if (constraint.contype === "CONSTR_PRIMARY" || constraint.contype === "CONSTR_UNIQUE") {
15889
+ const first = column ?? firstColumn(constraint.keys);
15890
+ return first === void 0 ? [] : [{ name, table, column: first }];
15891
+ }
15892
+ if (constraint.contype === "CONSTR_EXCLUSION") {
15893
+ const firstExclusion = bodyOf(constraint.exclusions?.[0], "List");
15894
+ const first = firstColumn(firstExclusion?.items);
15895
+ return first === void 0 ? [] : [{ name, table, column: first }];
15896
+ }
15897
+ return [];
15898
+ }
15899
+ function withRenamed2(indexes, rename) {
15900
+ const from = relationName(rename.relation);
15901
+ const to = rename.newname;
15902
+ if (from === void 0 || typeof to !== "string") return indexes;
15903
+ switch (rename.renameType) {
15904
+ case "OBJECT_TABLE":
15905
+ return indexes.map((i) => i.table === from ? { ...i, table: to } : i);
15906
+ case "OBJECT_COLUMN":
15907
+ return indexes.map(
15908
+ (i) => i.table === from && i.column === rename.subname ? { ...i, column: to } : i
15909
+ );
15910
+ case "OBJECT_INDEX":
15911
+ return indexes.map((i) => i.name === from ? { ...i, name: to } : i);
15912
+ default:
15913
+ return indexes;
15914
+ }
15915
+ }
15916
+ function relationName(relation) {
15917
+ const name = relation?.relname;
15918
+ return typeof name === "string" ? name : void 0;
15919
+ }
15920
+ function firstColumn(list) {
15921
+ const first = list?.[0];
15922
+ const element = bodyOf(first, "IndexElem");
15923
+ if (typeof element?.name === "string") return element.name;
15924
+ const text = bodyOf(first, "String")?.sval;
15925
+ return typeof text === "string" ? text : void 0;
15926
+ }
15927
+
15928
+ // src/roles/sql/orm/prisma-schema.ts
15929
+ var MODEL = /^model\s+(\w+)\s*\{([\s\S]*?)^\}/gm;
15930
+ var PROVIDER = /datasource\s+\w+\s*\{[^}]*?provider\s*=\s*"(\w+)"/s;
15931
+ var FIELD = /^(\w+)\s+(\w+)/;
15932
+ var MAP = /@map\(\s*"([^"]+)"/;
15933
+ var TABLE = /^\s*@@map\(\s*"([^"]+)"/m;
15934
+ var RELATION_FK = /@relation\([^)]*fields:\s*\[\s*(\w+)/;
15935
+ var BLOCK_INDEX = /^@@(?:index|unique|id)\(\s*(?:fields:\s*)?\[\s*(\w+)/;
15936
+ var COMPOUND = /^@@(?:unique|id)\(\s*(?:fields:\s*)?\[([^\]]+)\](?:.*?\bname:\s*"(\w+)")?/;
15937
+ function readPrismaSchema(text) {
15938
+ return {
15939
+ provider: PROVIDER.exec(text)?.[1] ?? "unknown",
15940
+ models: [...text.matchAll(MODEL)].map(([, name = "", body = ""]) => modelOf(name, body))
15941
+ };
15942
+ }
15943
+ function modelOf(name, body) {
15944
+ const model = {
15945
+ name,
15946
+ table: TABLE.exec(body)?.[1] ?? name,
15947
+ fields: /* @__PURE__ */ new Map(),
15948
+ foreignKeys: /* @__PURE__ */ new Map(),
15949
+ indexed: /* @__PURE__ */ new Set(),
15950
+ compoundKeys: /* @__PURE__ */ new Set()
15951
+ };
15952
+ for (const raw of body.split("\n")) {
15953
+ const line = raw.trim();
15954
+ if (line === "" || line.startsWith("//")) continue;
15955
+ if (line.startsWith("@@")) blockAttribute(model, line);
15956
+ else fieldLine(model, line);
15957
+ }
15958
+ return model;
15959
+ }
15960
+ function fieldLine(model, line) {
15961
+ const field = FIELD.exec(line);
15962
+ if (!field) return;
15963
+ const [, name = "", type2 = ""] = field;
15964
+ model.fields.set(name, { column: MAP.exec(line)?.[1] ?? name, type: type2 });
15965
+ if (/@id\b|@unique\b/.test(line)) model.indexed.add(name);
15966
+ const fk = RELATION_FK.exec(line)?.[1];
15967
+ if (fk) model.foreignKeys.set(name, fk);
15968
+ }
15969
+ function blockAttribute(model, line) {
15970
+ const first = BLOCK_INDEX.exec(line)?.[1];
15971
+ if (first) model.indexed.add(first);
15972
+ const compound = COMPOUND.exec(line);
15973
+ if (!compound) return;
15974
+ const [, fields = "", given] = compound;
15975
+ model.compoundKeys.add(
15976
+ fields.split(",").map((part) => part.trim().split(/[\s(]/)[0]).join("_")
15977
+ );
15978
+ if (given) model.compoundKeys.add(given);
15979
+ }
15980
+ var clientNameOf = (model) => model.name.charAt(0).toLowerCase() + model.name.slice(1);
15981
+
15982
+ // src/roles/sql/orm/orm-context.ts
15983
+ function ormContext(cwd, settings) {
15984
+ let read2;
15985
+ const models = () => {
15986
+ read2 ??= readModels(cwd, settings);
15987
+ return read2;
15988
+ };
15989
+ return {
15990
+ modelOf: (name) => {
15991
+ const found = models().judged.get(name) ?? [];
15992
+ return found.length === 1 ? found[0] : void 0;
15993
+ },
15994
+ isPostgreSqlModel: (name) => models().postgres.has(name) && !models().others.has(name),
15995
+ referenceTables: new Set(settings.referenceTables),
15996
+ perRowWrites: settings.perRowWrites ?? [],
15997
+ scripts: settings.scripts ?? []
15998
+ };
15999
+ }
16000
+ function readModels(cwd, settings) {
16001
+ const schemas = [
16002
+ ...globSync4(["**/*.prisma"], {
16003
+ cwd,
16004
+ ignore: [...settings.ignore],
16005
+ onlyFiles: true,
16006
+ dot: false,
16007
+ followSymbolicLinks: false
16008
+ }),
16009
+ ...settings.indexesFrom.flatMap(
16010
+ (folder) => prismaFilesIn(join56(cwd, dirname10(folder))).map((file) => relative10(cwd, file))
16011
+ )
16012
+ ];
16013
+ const judged = /* @__PURE__ */ new Map();
16014
+ const postgres = /* @__PURE__ */ new Set();
16015
+ const others = /* @__PURE__ */ new Set();
16016
+ for (const schema of new Set(schemas)) {
16017
+ const text = readText(join56(cwd, schema));
16018
+ if (text === void 0) continue;
16019
+ const parsed2 = readPrismaSchema(text);
16020
+ const declared = parsed2.provider === "postgresql" ? postgres : others;
16021
+ for (const model of parsed2.models) declared.add(clientNameOf(model));
16022
+ if (parsed2.provider !== "postgresql") continue;
16023
+ for (const one of judgedOf(cwd, schema, parsed2)) {
16024
+ const name = clientNameOf(one.model);
16025
+ judged.set(name, [...judged.get(name) ?? [], one]);
16026
+ }
16027
+ }
16028
+ return { judged, postgres, others };
16029
+ }
16030
+ function judgedModelsOf(cwd, schema) {
16031
+ const text = readText(join56(cwd, schema));
16032
+ return text === void 0 ? [] : judgedOf(cwd, schema, readPrismaSchema(text));
16033
+ }
16034
+ function judgedOf(cwd, schema, parsed2) {
16035
+ const migrations = join56(cwd, dirname10(schema), "migrations");
16036
+ const folders = migrationsIn(migrations);
16037
+ if (parsed2.provider !== "postgresql" || folders.length === 0) return [];
16038
+ const indexes = indexColumnsOf(
16039
+ folders.flatMap((folder) => {
16040
+ const sql = readText(join56(migrations, folder, "migration.sql"));
16041
+ return sql === void 0 ? [] : [{ text: sql }];
16042
+ })
16043
+ );
16044
+ const modelNames = new Set(parsed2.models.map((model) => model.name));
16045
+ return parsed2.models.map((model) => ({ model, indexes, schema, modelNames }));
16046
+ }
16047
+ function prismaFilesIn(directory) {
16048
+ try {
16049
+ return readdirSync12(directory).filter((name) => name.endsWith(".prisma")).map((name) => join56(directory, name));
16050
+ } catch {
16051
+ return [];
16052
+ }
16053
+ }
16054
+ function readText(path2) {
16055
+ try {
16056
+ return readFileSync33(path2, "utf8");
16057
+ } catch {
16058
+ return void 0;
16059
+ }
16060
+ }
16061
+
16062
+ // src/roles/sql/orm/rules/filter-without-index.ts
16063
+ var NOT_JUDGED = /* @__PURE__ */ new Set([
16064
+ "some",
16065
+ "every",
16066
+ "none",
16067
+ "is",
16068
+ "isNot",
16069
+ "contains",
16070
+ "startsWith",
16071
+ "endsWith",
16072
+ "search"
16073
+ ]);
16074
+ var COMBINATORS = /* @__PURE__ */ new Set(["AND", "OR", "NOT"]);
16075
+ var filterWithoutIndex = {
16076
+ name: ORM_FILTER_INDEX_RULE,
16077
+ 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"',
16078
+ check: (call, context2) => {
16079
+ if (!READ_OPERATIONS.includes(call.operation)) return void 0;
16080
+ const judged = context2.modelOf(call.model);
16081
+ if (judged === void 0 || context2.referenceTables.has(judged.model.table)) return void 0;
16082
+ const columns = unindexedColumns(propertyOf(call.args, "where"), judged);
16083
+ if (columns === void 0) return void 0;
16084
+ return messageOf2(call, judged, columns);
16085
+ }
16086
+ };
16087
+ function unindexedColumns(where, judged) {
16088
+ if (where === void 0) return void 0;
16089
+ const { keys, spread } = keysOf(where);
16090
+ const filtered = keys.filter((key) => !COMBINATORS.has(key));
16091
+ if (spread || filtered.length === 0) return void 0;
16092
+ const columns = [];
16093
+ for (const key of filtered) {
16094
+ const column = columnOf(key, where, judged);
16095
+ if (column === void 0 || isIndexed(column, judged)) return void 0;
16096
+ columns.push(column.column);
16097
+ }
16098
+ return columns;
16099
+ }
16100
+ function columnOf(key, where, { model, modelNames }) {
16101
+ if (model.compoundKeys.has(key)) return void 0;
16102
+ if (readsAnotherTable(propertyOf(where, key))) return void 0;
16103
+ const scalar = model.foreignKeys.get(key) ?? key;
16104
+ const field = model.fields.get(scalar);
16105
+ if (field === void 0 || scalar === key && modelNames.has(field.type)) return void 0;
16106
+ return { field: scalar, column: field.column };
16107
+ }
16108
+ function readsAnotherTable(value) {
16109
+ if (value?.type === "ArrayExpression") {
16110
+ return (value.elements ?? []).some(
16111
+ (element) => readsAnotherTable(element)
16112
+ );
16113
+ }
16114
+ if (value?.type !== "ObjectExpression") return false;
16115
+ return value.properties.some((p) => {
16116
+ if (p.type !== "Property") return true;
16117
+ const key = p.key.name ?? p.key.value;
16118
+ return NOT_JUDGED.has(key) || readsAnotherTable(p.value);
16119
+ });
16120
+ }
16121
+ function isIndexed({ field, column }, judged) {
16122
+ return judged.model.indexed.has(field) || (judged.indexes.get(judged.model.table)?.has(column) ?? false);
16123
+ }
16124
+ function messageOf2(call, judged, columns) {
16125
+ const named = columns.map((column) => `\`${column}\``).join(", ");
16126
+ 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`;
16127
+ }
16128
+
16129
+ // src/roles/sql/orm/rules/new-client.ts
16130
+ import { matchesGlob as matchesGlob2 } from "node:path";
16131
+ var newClient = {
16132
+ name: ORM_NEW_CLIENT_RULE,
16133
+ help: "inject the module's database service (the one that extends PrismaClient); a one-off script belongs in a folder that `orm.scripts` names",
16134
+ check: () => void 0,
16135
+ checkFile: (program, file, context2) => {
16136
+ if (context2.scripts.some((pattern) => matchesGlob2(file, pattern))) return [];
16137
+ const found = [];
16138
+ walkWithAncestors(program, (node) => {
16139
+ if (node.type === "NewExpression" && namesPrismaClient(node.callee)) {
16140
+ found.push({
16141
+ offset: node.start,
16142
+ message: "this code creates its own PrismaClient: each one opens its own pool of connections to the database, beside the one the module shares"
16143
+ });
16144
+ }
16145
+ });
16146
+ return found;
16147
+ }
16148
+ };
16149
+ function namesPrismaClient(callee) {
16150
+ if (callee?.type === "Identifier") return callee.name === "PrismaClient";
16151
+ return callee?.type === "MemberExpression" && callee.property?.name === "PrismaClient";
16152
+ }
16153
+
16154
+ // src/roles/sql/orm/batches.ts
16155
+ var BATCHES = /chunk|batch|slice\(|group|frontier|\bpage/i;
16156
+ var SET_KEYS = /* @__PURE__ */ new Set(["in", "notIn", "OR", "AND"]);
16157
+ var KEYSET = /* @__PURE__ */ new Set(["gt", "gte", "lt", "lte"]);
16158
+ function runsPerBatch(call, loop) {
16159
+ if (BATCHES.test(loop.walks)) return true;
16160
+ const where = propertyOf(call.args, "where");
16161
+ if (readsAsSet(where, loop.vars)) return true;
16162
+ return propertyOf(call.args, "take") !== void 0 && (propertyOf(call.args, "cursor") !== void 0 || comparesKeyset(where));
16163
+ }
16164
+ function readsAsSet(node, vars) {
16165
+ if (node === null || typeof node !== "object") return false;
16166
+ if (Array.isArray(node)) return node.some((item) => readsAsSet(item, vars));
16167
+ const n = node;
16168
+ if (n.type === "Property" && SET_KEYS.has(keyOf(n)) && rootsAt(n.value, vars)) {
16169
+ return true;
16170
+ }
16171
+ return Object.entries(n).some(
16172
+ ([key, child]) => key !== "parent" && typeof child === "object" && readsAsSet(child, vars)
16173
+ );
16174
+ }
16175
+ function rootsAt(value, vars) {
16176
+ let node = value;
16177
+ while (node?.type === "MemberExpression") node = node.object;
16178
+ return node?.type === "Identifier" && vars.has(node.name);
16179
+ }
16180
+ function comparesKeyset(where) {
16181
+ if (where?.type !== "ObjectExpression") return false;
16182
+ return where.properties.some((p) => {
16183
+ const value = p.value;
16184
+ return value?.type === "ObjectExpression" && value.properties.some((q) => KEYSET.has(keyOf(q)));
16185
+ });
16186
+ }
16187
+ function keyOf(property) {
16188
+ const key = property.key;
16189
+ return key?.name ?? key?.value ?? "";
16190
+ }
16191
+ function shortly(text) {
16192
+ const line = text.replace(/\s+/g, " ").trim();
16193
+ return line.length > 60 ? `${line.slice(0, 57)}...` : line;
16194
+ }
16195
+
16196
+ // src/roles/sql/orm/rules/query-in-loop.ts
16197
+ var queryInLoop = {
16198
+ name: ORM_QUERY_LOOP_RULE,
16199
+ 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",
16200
+ check: (call, context2) => {
16201
+ if (!READ_OPERATIONS.includes(call.operation) || call.loop === void 0) return void 0;
16202
+ if (!context2.isPostgreSqlModel(call.model)) return void 0;
16203
+ if (runsPerBatch(call, call.loop)) return void 0;
16204
+ return `this ${call.operation} on ${call.model} runs once per element of \`${shortly(call.loop.walks)}\`: the number of queries grows with the data`;
16205
+ }
16206
+ };
16207
+
16208
+ // src/roles/sql/orm/rules/write-in-loop.ts
16209
+ var writeInLoop = {
16210
+ name: ORM_WRITE_LOOP_RULE,
16211
+ 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",
16212
+ check: (call, context2, file) => {
16213
+ if (!WRITE_OPERATIONS.includes(call.operation) || call.loop === void 0) return void 0;
16214
+ if (!context2.isPostgreSqlModel(call.model) || isNamed(call, context2, file)) return void 0;
16215
+ if (runsPerBatch(call, call.loop)) return void 0;
16216
+ 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`;
16217
+ }
16218
+ };
16219
+ function isNamed(call, context2, file) {
16220
+ const written = `${call.model}.${call.operation}`;
16221
+ return context2.perRowWrites.some((entry) => entry.file === file && entry.call === written);
16222
+ }
16223
+
16224
+ // src/roles/sql/orm/orm-rules.ts
16225
+ var ALL_ORM_RULES = [
16226
+ filterWithoutIndex,
16227
+ queryInLoop,
16228
+ writeInLoop,
16229
+ newClient
16230
+ ];
16231
+ function ormRules(rules) {
16232
+ return ALL_ORM_RULES.filter((rule) => rules[rule.name] !== "off");
16233
+ }
16234
+
16235
+ // src/roles/sql/orm/rules/foreign-key-without-index.ts
16236
+ var foreignKeyWithoutIndex = {
16237
+ name: ORM_FK_INDEX_RULE,
16238
+ help: "index the foreign key in the schema (`@@index([field])`) and in a new migration; Prisma's guide: index the relation scalar fields"
16239
+ };
16240
+ function foreignKeyFindings(cwd, changes) {
16241
+ return changes.flatMap((change) => {
16242
+ const before = new Map(readPrismaSchema(change.base).models.map((model) => [model.name, model]));
16243
+ return judgedModelsOf(cwd, change.file).flatMap(
16244
+ (judged) => addedForeignKeys(judged.model, before.get(judged.model.name)).filter(([, scalar]) => !isIndexed2(judged, scalar)).map(([relation, scalar]) => findingOn(change, judged, relation, scalar))
16245
+ );
16246
+ });
16247
+ }
16248
+ function addedForeignKeys(model, base) {
16249
+ const said = /* @__PURE__ */ new Set();
16250
+ return [...model.foreignKeys].filter(([relation, scalar]) => {
16251
+ if (base?.foreignKeys.get(relation) === scalar || said.has(scalar)) return false;
16252
+ said.add(scalar);
16253
+ return true;
16254
+ });
16255
+ }
16256
+ function isIndexed2(judged, scalar) {
16257
+ const column = judged.model.fields.get(scalar)?.column ?? scalar;
16258
+ return judged.model.indexed.has(scalar) || (judged.indexes.get(judged.model.table)?.has(column) ?? false);
16259
+ }
16260
+ function findingOn(change, judged, relation, scalar) {
16261
+ const { model } = judged;
16262
+ const column = model.fields.get(scalar)?.column ?? scalar;
16263
+ const target = model.fields.get(relation)?.type ?? "the row it points at";
16264
+ 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}\``;
16265
+ return findingOf2(change, foreignKeyWithoutIndex, {
16266
+ offset: offsetOf(change.text, model.name, relation),
16267
+ message
16268
+ });
16269
+ }
16270
+ function offsetOf(text, model, relation) {
16271
+ const start = new RegExp(`^model\\s+${model}\\s*\\{`, "m").exec(text)?.index ?? 0;
16272
+ const field = new RegExp(`^\\s*${relation}\\s`, "m").exec(text.slice(start));
16273
+ return field === null ? start : start + field.index + (field[0].length - field[0].trimStart().length);
16274
+ }
16275
+
16276
+ // src/roles/sql/orm/rules/model-naming.ts
16277
+ var modelNaming = {
16278
+ name: ORM_MODEL_NAMING_RULE,
16279
+ help: 'name the model in PascalCase and in the singular, and map its table with `@@map`; Prisma\'s guide: `model User { ... @@map("users") }`'
16280
+ };
16281
+ var PASCAL_CASE = /^[A-Z][A-Za-z0-9]*$/;
16282
+ var READS_PLURAL = /[^s]s$/;
16283
+ var SINGULAR_ENDINGS = /(?:ss|us|is|ness)$/;
16284
+ function modelNamingFindings(changes) {
16285
+ return changes.flatMap((change) => {
16286
+ const now = readPrismaSchema(change.text);
16287
+ if (now.provider !== "postgresql") return [];
16288
+ const before = new Set(readPrismaSchema(change.base).models.map((model) => model.name));
16289
+ return now.models.filter((model) => !before.has(model.name)).flatMap((model) => {
16290
+ const problem = problemOf(model.name);
16291
+ return problem === void 0 ? [] : [
16292
+ findingOf2(change, modelNaming, {
16293
+ offset: offsetOf2(change.text, model.name),
16294
+ message: problem
16295
+ })
16296
+ ];
16297
+ });
16298
+ });
16299
+ }
16300
+ function problemOf(name) {
16301
+ if (!PASCAL_CASE.test(name)) {
16302
+ return `the model \`${name}\` this branch adds is not in PascalCase: the client reads it as \`${name}\`, unlike the other models`;
16303
+ }
16304
+ if (READS_PLURAL.test(name) && !SINGULAR_ENDINGS.test(name)) {
16305
+ 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`;
16306
+ }
16307
+ return void 0;
16308
+ }
16309
+ function offsetOf2(text, name) {
16310
+ return new RegExp(`^model\\s+${name}\\s*\\{`, "m").exec(text)?.index ?? 0;
16311
+ }
16312
+
16313
+ // src/roles/sql/raw/check-templates.ts
16314
+ import { join as join57 } from "node:path";
16315
+ import { parseSync as parseSync10 } from "oxc-parser";
16316
+
16317
+ // src/roles/sql/raw/joined-text.ts
16318
+ function joined(parts, fill) {
16319
+ const text = { sql: "", pieces: [] };
16320
+ parts.forEach((part, index) => {
16321
+ if (index > 0) {
16322
+ text.pieces.push({ at: text.sql.length, part, fill: true });
16323
+ text.sql += fill(index);
16324
+ }
16325
+ text.pieces.push({ at: text.sql.length, part, fill: false });
16326
+ text.sql += part.text;
16327
+ });
16328
+ return text;
16329
+ }
16330
+ function fileOffsetOf(text, index) {
16331
+ const piece = [...text.pieces].reverse().find((candidate) => candidate.at <= index);
16332
+ if (piece === void 0) return text.pieces[0]?.part.start ?? 0;
16333
+ if (piece.fill) return piece.part.start - 1;
16334
+ const inPart = index - piece.at;
16335
+ switch (piece.part.placing) {
16336
+ case "exact":
16337
+ return piece.part.start + inPart;
16338
+ case "crlf":
16339
+ return piece.part.start + sourceIndexAfterCrlf(piece.part.source, inPart);
16340
+ case "start":
16341
+ return piece.part.start;
16342
+ }
16343
+ }
16344
+ function sourceIndexAfterCrlf(source2, index) {
16345
+ let read2 = 0;
16346
+ for (let at = 0; at < source2.length; at++) {
16347
+ if (source2[at] === "\r" && source2[at + 1] === "\n") continue;
16348
+ if (read2 === index) return at;
16349
+ read2++;
16350
+ }
16351
+ return source2.length;
16352
+ }
16353
+
16354
+ // src/roles/sql/raw/read-template.ts
16355
+ var WRAPS = [
16356
+ ["statement", "", ""],
16357
+ ["expression", "SELECT ", ""],
16358
+ ["predicate", "SELECT 1 WHERE ", ""],
16359
+ ["from-item", "SELECT 1 FROM ", ""],
16360
+ ["after-from", "SELECT 1 FROM t ", ""],
16361
+ ["select-list", "SELECT ", " FROM t"],
16362
+ ["order-by", "SELECT 1 FROM t ORDER BY ", ""],
16363
+ ["set-list", "UPDATE t SET ", ""],
16364
+ ["values", "INSERT INTO t VALUES ", ""],
16365
+ ["cte", "WITH ", " SELECT 1"],
16366
+ ["and-tail", "SELECT 1 FROM t WHERE true ", ""],
16367
+ ["comma-tail", "SELECT 1 ", " FROM t"]
16368
+ ];
16369
+ var FILLS = [
16370
+ ["value", (n) => `$${n}`],
16371
+ ["identifier", (n) => `__p${n}`],
16372
+ ["nothing", () => ""],
16373
+ ["list", (n) => `($${n})`]
16374
+ ];
16375
+ function readTemplate(template) {
16376
+ if (template.parts.every((part) => part.text.trim() === "")) return { kind: "empty" };
16377
+ let firstError;
16378
+ for (const [fillName, fill] of FILLS) {
16379
+ const text = joined(template.parts, fill);
16380
+ for (const [wrap, before, after] of WRAPS) {
16381
+ const parsed2 = parseSql(`${before}${text.sql}${after}`);
16382
+ if (parsed2.ok) {
16383
+ return {
16384
+ kind: "read",
16385
+ reading: readingOf(
16386
+ parsed2.statements,
16387
+ { wrap, before, fill: fillName, values: template.values },
16388
+ text
16389
+ )
16390
+ };
16391
+ }
16392
+ firstError ??= parsed2.message;
16393
+ }
16394
+ }
16395
+ return { kind: "unread", reason: `PostgreSQL's parser does not read it alone (${firstError})` };
16396
+ }
16397
+ function readingOf(statements, {
16398
+ wrap,
16399
+ before,
16400
+ fill,
16401
+ values
16402
+ }, text) {
16403
+ const wrapped = `${before}${text.sql}`;
16404
+ const indexIn = (location) => indexOfByte(wrapped, location) - before.length;
16405
+ return {
16406
+ statements,
16407
+ wrap,
16408
+ fill,
16409
+ own: (location) => {
16410
+ const index = indexIn(location);
16411
+ return index >= 0 && index < text.sql.length;
16412
+ },
16413
+ fileOffset: (location) => fileOffsetOf(text, indexIn(location)),
16414
+ valueStart: (n) => fill === "value" ? values[n - 1] : void 0
16415
+ };
16416
+ }
16417
+
16418
+ // src/roles/sql/raw/template-rule.ts
16419
+ var NO_CONTEXT = {
16420
+ trigramIndexes: () => [],
16421
+ indexesFrom: () => ({ read: [], empty: [] })
16422
+ };
16423
+
16424
+ // src/roles/sql/raw/value-starts.ts
16425
+ var MAX_DEPTH2 = 8;
16426
+ function valueStart(node, bindings, depth = 0) {
16427
+ if (depth > MAX_DEPTH2) return void 0;
16428
+ const current = unwrap(node);
16429
+ const deeper = (next) => valueStart(next, bindings, depth + 1);
16430
+ switch (current.type) {
16431
+ case "Literal":
16432
+ return typeof current.value === "string" ? current.value : void 0;
16433
+ case "TemplateLiteral":
16434
+ return templateStart(current, deeper);
16435
+ case "BinaryExpression":
16436
+ return current.operator === "+" ? sumStart(current, deeper) : void 0;
16437
+ case "Identifier":
16438
+ return nameStart(current.name, bindings, deeper);
16439
+ default:
16440
+ return void 0;
16441
+ }
16442
+ }
16443
+ function templateStart(node, deeper) {
16444
+ const [first] = node.quasis;
16445
+ const value = first?.value;
16446
+ const text = value?.cooked ?? value?.raw;
16447
+ if (text === void 0) return void 0;
16448
+ const [expression] = node.expressions;
16449
+ if (text !== "" || expression === void 0) return text;
16450
+ return deeper(expression);
16451
+ }
16452
+ function sumStart(node, deeper) {
16453
+ const left = deeper(node.left);
16454
+ if (left !== "") return left;
16455
+ return deeper(node.right);
16456
+ }
16457
+ function nameStart(name, bindings, deeper) {
16458
+ const found = bindings.get(name) ?? [];
16459
+ const [binding] = found;
16460
+ if (found.length !== 1 || binding?.kind !== "const") return void 0;
16461
+ return deeper(binding.init);
16462
+ }
16463
+
16464
+ // src/roles/sql/raw/templates.ts
16465
+ function sqlTemplatesOf(program, prisma, fileText) {
16466
+ const templates = [];
16467
+ let bindings;
16468
+ const bindingsOnce = () => {
16469
+ bindings ??= bindingsOf(program);
16470
+ return bindings;
16471
+ };
16472
+ walk(program, (node) => {
16473
+ if (node.type !== "TaggedTemplateExpression") return;
16474
+ const tag = tagOf(node.tag, prisma);
16475
+ if (tag === void 0) return;
16476
+ const quasis = node.quasi.quasis;
16477
+ const parts = quasis.map((element) => partOf(element, fileText));
16478
+ const expressions = node.quasi.expressions;
16479
+ const values = expressions.map((expression) => valueStart(expression, bindingsOnce()));
16480
+ templates.push({ tag, parts, values, start: node.start });
16481
+ });
16482
+ return templates;
16483
+ }
16484
+ function tagOf(tag, prisma) {
16485
+ const member = unwrap(tag);
16486
+ const name = memberName(member);
16487
+ if (name === "$queryRaw" || name === "$executeRaw") return name;
16488
+ if (name === "sql" && isPrismaObject(unwrap(member.object), prisma))
16489
+ return "Prisma.sql";
16490
+ return void 0;
16491
+ }
16492
+ function partOf(element, fileText) {
16493
+ const value = element.value;
16494
+ const text = value.cooked ?? value.raw;
16495
+ const start = element.start + 1;
16496
+ const source2 = fileText.slice(start, element.end - (element.tail ? 1 : 2));
16497
+ const placing = source2 === text ? "exact" : source2.replace(/\r\n/g, "\n") === text ? "crlf" : "start";
16498
+ return { text, start, placing, source: source2 };
16499
+ }
16500
+
16501
+ // src/roles/sql/raw/check-templates.ts
16502
+ async function checkSqlTemplates(cwd, files, readFile, { rules, context: context2 = NO_CONTEXT }) {
16503
+ const run = { templates: 0, read: 0, unread: [], unparsed: [], findings: [] };
16504
+ if (files.length === 0) return run;
16505
+ const loaded2 = await parserLoaded2();
16506
+ if (!loaded2.ok) {
16507
+ for (const file of files) run.unparsed.push({ file, reason: loaded2.reason });
16508
+ return run;
16509
+ }
16510
+ for (const file of files) {
16511
+ const text = readFile(join57(cwd, file));
16512
+ if (text === void 0) {
16513
+ run.unparsed.push({ file, reason: "could not be read, so its SQL templates are not read" });
16514
+ continue;
16515
+ }
16516
+ checkFile2({ file, text, rules, context: context2 }, run);
16517
+ }
16518
+ return run;
15637
16519
  }
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}`;
16520
+ async function parserLoaded2() {
16521
+ try {
16522
+ await loadSqlParser();
16523
+ return { ok: true };
16524
+ } catch (error) {
16525
+ const why = error instanceof Error ? error.message : String(error);
16526
+ return {
16527
+ ok: false,
16528
+ reason: `PostgreSQL's parser could not be loaded (${why}), so its SQL templates are not read`
16529
+ };
16530
+ }
15642
16531
  }
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}`;
16532
+ function checkFile2(input, run) {
16533
+ const { file, text } = input;
16534
+ try {
16535
+ const { program, errors } = parseSync10(file, text, { sourceType: "module" });
16536
+ if (errors.length > 0) {
16537
+ const reason = `does not parse (${errors[0]?.message ?? "unknown error"})`;
16538
+ run.unparsed.push({ file, reason: `${reason}, so its SQL templates are not read` });
16539
+ return;
16540
+ }
16541
+ const tree = program;
16542
+ for (const template of sqlTemplatesOf(tree, prismaImportsOf(tree), text)) {
16543
+ checkTemplate(input, template, run);
16544
+ }
16545
+ } catch (error) {
16546
+ const why = error instanceof Error ? error.message : String(error);
16547
+ run.unparsed.push({
16548
+ file,
16549
+ reason: `could not be read (${why}), so its SQL templates are not read`
16550
+ });
16551
+ }
15650
16552
  }
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]);
16553
+ function checkTemplate(input, template, run) {
16554
+ const { line } = positionOf(input.text, template.start);
16555
+ let result;
16556
+ try {
16557
+ result = readTemplate(template);
16558
+ } catch (error) {
16559
+ run.templates++;
16560
+ run.unread.push({ file: input.file, line, reason: `could not be read (${messageOf3(error)})` });
16561
+ return;
15662
16562
  }
15663
- return void 0;
16563
+ if (result.kind === "empty") return;
16564
+ run.templates++;
16565
+ if (result.kind === "unread") {
16566
+ run.unread.push({ file: input.file, line, reason: result.reason });
16567
+ return;
16568
+ }
16569
+ run.read++;
16570
+ for (const rule of input.rules) checkRule(input, rule, result.reading, run);
15664
16571
  }
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);
16572
+ function checkRule(input, rule, reading, run) {
16573
+ let hits;
16574
+ try {
16575
+ hits = rule.check(reading, input.context);
16576
+ } catch {
16577
+ return;
16578
+ }
16579
+ for (const hit of hits) {
16580
+ const offset = reading.fileOffset(hit.location);
16581
+ run.findings.push(findingOf2(input, rule, { offset, message: hit.message }));
15677
16582
  }
15678
- return qualifiers;
16583
+ }
16584
+ function messageOf3(error) {
16585
+ return error instanceof Error ? error.message : String(error);
15679
16586
  }
15680
16587
 
15681
16588
  // src/roles/sql/raw/rules/exists-union-correlated-outside.ts
@@ -15683,11 +16590,11 @@ var existsUnionCorrelatedOutside = {
15683
16590
  name: EXISTS_UNION_RULE,
15684
16591
  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
16592
  check: (reading) => existsSublinks(reading).flatMap(({ location, select }) => {
15686
- const union = unionFilteredOutside(select);
15687
- return union === void 0 ? [] : [
16593
+ const union2 = unionFilteredOutside(select);
16594
+ return union2 === void 0 ? [] : [
15688
16595
  {
15689
16596
  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`
16597
+ 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
16598
  }
15692
16599
  ];
15693
16600
  })
@@ -15706,8 +16613,8 @@ function existsSublinks(reading) {
15706
16613
  return found;
15707
16614
  }
15708
16615
  function unionFilteredOutside(select) {
15709
- for (const { alias, union } of derivedUnions(select)) {
15710
- if (setBranches(union).some(isCorrelated)) continue;
16616
+ for (const { alias, union: union2 } of derivedUnions(select)) {
16617
+ if (setBranches(union2).some(isCorrelated)) continue;
15711
16618
  const filter = columnsUnder(select.whereClause).find(
15712
16619
  (names) => names.length === 2 && names[0] === alias
15713
16620
  );
@@ -15718,9 +16625,9 @@ function unionFilteredOutside(select) {
15718
16625
  function* derivedUnions(select) {
15719
16626
  for (const node of pgNodes(select.fromClause)) {
15720
16627
  const derived = bodyOf(node, "RangeSubselect");
15721
- const union = bodyOf(derived?.subquery, "SelectStmt");
16628
+ const union2 = bodyOf(derived?.subquery, "SelectStmt");
15722
16629
  const alias = derived ? aliasOf(derived) : void 0;
15723
- if (union?.op === "SETOP_UNION" && alias !== void 0) yield { alias, union };
16630
+ if (union2?.op === "SETOP_UNION" && alias !== void 0) yield { alias, union: union2 };
15724
16631
  }
15725
16632
  }
15726
16633
  function isCorrelated(branch) {
@@ -16146,7 +17053,7 @@ function levelCounts(findings) {
16146
17053
  function plural2(count, noun, many = `${noun}s`) {
16147
17054
  return `${count} ${count === 1 ? noun : many}`;
16148
17055
  }
16149
- function problemOf(finding3) {
17056
+ function problemOf2(finding3) {
16150
17057
  const own = SENTINEL_RULES.includes(finding3.rule);
16151
17058
  return sentence(finding3.message) + (!own && finding3.help ? ` Fix: ${endOf(finding3.help)}` : "");
16152
17059
  }
@@ -16179,7 +17086,7 @@ var placeOf = (finding3) => `${finding3.file}:${finding3.line}:${finding3.column
16179
17086
 
16180
17087
  // src/roles/sql/report/outputs.ts
16181
17088
  import { existsSync as existsSync38, mkdirSync as mkdirSync10, unlinkSync as unlinkSync3, writeFileSync as writeFileSync13 } from "node:fs";
16182
- import { join as join55 } from "node:path";
17089
+ import { join as join58 } from "node:path";
16183
17090
 
16184
17091
  // src/roles/sql/report/render-html.ts
16185
17092
  var PAGE_SIZE2 = 50;
@@ -16221,7 +17128,7 @@ function findingsOf(report, side) {
16221
17128
  (finding3) => finding3.rule !== SYNTAX_ERROR && isMigration(finding3.file) === (side === "migrations")
16222
17129
  );
16223
17130
  }
16224
- var isMigration = (file) => file.endsWith(".sql");
17131
+ var isMigration = (file) => file.endsWith(".sql") || file.endsWith(".prisma");
16225
17132
  function migrationsCount(report) {
16226
17133
  return countedFindings(report.findings).filter((finding3) => isMigration(finding3.file)).length;
16227
17134
  }
@@ -16256,7 +17163,8 @@ function readCard(report) {
16256
17163
  const parts = [
16257
17164
  report.read.length > 0 ? plural2(report.read.length, "migration") : null,
16258
17165
  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
17166
+ report.templates.templates > 0 ? plural2(report.templates.templates, "SQL template") : null,
17167
+ (report.orm?.calls ?? 0) > 0 ? plural2(report.orm?.calls ?? 0, "Prisma read") : null
16260
17168
  ].filter((part) => part !== null);
16261
17169
  const notRead = notReadCount(report);
16262
17170
  return `<div class="kpi${notRead > 0 ? " band-above" : ""}">
@@ -16266,7 +17174,7 @@ function readCard(report) {
16266
17174
  </div>`;
16267
17175
  }
16268
17176
  function notReadCount(report) {
16269
- return report.unread.length + unparsedMigrations(report.findings).length + report.unsafe.unparsed.length + report.templates.unread.length + report.templates.unparsed.length;
17177
+ 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
17178
  }
16271
17179
  function toolsCard(report) {
16272
17180
  const counted = countedFindings(report.findings);
@@ -16286,15 +17194,15 @@ function toolsCard(report) {
16286
17194
  </div>`;
16287
17195
  }
16288
17196
  function codePanel(report, findings) {
16289
- const readAny = report.unsafe.read.length > 0 || report.templates.read.length > 0;
17197
+ const readAny = report.unsafe.read.length > 0 || report.templates.read.length > 0 || (report.orm?.read.length ?? 0) > 0;
16290
17198
  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
17199
  return `${unparsedBox(
16292
17200
  "These TypeScript files could not be read, so nothing in them is checked.",
16293
- [...report.unsafe.unparsed, ...report.templates.unparsed]
17201
+ [...report.unsafe.unparsed, ...report.templates.unparsed, ...report.orm?.unparsed ?? []]
16294
17202
  )}
16295
17203
  ${findingsTable("code", findings, empty)}
16296
17204
  <h2>What was read</h2>
16297
- <div class="card">${unsafeLine(report)}${templatesLine(report)}</div>`;
17205
+ <div class="card">${unsafeLine(report)}${templatesLine(report)}${ormLine(report)}</div>`;
16298
17206
  }
16299
17207
  function migrationsPanel(report, findings) {
16300
17208
  if (report.migrations === 0) return '<p class="empty">This module holds no migration.</p>';
@@ -16379,7 +17287,7 @@ function tagsOf(finding3) {
16379
17287
  }
16380
17288
  function rowOf(finding3, fullNoteShown) {
16381
17289
  const who = SENTINEL_RULES.includes(finding3.rule) ? "sentinel" : "squawk";
16382
- const problem = problemOf(finding3);
17290
+ const problem = problemOf2(finding3);
16383
17291
  const find = `${finding3.file} ${finding3.rule} ${problem}`.toLowerCase();
16384
17292
  const level = finding3.level === "error" ? '<span class="level-error">error</span>' : "warning";
16385
17293
  const details2 = detailsOf(finding3, fullNoteShown);
@@ -16454,6 +17362,14 @@ function templatesLine(report) {
16454
17362
  );
16455
17363
  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
17364
  }
17365
+ function ormLine(report) {
17366
+ const orm = report.orm;
17367
+ if (orm === void 0 || orm.files.length === 0) return "";
17368
+ if (orm.read.length === 0) {
17369
+ 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>`;
17370
+ }
17371
+ return `<p><b>Prisma reads.</b> ${plural2(orm.calls, "Prisma Client read")} (<code>findMany</code>, <code>findFirst</code>, <code>findUnique</code>) 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>${fileList(orm.read)}`;
17372
+ }
16457
17373
  function fileList(files) {
16458
17374
  if (files.length === 0) return "";
16459
17375
  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>`;
@@ -16540,7 +17456,8 @@ function headline4(report) {
16540
17456
  const migrations = report.read.length;
16541
17457
  const files = report.unsafe.read.length;
16542
17458
  const templates = report.templates.read.length > 0 ? report.templates.templates : 0;
16543
- if (migrations === 0 && files === 0 && templates === 0) {
17459
+ const ormCalls = report.orm !== void 0 && report.orm.read.length > 0 ? report.orm.calls : 0;
17460
+ if (migrations === 0 && files === 0 && templates === 0 && ormCalls === 0) {
16544
17461
  return `No migration or raw SQL call added or changed by this branch, ${against}: nothing to check.`;
16545
17462
  }
16546
17463
  const counts = (count, what, noun) => `**${count}** ${what} ${noun}${count === 1 ? "" : "s"}`;
@@ -16551,9 +17468,14 @@ function headline4(report) {
16551
17468
  const items = [
16552
17469
  ...migrations > 0 ? [`**${migrations}** migration${migrations === 1 ? "" : "s"}`] : [],
16553
17470
  ...files > 0 ? calls : [],
16554
- ...templates > 0 ? [counts(templates, "SQL", "template")] : []
17471
+ ...templates > 0 ? [counts(templates, "SQL", "template")] : [],
17472
+ ...ormCalls > 0 ? [counts(ormCalls, "Prisma", "read")] : []
16555
17473
  ];
16556
- const codeFiles2 = (/* @__PURE__ */ new Set([...report.unsafe.read, ...report.templates.read])).size;
17474
+ const codeFiles2 = (/* @__PURE__ */ new Set([
17475
+ ...report.unsafe.read,
17476
+ ...report.templates.read,
17477
+ ...report.orm?.read ?? []
17478
+ ])).size;
16557
17479
  const where = codeFiles2 > 0 ? ` in ${codeFiles2} file${codeFiles2 === 1 ? "" : "s"}` : "";
16558
17480
  const read2 = items.length > 1 ? `${items.slice(0, -1).join(", ")} and ${items.at(-1)}${where}` : `${items.join("")}${where}`;
16559
17481
  const findings = countedFindings(report.findings).length;
@@ -16563,7 +17485,7 @@ function headline4(report) {
16563
17485
  return `Read ${read2} this branch adds or changes, ${against}: ${found}.`;
16564
17486
  }
16565
17487
  function readAnything(report) {
16566
- return report.read.length > 0 || report.unsafe.read.length > 0 || report.templates.read.length > 0;
17488
+ return report.read.length > 0 || report.unsafe.read.length > 0 || report.templates.read.length > 0 || (report.orm?.read.length ?? 0) > 0;
16567
17489
  }
16568
17490
  function fileBlocks(report) {
16569
17491
  const findings = report.findings.filter((finding3) => finding3.rule !== SYNTAX_ERROR);
@@ -16596,7 +17518,7 @@ function fileBlocks(report) {
16596
17518
  }
16597
17519
  function rowOf2(finding3) {
16598
17520
  const level = finding3.level === "error" ? "\u2717 error" : "warn";
16599
- return `| ${finding3.line} | ${level} | \`${finding3.rule}\` | ${cell3(problemOf(finding3))} |`;
17521
+ return `| ${finding3.line} | ${level} | \`${finding3.rule}\` | ${cell3(problemOf2(finding3))} |`;
16600
17522
  }
16601
17523
  function cell3(text) {
16602
17524
  return text.replace(/\|/g, "\\|").replace(/\s*\n\s*/g, " ");
@@ -16675,12 +17597,12 @@ var writesFiles2 = (shapes) => shapes.some((shape) => shape !== "console");
16675
17597
  function writeOutputs2(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
16676
17598
  if (!writesFiles2(shapes)) return [];
16677
17599
  removeOutputs2(cwd, shapes);
16678
- mkdirSync10(join55(cwd, REPORT_DIR3), { recursive: true });
17600
+ mkdirSync10(join58(cwd, REPORT_DIR3), { recursive: true });
16679
17601
  const written = [];
16680
17602
  for (const shape of shapes) {
16681
17603
  if (shape === "console") continue;
16682
- const path2 = join55(REPORT_DIR3, SHAPE_FILE3[shape]);
16683
- writeFileSync13(join55(cwd, path2), render2(report, shape, now));
17604
+ const path2 = join58(REPORT_DIR3, SHAPE_FILE3[shape]);
17605
+ writeFileSync13(join58(cwd, path2), render2(report, shape, now));
16684
17606
  written.push(path2);
16685
17607
  }
16686
17608
  return written;
@@ -16688,7 +17610,7 @@ function writeOutputs2(cwd, report, shapes, now = /* @__PURE__ */ new Date()) {
16688
17610
  function removeOutputs2(cwd, keeping = []) {
16689
17611
  for (const [shape, name] of Object.entries(SHAPE_FILE3)) {
16690
17612
  if (keeping.includes(shape)) continue;
16691
- const path2 = join55(cwd, REPORT_DIR3, name);
17613
+ const path2 = join58(cwd, REPORT_DIR3, name);
16692
17614
  if (existsSync38(path2)) unlinkSync3(path2);
16693
17615
  }
16694
17616
  }
@@ -16699,23 +17621,23 @@ function render2(report, shape, now) {
16699
17621
  }
16700
17622
 
16701
17623
  // 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";
17624
+ import { existsSync as existsSync39, readFileSync as readFileSync34, realpathSync as realpathSync2 } from "node:fs";
17625
+ import { dirname as dirname11, join as join59, matchesGlob as matchesGlob3, relative as relative11, resolve as resolve9, sep as sep6 } from "node:path";
17626
+ import { globSync as globSync5 } from "tinyglobby";
16705
17627
  var WALK2 = { onlyFiles: true, dot: false, followSymbolicLinks: false };
16706
17628
  var ADOPTION_FILE = "sql.config.mjs";
16707
17629
  function adoptedInnerModules(cwd, nested) {
16708
17630
  return (nested ?? adoptedInnerDirs(cwd)).map((dir) => `${dir}/**`);
16709
17631
  }
16710
17632
  function adoptedInnerDirs(cwd) {
16711
- return globSync4([`**/${ADOPTION_FILE}`], {
17633
+ return globSync5([`**/${ADOPTION_FILE}`], {
16712
17634
  ...WALK2,
16713
17635
  cwd,
16714
17636
  ignore: ["**/node_modules/**"]
16715
17637
  }).map((file) => file.slice(0, -ADOPTION_FILE.length - 1)).filter((dir) => dir !== "");
16716
17638
  }
16717
17639
  function migrationFiles(cwd, settings, nested) {
16718
- return globSync4(settings.migrations.include, {
17640
+ return globSync5(settings.migrations.include, {
16719
17641
  ...WALK2,
16720
17642
  cwd,
16721
17643
  ignore: [
@@ -16726,16 +17648,16 @@ function migrationFiles(cwd, settings, nested) {
16726
17648
  }).sort();
16727
17649
  }
16728
17650
  function migrationRoots(cwd, settings, migrations, nested) {
16729
- const locks = globSync4(["**/migration_lock.toml"], {
17651
+ const locks = globSync5(["**/migration_lock.toml"], {
16730
17652
  ...WALK2,
16731
17653
  cwd,
16732
17654
  ignore: ["**/node_modules/**", ...settings.ignore, ...adoptedInnerModules(cwd, nested)]
16733
- }).map((file) => dirname10(file));
16734
- const holding = migrations.map((file) => dirname10(dirname10(file)));
17655
+ }).map((file) => dirname11(file));
17656
+ const holding = migrations.map((file) => dirname11(dirname11(file)));
16735
17657
  return [.../* @__PURE__ */ new Set([...locks, ...holding])].sort();
16736
17658
  }
16737
17659
  function codeFiles(cwd, settings, nested) {
16738
- return globSync4(["**/*.{ts,mts,cts}"], {
17660
+ return globSync5(["**/*.{ts,mts,cts}"], {
16739
17661
  ...WALK2,
16740
17662
  cwd,
16741
17663
  ignore: [
@@ -16746,6 +17668,13 @@ function codeFiles(cwd, settings, nested) {
16746
17668
  ]
16747
17669
  }).sort();
16748
17670
  }
17671
+ function prismaSchemaFiles(cwd, settings, nested) {
17672
+ return globSync5(["**/*.prisma"], {
17673
+ ...WALK2,
17674
+ cwd,
17675
+ ignore: [...settings.ignore, ...adoptedInnerModules(cwd, nested)]
17676
+ }).sort();
17677
+ }
16749
17678
  var UNSAFE_CALL = /\$(?:queryRaw|executeRaw)Unsafe\b/;
16750
17679
  var PRISMA_IMPORT = /from\s*['"]@prisma\//;
16751
17680
  var RAW_CALL = /\.raw\s*\(/;
@@ -16765,7 +17694,7 @@ function callsUnsafe(text) {
16765
17694
  }
16766
17695
  function fileMatches(cwd, file, test) {
16767
17696
  try {
16768
- return test(readFileSync32(join56(cwd, file), "utf8"));
17697
+ return test(readFileSync34(join59(cwd, file), "utf8"));
16769
17698
  } catch {
16770
17699
  return false;
16771
17700
  }
@@ -16775,17 +17704,21 @@ var SQL_TEMPLATE = /\.sql\s*`/;
16775
17704
  function holdsSqlTemplate(text) {
16776
17705
  return PRISMA_TEMPLATE.test(text) || PRISMA_IMPORT.test(text) && SQL_TEMPLATE.test(text);
16777
17706
  }
16778
- function filesWithSql(cwd, files) {
16779
- const found = { unsafe: [], templates: [] };
17707
+ var PRISMA_CALL = /\.(?:find(?:Many|First|Unique)(?:OrThrow)?|create(?:Many(?:AndReturn)?)?|update(?:Many(?:AndReturn)?)?|upsert|delete(?:Many)?)\s*\(|new\s+(?:\w+\.)?PrismaClient\b/;
17708
+ function filesWithSql(cwd, files, tests = []) {
17709
+ const found = { unsafe: [], templates: [], orm: [] };
16780
17710
  for (const file of files) {
16781
17711
  let text;
16782
17712
  try {
16783
- text = readFileSync32(join56(cwd, file), "utf8");
17713
+ text = readFileSync34(join59(cwd, file), "utf8");
16784
17714
  } catch {
16785
17715
  continue;
16786
17716
  }
16787
17717
  if (callsUnsafe(text)) found.unsafe.push(file);
16788
17718
  if (holdsSqlTemplate(text)) found.templates.push(file);
17719
+ if (PRISMA_CALL.test(text) && !tests.some((pattern) => matchesGlob3(file, pattern))) {
17720
+ found.orm.push(file);
17721
+ }
16789
17722
  }
16790
17723
  return found;
16791
17724
  }
@@ -16806,33 +17739,33 @@ function rawSqlInParent(cwd) {
16806
17739
  return void 0;
16807
17740
  }
16808
17741
  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("/")}/`;
17742
+ if (stop === void 0 || dirname11(here) === here) return void 0;
17743
+ const parent = findModuleRoot(dirname11(here), stop);
17744
+ if (parent === void 0 || existsSync39(join59(parent, ADOPTION_FILE))) return void 0;
17745
+ const mine = `${relative11(parent, here).split(sep6).join("/")}/`;
16813
17746
  const files = filesWithUnsafeCalls(
16814
17747
  parent,
16815
17748
  codeFiles(parent, defaults4).filter((file) => !file.startsWith(mine))
16816
17749
  );
16817
17750
  if (files.length === 0) return void 0;
16818
- return { dir: relative10(here, parent).split(sep6).join("/"), files };
17751
+ return { dir: relative11(here, parent).split(sep6).join("/"), files };
16819
17752
  }
16820
17753
  function migrationsInNested(cwd, settings = defaults4, nested = adoptedInnerDirs(cwd)) {
16821
17754
  const out = [];
16822
17755
  for (const dir of nested) {
16823
- const count = migrationFiles(join56(cwd, dir), defaults4).length;
17756
+ const count = migrationFiles(join59(cwd, dir), defaults4).length;
16824
17757
  if (count > 0) out.push({ dir, count, adopted: true });
16825
17758
  }
16826
17759
  const root = resolve9(cwd);
16827
17760
  const owner = /* @__PURE__ */ new Map();
16828
17761
  const counts = /* @__PURE__ */ new Map();
16829
17762
  for (const file of migrationFiles(cwd, settings, nested)) {
16830
- const folder = dirname10(join56(root, file));
17763
+ const folder = dirname11(join59(root, file));
16831
17764
  if (!owner.has(folder)) {
16832
17765
  const project = findModuleRoot(folder, root);
16833
17766
  owner.set(
16834
17767
  folder,
16835
- project === void 0 ? void 0 : relative10(root, project).split(sep6).join("/")
17768
+ project === void 0 ? void 0 : relative11(root, project).split(sep6).join("/")
16836
17769
  );
16837
17770
  }
16838
17771
  const dir = owner.get(folder);
@@ -16842,105 +17775,6 @@ function migrationsInNested(cwd, settings = defaults4, nested = adoptedInnerDirs
16842
17775
  return out.sort((a, b) => a.dir.localeCompare(b.dir));
16843
17776
  }
16844
17777
 
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
17778
  // src/roles/sql/adapters/squawk/resolve-squawk.ts
16945
17779
  function resolveSquawk(cwd) {
16946
17780
  return resolveBin(cwd, "squawk") ?? binFromOwnInstall("squawk-cli", "squawk");
@@ -16951,9 +17785,9 @@ function squawkNotFound(cwd) {
16951
17785
 
16952
17786
  // src/roles/sql/adapters/squawk/run-squawk.ts
16953
17787
  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";
17788
+ import { mkdtempSync as mkdtempSync4, readFileSync as readFileSync35, rmSync as rmSync8, writeFileSync as writeFileSync15 } from "node:fs";
16955
17789
  import { tmpdir as tmpdir4 } from "node:os";
16956
- import { join as join59 } from "node:path";
17790
+ import { join as join61 } from "node:path";
16957
17791
 
16958
17792
  // src/roles/sql/adapters/squawk/read-output.ts
16959
17793
  function readSquawkOutput(stdout, stderr) {
@@ -17011,7 +17845,7 @@ function toFinding(entry) {
17011
17845
  // src/roles/sql/adapters/squawk/squawk-config.ts
17012
17846
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync7, writeFileSync as writeFileSync14 } from "node:fs";
17013
17847
  import { tmpdir as tmpdir3 } from "node:os";
17014
- import { join as join58 } from "node:path";
17848
+ import { join as join60 } from "node:path";
17015
17849
  function squawkToml(settings) {
17016
17850
  const squawks = (rule) => !NOT_SQUAWK_CONFIG.includes(rule);
17017
17851
  const off = rulesOff(settings.rules ?? {}).filter(squawks);
@@ -17025,9 +17859,9 @@ function squawkToml(settings) {
17025
17859
  ].join("\n");
17026
17860
  }
17027
17861
  function withSquawkConfig(settings, use) {
17028
- const dir = mkdtempSync3(join58(tmpdir3(), "sentinel-squawk-"));
17862
+ const dir = mkdtempSync3(join60(tmpdir3(), "sentinel-squawk-"));
17029
17863
  try {
17030
- const configPath = join58(dir, "squawk.toml");
17864
+ const configPath = join60(dir, "squawk.toml");
17031
17865
  writeFileSync14(configPath, squawkToml(settings));
17032
17866
  return use(configPath);
17033
17867
  } finally {
@@ -17108,7 +17942,7 @@ function quietTimeoutFiles(invocation, readable, statements, wrapped) {
17108
17942
  for (const file of readable) {
17109
17943
  const read2 = statements.get(file);
17110
17944
  if (read2 === void 0 || !wrapped(file)) continue;
17111
- const text = readText(invocation.cwd, file);
17945
+ const text = readText2(invocation.cwd, file);
17112
17946
  if (text !== void 0 && onlyBuildsNewTables(read2.types, text, false)) texts.set(file, text);
17113
17947
  }
17114
17948
  if (texts.size === 0) return /* @__PURE__ */ new Set();
@@ -17117,9 +17951,9 @@ function quietTimeoutFiles(invocation, readable, statements, wrapped) {
17117
17951
  return new Set([...texts.keys()].filter((file) => !onExisting.has(file)));
17118
17952
  }
17119
17953
  function indexesOnExistingTables(invocation, files) {
17120
- const dir = mkdtempSync4(join59(tmpdir4(), "sentinel-squawk-"));
17954
+ const dir = mkdtempSync4(join61(tmpdir4(), "sentinel-squawk-"));
17121
17955
  try {
17122
- const configPath = join59(dir, "squawk.toml");
17956
+ const configPath = join61(dir, "squawk.toml");
17123
17957
  writeFileSync15(configPath, DEFAULT_SQUAWK_TOML);
17124
17958
  const found = /* @__PURE__ */ new Set();
17125
17959
  for (const batch of batches(files)) {
@@ -17133,9 +17967,9 @@ function indexesOnExistingTables(invocation, files) {
17133
17967
  rmSync8(dir, { recursive: true, force: true });
17134
17968
  }
17135
17969
  }
17136
- function readText(cwd, file) {
17970
+ function readText2(cwd, file) {
17137
17971
  try {
17138
- return readFileSync34(join59(cwd, file), "utf8");
17972
+ return readFileSync35(join61(cwd, file), "utf8");
17139
17973
  } catch {
17140
17974
  return void 0;
17141
17975
  }
@@ -17217,7 +18051,7 @@ function openable(cwd, files) {
17217
18051
  const utf8 = new TextDecoder("utf-8", { fatal: true });
17218
18052
  for (const file of files) {
17219
18053
  try {
17220
- utf8.decode(readFileSync34(join59(cwd, file)));
18054
+ utf8.decode(readFileSync35(join61(cwd, file)));
17221
18055
  readable.push(file);
17222
18056
  } catch (error) {
17223
18057
  unread.push({ file, reason: unreadReason(error) });
@@ -17321,6 +18155,7 @@ function summariseMigrations(outcome) {
17321
18155
  whatWasRead(outcome),
17322
18156
  ...codeReadLines(outcome),
17323
18157
  ...templateLines(outcome.templates),
18158
+ ...ormLines(outcome.orm),
17324
18159
  ...offLines(outcome),
17325
18160
  ...unreadLines(outcome.unread),
17326
18161
  ...unparsedLines(outcome.code.unparsed),
@@ -17356,6 +18191,18 @@ function codeReadLines({ code, rulesOff: rulesOff2 }) {
17356
18191
  `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
18192
  ];
17358
18193
  }
18194
+ function ormLines(orm) {
18195
+ if (orm === void 0 || orm.files === 0) return [];
18196
+ if (orm.read === 0) {
18197
+ return [
18198
+ `${orm.files} file(s) make Prisma Client calls; none is added or changed by this branch, so none is read.`
18199
+ ];
18200
+ }
18201
+ return [
18202
+ `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.`,
18203
+ ...orm.unparsed.map(({ file, reason }) => ` ${file}: ${reason}`)
18204
+ ];
18205
+ }
17359
18206
  var TEMPLATE_PLACES = 3;
17360
18207
  var TEMPLATE_TAGS = "$queryRaw, $executeRaw, Prisma.sql";
17361
18208
  function templateLines(templates) {
@@ -17512,7 +18359,7 @@ var SquawkAdapter = class extends BaseAdapter {
17512
18359
  skipped: `no migration (${defaults4.migrations.include.join(", ")}) and no raw SQL call in this module: nothing for the ${TARGET3} role to read.`
17513
18360
  };
17514
18361
  }
17515
- const hasConfig = existsSync40(join60(context2.cwd, SQL_CONFIG_FILE));
18362
+ const hasConfig = existsSync40(join62(context2.cwd, SQL_CONFIG_FILE));
17516
18363
  const declared = moduleScripts(context2.cwd);
17517
18364
  const missingScripts = Object.keys(scripts2()).filter((name) => !(name in declared));
17518
18365
  return {
@@ -17613,7 +18460,7 @@ var SquawkAdapter = class extends BaseAdapter {
17613
18460
  const reading = whatTheModuleHolds(ctx.cwd, config);
17614
18461
  const selection = branchFiles(ctx.cwd, reading);
17615
18462
  if (!selection.ok) return failing(selection.reason, countsOf(reading));
17616
- const { read: read2, base, code, templateCode } = selection;
18463
+ const { read: read2, base, code, templateCode, ormCode, schemaCode } = selection;
17617
18464
  const run = this.checkMigrations(ctx.cwd, config, read2);
17618
18465
  if (!run.ok) return failing(run.reason, countsOf(reading));
17619
18466
  const history = appliedChanges(ctx.cwd, config, base ?? selection.quietBase, reading.nested);
@@ -17623,6 +18470,16 @@ var SquawkAdapter = class extends BaseAdapter {
17623
18470
  rules: templateRules(config.rules),
17624
18471
  context: trigramContext(ctx.cwd, reading.migrations, config.migrations.indexesFrom)
17625
18472
  });
18473
+ const orm = await checkOrmCalls(ctx.cwd, ormCode, readAbsolute, {
18474
+ rules: ormRules(config.rules),
18475
+ context: ormContext(ctx.cwd, {
18476
+ indexesFrom: config.migrations.indexesFrom,
18477
+ referenceTables: config.orm.referenceTables,
18478
+ perRowWrites: config.orm.perRowWrites,
18479
+ scripts: config.orm.scripts,
18480
+ ignore: config.ignore
18481
+ })
18482
+ });
17626
18483
  const findings = withNotes(
17627
18484
  [
17628
18485
  ...history.findings,
@@ -17630,9 +18487,11 @@ var SquawkAdapter = class extends BaseAdapter {
17630
18487
  ...run.findings,
17631
18488
  ...enumFindings(ctx.cwd, config, read2, run),
17632
18489
  ...unsafe.findings,
17633
- ...templates.findings
18490
+ ...templates.findings,
18491
+ ...orm.findings,
18492
+ ...await schemaFindings(ctx.cwd, config, schemaCode, base)
17634
18493
  ],
17635
- (file) => readText2(ctx.cwd, file),
18494
+ (file) => readText3(ctx.cwd, file),
17636
18495
  config.rules
17637
18496
  );
17638
18497
  const outcome = {
@@ -17649,12 +18508,19 @@ var SquawkAdapter = class extends BaseAdapter {
17649
18508
  rawCalls: unsafe.rawCalls,
17650
18509
  unparsed: unsafe.unparsed
17651
18510
  },
17652
- templates: templatesOutcome(reading, templateCode, templates)
18511
+ templates: templatesOutcome(reading, templateCode, templates),
18512
+ orm: {
18513
+ files: reading.orm.length,
18514
+ read: ormCode.length,
18515
+ calls: orm.calls,
18516
+ writes: orm.writes,
18517
+ unparsed: orm.unparsed
18518
+ }
17653
18519
  };
17654
18520
  if (mode.speaking) {
17655
18521
  for (const line of describeRun(outcome, reading, config, selection.quietNote)) this.say(line);
17656
18522
  for (const dir of reading.nested) {
17657
- const count = migrationFiles(join60(ctx.cwd, dir), defaults4).length;
18523
+ const count = migrationFiles(join62(ctx.cwd, dir), defaults4).length;
17658
18524
  if (count > 0)
17659
18525
  this.say(
17660
18526
  `the ${count} migration(s) under ${dir} are reported by that project, which adopted the role itself.`
@@ -17666,7 +18532,7 @@ var SquawkAdapter = class extends BaseAdapter {
17666
18532
  reportOf(
17667
18533
  ctx,
17668
18534
  config,
17669
- { reading, read: read2, code: unsafeOff ? [] : code, templateCode },
18535
+ { reading, read: read2, code: unsafeOff ? [] : code, templateCode, ormCode },
17670
18536
  {
17671
18537
  outcome,
17672
18538
  findings
@@ -17732,7 +18598,7 @@ var SquawkAdapter = class extends BaseAdapter {
17732
18598
  const expected = Object.keys(scripts2());
17733
18599
  const missing = expected.filter((name) => !(name in declared));
17734
18600
  const adopted = missing.length < expected.length;
17735
- const hasConfig = existsSync40(join60(ctx.cwd, SQL_CONFIG_FILE));
18601
+ const hasConfig = existsSync40(join62(ctx.cwd, SQL_CONFIG_FILE));
17736
18602
  return {
17737
18603
  adopted,
17738
18604
  preset: adopted ? ctx.preset : null,
@@ -17786,10 +18652,18 @@ function describeRun(outcome, reading, config, quietNote = null) {
17786
18652
  return summariseMigrations(outcome);
17787
18653
  }
17788
18654
  function branchFiles(cwd, reading) {
17789
- const { migrations, unsafe, templates } = reading;
17790
- if (migrations.length === 0 && unsafe.length === 0 && templates.length === 0) {
18655
+ const { migrations, unsafe, templates, orm, schemas } = reading;
18656
+ if (migrations.length === 0 && unsafe.length === 0 && templates.length === 0 && orm.length === 0 && schemas.length === 0) {
17791
18657
  const quiet = branchChanges(cwd, process.env, "migrations and raw SQL calls");
17792
- const none = { ok: true, read: [], code: [], templateCode: [], base: null };
18658
+ const none = {
18659
+ ok: true,
18660
+ read: [],
18661
+ code: [],
18662
+ templateCode: [],
18663
+ ormCode: [],
18664
+ schemaCode: [],
18665
+ base: null
18666
+ };
17793
18667
  if (quiet.ok) return { ...none, quietBase: quiet.base, quietNote: null };
17794
18668
  const quietNote = insideRepository(cwd) ? `the migrations this branch deletes were not looked for: ${quiet.reason}` : null;
17795
18669
  return { ...none, quietBase: null, quietNote };
@@ -17802,6 +18676,8 @@ function branchFiles(cwd, reading) {
17802
18676
  read: changed(migrations),
17803
18677
  code: changed(unsafe),
17804
18678
  templateCode: changed(templates),
18679
+ ormCode: changed(orm),
18680
+ schemaCode: changed(schemas),
17805
18681
  base: changes.base,
17806
18682
  quietBase: null,
17807
18683
  quietNote: null
@@ -17822,6 +18698,21 @@ function appliedChanges(cwd, config, base, nested) {
17822
18698
  if (!reading.ok) return reading;
17823
18699
  return { ok: true, findings: historyFindings(reading.changes, base.ref) };
17824
18700
  }
18701
+ async function schemaFindings(cwd, config, schemas, base) {
18702
+ const foreignKeys = config.rules[ORM_FK_INDEX_RULE] !== "off";
18703
+ const naming = config.rules[ORM_MODEL_NAMING_RULE] !== "off";
18704
+ if (base === null || schemas.length === 0 || !(foreignKeys || naming)) return [];
18705
+ const changes = schemas.flatMap((file) => {
18706
+ const text = readText3(cwd, file);
18707
+ const before = textAtCommit(cwd, base.sha, file);
18708
+ return text === void 0 || before === void 0 ? [] : [{ file, text, base: before }];
18709
+ });
18710
+ const indexed = foreignKeys && (await parserLoaded()).ok;
18711
+ return [
18712
+ ...indexed ? foreignKeyFindings(cwd, changes) : [],
18713
+ ...naming ? modelNamingFindings(changes) : []
18714
+ ];
18715
+ }
17825
18716
  function missingFiles(cwd, config, reading, said) {
17826
18717
  if (config.rules[FOLDER_RULE] === "off") return [];
17827
18718
  const already = new Set(said.map((finding3) => finding3.file));
@@ -17834,20 +18725,22 @@ function enumFindings(cwd, config, files, run) {
17834
18725
  if (config.rules[ENUM_VALUE_RULE] === "off") return [];
17835
18726
  return files.flatMap((file) => {
17836
18727
  const count = run.statementCounts?.get(file);
17837
- const text = count === void 0 ? void 0 : readText2(cwd, file);
18728
+ const text = count === void 0 ? void 0 : readText3(cwd, file);
17838
18729
  return count === void 0 || text === void 0 ? [] : enumValueFindings(file, text, count);
17839
18730
  });
17840
18731
  }
17841
18732
  function whatTheModuleHolds(cwd, config) {
17842
18733
  const nested = adoptedInnerDirs(cwd);
17843
18734
  const code = codeFiles(cwd, config, nested);
17844
- const { unsafe, templates } = filesWithSql(cwd, code);
18735
+ const { unsafe, templates, orm } = filesWithSql(cwd, code, config.unsafe.tests);
17845
18736
  return {
17846
18737
  migrations: migrationFiles(cwd, config, nested),
17847
18738
  codeFiles: code.length,
17848
18739
  unsafe,
17849
18740
  unsafeFiles: unsafe.length,
17850
18741
  templates,
18742
+ orm,
18743
+ schemas: prismaSchemaFiles(cwd, config, nested),
17851
18744
  nested
17852
18745
  };
17853
18746
  }
@@ -17901,7 +18794,7 @@ function metricsOf(outcome) {
17901
18794
  };
17902
18795
  }
17903
18796
  function reportOf(ctx, config, files, result) {
17904
- const { reading, read: read2, code, templateCode } = files;
18797
+ const { reading, read: read2, code, templateCode, ormCode } = files;
17905
18798
  const { outcome, findings } = result;
17906
18799
  return {
17907
18800
  module: ctx.module,
@@ -17929,19 +18822,26 @@ function reportOf(ctx, config, files, result) {
17929
18822
  unread: [...outcome.templates.unread],
17930
18823
  unparsed: [...outcome.templates.unparsed]
17931
18824
  },
18825
+ orm: {
18826
+ files: reading.orm,
18827
+ read: [...ormCode],
18828
+ calls: outcome.orm?.calls ?? 0,
18829
+ writes: outcome.orm?.writes ?? 0,
18830
+ unparsed: [...outcome.orm?.unparsed ?? []]
18831
+ },
17932
18832
  settings: settingsList2(config)
17933
18833
  };
17934
18834
  }
17935
18835
  function readAbsolute(path2) {
17936
18836
  try {
17937
- return readFileSync35(path2, "utf8");
18837
+ return readFileSync36(path2, "utf8");
17938
18838
  } catch {
17939
18839
  return void 0;
17940
18840
  }
17941
18841
  }
17942
- function readText2(cwd, file) {
18842
+ function readText3(cwd, file) {
17943
18843
  try {
17944
- return readFileSync35(join60(cwd, file), "utf8");
18844
+ return readFileSync36(join62(cwd, file), "utf8");
17945
18845
  } catch {
17946
18846
  return void 0;
17947
18847
  }
@@ -17986,9 +18886,9 @@ function registerSql() {
17986
18886
 
17987
18887
  // src/roles/static-analysis/adapters/jscpd/jscpd.adapter.ts
17988
18888
  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";
18889
+ import { existsSync as existsSync44, mkdirSync as mkdirSync12, readFileSync as readFileSync40, unlinkSync as unlinkSync4, writeFileSync as writeFileSync17 } from "node:fs";
18890
+ import { join as join67, relative as relative12, sep as sep7 } from "node:path";
18891
+ import { globSync as globSync9 } from "tinyglobby";
17992
18892
 
17993
18893
  // src/roles/static-analysis/bundle/budgets.ts
17994
18894
  var TRANSFER_REFERENCES = {
@@ -18016,31 +18916,31 @@ function bandFor(valueKb, referenceKb) {
18016
18916
  }
18017
18917
 
18018
18918
  // 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";
18919
+ import { existsSync as existsSync42, readFileSync as readFileSync38 } from "node:fs";
18920
+ import { basename as basename4, join as join64 } from "node:path";
18021
18921
  import { pathToFileURL as pathToFileURL7 } from "node:url";
18022
18922
  import { gzipSync } from "node:zlib";
18023
- import { globSync as globSync6 } from "tinyglobby";
18923
+ import { globSync as globSync7 } from "tinyglobby";
18024
18924
 
18025
18925
  // 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";
18926
+ import { existsSync as existsSync41, readFileSync as readFileSync37, statSync as statSync8 } from "node:fs";
18927
+ import { join as join63 } from "node:path";
18928
+ import { globSync as globSync6 } from "tinyglobby";
18029
18929
  var MANIFEST_GLOB = "server/_tanstack-start-manifest*.mjs";
18030
18930
  function candidateDirs(cwd) {
18031
18931
  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")];
18932
+ const fromDeclaration = Array.isArray(declared) ? declared.filter((token) => typeof token === "string").map((token) => join63(cwd, token.replace(/^\{projectRoot\}\//, ""))) : [];
18933
+ return [...fromDeclaration, join63(cwd, ".output"), join63(cwd, "dist"), join63(cwd, "build")];
18034
18934
  }
18035
18935
  function findBuildOutput(cwd) {
18036
18936
  const lookedIn = [];
18037
18937
  for (const dir of candidateDirs(cwd)) {
18038
18938
  lookedIn.push(dir);
18039
18939
  if (!existsSync41(dir)) continue;
18040
- const found = globSync5(MANIFEST_GLOB, { cwd: dir, absolute: true, dot: false });
18940
+ const found = globSync6(MANIFEST_GLOB, { cwd: dir, absolute: true, dot: false });
18041
18941
  if (found.length === 0) continue;
18042
18942
  const manifestPath = found[0];
18043
- const publicDir = join61(dir, "public");
18943
+ const publicDir = join63(dir, "public");
18044
18944
  if (!existsSync41(publicDir)) continue;
18045
18945
  return { manifestPath, publicDir, ...dateOf(dir, manifestPath) };
18046
18946
  }
@@ -18063,10 +18963,10 @@ function findBuildOutput(cwd) {
18063
18963
  };
18064
18964
  }
18065
18965
  function dateOf(dir, manifestPath) {
18066
- const record = join61(dir, "nitro.json");
18966
+ const record = join63(dir, "nitro.json");
18067
18967
  if (existsSync41(record)) {
18068
18968
  try {
18069
- const parsed2 = JSON.parse(readFileSync36(record, "utf8"));
18969
+ const parsed2 = JSON.parse(readFileSync37(record, "utf8"));
18070
18970
  if (typeof parsed2.date === "string") {
18071
18971
  const date = new Date(parsed2.date);
18072
18972
  if (!Number.isNaN(date.getTime())) return { builtAt: date, builtAtFrom: "build record" };
@@ -18092,9 +18992,9 @@ function kindOf3(path2) {
18092
18992
  return "other";
18093
18993
  }
18094
18994
  function resolveAnnounced(publicDir, announced) {
18095
- const direct = join62(publicDir, announced);
18995
+ const direct = join64(publicDir, announced);
18096
18996
  if (existsSync42(direct)) return direct;
18097
- const stripped = join62(publicDir, announced.replace(/^\/[^/]+\//, "/"));
18997
+ const stripped = join64(publicDir, announced.replace(/^\/[^/]+\//, "/"));
18098
18998
  return existsSync42(stripped) ? stripped : void 0;
18099
18999
  }
18100
19000
  function emptyWeight() {
@@ -18131,7 +19031,7 @@ async function scanBundle(cwd) {
18131
19031
  unresolved.push(announced);
18132
19032
  measured.set(announced, void 0);
18133
19033
  } else {
18134
- const buffer = readFileSync37(path2);
19034
+ const buffer = readFileSync38(path2);
18135
19035
  measured.set(announced, {
18136
19036
  parsed: buffer.length,
18137
19037
  transfer: gzipSync(buffer, { level: 9 }).length
@@ -18211,14 +19111,14 @@ function scanDynamicLayer(publicDir, references) {
18211
19111
  const referenced = new Set([...references].map((announced) => basename4(announced)));
18212
19112
  const groups = /* @__PURE__ */ new Map();
18213
19113
  const all2 = emptyWeight();
18214
- for (const path2 of globSync6("assets/*.{js,mjs,cjs}", {
19114
+ for (const path2 of globSync7("assets/*.{js,mjs,cjs}", {
18215
19115
  cwd: publicDir,
18216
19116
  absolute: true,
18217
19117
  dot: false
18218
19118
  })) {
18219
19119
  const name = basename4(path2);
18220
19120
  if (referenced.has(name)) continue;
18221
- const buffer = readFileSync37(path2);
19121
+ const buffer = readFileSync38(path2);
18222
19122
  const size = { parsed: buffer.length, transfer: gzipSync(buffer, { level: 9 }).length };
18223
19123
  add(all2, size);
18224
19124
  const group = groupOf(name);
@@ -18279,7 +19179,7 @@ function collectComplexity() {
18279
19179
 
18280
19180
  // src/roles/static-analysis/coverage.ts
18281
19181
  import path from "node:path";
18282
- import { globSync as globSync7 } from "tinyglobby";
19182
+ import { globSync as globSync8 } from "tinyglobby";
18283
19183
  var UNREADABLE_EXTENSIONS = [".svelte", ".vue", ".astro"];
18284
19184
  function hasUnreadableCode(coverage) {
18285
19185
  return coverage.unread > 0;
@@ -18289,9 +19189,9 @@ function coverageOf(cwd, config) {
18289
19189
  const readable = extensionsOf(config.languages).map((extension) => extension.slice(1)).join(",");
18290
19190
  const roots = measuredRoots(cwd);
18291
19191
  const under2 = (extensions) => roots.map((root) => root === "." ? `**/*.{${extensions}}` : `${root}/**/*.{${extensions}}`);
18292
- const read2 = readable ? globSync7(under2(readable), { cwd, ignore, dot: false }).length : 0;
19192
+ const read2 = readable ? globSync8(under2(readable), { cwd, ignore, dot: false }).length : 0;
18293
19193
  const unreadable = UNREADABLE_EXTENSIONS.map((extension) => extension.slice(1)).join(",");
18294
- const found = globSync7(under2(unreadable), { cwd, ignore, dot: false });
19194
+ const found = globSync8(under2(unreadable), { cwd, ignore, dot: false });
18295
19195
  const total = read2 + found.length;
18296
19196
  return {
18297
19197
  read: read2,
@@ -18310,7 +19210,7 @@ function unreadableNote(coverage) {
18310
19210
  import { spawnSync as spawnSync17 } from "node:child_process";
18311
19211
  import { existsSync as existsSync43, mkdirSync as mkdirSync11, mkdtempSync as mkdtempSync5, rmSync as rmSync9, writeFileSync as writeFileSync16 } from "node:fs";
18312
19212
  import { tmpdir as tmpdir5 } from "node:os";
18313
- import { join as join63 } from "node:path";
19213
+ import { join as join65 } from "node:path";
18314
19214
  var ROOT_FILES = ["nx.json", "tsconfig.base.json"];
18315
19215
  function git5(cwd, args) {
18316
19216
  const run = spawnSync17("git", args, { cwd, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 });
@@ -18336,9 +19236,9 @@ function checkoutModuleAt(workspaceRoot, modulePath, sha) {
18336
19236
  if (!listed.ok) return { ok: false, reason: `git could not list the base: ${listed.said}` };
18337
19237
  const present = new Set(listed.out.split("\n").filter((line) => line !== ""));
18338
19238
  const existed = present.has(modulePath);
18339
- const root = mkdtempSync5(join63(tmpdir5(), "sentinel-static-base-"));
19239
+ const root = mkdtempSync5(join65(tmpdir5(), "sentinel-static-base-"));
18340
19240
  const dispose = () => rmSync9(root, { recursive: true, force: true });
18341
- const moduleDir = join63(root, modulePath);
19241
+ const moduleDir = join65(root, modulePath);
18342
19242
  mkdirSync11(moduleDir, { recursive: true });
18343
19243
  const paths2 = [
18344
19244
  ...ROOT_FILES.filter((file) => present.has(file)),
@@ -18365,7 +19265,7 @@ function checkoutModuleAt(workspaceRoot, modulePath, sha) {
18365
19265
  };
18366
19266
  }
18367
19267
  }
18368
- if (!existsSync43(join63(root, "nx.json"))) writeFileSync16(join63(root, "nx.json"), "{}\n");
19268
+ if (!existsSync43(join65(root, "nx.json"))) writeFileSync16(join65(root, "nx.json"), "{}\n");
18369
19269
  return { ok: true, moduleDir, existed, dispose };
18370
19270
  }
18371
19271
 
@@ -18462,21 +19362,21 @@ function comparePlaces(branch, base, renames) {
18462
19362
  }
18463
19363
 
18464
19364
  // src/roles/static-analysis/excerpt.ts
18465
- import { readFileSync as readFileSync38 } from "node:fs";
18466
- import { join as join64 } from "node:path";
19365
+ import { readFileSync as readFileSync39 } from "node:fs";
19366
+ import { join as join66 } from "node:path";
18467
19367
  var WINDOW = { lines: 10, nesting: { before: 3, after: 6 } };
18468
19368
  var NESTS_UPWARD = /* @__PURE__ */ new Set(["max-depth", "max-nested-callbacks"]);
18469
19369
  var SHOWS_THE_HEAD = /* @__PURE__ */ new Set(["max-lines"]);
18470
19370
  var WHOLE_FILE = /* @__PURE__ */ new Set(["unusedFiles", "usedOnlyByTests"]);
18471
- function linesOf(cache, cwd, relative12) {
18472
- if (cache.has(relative12)) return cache.get(relative12);
19371
+ function linesOf(cache, cwd, relative13) {
19372
+ if (cache.has(relative13)) return cache.get(relative13);
18473
19373
  let lines;
18474
19374
  try {
18475
- lines = readFileSync38(join64(cwd, relative12), "utf8").split("\n");
19375
+ lines = readFileSync39(join66(cwd, relative13), "utf8").split("\n");
18476
19376
  } catch {
18477
19377
  lines = void 0;
18478
19378
  }
18479
- cache.set(relative12, lines);
19379
+ cache.set(relative13, lines);
18480
19380
  return lines;
18481
19381
  }
18482
19382
  function pointOf(path2) {
@@ -18790,7 +19690,7 @@ var JscpdAdapter = class extends BaseAdapter {
18790
19690
  operations: [
18791
19691
  // `write` and not `merge-json`: this file is code, and the engine's in-place merge is for
18792
19692
  // 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() }],
19693
+ ...existsSync44(join67(context2.cwd, STATIC_CONFIG_FILE)) ? [] : [{ kind: "write", path: STATIC_CONFIG_FILE, contents: configStub5() }],
18794
19694
  manifestOperation(context2.cwd, scripts3()),
18795
19695
  ...nxTargetOperations({ cwd: context2.cwd, targets: targets3() })
18796
19696
  // The report directory is ignored ONCE at the workspace root, by `--init`'s workspace prep,
@@ -19012,7 +19912,7 @@ var JscpdAdapter = class extends BaseAdapter {
19012
19912
  const declared = moduleScripts(ctx.cwd);
19013
19913
  const missing = Object.keys(scripts3()).filter((name) => !(name in declared));
19014
19914
  const adopted = missing.length < Object.keys(scripts3()).length;
19015
- const hasConfig = existsSync44(join65(ctx.cwd, STATIC_CONFIG_FILE));
19915
+ const hasConfig = existsSync44(join67(ctx.cwd, STATIC_CONFIG_FILE));
19016
19916
  return {
19017
19917
  adopted,
19018
19918
  preset: adopted ? ctx.preset : null,
@@ -19104,7 +20004,7 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19104
20004
  try {
19105
20005
  const ran = runTool(jscpd, args, cwd, "dead-code");
19106
20006
  if (ran.kind !== "ran") return ran;
19107
- const path2 = join65(rawReportDir, RAW_REPORT["dead-code"]);
20007
+ const path2 = join67(rawReportDir, RAW_REPORT["dead-code"]);
19108
20008
  if (!existsSync44(path2)) {
19109
20009
  process.stderr.write(
19110
20010
  `sentinel static-analysis(jscpd): the dead-code pass wrote no ${RAW_REPORT["dead-code"]}
@@ -19112,7 +20012,7 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19112
20012
  );
19113
20013
  return { kind: "failed", code: 1 };
19114
20014
  }
19115
- const parsed2 = safeParseDeadCode(readFileSync39(path2, "utf8"));
20015
+ const parsed2 = safeParseDeadCode(readFileSync40(path2, "utf8"));
19116
20016
  const statistics = parsed2?.statistics;
19117
20017
  if (!statistics) {
19118
20018
  process.stderr.write(
@@ -19135,11 +20035,11 @@ function runDeadCode(jscpd, config, paths2, cwd, extraEntries = []) {
19135
20035
  }
19136
20036
  }
19137
20037
  function moduleRelative(name, roots, cwd) {
19138
- if (existsSync44(join65(cwd, name))) return name;
20038
+ if (existsSync44(join67(cwd, name))) return name;
19139
20039
  for (const root of roots) {
19140
20040
  if (root === ".") continue;
19141
20041
  const candidate = `${root}/${name}`;
19142
- if (existsSync44(join65(cwd, candidate))) return candidate;
20042
+ if (existsSync44(join67(cwd, candidate))) return candidate;
19143
20043
  }
19144
20044
  return name;
19145
20045
  }
@@ -19148,8 +20048,8 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19148
20048
  try {
19149
20049
  const ran = runTool(jscpd, args, cwd, scope);
19150
20050
  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;
20051
+ const path2 = join67(rawReportDir, RAW_REPORT.duplication);
20052
+ const parsed2 = existsSync44(path2) ? safeParse(readFileSync40(path2, "utf8")) : void 0;
19153
20053
  const total = parsed2?.statistics?.total;
19154
20054
  if (!total) {
19155
20055
  process.stderr.write(
@@ -19159,7 +20059,7 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19159
20059
  return { kind: "failed", code: 1 };
19160
20060
  }
19161
20061
  const seen = /* @__PURE__ */ new Map();
19162
- const relative12 = (name) => {
20062
+ const relative13 = (name) => {
19163
20063
  if (name === void 0) return void 0;
19164
20064
  const hit = seen.get(name);
19165
20065
  if (hit !== void 0) return hit;
@@ -19173,8 +20073,8 @@ function runDuplication(jscpd, config, paths2, scope, cwd) {
19173
20073
  formats: parsed2?.statistics?.formats ?? {},
19174
20074
  duplicates: (parsed2?.duplicates ?? []).map((entry) => ({
19175
20075
  ...entry,
19176
- ...entry.firstFile ? { firstFile: { ...entry.firstFile, name: relative12(entry.firstFile.name) } } : {},
19177
- ...entry.secondFile ? { secondFile: { ...entry.secondFile, name: relative12(entry.secondFile.name) } } : {}
20076
+ ...entry.firstFile ? { firstFile: { ...entry.firstFile, name: relative13(entry.firstFile.name) } } : {},
20077
+ ...entry.secondFile ? { secondFile: { ...entry.secondFile, name: relative13(entry.secondFile.name) } } : {}
19178
20078
  }))
19179
20079
  };
19180
20080
  } finally {
@@ -19408,7 +20308,7 @@ async function deltaAgainstBase(inputs, branch) {
19408
20308
  });
19409
20309
  const workspaceRoot = workspaceRootFrom(ctx.cwd);
19410
20310
  if (workspaceRoot === void 0) return unavailable("the module is not inside a workspace");
19411
- const modulePath = relative11(workspaceRoot, ctx.cwd).split(sep7).join("/");
20311
+ const modulePath = relative12(workspaceRoot, ctx.cwd).split(sep7).join("/");
19412
20312
  const moved = branchRenames(ctx.cwd, changes.base.sha);
19413
20313
  if (!moved.ok) return unavailable(moved.reason);
19414
20314
  const checkout = checkoutModuleAt(workspaceRoot, modulePath, changes.base.sha);
@@ -19437,9 +20337,9 @@ function moduleRenames(cwd, renames) {
19437
20337
  function moduleRootsOf(workspaceRoot) {
19438
20338
  const roots = [];
19439
20339
  for (const area of ["apps", "libs"]) {
19440
- const base = join65(workspaceRoot, area);
20340
+ const base = join67(workspaceRoot, area);
19441
20341
  if (!existsSync44(base)) continue;
19442
- for (const entry of globSync8([`${area}/**/package.json`, `${area}/**/project.json`], {
20342
+ for (const entry of globSync9([`${area}/**/package.json`, `${area}/**/project.json`], {
19443
20343
  cwd: workspaceRoot,
19444
20344
  ignore: ["**/node_modules/**"],
19445
20345
  dot: false
@@ -19780,7 +20680,7 @@ var PICTURE_FILE = `${TARGET}-graph.svg`;
19780
20680
  function clearStaleOutputs(cwd, keeping) {
19781
20681
  for (const name of [...Object.values(SHAPE_FILE4), PICTURE_FILE]) {
19782
20682
  if (keeping.has(name)) continue;
19783
- const path2 = join65(cwd, REPORT_DIR, name);
20683
+ const path2 = join67(cwd, REPORT_DIR, name);
19784
20684
  if (existsSync44(path2)) unlinkSync4(path2);
19785
20685
  }
19786
20686
  }
@@ -19799,11 +20699,11 @@ function drawsPicture(graph, coverage) {
19799
20699
  async function emit(report, shape, cwd, graph, coverage) {
19800
20700
  if (shape === "console") return [];
19801
20701
  const detailed = shape === "markdown" ? report : withExcerpts(report, cwd);
19802
- mkdirSync12(join65(cwd, REPORT_DIR), { recursive: true });
20702
+ mkdirSync12(join67(cwd, REPORT_DIR), { recursive: true });
19803
20703
  const written = [];
19804
20704
  if (shape === "html" && drawsPicture(graph, coverage)) {
19805
20705
  const drawn = layOut(graph.graph, graph.communityOf);
19806
- const path2 = join65(cwd, REPORT_DIR, PICTURE_FILE);
20706
+ const path2 = join67(cwd, REPORT_DIR, PICTURE_FILE);
19807
20707
  await writeGraphPicture(drawn, path2);
19808
20708
  written.push(`${REPORT_DIR}/${PICTURE_FILE}`);
19809
20709
  detailed.picture = buildExplorer(drawn, graph.communityOf).markup;
@@ -19811,7 +20711,7 @@ async function emit(report, shape, cwd, graph, coverage) {
19811
20711
  const RENDER = { json: renderJson, html: renderHtml, markdown: renderMarkdown };
19812
20712
  const name = SHAPE_FILE4[shape] ?? `${TARGET}.${shape}`;
19813
20713
  const body = RENDER[shape](detailed);
19814
- writeFileSync17(join65(cwd, REPORT_DIR, name), body, "utf8");
20714
+ writeFileSync17(join67(cwd, REPORT_DIR, name), body, "utf8");
19815
20715
  written.unshift(`${REPORT_DIR}/${name}`);
19816
20716
  return written;
19817
20717
  }
@@ -19845,9 +20745,9 @@ function registerTest() {
19845
20745
 
19846
20746
  // src/roles/typescript/adapters/tsc/tsc.adapter.ts
19847
20747
  import { spawnSync as spawnSync19 } from "node:child_process";
19848
- import { existsSync as existsSync45, readdirSync as readdirSync12, readFileSync as readFileSync41 } from "node:fs";
20748
+ import { existsSync as existsSync45, readdirSync as readdirSync13, readFileSync as readFileSync42 } from "node:fs";
19849
20749
  import { createRequire } from "node:module";
19850
- import { join as join67 } from "node:path";
20750
+ import { join as join69 } from "node:path";
19851
20751
 
19852
20752
  // src/roles/typescript/config-policy.ts
19853
20753
  var PERMITTED_COMPILER_OPTIONS = [
@@ -19901,11 +20801,11 @@ function standardOverrides(compilerOptions, preset) {
19901
20801
  }
19902
20802
  function legacyCompromises(compilerOptions, preset) {
19903
20803
  const stack = preset !== void 0 && hasShippedPreset(preset) ? tsPresetFor(preset).compilerOptions : {};
19904
- const applied2 = appliedOptions({ compilerOptions: stack });
20804
+ const applied3 = appliedOptions({ compilerOptions: stack });
19905
20805
  return Object.entries(tsLegacyLayer().compilerOptions).filter(
19906
20806
  ([key]) => !(key in stack) && !(compilerOptions !== void 0 && key in compilerOptions)
19907
20807
  ).map(([key, value]) => {
19908
- const standard = applied2.has(key) ? JSON.parse(applied2.get(key) ?? "null") : null;
20808
+ const standard = applied3.has(key) ? JSON.parse(applied3.get(key) ?? "null") : null;
19909
20809
  return {
19910
20810
  rule: key,
19911
20811
  value,
@@ -19960,8 +20860,8 @@ function readTsconfigAdoption(cwd) {
19960
20860
  }
19961
20861
 
19962
20862
  // src/roles/typescript/adapters/tsc/plan.ts
19963
- import { readFileSync as readFileSync40 } from "node:fs";
19964
- import { join as join66 } from "node:path";
20863
+ import { readFileSync as readFileSync41 } from "node:fs";
20864
+ import { join as join68 } from "node:path";
19965
20865
 
19966
20866
  // src/roles/typescript/typecheck-script.ts
19967
20867
  var SENTINEL_TYPECHECK_COMMAND = "sentinel --run --typescript";
@@ -20056,7 +20956,7 @@ function planAdoption(context2) {
20056
20956
  };
20057
20957
  }
20058
20958
  const existing = parseJsonc(
20059
- readFileSync40(join66(context2.cwd, target.path), "utf8"),
20959
+ readFileSync41(join68(context2.cwd, target.path), "utf8"),
20060
20960
  target.path
20061
20961
  );
20062
20962
  const extendsChain = composeExtends(existing.extends, preset);
@@ -20116,10 +21016,10 @@ var PHASED_STRICTNESS_WARNING = `sentinel typescript: phase 1 (non-breaking) \u2
20116
21016
  var TSCONFIG_FILE = /^tsconfig.*\.json$/;
20117
21017
  function configStateOf(reason, moduleDir) {
20118
21018
  if (reason !== "extends-base") return reason;
20119
- const onBase = readdirSync12(moduleDir).filter((name) => TSCONFIG_FILE.test(name)).some((name) => {
21019
+ const onBase = readdirSync13(moduleDir).filter((name) => TSCONFIG_FILE.test(name)).some((name) => {
20120
21020
  try {
20121
21021
  const config = parseJsonc(
20122
- readFileSync41(join67(moduleDir, name), "utf8"),
21022
+ readFileSync42(join69(moduleDir, name), "utf8"),
20123
21023
  name
20124
21024
  );
20125
21025
  return extendsList(config).some(isBaseEntry);
@@ -20210,7 +21110,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20210
21110
  let chain;
20211
21111
  try {
20212
21112
  const parsed2 = parseJsonc(
20213
- readFileSync41(join67(cwd, target.path), "utf8"),
21113
+ readFileSync42(join69(cwd, target.path), "utf8"),
20214
21114
  target.path
20215
21115
  );
20216
21116
  chain = parsed2.extends;
@@ -20223,7 +21123,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20223
21123
  );
20224
21124
  if (preset === void 0) return void 0;
20225
21125
  try {
20226
- createRequire(join67(cwd, "noop.js")).resolve(preset);
21126
+ createRequire(join69(cwd, "noop.js")).resolve(preset);
20227
21127
  return void 0;
20228
21128
  } catch {
20229
21129
  return preset;
@@ -20319,7 +21219,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20319
21219
  referencedProjects(cwd, config) {
20320
21220
  try {
20321
21221
  const parsed2 = parseJsonc(
20322
- readFileSync41(join67(cwd, config), "utf8"),
21222
+ readFileSync42(join69(cwd, config), "utf8"),
20323
21223
  config
20324
21224
  );
20325
21225
  const referenced = (parsed2.references ?? []).map((reference) => reference.path).filter((path2) => typeof path2 === "string" && path2.length > 0);
@@ -20335,7 +21235,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20335
21235
  * check.
20336
21236
  */
20337
21237
  typecheckTarget(cwd) {
20338
- if (existsSync45(join67(cwd, "tsconfig.json"))) return "tsconfig.json";
21238
+ if (existsSync45(join69(cwd, "tsconfig.json"))) return "tsconfig.json";
20339
21239
  const target = resolveTsconfigTarget(cwd);
20340
21240
  return target.reason === "none" ? null : target.path;
20341
21241
  }
@@ -20348,7 +21248,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20348
21248
  const target = resolveTsconfigTarget(ctx.cwd);
20349
21249
  const { preset } = readTsconfigAdoption(ctx.cwd);
20350
21250
  const stack = preset === null ? void 0 : preset.slice(preset.lastIndexOf("/") + 1);
20351
- const config = this.readConfig(join67(ctx.cwd, target.path));
21251
+ const config = this.readConfig(join69(ctx.cwd, target.path));
20352
21252
  const options = config?.compilerOptions;
20353
21253
  const overrides = standardOverrides(options, stack);
20354
21254
  const legacy = config !== void 0 && extendsList(config).some(isLegacyEntry) ? legacyCompromises(options, stack) : [];
@@ -20366,7 +21266,7 @@ var TscAdapter = class _TscAdapter extends BaseAdapter {
20366
21266
  readConfig(file) {
20367
21267
  if (!existsSync45(file)) return void 0;
20368
21268
  try {
20369
- return parseJsonc(readFileSync41(file, "utf8"), file);
21269
+ return parseJsonc(readFileSync42(file, "utf8"), file);
20370
21270
  } catch {
20371
21271
  return void 0;
20372
21272
  }
@@ -20563,7 +21463,7 @@ function replaceLines(current, replacements) {
20563
21463
  }
20564
21464
 
20565
21465
  // 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";
21466
+ import { existsSync as existsSync46, readFileSync as readFileSync43, renameSync as renameSync2, rmSync as rmSync10, writeFileSync as writeFileSync18 } from "node:fs";
20567
21467
  import { resolve as resolve10, sep as sep8 } from "node:path";
20568
21468
  import { applyEdits, findNodeAtLocation, modify, parseTree } from "jsonc-parser";
20569
21469
  function resolveWithinRoot(cwd, relativePath) {
@@ -20575,7 +21475,7 @@ function resolveWithinRoot(cwd, relativePath) {
20575
21475
  return absolutePath;
20576
21476
  }
20577
21477
  function readIfExists(absolutePath) {
20578
- return existsSync46(absolutePath) ? readFileSync42(absolutePath, "utf8") : void 0;
21478
+ return existsSync46(absolutePath) ? readFileSync43(absolutePath, "utf8") : void 0;
20579
21479
  }
20580
21480
  function* leaves(value, prefix = []) {
20581
21481
  for (const [key, keyValue] of Object.entries(value)) {
@@ -20693,8 +21593,8 @@ function applyPlan(cwd, plan3) {
20693
21593
  }
20694
21594
 
20695
21595
  // 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";
21596
+ import { existsSync as existsSync47, readdirSync as readdirSync14, readFileSync as readFileSync44 } from "node:fs";
21597
+ import { join as join70 } from "node:path";
20698
21598
  var PATH_SIGNALS = [
20699
21599
  {
20700
21600
  preset: "nest",
@@ -20722,18 +21622,18 @@ function sourceImports(cwd, pattern) {
20722
21622
  const dir = stack.pop();
20723
21623
  let entries;
20724
21624
  try {
20725
- entries = readdirSync13(dir, { withFileTypes: true });
21625
+ entries = readdirSync14(dir, { withFileTypes: true });
20726
21626
  } catch {
20727
21627
  continue;
20728
21628
  }
20729
21629
  for (const entry of entries) {
20730
21630
  if (entry.isDirectory()) {
20731
- if (!NOT_SCANNED.has(entry.name)) stack.push(join68(dir, entry.name));
21631
+ if (!NOT_SCANNED.has(entry.name)) stack.push(join70(dir, entry.name));
20732
21632
  continue;
20733
21633
  }
20734
21634
  if (!SOURCE_FILE.test(entry.name)) continue;
20735
21635
  try {
20736
- if (pattern.test(readFileSync43(join68(dir, entry.name), "utf8"))) return true;
21636
+ if (pattern.test(readFileSync44(join70(dir, entry.name), "utf8"))) return true;
20737
21637
  } catch {
20738
21638
  continue;
20739
21639
  }
@@ -20742,11 +21642,11 @@ function sourceImports(cwd, pattern) {
20742
21642
  return false;
20743
21643
  }
20744
21644
  function dependencyNames(cwd) {
20745
- const path2 = join68(cwd, "package.json");
21645
+ const path2 = join70(cwd, "package.json");
20746
21646
  if (!existsSync47(path2)) return [];
20747
21647
  try {
20748
21648
  const manifest = parseJsonc(
20749
- readFileSync43(path2, "utf8"),
21649
+ readFileSync44(path2, "utf8"),
20750
21650
  path2
20751
21651
  );
20752
21652
  return [
@@ -20761,7 +21661,7 @@ var REACT_TYPESCRIPT_PRESET = "@hublo/sentinel/typescript/react";
20761
21661
  function reactTsconfigEvidence(cwd) {
20762
21662
  let entries;
20763
21663
  try {
20764
- entries = readdirSync13(cwd).filter(
21664
+ entries = readdirSync14(cwd).filter(
20765
21665
  (name) => name.startsWith("tsconfig") && name.endsWith(".json")
20766
21666
  );
20767
21667
  } catch {
@@ -20769,7 +21669,7 @@ function reactTsconfigEvidence(cwd) {
20769
21669
  }
20770
21670
  for (const name of entries) {
20771
21671
  try {
20772
- const config = parseJsonc(readFileSync43(join68(cwd, name), "utf8"), name);
21672
+ const config = parseJsonc(readFileSync44(join70(cwd, name), "utf8"), name);
20773
21673
  if (config.compilerOptions?.jsx !== void 0) return 'its tsconfig sets "jsx"';
20774
21674
  const extended = Array.isArray(config.extends) ? config.extends : config.extends === void 0 ? [] : [config.extends];
20775
21675
  if (extended.some((entry) => entry === REACT_TYPESCRIPT_PRESET)) {