veoflow 0.5.4 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/veo.mjs CHANGED
@@ -2045,16 +2045,16 @@ function applySelection(source, paths, selected, options2 = {}) {
2045
2045
  `${path} can't be analyzed (${first.notAnalyzable === "over-hard-cap" ? "it is over the 64 MB cap" : first.notAnalyzable === "symlink" ? "it is a symbolic link" : "type declarations are not analyzed"})`,
2046
2046
  { fields: ["paths"] }
2047
2047
  );
2048
- const inside3 = (p) => p === path || p.startsWith(`${path}/`);
2048
+ const inside4 = (p) => p === path || p.startsWith(`${path}/`);
2049
2049
  const written2 = (rule) => {
2050
2050
  const r = rule.replace(/^\/+/, "").replace(/\/+$/, "");
2051
- return rule.startsWith("/") && (kind === "dir" ? inside3(r) : r === path);
2051
+ return rule.startsWith("/") && (kind === "dir" ? inside4(r) : r === path);
2052
2052
  };
2053
2053
  if (selected) {
2054
2054
  rules = { ...rules, exclude: rules.exclude.filter((r) => !written2(r)) };
2055
- if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside3(p)), path] };
2056
- if (options2.keep) rules = { ...rules, kept: [...rules.kept.filter((p) => !inside3(p)), path] };
2057
- for (const o of rules.optIn.filter((p) => p !== path && inside3(p))) {
2055
+ if (entry().excludedBy) rules = { ...rules, optIn: [...rules.optIn.filter((p) => !inside4(p)), path] };
2056
+ if (options2.keep) rules = { ...rules, kept: [...rules.kept.filter((p) => !inside4(p)), path] };
2057
+ for (const o of rules.optIn.filter((p) => p !== path && inside4(p))) {
2058
2058
  const without = { ...rules, optIn: rules.optIn.filter((p) => p !== o) };
2059
2059
  let needed = false;
2060
2060
  try {
@@ -2067,8 +2067,8 @@ function applySelection(source, paths, selected, options2 = {}) {
2067
2067
  } else {
2068
2068
  rules = {
2069
2069
  ...rules,
2070
- optIn: rules.optIn.filter((p) => !inside3(p)),
2071
- kept: rules.kept.filter((p) => !inside3(p))
2070
+ optIn: rules.optIn.filter((p) => !inside4(p)),
2071
+ kept: rules.kept.filter((p) => !inside4(p))
2072
2072
  };
2073
2073
  if (!entry().excludedBy)
2074
2074
  rules = { ...rules, exclude: [...rules.exclude, kind === "dir" ? `/${path}/` : `/${path}`] };
@@ -2244,6 +2244,14 @@ function processAlive(pid) {
2244
2244
  return e.code === "EPERM";
2245
2245
  }
2246
2246
  }
2247
+ function sortById(rows) {
2248
+ if (!rows.some((r) => SURROGATE.test(r.id)))
2249
+ return rows.sort(
2250
+ (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0
2251
+ );
2252
+ const bytes = new Map(rows.map((r) => [r, Buffer.from(r.id)]));
2253
+ return rows.sort((a, b) => Buffer.compare(bytes.get(a), bytes.get(b)));
2254
+ }
2247
2255
  function lockIsLive(lock) {
2248
2256
  const pid = Number(lock.pid);
2249
2257
  if (pid === process.pid) return liveOwners.has(String(lock.owner));
@@ -2266,7 +2274,7 @@ function toRunInfo(row) {
2266
2274
  ...row.analysis ? { analysis: JSON.parse(String(row.analysis)) } : {}
2267
2275
  };
2268
2276
  }
2269
- var SCRATCH_RUNS, DEFAULT_RETENTION_GRACE_MS, CoalescedError, StaleCurrentRunError, ProjectLockedError, SCHEMA, CLOSED_HERE, liveOwners, STAGE_NAME, GraphReader, ProjectStore, RunHandle;
2277
+ var SCRATCH_RUNS, DEFAULT_RETENTION_GRACE_MS, CoalescedError, StaleCurrentRunError, ProjectLockedError, SCHEMA, CLOSED_HERE, liveOwners, SURROGATE, STAGE_NAME, GraphReader, ProjectStore, RunHandle;
2270
2278
  var init_project_store = __esm({
2271
2279
  "packages/store/src/project-store.ts"() {
2272
2280
  "use strict";
@@ -2371,6 +2379,7 @@ CREATE TABLE IF NOT EXISTS lock (
2371
2379
  `;
2372
2380
  CLOSED_HERE = "SELECT from_run, hash FROM facts WHERE id = :id AND +to_run = :run";
2373
2381
  liveOwners = /* @__PURE__ */ new Set();
2382
+ SURROGATE = /[\uD800-\uDFFF]/;
2374
2383
  STAGE_NAME = /^[a-z0-9][a-z0-9-]*$/;
2375
2384
  GraphReader = class _GraphReader {
2376
2385
  /**
@@ -2417,8 +2426,9 @@ CREATE TABLE IF NOT EXISTS lock (
2417
2426
  return this.#db.prepare(sql).all({ stage, ...this.pin }).map((r) => r.scope);
2418
2427
  }
2419
2428
  rows(where, params) {
2420
- const sql = `SELECT payload, rev FROM facts WHERE ${this.visible} AND ${where} ORDER BY id`;
2421
- return this.#db.prepare(sql).all({ ...params, ...this.pin }).map((r) => {
2429
+ const sql = `SELECT id, payload, rev FROM facts WHERE ${this.visible} AND ${where}`;
2430
+ const found = sortById(this.#db.prepare(sql).all({ ...params, ...this.pin }));
2431
+ return found.map((r) => {
2422
2432
  const fact = JSON.parse(r.payload);
2423
2433
  if ("evidence" in fact && fact.evidence && !fact.evidence.commit) fact.evidence.commit = String(r.rev);
2424
2434
  return fact;
@@ -2494,10 +2504,24 @@ CREATE TABLE IF NOT EXISTS lock (
2494
2504
  }
2495
2505
  return out;
2496
2506
  }
2497
- /** The stages that wrote the visible facts, in name order. */
2507
+ /**
2508
+ * The stages that wrote the visible facts, in name order. Asked on almost
2509
+ * every read, so it never reads every fact: the stage names come from
2510
+ * stepping through the stage index (one seek per stage), and each is kept
2511
+ * if one of its facts is visible here.
2512
+ */
2498
2513
  writtenStages() {
2499
- const rows = this.#db.prepare(`SELECT DISTINCT stage FROM facts WHERE ${this.visible} ORDER BY stage`).all(this.pin);
2500
- return rows.map((r) => r.stage);
2514
+ const names = this.#db.prepare(
2515
+ `WITH RECURSIVE s(stage) AS (
2516
+ SELECT MIN(stage) FROM facts INDEXED BY facts_by_scope
2517
+ UNION ALL
2518
+ SELECT (SELECT MIN(stage) FROM facts INDEXED BY facts_by_scope WHERE stage > s.stage) FROM s WHERE s.stage IS NOT NULL
2519
+ ) SELECT stage FROM s WHERE stage IS NOT NULL ORDER BY stage`
2520
+ ).all();
2521
+ const visible = this.#db.prepare(
2522
+ `SELECT 1 FROM facts INDEXED BY facts_by_scope WHERE stage = :stage AND ${this.visible} LIMIT 1`
2523
+ );
2524
+ return names.map((r) => r.stage).filter((stage) => visible.get({ stage, ...this.pin }) !== void 0);
2501
2525
  }
2502
2526
  /** Every visible fact, ordered by id (for diffs and exports). */
2503
2527
  all() {
@@ -2594,14 +2618,14 @@ CREATE TABLE IF NOT EXISTS lock (
2594
2618
  SELECT a.id, a.type, a.file, a.src, 'removed' AS change
2595
2619
  FROM a LEFT JOIN b ON b.id = a.id WHERE b.id IS NULL`
2596
2620
  ).all({ ...pinParams(pa, "a_"), ...pinParams(pb, "b_") });
2597
- const cmp9 = (x, y) => x < y ? -1 : x > y ? 1 : 0;
2621
+ const cmp11 = (x, y) => x < y ? -1 : x > y ? 1 : 0;
2598
2622
  return rows.map((r) => ({
2599
2623
  id: r.id,
2600
2624
  type: r.type,
2601
2625
  change: r.change,
2602
2626
  file: r.file,
2603
2627
  source: changeSource(r.id, r.file, r.src)
2604
- })).sort((x, y) => cmp9(x.file ?? "", y.file ?? "") || cmp9(x.type, y.type) || cmp9(x.id, y.id));
2628
+ })).sort((x, y) => cmp11(x.file ?? "", y.file ?? "") || cmp11(x.type, y.type) || cmp11(x.id, y.id));
2605
2629
  }
2606
2630
  /** How many facts of each type a committed run's graph holds. */
2607
2631
  factCounts(run2) {
@@ -4921,9 +4945,9 @@ function runTemplateLink(ctx) {
4921
4945
  if (ownerRoot) {
4922
4946
  const abs = join9(ownerRoot.root, ...owner.path.split("/").slice(0, -1), ...d.specifier.split("/"));
4923
4947
  for (const r of roots) {
4924
- const inside3 = relative2(r.root, abs);
4925
- if (inside3 && !inside3.startsWith("..") && !inside3.startsWith(sep5) && !/^[a-zA-Z]:/.test(inside3)) {
4926
- const inRel = inside3.split(sep5).join("/");
4948
+ const inside4 = relative2(r.root, abs);
4949
+ if (inside4 && !inside4.startsWith("..") && !inside4.startsWith(sep5) && !/^[a-zA-Z]:/.test(inside4)) {
4950
+ const inRel = inside4.split(sep5).join("/");
4927
4951
  const file2 = fileById.get(ids.file(r.source, inRel));
4928
4952
  if (file2)
4929
4953
  return file2.language === "angular-template" ? { kind: "file", file: file2 } : { kind: "not-analyzed" };
@@ -5210,6 +5234,7 @@ var init_engine = __esm({
5210
5234
  LICENSE_FINDINGS = /* @__PURE__ */ new Set(["license", "entitlement", "frozen"]);
5211
5235
  Engine = class {
5212
5236
  afterCommit;
5237
+ afterSummaries;
5213
5238
  catalog;
5214
5239
  /** Run events from every project (run.started, stage.completed, ...). */
5215
5240
  events = new EventEmitter();
@@ -5247,6 +5272,7 @@ var init_engine = __esm({
5247
5272
  this.license = options2.license ?? {};
5248
5273
  this.runner = options2.runner;
5249
5274
  this.afterCommit = options2.afterCommit;
5275
+ this.afterSummaries = options2.afterSummaries;
5250
5276
  if (options2.runner && options2.repository)
5251
5277
  throw new Error(
5252
5278
  "a runner's run processes use the SQLite backend: give a runner or a repository, not both"
@@ -5755,6 +5781,7 @@ var init_engine = __esm({
5755
5781
  entry.runId = e.runId;
5756
5782
  onStarted?.(e.runId);
5757
5783
  }
5784
+ if (e.type === "run.committed") entry.committedAt = Date.now();
5758
5785
  this.events.emit("event", e);
5759
5786
  }
5760
5787
  }).then((info) => {
@@ -5764,6 +5791,14 @@ var init_engine = __esm({
5764
5791
  this.afterCommit(this, project2.id, info.runId);
5765
5792
  } catch (e) {
5766
5793
  process.stderr.write(`veoflow: after the run: ${e.message}
5794
+ `);
5795
+ }
5796
+ this.events.emit("summarized", { projectId: project2.id, runId: info.runId });
5797
+ if (this.afterSummaries && info.kind === "history")
5798
+ try {
5799
+ this.afterSummaries(this, project2.id, info.runId);
5800
+ } catch (e) {
5801
+ process.stderr.write(`veoflow: after the run: ${e.message}
5767
5802
  `);
5768
5803
  }
5769
5804
  try {
@@ -5802,6 +5837,9 @@ var init_engine = __esm({
5802
5837
  };
5803
5838
  let started = null;
5804
5839
  let cancelling = false;
5840
+ let counted = () => {
5841
+ };
5842
+ const summarized = new Promise((r) => counted = r);
5805
5843
  const done = new Promise((resolve9, reject) => {
5806
5844
  let settled = false;
5807
5845
  child.on("message", (m) => {
@@ -5811,7 +5849,10 @@ var init_engine = __esm({
5811
5849
  entry.runId = m.event.runId;
5812
5850
  onStarted?.(m.event.runId);
5813
5851
  }
5852
+ if (m.event.type === "run.committed") entry.committedAt = Date.now();
5814
5853
  this.events.emit("event", m.event);
5854
+ } else if (m.type === "summarized") {
5855
+ counted();
5815
5856
  } else if (m.type === "done") {
5816
5857
  settled = true;
5817
5858
  resolve9(m.run);
@@ -5857,7 +5898,9 @@ var init_engine = __esm({
5857
5898
  child.kill();
5858
5899
  },
5859
5900
  done: done.catch(() => void 0),
5860
- process: child
5901
+ process: child,
5902
+ // However the process ends, nothing waits on its counts after.
5903
+ summarized: Promise.race([summarized, done.catch(() => void 0)])
5861
5904
  };
5862
5905
  const runs = this.inflight.get(project2.id) ?? /* @__PURE__ */ new Set();
5863
5906
  this.inflight.set(project2.id, runs.add(entry));
@@ -5867,7 +5910,9 @@ var init_engine = __esm({
5867
5910
  /** Serve one run request in a run process (`veoflow __run`, #129). */
5868
5911
  async serveRunRequest(request, send) {
5869
5912
  const listener = (event) => send({ type: "event", event });
5913
+ const summarized = () => send({ type: "summarized" });
5870
5914
  this.events.on("event", listener);
5915
+ this.events.on("summarized", summarized);
5871
5916
  try {
5872
5917
  const project2 = this.resolveProject({ project: request.project });
5873
5918
  const run2 = await this.runProject(project2, void 0, request.retire, request.options);
@@ -5877,6 +5922,7 @@ var init_engine = __esm({
5877
5922
  send({ type: "error", error: err });
5878
5923
  } finally {
5879
5924
  this.events.off("event", listener);
5925
+ this.events.off("summarized", summarized);
5880
5926
  }
5881
5927
  }
5882
5928
  /**
@@ -6531,6 +6577,26 @@ var init_engine = __esm({
6531
6577
  runInProgress(project2) {
6532
6578
  return (this.inflight.get(project2)?.size ?? 0) > 0;
6533
6579
  }
6580
+ /**
6581
+ * Wait while a run of the project that has committed is still finishing in
6582
+ * its process (#372): counting its findings and their impact, kept with the
6583
+ * run (D75). A read that needs those counts waits for them rather than
6584
+ * counting them again, which would hold this process for as long. A run
6585
+ * that hasn't committed is never waited for, and one is waited for at most
6586
+ * `limitMs` after it committed, however many reads wait. `all` waits for
6587
+ * the work after the summaries too (the connected grouping, #374).
6588
+ */
6589
+ async finishing(project2, limitMs = 6e4, all2 = false) {
6590
+ const now2 = Date.now();
6591
+ const waits = [...this.inflight.get(project2) ?? []].filter((r) => r.committedAt !== void 0 && r.committedAt + limitMs > now2).map((r) => {
6592
+ let timer;
6593
+ return Promise.race([
6594
+ all2 ? r.done : r.summarized ?? r.done,
6595
+ new Promise((done) => timer = setTimeout(done, r.committedAt + limitMs - now2))
6596
+ ]).finally(() => clearTimeout(timer));
6597
+ });
6598
+ await Promise.all(waits);
6599
+ }
6534
6600
  /** What a run read of each source (planner): its offers, what it left out, its notices (#330). */
6535
6601
  runSources(project2, run2) {
6536
6602
  if (run2 === null) return [];
@@ -7111,6 +7177,18 @@ var init_engine = __esm({
7111
7177
  });
7112
7178
 
7113
7179
  // packages/query/src/view.ts
7180
+ function hideReveal(reveal, file2) {
7181
+ const gone = /* @__PURE__ */ new Set([file2]);
7182
+ for (let grew = true; grew; ) {
7183
+ grew = false;
7184
+ for (const r of reveal)
7185
+ if (!gone.has(r.file) && gone.has(r.from)) {
7186
+ gone.add(r.file);
7187
+ grew = true;
7188
+ }
7189
+ }
7190
+ return reveal.filter((r) => !gone.has(r.file));
7191
+ }
7114
7192
  var INITIAL_VIEW, str, oneOf, all, none, COMMANDS, ACTIONS;
7115
7193
  var init_view = __esm({
7116
7194
  "packages/query/src/view.ts"() {
@@ -7134,7 +7212,10 @@ var init_view = __esm({
7134
7212
  compare: null,
7135
7213
  only: null,
7136
7214
  area: null,
7137
- reach: null
7215
+ reach: null,
7216
+ grouping: "declared",
7217
+ differences: false,
7218
+ reveal: []
7138
7219
  };
7139
7220
  str = (field, optional2 = false) => (a) => optional2 && a[field] === void 0 || typeof a[field] === "string" && a[field].length > 0 ? [] : [field];
7140
7221
  oneOf = (field, values) => (a) => values.includes(a[field]) ? [] : [field];
@@ -7171,7 +7252,9 @@ var init_view = __esm({
7171
7252
  file: a.file,
7172
7253
  selection: null,
7173
7254
  fileLevel: s.tab === "imports",
7174
- pick: s.tab === "imports" ? null : s.pick
7255
+ pick: s.tab === "imports" ? null : s.pick,
7256
+ // What was revealed belongs to the file it was revealed on (#378), at its level (as openImportsFile).
7257
+ reveal: a.file === s.file && (s.tab !== "imports" || s.fileLevel) ? s.reveal : []
7175
7258
  })
7176
7259
  },
7177
7260
  select: {
@@ -7182,6 +7265,8 @@ var init_view = __esm({
7182
7265
  ...s,
7183
7266
  file: a.file ?? s.file,
7184
7267
  selection: { kind: a.kind, id: a.id },
7268
+ // What was revealed belongs to the file it was revealed on (#378).
7269
+ reveal: (a.file ?? s.file) === s.file ? s.reveal : [],
7185
7270
  panel: "evidence",
7186
7271
  // Functions, calls and call sites are the File tab's.
7187
7272
  tab: "file",
@@ -7211,9 +7296,27 @@ var init_view = __esm({
7211
7296
  a.tab === "reach" && !s.reach ? s : (
7212
7297
  // From the File tab with a file open, Imports opens at that file: its imports
7213
7298
  // and cross-file calls, in its own group (#289), never a group left from before.
7214
- a.tab === "imports" && s.tab === "file" && s.file ? { ...s, tab: "imports", fileLevel: true, group: null, pick: null, only: null, expand: [] } : (
7299
+ a.tab === "imports" && s.tab === "file" && s.file ? {
7300
+ ...s,
7301
+ tab: "imports",
7302
+ fileLevel: true,
7303
+ group: null,
7304
+ pick: null,
7305
+ only: null,
7306
+ expand: [],
7307
+ reveal: []
7308
+ } : (
7215
7309
  // Imports again while on it: a fresh start, at the project map.
7216
- a.tab === "imports" && s.tab === "imports" ? { ...s, fileLevel: false, group: null, pick: null, only: null, expand: [], area: null } : { ...s, tab: a.tab }
7310
+ a.tab === "imports" && s.tab === "imports" ? {
7311
+ ...s,
7312
+ fileLevel: false,
7313
+ group: null,
7314
+ pick: null,
7315
+ only: null,
7316
+ expand: [],
7317
+ area: null,
7318
+ reveal: []
7319
+ } : { ...s, tab: a.tab }
7217
7320
  )
7218
7321
  )
7219
7322
  )
@@ -7288,12 +7391,32 @@ var init_view = __esm({
7288
7391
  file: a.file,
7289
7392
  group: a.group ?? s.group,
7290
7393
  fileLevel: true,
7394
+ // What was revealed belongs to the file it was revealed on (#378).
7395
+ reveal: a.file === s.file && s.fileLevel ? s.reveal : [],
7291
7396
  // A finding opens with its import picked (its code and Explain in Details).
7292
7397
  pick: a.pick ?? null,
7293
7398
  panel: a.pick ? "evidence" : s.panel,
7294
7399
  selection: null
7295
7400
  })
7296
7401
  },
7402
+ revealFile: {
7403
+ description: "On a file's Imports level, show another file's imports and calls in place (or hide them again, with what was revealed from it)",
7404
+ control: { kind: "canvas", testId: "reveal-file" },
7405
+ check: all(str("file"), str("from", true)),
7406
+ apply: (s, a) => s.reveal.some((r) => r.file === a.file) ? { ...s, reveal: hideReveal(s.reveal, a.file) } : (
7407
+ // Only at a file's Imports level, and never the open file itself.
7408
+ a.file === s.file || !s.file || s.tab !== "imports" || !s.fileLevel ? s : {
7409
+ ...s,
7410
+ reveal: [...s.reveal, { file: a.file, from: a.from ?? s.file }]
7411
+ }
7412
+ )
7413
+ },
7414
+ resetReveal: {
7415
+ description: "On a file's Imports level, hide every file revealed in place: the open file's own imports and calls only",
7416
+ control: { kind: "button", testId: "reset-reveal" },
7417
+ check: none,
7418
+ apply: (s) => ({ ...s, reveal: [] })
7419
+ },
7297
7420
  toggleFolder: {
7298
7421
  description: "Open or close a folder in a large group on the Imports tab",
7299
7422
  control: { kind: "canvas", testId: "toggle-folder" },
@@ -7360,6 +7483,28 @@ var init_view = __esm({
7360
7483
  check: str("id", true),
7361
7484
  apply: (s, a) => ({ ...s, only: a.id ?? null })
7362
7485
  },
7486
+ setGrouping: {
7487
+ description: "Group the project map by its packages and folders (declared), or by how its files connect (connected)",
7488
+ control: { kind: "select", testId: "set-grouping" },
7489
+ check: oneOf("grouping", ["declared", "connected"]),
7490
+ // Group ids differ between groupings: back to the map, nothing picked.
7491
+ apply: (s, a) => a.grouping === s.grouping ? s : {
7492
+ ...s,
7493
+ grouping: a.grouping,
7494
+ differences: a.grouping === "connected" && s.differences,
7495
+ group: null,
7496
+ pick: null,
7497
+ area: null,
7498
+ expand: [],
7499
+ only: null
7500
+ }
7501
+ },
7502
+ toggleDifferences: {
7503
+ description: "Mark, on the map grouped by how files connect, the declared groups it splits or merges",
7504
+ control: { kind: "toggle", testId: "toggle-differences" },
7505
+ check: none,
7506
+ apply: (s) => ({ ...s, differences: !s.differences })
7507
+ },
7363
7508
  togglePending: {
7364
7509
  description: "Show or hide imports waiting for another source (pending)",
7365
7510
  control: { kind: "toggle", testId: "toggle-pending" },
@@ -7647,6 +7792,845 @@ var init_builtins = __esm({
7647
7792
  }
7648
7793
  });
7649
7794
 
7795
+ // packages/stage2/src/cluster.ts
7796
+ import { posix as posix2 } from "node:path";
7797
+ function rollUp(out, groupOf, input2, fnFile) {
7798
+ const byId = new Map(out.map((g) => [g.id, g]));
7799
+ const roll = /* @__PURE__ */ new Map();
7800
+ const rollOf = (from, to) => {
7801
+ const key = `${from}\0${to}`;
7802
+ let r = roll.get(key);
7803
+ if (!r) roll.set(key, r = { imports: [], calls: [], references: [] });
7804
+ return r;
7805
+ };
7806
+ for (const e of input2.imports) {
7807
+ const from = groupOf.get(e.from);
7808
+ if (!from) continue;
7809
+ if (e.to.startsWith("package|")) {
7810
+ const g = byId.get(from);
7811
+ if (!g.externalPackages.includes(e.to)) g.externalPackages.push(e.to);
7812
+ continue;
7813
+ }
7814
+ const to = groupOf.get(e.to);
7815
+ if (to && to !== from) rollOf(from, to).imports.push(e);
7816
+ }
7817
+ for (const c of input2.calls) {
7818
+ const fromFile = fnFile.get(c.from);
7819
+ const toFile = fnFile.get(c.to);
7820
+ const from = fromFile ? groupOf.get(fromFile) : void 0;
7821
+ const to = toFile ? groupOf.get(toFile) : void 0;
7822
+ if (from && to && from !== to) rollOf(from, to).calls.push(c);
7823
+ }
7824
+ for (const c of input2.references ?? []) {
7825
+ const fromFile = fnFile.get(c.from);
7826
+ const toFile = fnFile.get(c.to);
7827
+ const from = fromFile ? groupOf.get(fromFile) : void 0;
7828
+ const to = toFile ? groupOf.get(toFile) : void 0;
7829
+ if (from && to && from !== to) rollOf(from, to).references.push(c);
7830
+ }
7831
+ for (const g of out) g.externalPackages.sort(cmp);
7832
+ const carries = /* @__PURE__ */ new Map();
7833
+ for (const s of input2.symbols ?? []) {
7834
+ const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
7835
+ const u = s.uses;
7836
+ const yes = u === null || u.calls + u.jsx + u.extends > 0;
7837
+ carries.set(key, (carries.get(key) ?? false) || yes);
7838
+ }
7839
+ const carrying = (e) => carries.get(e.id.slice("IMPORTS|".length)) ?? true;
7840
+ return [...roll].map(([key, r]) => {
7841
+ const [from, to] = key.split("\0");
7842
+ const first = (xs) => [...xs].sort((a, b) => cmp(a.id, b.id))[0];
7843
+ const evidence = (first(r.imports) ?? first(r.calls) ?? first(r.references)).evidence;
7844
+ return {
7845
+ type: "DEPENDS_ON",
7846
+ id: ids.dependsOn(from, to),
7847
+ from,
7848
+ to,
7849
+ imports: r.imports.length,
7850
+ calls: r.calls.length,
7851
+ ...r.references.length ? { references: r.references.length } : {},
7852
+ carrying: r.imports.filter(carrying).length,
7853
+ evidence
7854
+ };
7855
+ }).sort((a, b) => cmp(a.id, b.id));
7856
+ }
7857
+ function ancestors(dir) {
7858
+ if (!dir) return [""];
7859
+ const parts = dir.split("/");
7860
+ return ["", ...parts.map((_, i) => parts.slice(0, i + 1).join("/"))];
7861
+ }
7862
+ function nameCluster(list) {
7863
+ const dirs = list.map((f) => {
7864
+ const d = posix2.dirname(f.path);
7865
+ return d === "." ? "" : d;
7866
+ });
7867
+ const counts = /* @__PURE__ */ new Map();
7868
+ for (const d of dirs) for (const a of ancestors(d)) counts.set(a, (counts.get(a) ?? 0) + 1);
7869
+ const root = [...counts].filter(([, n2]) => n2 === list.length).sort((x, y) => y[0].length - x[0].length)[0][0];
7870
+ const need = Math.ceil(list.length * 0.75);
7871
+ const main2 = [...counts].filter(([dir, n2]) => n2 >= need && inside2(`${dir}/x`, root)).sort((x, y) => y[0].length - x[0].length || y[1] - x[1] || cmp(x[0], y[0]))[0][0];
7872
+ const outside = list.length - counts.get(main2);
7873
+ const roles = /* @__PURE__ */ new Map();
7874
+ for (const f of list) {
7875
+ const parts = posix2.basename(f.path).split(".");
7876
+ if (parts.length >= 3)
7877
+ roles.set(parts[parts.length - 2], (roles.get(parts[parts.length - 2]) ?? 0) + 1);
7878
+ }
7879
+ const [role, shared] = [...roles].sort((x, y) => y[1] - x[1] || cmp(x[0], y[0]))[0] ?? ["", 0];
7880
+ const base2 = `${main2 || "(root)"}${list.length > 1 && shared >= Math.ceil(list.length * 0.6) ? ` \xB7 ${role} files` : ""}`;
7881
+ const name = outside > 0 ? `${base2} (+${outside} elsewhere in ${root || "the repository"})` : base2;
7882
+ return { name, root, main: main2, files: list };
7883
+ }
7884
+ function disambiguate() {
7885
+ const seen = /* @__PURE__ */ new Set();
7886
+ return (c) => {
7887
+ const key = c.main || "(root)";
7888
+ const taken = seen.has(key);
7889
+ seen.add(key);
7890
+ if (!taken) return { key, name: c.name, root: c.root, files: c.files };
7891
+ const first = [...c.files].map((f) => f.path).sort(cmp).find((p) => inside2(p, c.main));
7892
+ const within = c.main ? first.slice(c.main.length + 1) : first;
7893
+ const counts = /* @__PURE__ */ new Map();
7894
+ for (const f of c.files) {
7895
+ if (!inside2(f.path, c.main)) continue;
7896
+ const rel = posix2.dirname(c.main ? f.path.slice(c.main.length + 1) : f.path);
7897
+ if (rel === ".") continue;
7898
+ const parts = rel.split("/");
7899
+ for (let i = 1; i <= parts.length; i++) {
7900
+ const d = parts.slice(0, i).join("/");
7901
+ counts.set(d, (counts.get(d) ?? 0) + 1);
7902
+ }
7903
+ }
7904
+ const [folder, n2] = [...counts].sort(
7905
+ (a, b) => b[1] - a[1] || b[0].split("/").length - a[0].split("/").length || cmp(a[0], b[0])
7906
+ )[0] ?? ["", 0];
7907
+ const name = n2 >= 2 ? `${c.name} \xB7 mostly ${folder} (${n2} of ${c.files.length})` : `${c.name} (${within})`;
7908
+ return { key: `${key} (${within})`, name, root: c.root, files: c.files };
7909
+ };
7910
+ }
7911
+ function louvain(n2, edges) {
7912
+ let assignment = Array.from({ length: n2 }, (_, i) => i);
7913
+ let nodes = n2;
7914
+ let graph = edges;
7915
+ for (let level = 0; level < 10; level++) {
7916
+ const { community, moved } = localMoves(nodes, graph);
7917
+ if (!moved) break;
7918
+ const renumber2 = /* @__PURE__ */ new Map();
7919
+ for (let i = 0; i < nodes; i++)
7920
+ if (!renumber2.has(community[i])) renumber2.set(community[i], renumber2.size);
7921
+ assignment = assignment.map((c) => renumber2.get(community[c]));
7922
+ const agg = /* @__PURE__ */ new Map();
7923
+ for (const e of graph) {
7924
+ const a = renumber2.get(community[e.a]);
7925
+ const b = renumber2.get(community[e.b]);
7926
+ const key = a < b ? `${a} ${b}` : `${b} ${a}`;
7927
+ agg.set(key, (agg.get(key) ?? 0) + e.w);
7928
+ }
7929
+ nodes = renumber2.size;
7930
+ graph = [...agg].map(([k, w]) => {
7931
+ const [a, b] = k.split(" ").map(Number);
7932
+ return { a, b, w };
7933
+ });
7934
+ }
7935
+ const refined = localMoves(n2, edges, assignment).community;
7936
+ const renumber = /* @__PURE__ */ new Map();
7937
+ return refined.map((c) => {
7938
+ if (!renumber.has(c)) renumber.set(c, renumber.size);
7939
+ return renumber.get(c);
7940
+ });
7941
+ }
7942
+ function localMoves(n2, edges, initial) {
7943
+ const adj = Array.from({ length: n2 }, () => /* @__PURE__ */ new Map());
7944
+ const selfLoop = new Array(n2).fill(0);
7945
+ let total = 0;
7946
+ for (const e of edges) {
7947
+ if (e.a === e.b) selfLoop[e.a] += e.w;
7948
+ else {
7949
+ adj[e.a].set(e.b, (adj[e.a].get(e.b) ?? 0) + e.w);
7950
+ adj[e.b].set(e.a, (adj[e.b].get(e.a) ?? 0) + e.w);
7951
+ }
7952
+ total += e.w;
7953
+ }
7954
+ const community = initial ? [...initial] : Array.from({ length: n2 }, (_, i) => i);
7955
+ if (total === 0) return { community, moved: false };
7956
+ const m2 = 2 * total;
7957
+ const degree = adj.map((m, i) => [...m.values()].reduce((s, w) => s + w, 0) + 2 * selfLoop[i]);
7958
+ let size = n2;
7959
+ for (const c of community) if (c + 1 > size) size = c + 1;
7960
+ const communityDegree = new Array(size).fill(0);
7961
+ for (let i = 0; i < n2; i++) communityDegree[community[i]] += degree[i];
7962
+ let moved = false;
7963
+ for (let pass = 0; pass < 50; pass++) {
7964
+ let changed = false;
7965
+ for (let i = 0; i < n2; i++) {
7966
+ const own2 = community[i];
7967
+ const links = /* @__PURE__ */ new Map();
7968
+ for (const [j, w] of adj[i]) links.set(community[j], (links.get(community[j]) ?? 0) + w);
7969
+ communityDegree[own2] -= degree[i];
7970
+ const gain = (c) => (links.get(c) ?? 0) - communityDegree[c] * degree[i] / m2;
7971
+ let best = own2;
7972
+ let bestGain = gain(own2);
7973
+ for (const c of [...links.keys()].sort((x, y) => x - y)) {
7974
+ const g = gain(c);
7975
+ if (g > bestGain + 1e-12 || Math.abs(g - bestGain) <= 1e-12 && c < best) {
7976
+ best = c;
7977
+ bestGain = g;
7978
+ }
7979
+ }
7980
+ communityDegree[best] += degree[i];
7981
+ if (best !== own2) {
7982
+ community[i] = best;
7983
+ changed = true;
7984
+ moved = true;
7985
+ }
7986
+ }
7987
+ if (!changed) break;
7988
+ }
7989
+ return { community, moved };
7990
+ }
7991
+ var cmp, inside2, byKey;
7992
+ var init_cluster = __esm({
7993
+ "packages/stage2/src/cluster.ts"() {
7994
+ "use strict";
7995
+ init_src();
7996
+ cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
7997
+ inside2 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
7998
+ byKey = (a, b) => cmp(a.main, b.main) || b.files.length - a.files.length || cmp(a.files[0].path, b.files[0].path);
7999
+ }
8000
+ });
8001
+
8002
+ // packages/query-imports/src/connected.ts
8003
+ import { posix as posix3 } from "node:path";
8004
+ function boundariesOf(declared2, byId) {
8005
+ const out = /* @__PURE__ */ new Map();
8006
+ for (const g of [...declared2].sort((a, b) => cmp2(a.id, b.id))) {
8007
+ const b = g.boundary ?? {
8008
+ kind: g.kind === "cluster" ? "folder" : g.kind,
8009
+ name: g.kind === "cluster" ? g.root || g.name : g.name,
8010
+ root: g.root
8011
+ };
8012
+ const key = `${g.source}\0${b.root}`;
8013
+ let entry = out.get(key);
8014
+ if (!entry)
8015
+ out.set(
8016
+ key,
8017
+ entry = {
8018
+ key,
8019
+ kind: b.kind,
8020
+ name: b.name,
8021
+ root: b.root,
8022
+ source: g.source,
8023
+ files: [],
8024
+ declared: []
8025
+ }
8026
+ );
8027
+ entry.declared.push(g);
8028
+ for (const f of g.files) {
8029
+ const file2 = byId.get(f);
8030
+ if (file2) entry.files.push(file2);
8031
+ }
8032
+ }
8033
+ for (const b of out.values()) b.files.sort((x, y) => cmp2(x.path, y.path));
8034
+ return [...out.values()].sort((a, b) => cmp2(a.source, b.source) || cmp2(a.root, b.root));
8035
+ }
8036
+ function declaredWhy(g) {
8037
+ if (g.kind === "repository") return `Declared: the repository ${g.name}`;
8038
+ if (g.kind === "workspace-package")
8039
+ return `Declared: the workspace package ${g.name} (${g.root || "its root"})`;
8040
+ if (g.boundary?.split === "folders") return `Declared: the folder ${g.root}`;
8041
+ if (g.boundary)
8042
+ return `Declared: part of ${g.boundary.kind === "folder" ? `the folder ${g.boundary.name}` : g.boundary.name}, split by how its files connect`;
8043
+ return `Declared: a cluster of ${g.root || "the repository"}, split by how its files connect`;
8044
+ }
8045
+ function connectedGrouping(input2) {
8046
+ const byId = new Map(input2.files.map((f) => [f.id, f]));
8047
+ const fileOf = (fn) => input2.fnFile.get(fn);
8048
+ const user = (id) => {
8049
+ const f = byId.get(id);
8050
+ return !!f && input2.own(f) && !isTestPath(f.path);
8051
+ };
8052
+ const links = /* @__PURE__ */ new Map();
8053
+ const callsInto = /* @__PURE__ */ new Map();
8054
+ const add2 = (m, from, to, n2 = 1) => {
8055
+ let row = m.get(from);
8056
+ if (!row) m.set(from, row = /* @__PURE__ */ new Map());
8057
+ row.set(to, (row.get(to) ?? 0) + n2);
8058
+ };
8059
+ const pairs = /* @__PURE__ */ new Set();
8060
+ const path = (from, to, key) => {
8061
+ if (!from || !to || from === to || !byId.has(from) || !byId.has(to)) return;
8062
+ if (pairs.has(key)) return;
8063
+ pairs.add(key);
8064
+ add2(links, from, to);
8065
+ add2(callsInto, from, to);
8066
+ };
8067
+ for (const c of input2.calls) path(fileOf(c.from), fileOf(c.to), `${c.from}\0${c.to}`);
8068
+ for (const r of input2.references)
8069
+ if (r.exit === void 0) path(fileOf(r.from), fileOf(r.to), `${r.from}\0${r.to}`);
8070
+ const told = /* @__PURE__ */ new Map();
8071
+ for (const s of input2.symbols) {
8072
+ const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
8073
+ told.set(key, (told.get(key) ?? true) && s.uses !== null);
8074
+ }
8075
+ for (const e of input2.imports) {
8076
+ if (e.to.startsWith("package|") || e.from === e.to || !byId.has(e.from) || !byId.has(e.to)) continue;
8077
+ if (told.get(e.id.slice("IMPORTS|".length)) ?? false) continue;
8078
+ add2(links, e.from, e.to);
8079
+ }
8080
+ const uses = /* @__PURE__ */ new Map();
8081
+ const users = /* @__PURE__ */ new Map();
8082
+ for (const [from, row] of links) {
8083
+ if (!user(from)) continue;
8084
+ for (const to of row.keys()) {
8085
+ (uses.get(from) ?? uses.set(from, /* @__PURE__ */ new Set()).get(from)).add(to);
8086
+ (users.get(to) ?? users.set(to, /* @__PURE__ */ new Set()).get(to)).add(from);
8087
+ }
8088
+ }
8089
+ const linkCount = (a, b) => user(a) ? links.get(a)?.get(b) ?? 0 : 0;
8090
+ const boundaries = boundariesOf(input2.declared, byId);
8091
+ const boundaryOf = /* @__PURE__ */ new Map();
8092
+ for (const b of boundaries) for (const f of b.files) boundaryOf.set(f.id, b);
8093
+ const shared = /* @__PURE__ */ new Set();
8094
+ const sharedOf = /* @__PURE__ */ new Map();
8095
+ for (const b of boundaries) {
8096
+ const members2 = b.files.filter((f) => user(f.id));
8097
+ const inB = new Set(b.files.map((f) => f.id));
8098
+ const n2 = members2.length - 1;
8099
+ const need = Math.max(SHARED_MIN_USERS, SHARED_SQRT_FACTOR * Math.sqrt(Math.max(n2, 0)));
8100
+ const qualifies = (group) => {
8101
+ const by = /* @__PURE__ */ new Set();
8102
+ const used = /* @__PURE__ */ new Set();
8103
+ for (const f of group) {
8104
+ for (const u of users.get(f) ?? []) if (inB.has(u) && !group.has(u)) by.add(u);
8105
+ for (const t of uses.get(f) ?? []) if (inB.has(t) && !group.has(t)) used.add(t);
8106
+ }
8107
+ return by.size >= need && used.size <= by.size * SHARED_MAX_USES;
8108
+ };
8109
+ const layer = /* @__PURE__ */ new Set();
8110
+ for (const f of members2) if (qualifies(/* @__PURE__ */ new Set([f.id]))) layer.add(f.id);
8111
+ if (layer.size) {
8112
+ const list = [...layer].sort((x, y) => cmp2(byId.get(x).path, byId.get(y).path));
8113
+ sharedOf.set(b.key, list);
8114
+ for (const f of list) shared.add(f);
8115
+ }
8116
+ }
8117
+ const counted = (id) => user(id) && !shared.has(id);
8118
+ const memo2 = (m) => {
8119
+ const cache = /* @__PURE__ */ new Map();
8120
+ return (id) => {
8121
+ let list = cache.get(id);
8122
+ if (!list) cache.set(id, list = [...m.get(id) ?? []].filter((x) => !shared.has(x)).sort(cmp2));
8123
+ return list;
8124
+ };
8125
+ };
8126
+ const usersOf = memo2(users);
8127
+ const usersN = (t) => usersOf(t).length;
8128
+ const usesOf2 = memo2(uses);
8129
+ const similarity = (files) => {
8130
+ const index = new Map(files.map((f, i) => [f, i]));
8131
+ const direct = /* @__PURE__ */ new Map();
8132
+ const usage = /* @__PURE__ */ new Map();
8133
+ const dependence = /* @__PURE__ */ new Map();
8134
+ const bump = (m, a, b, w) => {
8135
+ if (a === b) return;
8136
+ const key = a < b ? `${a} ${b}` : `${b} ${a}`;
8137
+ m.set(key, (m.get(key) ?? 0) + w);
8138
+ };
8139
+ for (const a of files)
8140
+ for (const t of usesOf2(a)) {
8141
+ const j = index.get(t);
8142
+ if (j !== void 0) bump(direct, index.get(a), j, linkCount(a, t) * discount(usersN(t)));
8143
+ }
8144
+ const usersSeen = /* @__PURE__ */ new Set();
8145
+ for (const f of files) for (const u of usersOf(f)) usersSeen.add(u);
8146
+ for (const u of [...usersSeen].sort(cmp2)) {
8147
+ const used = usesOf2(u).filter((t) => index.has(t));
8148
+ if (used.length < 2 || usesOf2(u).length > COMMON_MAX) continue;
8149
+ const w = discount(usesOf2(u).length);
8150
+ for (let x = 0; x < used.length; x++)
8151
+ for (let y = x + 1; y < used.length; y++) bump(usage, index.get(used[x]), index.get(used[y]), w);
8152
+ }
8153
+ const targets = /* @__PURE__ */ new Map();
8154
+ for (const f of files)
8155
+ if (counted(f))
8156
+ for (const t of usesOf2(f)) {
8157
+ const list = targets.get(t) ?? [];
8158
+ list.push(index.get(f));
8159
+ targets.set(t, list);
8160
+ }
8161
+ for (const [t, list] of [...targets].sort((a, b) => cmp2(a[0], b[0]))) {
8162
+ if (list.length < 2 || usersN(t) > COMMON_MAX) continue;
8163
+ const w = discount(usersN(t));
8164
+ for (let x = 0; x < list.length; x++)
8165
+ for (let y = x + 1; y < list.length; y++) bump(dependence, list[x], list[y], w);
8166
+ }
8167
+ const total = /* @__PURE__ */ new Map();
8168
+ for (const [k, w] of direct) total.set(k, (total.get(k) ?? 0) + w);
8169
+ for (const [k, w] of usage) total.set(k, (total.get(k) ?? 0) + w * CO_WEIGHT);
8170
+ for (const [k, w] of dependence) total.set(k, (total.get(k) ?? 0) + w * CO_WEIGHT);
8171
+ const pairKey = (a, b) => {
8172
+ const x = index.get(a);
8173
+ const y = index.get(b);
8174
+ return x < y ? `${x} ${y}` : `${y} ${x}`;
8175
+ };
8176
+ const adjacency = (m) => {
8177
+ const adj = files.map(() => /* @__PURE__ */ new Map());
8178
+ for (const [k, w] of m) {
8179
+ const [a, b] = k.split(" ").map(Number);
8180
+ adj[a].set(b, w);
8181
+ adj[b].set(a, w);
8182
+ }
8183
+ return adj;
8184
+ };
8185
+ return {
8186
+ edges: [...total].map(([k, w]) => {
8187
+ const [a, b] = k.split(" ").map(Number);
8188
+ return { a, b, w };
8189
+ }),
8190
+ /** By file index: its similarity to each other file, and its direct links. */
8191
+ near: adjacency(total),
8192
+ index,
8193
+ linked: adjacency(direct),
8194
+ usage: (a, b) => (usage.get(pairKey(a, b)) ?? 0) > 0,
8195
+ dependence: (a, b) => (dependence.get(pairKey(a, b)) ?? 0) > 0
8196
+ };
8197
+ };
8198
+ const modules = [];
8199
+ const pathOfId = (id) => byId.get(id).path;
8200
+ const byPath = (a, b) => cmp2(pathOfId(a), pathOfId(b));
8201
+ const folders = (root, parts) => {
8202
+ const counts = /* @__PURE__ */ new Map();
8203
+ const top = (path2) => {
8204
+ const rel = root ? path2.slice(root.length + 1) : path2;
8205
+ const at = rel.indexOf("/");
8206
+ return at < 0 ? root : root ? `${root}/${rel.slice(0, at)}` : rel.slice(0, at);
8207
+ };
8208
+ const own2 = /* @__PURE__ */ new Map();
8209
+ const note = (file2, part) => {
8210
+ for (let d = dirOf(pathOfId(file2)); inside3(d, root) && d !== root; d = dirOf(d)) {
8211
+ const m = counts.get(d) ?? /* @__PURE__ */ new Map();
8212
+ m.set(part, (m.get(part) ?? 0) + 1);
8213
+ counts.set(d, m);
8214
+ }
8215
+ };
8216
+ parts.forEach((p, i) => p.forEach((f) => note(f, i)));
8217
+ return {
8218
+ place(file2) {
8219
+ const path2 = pathOfId(file2);
8220
+ for (let d = dirOf(path2); inside3(d, root) && d !== root; d = dirOf(d)) {
8221
+ const m = counts.get(d);
8222
+ if (!m) continue;
8223
+ const [best] = [...m].sort((x, y) => y[1] - x[1] || x[0] - y[0])[0];
8224
+ parts[best].push(file2);
8225
+ note(file2, best);
8226
+ return best;
8227
+ }
8228
+ const key = top(path2);
8229
+ if (key === root && parts.some((p) => p.length)) {
8230
+ let largest = 0;
8231
+ parts.forEach((p, i) => {
8232
+ if (p.length > parts[largest].length) largest = i;
8233
+ });
8234
+ parts[largest].push(file2);
8235
+ note(file2, largest);
8236
+ return largest;
8237
+ }
8238
+ let part = own2.get(key);
8239
+ if (part === void 0) {
8240
+ own2.set(key, part = parts.length);
8241
+ parts.push([]);
8242
+ }
8243
+ parts[part].push(file2);
8244
+ note(file2, part);
8245
+ return part;
8246
+ },
8247
+ note
8248
+ };
8249
+ };
8250
+ for (const b of boundaries) {
8251
+ const nodes = b.files.map((f) => f.id).filter(counted);
8252
+ const rest = b.files.map((f) => f.id).filter((f) => !counted(f) && !shared.has(f));
8253
+ const sim = similarity(nodes);
8254
+ const community = nodes.length ? louvain(nodes.length, sim.edges) : [];
8255
+ const groupsOf = /* @__PURE__ */ new Map();
8256
+ community.forEach((c, i) => {
8257
+ const list = groupsOf.get(c);
8258
+ if (list) list.push(i);
8259
+ else groupsOf.set(c, [i]);
8260
+ });
8261
+ const within = /* @__PURE__ */ new Map();
8262
+ const across = /* @__PURE__ */ new Map();
8263
+ for (const e of sim.edges) {
8264
+ const ca = community[e.a];
8265
+ const cb = community[e.b];
8266
+ if (ca === cb) within.set(ca, (within.get(ca) ?? 0) + e.w);
8267
+ else {
8268
+ across.set(ca, (across.get(ca) ?? 0) + e.w);
8269
+ across.set(cb, (across.get(cb) ?? 0) + e.w);
8270
+ }
8271
+ }
8272
+ const ownCount = b.files.filter((f) => user(f.id)).length;
8273
+ const minJoined = Math.max(PART_MIN_FILES, Math.floor(Math.log2(Math.max(ownCount, 1))));
8274
+ const joinedIn = (c, members2) => {
8275
+ const seen = /* @__PURE__ */ new Set();
8276
+ let largest = 0;
8277
+ for (const start of members2) {
8278
+ if (seen.has(start)) continue;
8279
+ let size = 0;
8280
+ const stack = [start];
8281
+ seen.add(start);
8282
+ while (stack.length) {
8283
+ const i = stack.pop();
8284
+ size++;
8285
+ for (const j of sim.linked[i].keys())
8286
+ if (!seen.has(j) && community[j] === c) {
8287
+ seen.add(j);
8288
+ stack.push(j);
8289
+ }
8290
+ }
8291
+ largest = Math.max(largest, size);
8292
+ }
8293
+ return largest;
8294
+ };
8295
+ const kept = [];
8296
+ const loose = [];
8297
+ for (const [c, members2] of [...groupsOf].sort((x, y) => x[1][0] - y[1][0])) {
8298
+ if (joinedIn(c, members2) >= minJoined && (within.get(c) ?? 0) >= (across.get(c) ?? 0))
8299
+ kept.push(members2);
8300
+ else loose.push(...members2);
8301
+ }
8302
+ let parts;
8303
+ let prior;
8304
+ if (kept.length < 2) {
8305
+ parts = [[...nodes]];
8306
+ prior = folders(b.root, parts);
8307
+ for (const f of rest) {
8308
+ parts[0].push(f);
8309
+ prior.note(f, 0);
8310
+ }
8311
+ rest.length = 0;
8312
+ } else {
8313
+ const partOf = /* @__PURE__ */ new Map();
8314
+ kept.forEach((p, i) => p.forEach((n2) => partOf.set(n2, i)));
8315
+ parts = kept.map((p) => p.map((i) => nodes[i]));
8316
+ prior = folders(b.root, parts);
8317
+ for (const i of loose.sort((x, y) => x - y)) {
8318
+ const toPart = /* @__PURE__ */ new Map();
8319
+ for (const [j, w] of sim.near[i]) {
8320
+ const p = partOf.get(j);
8321
+ if (p !== void 0) toPart.set(p, (toPart.get(p) ?? 0) + w);
8322
+ }
8323
+ let best = -1;
8324
+ let bestW = 0;
8325
+ for (const [p, w] of [...toPart].sort((x, y) => x[0] - y[0]))
8326
+ if (w > bestW + 1e-12) [best, bestW] = [p, w];
8327
+ if (best >= 0) {
8328
+ parts[best].push(nodes[i]);
8329
+ prior.note(nodes[i], best);
8330
+ partOf.set(i, best);
8331
+ } else partOf.set(i, prior.place(nodes[i]));
8332
+ }
8333
+ }
8334
+ const partOfFile = /* @__PURE__ */ new Map();
8335
+ parts.forEach((p, i) => p.forEach((f) => partOfFile.set(f, i)));
8336
+ for (const f of rest.sort(byPath)) {
8337
+ let best = -1;
8338
+ let most = 0;
8339
+ if (byId.get(f) && isTestPath(pathOfId(f)) && input2.own(byId.get(f))) {
8340
+ const toPart = /* @__PURE__ */ new Map();
8341
+ for (const [g, n2] of callsInto.get(f) ?? []) {
8342
+ const p = partOfFile.get(g);
8343
+ if (p !== void 0) toPart.set(p, (toPart.get(p) ?? 0) + n2);
8344
+ }
8345
+ for (const [p, n2] of [...toPart].sort((x, y) => x[0] - y[0])) if (n2 > most) [best, most] = [p, n2];
8346
+ }
8347
+ if (best >= 0) {
8348
+ parts[best].push(f);
8349
+ prior.note(f, best);
8350
+ } else prior.place(f);
8351
+ }
8352
+ for (const p of parts) {
8353
+ if (!p.length) continue;
8354
+ const files = [...p].sort(byPath);
8355
+ const placed = /* @__PURE__ */ new Map();
8356
+ const here = new Set(files);
8357
+ const linkedHere = /* @__PURE__ */ new Set();
8358
+ for (const f of files)
8359
+ for (const g of links.get(f)?.keys() ?? [])
8360
+ if (g !== f && here.has(g)) {
8361
+ linkedHere.add(f);
8362
+ if (user(f)) linkedHere.add(g);
8363
+ }
8364
+ for (const f of files) {
8365
+ const i = sim.index.get(f);
8366
+ const near = i === void 0 ? [] : [...sim.near[i].keys()].map((j) => nodes[j]).filter((g) => here.has(g));
8367
+ if (linkedHere.has(f)) placed.set(f, "joined");
8368
+ else if (near.some((g) => sim.usage(f, g))) placed.set(f, "used");
8369
+ else if (near.some((g) => sim.dependence(f, g))) placed.set(f, "using");
8370
+ else placed.set(f, "folder");
8371
+ }
8372
+ modules.push({ boundary: b, files, placed });
8373
+ }
8374
+ }
8375
+ const moduleOf = /* @__PURE__ */ new Map();
8376
+ modules.forEach((m, i) => {
8377
+ for (const f of m.files) moduleOf.set(f, i);
8378
+ });
8379
+ const between = /* @__PURE__ */ new Map();
8380
+ const outOf = new Array(modules.length).fill(0);
8381
+ for (const [from, row] of callsInto) {
8382
+ if (!counted(from)) continue;
8383
+ const a = moduleOf.get(from);
8384
+ if (a === void 0) continue;
8385
+ for (const [to, n2] of row) {
8386
+ const b = moduleOf.get(to);
8387
+ if (b === void 0 || b === a || shared.has(to)) continue;
8388
+ outOf[a] = outOf[a] + n2;
8389
+ between.set(`${a} ${b}`, (between.get(`${a} ${b}`) ?? 0) + n2);
8390
+ }
8391
+ }
8392
+ const parent = modules.map((_, i) => i);
8393
+ const find2 = (i) => parent[i] === i ? i : parent[i] = find2(parent[i]);
8394
+ const mutual = /* @__PURE__ */ new Map();
8395
+ for (let a = 0; a < modules.length; a++)
8396
+ for (let b = a + 1; b < modules.length; b++) {
8397
+ if (modules[a].boundary === modules[b].boundary) continue;
8398
+ if (modules[a].boundary.source !== modules[b].boundary.source) continue;
8399
+ const ab = between.get(`${a} ${b}`) ?? 0;
8400
+ const ba = between.get(`${b} ${a}`) ?? 0;
8401
+ if (Math.min(ab, ba) >= MERGE_MIN_CALLS && Math.min(ab, ba) >= Math.max(ab, ba) * MERGE_BALANCE && ab + ba >= Math.min(outOf[a], outOf[b]) * MERGE_SHARE) {
8402
+ mutual.set(`${a} ${b}`, [ab, ba]);
8403
+ parent[find2(b)] = find2(a);
8404
+ }
8405
+ }
8406
+ const sets = /* @__PURE__ */ new Map();
8407
+ modules.forEach((_, i) => {
8408
+ const r = find2(i);
8409
+ const list = sets.get(r);
8410
+ if (list) list.push(i);
8411
+ else sets.set(r, [i]);
8412
+ });
8413
+ const whole = (m) => m.files.length === m.boundary.files.length - (sharedOf.get(m.boundary.key)?.length ?? 0);
8414
+ const declaredSame = (files) => {
8415
+ const set2 = new Set(files);
8416
+ return input2.declared.find((g) => g.files.length === set2.size && g.files.every((f) => set2.has(f)));
8417
+ };
8418
+ const out = [];
8419
+ const reasons = [
8420
+ ["joined", "joined by calls"],
8421
+ ["used", "used by the same files"],
8422
+ ["using", "using the same files"],
8423
+ ["folder", "placed by its folder"]
8424
+ ];
8425
+ const describe4 = (m) => {
8426
+ const counts = reasons.map(([r, words]) => [[...m.placed.values()].filter((p) => p === r).length, words]).filter(([n3]) => n3 > 0);
8427
+ const n2 = m.files.length;
8428
+ const files = `${n2} file${n2 === 1 ? "" : "s"}`;
8429
+ const head = counts.length === 1 ? `${files} ${counts[0][1].replace("its folder", n2 === 1 ? "its folder" : "their folder")}` : `${files}, ${counts.map(
8430
+ ([k, words], i) => `${i === counts.length - 1 ? "and " : ""}${k} ${words.replace("its folder", k === 1 ? "its folder" : "their folder")}`
8431
+ ).join(counts.length > 2 ? ", " : " ")}`;
8432
+ return `Connected: ${head}${whole(m) ? `: all of ${m.boundary.name}` : `, part of ${m.boundary.name}`}`;
8433
+ };
8434
+ const singles = [];
8435
+ for (const [, members2] of [...sets].sort((a, b) => a[0] - b[0])) {
8436
+ if (members2.length === 1) {
8437
+ const m = modules[members2[0]];
8438
+ singles.push({ m, c: nameCluster(m.files.map((f) => byId.get(f))) });
8439
+ continue;
8440
+ }
8441
+ const ms = members2.map((i) => modules[i]);
8442
+ const files = ms.flatMap((m) => m.files).sort(byPath);
8443
+ const keyOf2 = (m) => whole(m) ? m.boundary.root : nameCluster(m.files.map((f) => byId.get(f))).main;
8444
+ const nameOf = (m) => whole(m) ? m.boundary.name : nameCluster(m.files.map((f) => byId.get(f))).name;
8445
+ const order = [...ms].sort((x, y) => cmp2(keyOf2(x), keyOf2(y)));
8446
+ const names = order.map(nameOf);
8447
+ let why = `Connected: ${names.slice(0, -1).join(", ")} and ${names[names.length - 1]} call into each other`;
8448
+ if (members2.length === 2) {
8449
+ const [ab, ba] = mutual.get(`${members2[0]} ${members2[1]}`) ?? [0, 0];
8450
+ why += ab === ba ? ` (${ab} calls each way)` : ` (${Math.max(ab, ba)} calls one way, ${Math.min(ab, ba)} the other)`;
8451
+ }
8452
+ out.push({
8453
+ type: "Group",
8454
+ id: `group|${ms[0].boundary.source}|module:${order.map(keyOf2).join("+")}`,
8455
+ name: names.join(" + "),
8456
+ kind: "module",
8457
+ source: ms[0].boundary.source,
8458
+ root: nameCluster(files.map((f) => byId.get(f))).root,
8459
+ files,
8460
+ externalPackages: [],
8461
+ why
8462
+ });
8463
+ }
8464
+ const mainCount = /* @__PURE__ */ new Map();
8465
+ for (const { m, c } of singles)
8466
+ if (!declaredSame(m.files))
8467
+ mainCount.set(
8468
+ `${m.boundary.source}\0${c.main}`,
8469
+ (mainCount.get(`${m.boundary.source}\0${c.main}`) ?? 0) + 1
8470
+ );
8471
+ const bySource = /* @__PURE__ */ new Map();
8472
+ for (const s of singles) {
8473
+ const list = bySource.get(s.m.boundary.source);
8474
+ if (list) list.push(s);
8475
+ else bySource.set(s.m.boundary.source, [s]);
8476
+ }
8477
+ for (const [source, list] of [...bySource].sort((a, b) => cmp2(a[0], b[0]))) {
8478
+ const named = disambiguate();
8479
+ const sorted = [...list].sort(
8480
+ (x, y) => cmp2(x.c.main, y.c.main) || y.c.files.length - x.c.files.length || cmp2(x.c.files[0].path, y.c.files[0].path)
8481
+ );
8482
+ for (const { m, c } of sorted) {
8483
+ const same = declaredSame(m.files);
8484
+ if (same) {
8485
+ out.push({
8486
+ type: "Group",
8487
+ id: same.id,
8488
+ name: same.name,
8489
+ kind: "module",
8490
+ source,
8491
+ root: same.root,
8492
+ files: m.files,
8493
+ externalPackages: [],
8494
+ why: describe4(m)
8495
+ });
8496
+ continue;
8497
+ }
8498
+ const d = named(c);
8499
+ let name = d.name;
8500
+ if ((mainCount.get(`${source}\0${c.main}`) ?? 0) > 1) {
8501
+ const prefix = sharedPrefix(c.files.map((f) => posix3.basename(f.path)));
8502
+ if (prefix) name = `${c.main || "(root)"} \xB7 ${prefix}* files`;
8503
+ }
8504
+ out.push({
8505
+ type: "Group",
8506
+ id: ids.cluster(source, d.key).replace("|cluster:", "|module:"),
8507
+ name,
8508
+ kind: "module",
8509
+ source,
8510
+ root: d.root,
8511
+ files: m.files,
8512
+ externalPackages: [],
8513
+ why: describe4(m)
8514
+ });
8515
+ }
8516
+ }
8517
+ const groupOf = /* @__PURE__ */ new Map();
8518
+ for (const g of out) for (const f of g.files) groupOf.set(f, g.id);
8519
+ for (const b of boundaries) {
8520
+ const layer = sharedOf.get(b.key);
8521
+ if (!layer) continue;
8522
+ const by = /* @__PURE__ */ new Set();
8523
+ for (const f of layer) for (const u of users.get(f) ?? []) if (!shared.has(u)) by.add(u);
8524
+ const groupsUsing = new Set([...by].map((u) => groupOf.get(u)).filter(Boolean));
8525
+ const files = layer.map((f) => byId.get(f));
8526
+ out.push({
8527
+ type: "Group",
8528
+ id: `group|${b.source}|shared:${b.root}`,
8529
+ name: `${b.name} \xB7 shared layer`,
8530
+ kind: "shared",
8531
+ source: b.source,
8532
+ root: nameCluster(files).root,
8533
+ files: layer,
8534
+ externalPackages: [],
8535
+ why: `Shared layer of ${b.name}: used by ${by.size} file${by.size === 1 ? "" : "s"} in ${groupsUsing.size} group${groupsUsing.size === 1 ? "" : "s"}`
8536
+ });
8537
+ for (const f of layer) groupOf.set(f, `group|${b.source}|shared:${b.root}`);
8538
+ }
8539
+ const taken = /* @__PURE__ */ new Set();
8540
+ for (const g of out) {
8541
+ if (taken.has(g.id)) g.id = `${g.id} (${byId.get(g.files[0]).path})`;
8542
+ taken.add(g.id);
8543
+ }
8544
+ out.sort((a, b) => cmp2(a.id, b.id));
8545
+ groupOf.clear();
8546
+ for (const g of out) for (const f of g.files) groupOf.set(f, g.id);
8547
+ const dependsOn = rollUp(out, groupOf, input2, input2.fnFile);
8548
+ for (const g of out) g.externalPackages.sort(cmp2);
8549
+ return { groups: out, dependsOn, differences: differencesOf(input2.declared, out) };
8550
+ }
8551
+ function sharedPrefix(names) {
8552
+ const counts = /* @__PURE__ */ new Map();
8553
+ for (const n3 of names) {
8554
+ const m = /^(.+?[-_.])/.exec(n3);
8555
+ if (m) counts.set(m[1], (counts.get(m[1]) ?? 0) + 1);
8556
+ }
8557
+ const [best, n2] = [...counts].sort((a, b) => b[1] - a[1] || cmp2(a[0], b[0]))[0] ?? ["", 0];
8558
+ return n2 >= Math.ceil(names.length * 0.6) && best ? best : null;
8559
+ }
8560
+ function differencesOf(declared2, connected) {
8561
+ const node2 = (side, id) => `${side}\0${id}`;
8562
+ const parent = /* @__PURE__ */ new Map();
8563
+ const find2 = (x) => {
8564
+ const p = parent.get(x) ?? x;
8565
+ if (p === x) return x;
8566
+ const r = find2(p);
8567
+ parent.set(x, r);
8568
+ return r;
8569
+ };
8570
+ const union2 = (a, b) => {
8571
+ const ra = find2(a);
8572
+ const rb = find2(b);
8573
+ if (ra !== rb) parent.set(rb, ra);
8574
+ };
8575
+ const declaredOf = /* @__PURE__ */ new Map();
8576
+ for (const g of declared2) for (const f of g.files) declaredOf.set(f, g.id);
8577
+ const counts = /* @__PURE__ */ new Map();
8578
+ for (const g of connected)
8579
+ for (const f of g.files) {
8580
+ const d = declaredOf.get(f);
8581
+ if (!d) continue;
8582
+ union2(node2("d", d), node2("c", g.id));
8583
+ const key = `${d}\0${g.id}`;
8584
+ counts.set(key, (counts.get(key) ?? 0) + 1);
8585
+ }
8586
+ const named = /* @__PURE__ */ new Map();
8587
+ for (const g of declared2) named.set(node2("d", g.id), { id: g.id, name: g.name });
8588
+ for (const g of connected) named.set(node2("c", g.id), { id: g.id, name: g.name });
8589
+ const sets = /* @__PURE__ */ new Map();
8590
+ for (const [key, g] of named) {
8591
+ const r = find2(key);
8592
+ const s = sets.get(r) ?? { declared: [], connected: [] };
8593
+ (key.startsWith("d\0") ? s.declared : s.connected).push(g);
8594
+ sets.set(r, s);
8595
+ }
8596
+ const byName = (a, b) => cmp2(a.name, b.name) || cmp2(a.id, b.id);
8597
+ return [...sets.values()].filter((s) => s.declared.length > 1 || s.connected.length > 1).map((s) => {
8598
+ const ids2 = new Set(s.connected.map((g) => g.id));
8599
+ return {
8600
+ declared: s.declared.sort(byName),
8601
+ connected: s.connected.sort(byName),
8602
+ files: [...counts].map(([key, count2]) => {
8603
+ const [d, c] = key.split("\0");
8604
+ return { declared: d, connected: c, count: count2 };
8605
+ }).filter((x) => ids2.has(x.connected)).sort((a, b) => cmp2(a.connected, b.connected) || cmp2(a.declared, b.declared))
8606
+ };
8607
+ }).sort((a, b) => cmp2(a.declared[0]?.id ?? "", b.declared[0]?.id ?? ""));
8608
+ }
8609
+ var SHARED_MIN_USERS, SHARED_SQRT_FACTOR, SHARED_MAX_USES, PART_MIN_FILES, MERGE_MIN_CALLS, MERGE_BALANCE, MERGE_SHARE, COMMON_MAX, CO_WEIGHT, cmp2, dirOf, inside3, discount;
8610
+ var init_connected = __esm({
8611
+ "packages/query-imports/src/connected.ts"() {
8612
+ "use strict";
8613
+ init_src();
8614
+ init_cluster();
8615
+ SHARED_MIN_USERS = 5;
8616
+ SHARED_SQRT_FACTOR = 2;
8617
+ SHARED_MAX_USES = 1 / 4;
8618
+ PART_MIN_FILES = 3;
8619
+ MERGE_MIN_CALLS = 2;
8620
+ MERGE_BALANCE = 1 / 3;
8621
+ MERGE_SHARE = 1 / 4;
8622
+ COMMON_MAX = 200;
8623
+ CO_WEIGHT = 0.5;
8624
+ cmp2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8625
+ dirOf = (path) => {
8626
+ const d = posix3.dirname(path);
8627
+ return d === "." ? "" : d;
8628
+ };
8629
+ inside3 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
8630
+ discount = (n2) => 1 / Math.log2(1 + Math.max(n2, 1));
8631
+ }
8632
+ });
8633
+
7650
8634
  // packages/query-imports/src/impact.ts
7651
8635
  function findingImpacts(reader, rows, own2, all2 = rows) {
7652
8636
  const into = /* @__PURE__ */ new Map();
@@ -7743,6 +8727,64 @@ var init_impact = __esm({
7743
8727
  }
7744
8728
  });
7745
8729
 
8730
+ // packages/query-imports/src/once.ts
8731
+ function onceReader(reader) {
8732
+ const byType = /* @__PURE__ */ new Map();
8733
+ const byFile = /* @__PURE__ */ new Map();
8734
+ const ofType = (type) => {
8735
+ let list = byType.get(type);
8736
+ if (!list) byType.set(type, list = reader.facts(type));
8737
+ return list;
8738
+ };
8739
+ const inFileOf = (type, file2) => {
8740
+ let index = byFile.get(type);
8741
+ if (!index) {
8742
+ index = /* @__PURE__ */ new Map();
8743
+ for (const f of ofType(type)) {
8744
+ const at = "file" in f && typeof f.file === "string" ? f.file : void 0;
8745
+ if (at === void 0) continue;
8746
+ const list = index.get(at);
8747
+ if (list) list.push(f);
8748
+ else index.set(at, [f]);
8749
+ }
8750
+ byFile.set(type, index);
8751
+ }
8752
+ return index.get(file2) ?? [];
8753
+ };
8754
+ const FILED = /* @__PURE__ */ new Set([
8755
+ "Function",
8756
+ "UnresolvedCallSite",
8757
+ "SiteResolution",
8758
+ "UnresolvedImport"
8759
+ ]);
8760
+ const KEPT = /* @__PURE__ */ new Set([...FILED, "File", "Group", "REFERENCES", "CALLS_CROSS_FILE"]);
8761
+ return {
8762
+ run: reader.run,
8763
+ ...reader.stages ? { stages: reader.stages } : {},
8764
+ ...reader.base !== void 0 ? { base: reader.base } : {},
8765
+ withStages: (stages) => reader.withStages(stages),
8766
+ fact: (id) => reader.fact(id),
8767
+ // As the store: a file given (not empty) reads that file's.
8768
+ facts: ((type, file2) => !KEPT.has(type) ? reader.facts(type, file2) : !file2 ? ofType(type) : FILED.has(type) ? inFileOf(type, file2) : reader.facts(type, file2)),
8769
+ factsTo: (type, dst) => reader.factsTo(type, dst),
8770
+ inFile: (file2) => reader.inFile(file2),
8771
+ callsFrom: (fn) => reader.callsFrom(fn),
8772
+ callsTo: (fn) => reader.callsTo(fn),
8773
+ countByFile: (type) => reader.countByFile(type),
8774
+ callCounts: (end2, ids2) => reader.callCounts(end2, ids2),
8775
+ count: (type) => reader.count(type),
8776
+ provenance: (ids2) => reader.provenance(ids2),
8777
+ writtenStages: () => reader.writtenStages(),
8778
+ scopesOf: (stage) => reader.scopesOf(stage),
8779
+ all: () => reader.all()
8780
+ };
8781
+ }
8782
+ var init_once = __esm({
8783
+ "packages/query-imports/src/once.ts"() {
8784
+ "use strict";
8785
+ }
8786
+ });
8787
+
7746
8788
  // packages/query-imports/src/symbols.ts
7747
8789
  function describeName(reader, e) {
7748
8790
  let target2 = null;
@@ -7879,7 +8921,7 @@ function listReferences(engine, args, cwd) {
7879
8921
  edges = edges.filter((e) => inFile.has(e.to));
7880
8922
  }
7881
8923
  }
7882
- edges.sort((a, b) => byPosition(a, b) || cmp(a.id, b.id));
8924
+ edges.sort((a, b) => byPosition(a, b) || cmp3(a.id, b.id));
7883
8925
  const references = edges.slice(0, limit).map((e) => ({
7884
8926
  id: e.id,
7885
8927
  from: endOf(reader, e.from),
@@ -7895,17 +8937,17 @@ function listReferences(engine, args, cwd) {
7895
8937
  }));
7896
8938
  return { ...meta3, direction, total: edges.length, truncated: edges.length > limit, references };
7897
8939
  }
7898
- var SYMBOL_IMPORTS_MAX, REFERENCES_MAX, cmp, pathOf, unusedName, byPosition;
8940
+ var SYMBOL_IMPORTS_MAX, REFERENCES_MAX, cmp3, pathOf, unusedName, byPosition;
7899
8941
  var init_symbols = __esm({
7900
8942
  "packages/query-imports/src/symbols.ts"() {
7901
8943
  "use strict";
7902
8944
  init_src();
7903
8945
  SYMBOL_IMPORTS_MAX = 500;
7904
8946
  REFERENCES_MAX = 500;
7905
- cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
8947
+ cmp3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
7906
8948
  pathOf = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
7907
8949
  unusedName = (e) => e.uses !== null && Object.values(e.uses).every((v) => v === 0);
7908
- byPosition = (a, b) => cmp(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp(a.local ?? "", b.local ?? "");
8950
+ byPosition = (a, b) => cmp3(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp3(a.local ?? "", b.local ?? "");
7909
8951
  }
7910
8952
  });
7911
8953
 
@@ -8061,7 +9103,7 @@ var init_totals = __esm({
8061
9103
  });
8062
9104
 
8063
9105
  // packages/query-imports/src/reads.ts
8064
- function cmp2(a, b) {
9106
+ function cmp4(a, b) {
8065
9107
  return a < b ? -1 : a > b ? 1 : 0;
8066
9108
  }
8067
9109
  function nonNegative2(offset) {
@@ -8094,16 +9136,100 @@ function fileFact(reader, id) {
8094
9136
  if (!f || f.type !== "File") throw new VeoError("not-found", `no file ${id}`, { kind: "file", id });
8095
9137
  return f;
8096
9138
  }
9139
+ function groupingOf(grouping) {
9140
+ if (grouping === void 0) return "declared";
9141
+ if (!GROUPINGS.includes(grouping))
9142
+ throw new VeoError("invalid-arguments", `grouping must be one of ${GROUPINGS.join(", ")}`, {
9143
+ fields: ["grouping"]
9144
+ });
9145
+ return grouping;
9146
+ }
9147
+ function deriveConnected(reader, pending) {
9148
+ return connectedGrouping({
9149
+ files: reader.facts("File"),
9150
+ declared: reader.facts("Group"),
9151
+ fnFile: new Map(reader.facts("Function").map((f) => [f.id, f.file])),
9152
+ imports: reader.facts("IMPORTS"),
9153
+ calls: reader.facts("CALLS_CROSS_FILE"),
9154
+ references: reader.facts("REFERENCES"),
9155
+ symbols: reader.facts("IMPORTS_SYMBOL"),
9156
+ own: (f) => f.origin === void 0 && !inPendingLibrary(f, pending)
9157
+ });
9158
+ }
9159
+ function connectedCounts(groups2, kept) {
9160
+ const groupOf = groupIndex([...groups2]);
9161
+ const counts = /* @__PURE__ */ new Map();
9162
+ for (const k of Object.values(kept)) {
9163
+ const g = groupOf.get(k.file)?.id;
9164
+ if (!g) continue;
9165
+ const c = counts.get(g) ?? zero();
9166
+ tally(c, k.kind);
9167
+ counts.set(g, c);
9168
+ }
9169
+ return counts;
9170
+ }
9171
+ function keepConnectedGrouping(engine, project2, run2) {
9172
+ const { reader, stage2: stage22 } = open(engine, { project: project2, run: run2 });
9173
+ if (!stage22) return;
9174
+ const pending = engine.pendingLibraries(project2, run2);
9175
+ const key = pendingKey(pending);
9176
+ const derived2 = deriveConnected(reader, pending);
9177
+ const impacts = keptImpacts(engine, project2, run2, key);
9178
+ const kept = {
9179
+ pending: key,
9180
+ made: engine.veoflow,
9181
+ ...derived2,
9182
+ ...impacts ? { findings: Object.fromEntries(connectedCounts(derived2.groups, impacts)) } : {}
9183
+ };
9184
+ engine.setRunSummary(project2, run2, CONNECTED_SUMMARY, kept);
9185
+ }
9186
+ function groupsView(engine, meta3, reader, run2, grouping) {
9187
+ const declared2 = reader.facts("Group");
9188
+ if (grouping === "declared")
9189
+ return {
9190
+ groups: declared2,
9191
+ dependsOn: reader.facts("DEPENDS_ON"),
9192
+ why: new Map(declared2.map((g) => [g.id, declaredWhy(g)]))
9193
+ };
9194
+ const pending = engine.pendingLibraries(meta3.project, run2);
9195
+ const made = engine.resolveProject({ project: meta3.project }).createdAt;
9196
+ const key = run2 === null ? null : `${meta3.project}\0${made}\0${run2}\0${pendingKey(pending)}`;
9197
+ let cache = connectedCache.get(engine);
9198
+ if (!cache) connectedCache.set(engine, cache = /* @__PURE__ */ new Map());
9199
+ const hit = key === null ? void 0 : cache.get(key);
9200
+ if (hit) return hit;
9201
+ const kept = run2 === null ? void 0 : engine.runSummary(meta3.project, run2, CONNECTED_SUMMARY);
9202
+ const usable = kept && kept.pending === pendingKey(pending) && (engine.veoflow === null || kept.made === engine.veoflow) ? kept : void 0;
9203
+ const derived2 = usable ?? deriveConnected(reader, pending);
9204
+ if (!usable && run2 !== null && declared2.length > 0)
9205
+ try {
9206
+ const keep = { pending: pendingKey(pending), made: engine.veoflow, ...derived2 };
9207
+ engine.setRunSummary(meta3.project, run2, CONNECTED_SUMMARY, keep);
9208
+ } catch {
9209
+ }
9210
+ const view = {
9211
+ groups: derived2.groups,
9212
+ dependsOn: derived2.dependsOn,
9213
+ why: new Map(derived2.groups.map((g) => [g.id, g.why])),
9214
+ differences: derived2.differences,
9215
+ ...usable?.findings ? { findings: new Map(Object.entries(usable.findings)) } : {}
9216
+ };
9217
+ if (key !== null) {
9218
+ if (cache.size >= CACHED_GROUPINGS) cache.delete(cache.keys().next().value);
9219
+ cache.set(key, view);
9220
+ }
9221
+ return view;
9222
+ }
8097
9223
  function groupIndex(groups2) {
8098
9224
  const byFile = /* @__PURE__ */ new Map();
8099
9225
  for (const g of groups2) for (const f of g.files) if (!byFile.has(f)) byFile.set(f, g);
8100
9226
  return byFile;
8101
9227
  }
8102
- function findingsIn(reader, groupOf, files) {
9228
+ function findingsIn(reader, groupOf, files, plain2 = false) {
8103
9229
  const each = (type) => files === null ? reader.facts(type) : files.flatMap((f) => reader.facts(type, f));
8104
9230
  const rows = [];
8105
9231
  const row = (fact, kind, text, reason, candidates, exhaustive) => {
8106
- const builtins = kind === "open-call" && UNTYPED_REASONS.has(reason) ? builtinsNamed(text) : [];
9232
+ const builtins = !plain2 && kind === "open-call" && UNTYPED_REASONS.has(reason) ? builtinsNamed(text) : [];
8107
9233
  rows.push({
8108
9234
  id: fact.id,
8109
9235
  kind,
@@ -8149,13 +9275,14 @@ function tally(counts, kind) {
8149
9275
  else if (kind === "pending") counts.pending++;
8150
9276
  else counts.openCalls++;
8151
9277
  }
8152
- function summary(g, functions, findings) {
9278
+ function summary(g, functions, findings, why) {
8153
9279
  let fns = 0;
8154
9280
  for (const f of g.files) fns += functions.get(f) ?? 0;
8155
9281
  return {
8156
9282
  id: g.id,
8157
9283
  name: g.name,
8158
9284
  kind: g.kind,
9285
+ why: why.get(g.id) ?? "",
8159
9286
  source: g.source,
8160
9287
  root: g.root,
8161
9288
  files: g.files.length,
@@ -8167,21 +9294,41 @@ function summary(g, functions, findings) {
8167
9294
  function listGroups(engine, args, cwd) {
8168
9295
  const limit = positiveLimit(args.limit, GROUPS_MAX, GROUPS_MAX);
8169
9296
  const offset = nonNegative2(args.offset);
9297
+ const grouping = groupingOf(args.grouping);
8170
9298
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8171
9299
  const inScope = (source) => args.source === void 0 || source === args.source;
8172
- const groups2 = reader.facts("Group").filter((g) => inScope(g.source)).sort((a, b) => cmp2(a.id, b.id));
9300
+ const run2 = args.run ?? meta3.committedRun;
9301
+ const view = groupsView(engine, meta3, reader, run2, grouping);
9302
+ const groups2 = view.groups.filter((g) => inScope(g.source)).sort((a, b) => cmp4(a.id, b.id));
8173
9303
  const groupOf = groupIndex(groups2);
8174
9304
  const findings = /* @__PURE__ */ new Map();
8175
9305
  let brokenImports2 = 0;
8176
9306
  let openCalls = 0;
8177
9307
  const files = reader.facts("File").filter((f) => inScope(f.source));
8178
- const run2 = args.run ?? meta3.committedRun;
8179
9308
  const pending = engine.pendingLibraries(meta3.project, run2);
8180
9309
  const ownFiles = new Set(files.filter(ownCodeTest(pending)).map((f) => f.id));
8181
9310
  let ownFindings;
8182
9311
  const kept = run2 === null ? void 0 : keptFindingSummary(engine, meta3.project, run2);
8183
9312
  if (kept) {
8184
- for (const g of groups2) if (kept.groups[g.id]) findings.set(g.id, kept.groups[g.id]);
9313
+ if (grouping === "declared") {
9314
+ for (const g of groups2) if (kept.groups[g.id]) findings.set(g.id, kept.groups[g.id]);
9315
+ } else {
9316
+ view.findings ??= (() => {
9317
+ const keptRows = run2 === null ? void 0 : keptImpacts(engine, meta3.project, run2, pendingKey(pending));
9318
+ if (keptRows) return connectedCounts(view.groups, keptRows);
9319
+ const all2 = groupIndex(view.groups);
9320
+ const counts = /* @__PURE__ */ new Map();
9321
+ for (const f of findingsIn(reader, all2, null, true)) {
9322
+ const g = all2.get(f.file)?.id;
9323
+ if (!g) continue;
9324
+ const c = counts.get(g) ?? zero();
9325
+ tally(c, f.kind);
9326
+ counts.set(g, c);
9327
+ }
9328
+ return counts;
9329
+ })();
9330
+ for (const g of groups2) if (view.findings.has(g.id)) findings.set(g.id, view.findings.get(g.id));
9331
+ }
8185
9332
  for (const [source, c] of Object.entries(kept.sources))
8186
9333
  if (inScope(source)) {
8187
9334
  brokenImports2 += c.broken;
@@ -8198,7 +9345,7 @@ function listGroups(engine, args, cwd) {
8198
9345
  }
8199
9346
  } else {
8200
9347
  ownFindings = { brokenImports: 0, openCalls: 0 };
8201
- for (const f of findingsIn(reader, groupOf, null)) {
9348
+ for (const f of findingsIn(reader, groupOf, null, true)) {
8202
9349
  if (!inScope(sourceOf2(f.file))) continue;
8203
9350
  if (f.kind === "broken") brokenImports2++;
8204
9351
  if (f.kind === "open-call") openCalls++;
@@ -8224,11 +9371,12 @@ function listGroups(engine, args, cwd) {
8224
9371
  for (const g of groups2) for (const p of g.externalPackages) importers.set(p, (importers.get(p) ?? 0) + 1);
8225
9372
  const packages = [...importers.keys()].map((id) => reader.fact(id)).filter((p) => p?.type === "ExternalPackage");
8226
9373
  packages.sort(
8227
- (a, b) => importers.get(b.id) - importers.get(a.id) || cmp2(a.name, b.name) || cmp2(a.id, b.id)
9374
+ (a, b) => importers.get(b.id) - importers.get(a.id) || cmp4(a.name, b.name) || cmp4(a.id, b.id)
8228
9375
  );
8229
9376
  return {
8230
9377
  ...meta3,
8231
9378
  stage2: stage22,
9379
+ grouping,
8232
9380
  stats: {
8233
9381
  files: files.length,
8234
9382
  functions: fnCount,
@@ -8245,8 +9393,8 @@ function listGroups(engine, args, cwd) {
8245
9393
  total: groups2.length,
8246
9394
  offset,
8247
9395
  truncated: groups2.length > offset + limit,
8248
- groups: shown.map((g) => summary(g, functions, findings)),
8249
- dependsOn: reader.facts("DEPENDS_ON").filter((d) => ids2.has(d.from) && ids2.has(d.to)).sort((a, b) => cmp2(a.id, b.id)).map(({ id, from, to, imports, calls, references, carrying, evidence }) => ({
9396
+ groups: shown.map((g) => summary(g, functions, findings, view.why)),
9397
+ dependsOn: view.dependsOn.filter((d) => ids2.has(d.from) && ids2.has(d.to)).sort((a, b) => cmp4(a.id, b.id)).map(({ id, from, to, imports, calls, references, carrying, evidence }) => ({
8250
9398
  id,
8251
9399
  from,
8252
9400
  to,
@@ -8259,9 +9407,14 @@ function listGroups(engine, args, cwd) {
8259
9407
  externalPackages: {
8260
9408
  total: packages.length,
8261
9409
  top: packages.slice(0, TOP_PACKAGES).map((p) => ({ id: p.id, name: p.name, ecosystem: p.ecosystem, groups: importers.get(p.id) }))
8262
- }
9410
+ },
9411
+ ...view.differences ? { differences: inScopeDifferences(view, groups2) } : {}
8263
9412
  };
8264
9413
  }
9414
+ function inScopeDifferences(view, groups2) {
9415
+ const ids2 = new Set(groups2.map((g) => g.id));
9416
+ return view.differences.filter((d) => d.connected.some((g) => ids2.has(g.id)));
9417
+ }
8265
9418
  function parentOf2(path) {
8266
9419
  const i = path.lastIndexOf("/");
8267
9420
  return i < 0 ? "" : path.slice(0, i);
@@ -8289,14 +9442,14 @@ function collapsedFolders(root, paths, expand, over) {
8289
9442
  return e ? e.files + e.folders.size : 0;
8290
9443
  };
8291
9444
  let visible = size(root);
8292
- const queue = [...children.get(root)?.folders ?? []].sort(cmp2);
9445
+ const queue = [...children.get(root)?.folders ?? []].sort(cmp4);
8293
9446
  while (queue.length) {
8294
9447
  const dir = queue.shift();
8295
9448
  const grows = size(dir) - 1;
8296
9449
  const asked = [...expand].some((x) => x === dir || x.startsWith(`${dir}/`));
8297
9450
  if (asked || visible === 1 || visible + grows <= over) {
8298
9451
  visible += grows;
8299
- queue.push(...[...children.get(dir)?.folders ?? []].sort(cmp2));
9452
+ queue.push(...[...children.get(dir)?.folders ?? []].sort(cmp4));
8300
9453
  } else collapsed.add(dir);
8301
9454
  }
8302
9455
  return collapsed;
@@ -8304,15 +9457,16 @@ function collapsedFolders(root, paths, expand, over) {
8304
9457
  function getGroup(engine, args, cwd) {
8305
9458
  if (typeof args.group !== "string" || !args.group)
8306
9459
  throw new VeoError("invalid-arguments", "group is required", { fields: ["group"] });
9460
+ const grouping = groupingOf(args.grouping);
8307
9461
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8308
- const group = reader.fact(args.group);
8309
- if (!group || group.type !== "Group")
8310
- throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
8311
- const groups2 = reader.facts("Group");
9462
+ const view = groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping);
9463
+ const group = view.groups.find((g) => g.id === args.group);
9464
+ if (!group) throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
9465
+ const groups2 = view.groups;
8312
9466
  const groupOf = groupIndex(groups2);
8313
9467
  const members2 = new Set(group.files);
8314
- const files = group.files.map((id) => reader.fact(id)).filter((f) => f?.type === "File").sort((a, b) => cmp2(a.path, b.path));
8315
- const root = group.kind === "cluster" ? "" : group.root;
9468
+ const files = group.files.map((id) => reader.fact(id)).filter((f) => f?.type === "File").sort((a, b) => cmp4(a.path, b.path));
9469
+ const root = group.kind === "repository" || group.kind === "workspace-package" ? group.root : "";
8316
9470
  const collapsed = collapsedFolders(
8317
9471
  root,
8318
9472
  files.map((f) => f.path),
@@ -8360,7 +9514,7 @@ function getGroup(engine, args, cwd) {
8360
9514
  findings: counts.get(f.id) ?? zero()
8361
9515
  })),
8362
9516
  ...folders.values()
8363
- ].sort((a, b) => cmp2(a.path, b.path) || cmp2(a.kind, b.kind));
9517
+ ].sort((a, b) => cmp4(a.path, b.path) || cmp4(a.kind, b.kind));
8364
9518
  const edges = /* @__PURE__ */ new Map();
8365
9519
  const stubs = /* @__PURE__ */ new Map();
8366
9520
  const add2 = (map2, from, to, evidence) => {
@@ -8454,8 +9608,8 @@ function getGroup(engine, args, cwd) {
8454
9608
  }
8455
9609
  }
8456
9610
  const packages = stubs.get("stub|packages");
8457
- packages?.packages.sort(cmp2);
8458
- const sorted = (m) => [...m.values()].filter((e) => kept.has(e.to) || stubs.has(e.to)).sort((a, b) => cmp2(a.id, b.id));
9611
+ packages?.packages.sort(cmp4);
9612
+ const sorted = (m) => [...m.values()].filter((e) => kept.has(e.to) || stubs.has(e.to)).sort((a, b) => cmp4(a.id, b.id));
8459
9613
  const functions = reader.countByFile("Function");
8460
9614
  const findings = /* @__PURE__ */ new Map();
8461
9615
  for (const c of counts.values()) {
@@ -8469,24 +9623,28 @@ function getGroup(engine, args, cwd) {
8469
9623
  return {
8470
9624
  ...meta3,
8471
9625
  stage2: stage22,
8472
- group: summary(group, functions, findings),
9626
+ grouping,
9627
+ group: summary(group, functions, findings, view.why),
8473
9628
  collapsed: collapsed.size > 0,
8474
9629
  total: nodes.length,
8475
9630
  truncated: nodes.length > GROUP_NODES_MAX,
8476
9631
  nodes: shown,
8477
9632
  imports: sorted(edges),
8478
- stubs: [...stubs.values()].sort((a, b) => cmp2(a.id, b.id)),
9633
+ stubs: [...stubs.values()].sort((a, b) => cmp4(a.id, b.id)),
8479
9634
  stubEdges: sorted(stubEdges),
8480
- calls: [...callEdges.values()].filter((e) => kept.has(e.to)).sort((a, b) => cmp2(a.id, b.id)),
8481
- callStubEdges: [...callStubs.values()].sort((a, b) => cmp2(a.id, b.id))
9635
+ calls: [...callEdges.values()].filter((e) => kept.has(e.to)).sort((a, b) => cmp4(a.id, b.id)),
9636
+ callStubEdges: [...callStubs.values()].sort((a, b) => cmp4(a.id, b.id))
8482
9637
  };
8483
9638
  }
8484
9639
  function resolveImports(engine, args, cwd) {
8485
9640
  if (typeof args.file !== "string" || !args.file)
8486
9641
  throw new VeoError("invalid-arguments", "file is required", { fields: ["file"] });
9642
+ const grouping = groupingOf(args.grouping);
8487
9643
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8488
9644
  const file2 = fileFact(reader, args.file);
8489
- const groupOf = groupIndex(reader.facts("Group"));
9645
+ const groupOf = groupIndex(
9646
+ groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping).groups
9647
+ );
8490
9648
  const ref = (id) => ({ id, path: pathOf2(id), group: groupOf.get(id)?.id ?? null });
8491
9649
  const imports = [
8492
9650
  ...reader.facts("IMPORTS", file2.id).map((e) => {
@@ -8570,21 +9728,22 @@ function listFindings(engine, args, cwd) {
8570
9728
  if (args.own !== void 0 && typeof args.own !== "boolean")
8571
9729
  throw new VeoError("invalid-arguments", "own must be true or false", { fields: ["own"] });
8572
9730
  const limit = positiveLimit(args.limit, 100, FINDINGS_MAX);
9731
+ const grouping = groupingOf(args.grouping);
8573
9732
  const { meta: meta3, reader, stage2: stage22 } = open(engine, args, cwd);
8574
9733
  const run2 = args.run ?? meta3.committedRun;
8575
9734
  const pending = engine.pendingLibraries(meta3.project, run2);
8576
9735
  const ownFiles = args.own ? new Set(
8577
9736
  reader.facts("File").filter(ownCodeTest(pending)).map((f) => f.id)
8578
9737
  ) : null;
8579
- const groups2 = reader.facts("Group");
9738
+ const view = groupsView(engine, meta3, reader, run2, grouping);
9739
+ const groups2 = view.groups;
8580
9740
  const groupOf = groupIndex(groups2);
8581
9741
  let inScope = () => true;
8582
9742
  let files = null;
8583
9743
  if (args.source !== void 0) inScope = (f) => sourceOf2(f.file) === args.source;
8584
9744
  else if (args.group !== void 0) {
8585
- const g = reader.fact(args.group);
8586
- if (!g || g.type !== "Group")
8587
- throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
9745
+ const g = groups2.find((x) => x.id === args.group);
9746
+ if (!g) throw new VeoError("not-found", `no group ${args.group}`, { kind: "group", id: args.group });
8588
9747
  files = g.files;
8589
9748
  } else if (args.file !== void 0) files = [fileFact(reader, args.file).id];
8590
9749
  const kinds = new Set(args.kind?.length ? args.kind : ["broken", "not-analyzed", "open-call"]);
@@ -8634,7 +9793,7 @@ function listFindings(engine, args, cwd) {
8634
9793
  if (kinds.has(k.kind)) order.push([id, k]);
8635
9794
  }
8636
9795
  order.sort(
8637
- ([ia, a], [ib, b]) => Number(!!a.last) - Number(!!b.last) || b.opens - a.opens || cmp2(a.file, b.file) || a.offset - b.offset || cmp2(ia, ib)
9796
+ ([ia, a], [ib, b]) => Number(!!a.last) - Number(!!b.last) || b.opens - a.opens || cmp4(a.file, b.file) || a.offset - b.offset || cmp4(ia, ib)
8638
9797
  );
8639
9798
  const page = order.slice(offset, offset + limit);
8640
9799
  const wanted2 = new Set(page.map(([id]) => id));
@@ -8660,7 +9819,7 @@ function listFindings(engine, args, cwd) {
8660
9819
  if (kinds.has(f.kind)) rows2.push(f);
8661
9820
  }
8662
9821
  const all2 = withImpact(rows2).sort(
8663
- (a, b) => Number(listedLast(a)) - Number(listedLast(b)) || (b.impact?.opens ?? 0) - (a.impact?.opens ?? 0) || byEvidence(a, b) || cmp2(a.id, b.id)
9822
+ (a, b) => Number(listedLast(a)) - Number(listedLast(b)) || (b.impact?.opens ?? 0) - (a.impact?.opens ?? 0) || byEvidence(a, b) || cmp4(a.id, b.id)
8664
9823
  );
8665
9824
  return {
8666
9825
  ...meta3,
@@ -8673,9 +9832,9 @@ function listFindings(engine, args, cwd) {
8673
9832
  };
8674
9833
  }
8675
9834
  const kept = run2 === null || args.source !== void 0 || args.file !== void 0 ? void 0 : keptFindingSummary(engine, meta3.project, run2);
8676
- const keptCounts = !kept ? void 0 : ownFiles ? args.group === void 0 ? ownCounts(kept, pending) : void 0 : args.group === void 0 ? kept.counts : kept.groups[args.group] ?? zero();
9835
+ const keptCounts = !kept ? void 0 : ownFiles ? args.group === void 0 ? ownCounts(kept, pending) : void 0 : args.group === void 0 ? kept.counts : grouping === "declared" ? kept.groups[args.group] ?? zero() : void 0;
8677
9836
  if (keptCounts) {
8678
- const order = (files ?? reader.facts("File").map((f) => f.id)).filter((f) => !ownFiles || ownFiles.has(f)).sort(cmp2);
9837
+ const order = (files ?? reader.facts("File").map((f) => f.id)).filter((f) => !ownFiles || ownFiles.has(f)).sort(cmp4);
8679
9838
  const total = [...kinds].reduce((n2, k) => n2 + keptCounts[KIND_COUNT[k]], 0);
8680
9839
  const page = [];
8681
9840
  let skipped = 0;
@@ -8755,7 +9914,7 @@ function siteLinks(engine, args, cwd) {
8755
9914
  return { ...meta3, stage2: stage22, links };
8756
9915
  }
8757
9916
  function summarizeFindings(engine, project2, run2) {
8758
- const { reader } = open(engine, { project: project2, run: run2 });
9917
+ const reader = onceReader(open(engine, { project: project2, run: run2 }).reader);
8759
9918
  const files = reader.facts("File");
8760
9919
  const summary2 = {
8761
9920
  counts: zero(),
@@ -8838,13 +9997,15 @@ function ownCounts(summary2, pending) {
8838
9997
  const own2 = ownBySource(summary2, pending);
8839
9998
  return own2 ? Object.values(own2).reduce(add, zero()) : void 0;
8840
9999
  }
8841
- var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf2, sourceOf2, byEvidence, FINDING_KINDS, UNTYPED_REASONS, listedLast, KIND_COUNT, zero, add, FINDINGS_SUMMARY, IMPACT_SUMMARY;
10000
+ var STAGE2, GROUPS_MAX, GROUP_NODES_MAX, GROUP_COLLAPSE_OVER, IMPORTS_MAX, FINDINGS_MAX, TOP_PACKAGES, pathOf2, sourceOf2, byEvidence, GROUPINGS, CONNECTED_SUMMARY, connectedCache, CACHED_GROUPINGS, FINDING_KINDS, UNTYPED_REASONS, listedLast, KIND_COUNT, zero, add, FINDINGS_SUMMARY, IMPACT_SUMMARY;
8842
10001
  var init_reads = __esm({
8843
10002
  "packages/query-imports/src/reads.ts"() {
8844
10003
  "use strict";
8845
10004
  init_src();
8846
10005
  init_builtins();
10006
+ init_connected();
8847
10007
  init_impact();
10008
+ init_once();
8848
10009
  init_symbols();
8849
10010
  init_totals();
8850
10011
  STAGE2 = "stage2";
@@ -8856,7 +10017,11 @@ var init_reads = __esm({
8856
10017
  TOP_PACKAGES = 20;
8857
10018
  pathOf2 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
8858
10019
  sourceOf2 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
8859
- byEvidence = (a, b) => cmp2(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp2(a.id, b.id);
10020
+ byEvidence = (a, b) => cmp4(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp4(a.id, b.id);
10021
+ GROUPINGS = ["declared", "connected"];
10022
+ CONNECTED_SUMMARY = "connected/v1";
10023
+ connectedCache = /* @__PURE__ */ new WeakMap();
10024
+ CACHED_GROUPINGS = 8;
8860
10025
  FINDING_KINDS = ["broken", "not-analyzed", "pending", "open-call"];
8861
10026
  UNTYPED_REASONS = /* @__PURE__ */ new Set(["dynamic-dispatch", "untyped"]);
8862
10027
  listedLast = (f) => f.mayBe?.projectFunctions === 0;
@@ -9212,7 +10377,7 @@ function explain(engine, args, cwd) {
9212
10377
  items.sort(
9213
10378
  (a, b) => (
9214
10379
  // Every item on a line has evidence (it was matched by it).
9215
- a.evidence.span.start.offset - b.evidence.span.start.offset || cmp3(a.kind, b.kind) || cmp3(a.id, b.id)
10380
+ a.evidence.span.start.offset - b.evidence.span.start.offset || cmp5(a.kind, b.kind) || cmp5(a.id, b.id)
9216
10381
  )
9217
10382
  );
9218
10383
  return {
@@ -9224,7 +10389,7 @@ function explain(engine, args, cwd) {
9224
10389
  ...file2.status !== "analyzed" ? { file: { status: file2.status, ...file2.reason ? { reason: file2.reason } : {} } } : {}
9225
10390
  };
9226
10391
  }
9227
- var EXPLAIN_MAX, pathOf3, cmp3, IMPORT_REASONS, SITE_REASONS, STATUS_WORDS, base, IMPORT_FIXES, CALL_FIXES, RESOLUTION_WORDS;
10392
+ var EXPLAIN_MAX, pathOf3, cmp5, IMPORT_REASONS, SITE_REASONS, STATUS_WORDS, base, IMPORT_FIXES, CALL_FIXES, RESOLUTION_WORDS;
9228
10393
  var init_explain = __esm({
9229
10394
  "packages/query-imports/src/explain.ts"() {
9230
10395
  "use strict";
@@ -9232,7 +10397,7 @@ var init_explain = __esm({
9232
10397
  init_builtins();
9233
10398
  EXPLAIN_MAX = 50;
9234
10399
  pathOf3 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9235
- cmp3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10400
+ cmp5 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9236
10401
  IMPORT_REASONS = {
9237
10402
  "file-not-found": "no file matches it",
9238
10403
  "not-exported": "the package's exports don't include that path",
@@ -9362,7 +10527,7 @@ function reach(engine, args, cwd) {
9362
10527
  const exits2 = [];
9363
10528
  let work = 0;
9364
10529
  let truncated = null;
9365
- let frontier = roots.map((f) => f.id).sort(cmp4);
10530
+ let frontier = roots.map((f) => f.id).sort(cmp6);
9366
10531
  if (frontier.length > budget.functions) {
9367
10532
  frontier = frontier.slice(0, budget.functions);
9368
10533
  truncated = { reason: "functions", depth: 0 };
@@ -9399,19 +10564,19 @@ function reach(engine, args, cwd) {
9399
10564
  if (!edges.has(key)) edges.set(key, e);
9400
10565
  }
9401
10566
  }
9402
- frontier = [...next].sort(cmp4);
10567
+ frontier = [...next].sort(cmp6);
9403
10568
  }
9404
- const functions = [...depthOf2.entries()].map(([id, depth]) => g.describe(id, depth)).sort((a, b) => a.depth - b.depth || cmp4(a.id, b.id));
10569
+ const functions = [...depthOf2.entries()].map(([id, depth]) => g.describe(id, depth)).sort((a, b) => a.depth - b.depth || cmp6(a.id, b.id));
9405
10570
  const reached = functions.filter((f) => f.depth > 0);
9406
10571
  const starts = direction === "backward" ? functions.flatMap((f) => {
9407
10572
  const c = reader.fact(`start|${f.id}`);
9408
10573
  return c?.type === "StartCandidate" ? [{ function: f.id, bases: [...new Set(c.bases.map((b) => b.kind))] }] : [];
9409
10574
  }) : [];
9410
10575
  const edgeList = [...edges.values()].sort(
9411
- (a, b) => byEvidence2(a, b) || cmp4(a.from, b.from) || cmp4(a.to, b.to) || cmp4(a.kind, b.kind)
10576
+ (a, b) => byEvidence2(a, b) || cmp6(a.from, b.from) || cmp6(a.to, b.to) || cmp6(a.kind, b.kind)
9412
10577
  );
9413
- gaps.sort((a, b) => byEvidence2(a, b) || cmp4(a.site, b.site));
9414
- exits2.sort((a, b) => byEvidence2(a, b) || cmp4(a.id, b.id));
10578
+ gaps.sort((a, b) => byEvidence2(a, b) || cmp6(a.site, b.site));
10579
+ exits2.sort((a, b) => byEvidence2(a, b) || cmp6(a.id, b.id));
9415
10580
  return {
9416
10581
  ...meta3,
9417
10582
  root: args.function !== void 0 ? { function: args.function } : { file: args.file },
@@ -9665,7 +10830,7 @@ function graphOf(reader, candidates) {
9665
10830
  };
9666
10831
  return { forward, backward, describe: describe4 };
9667
10832
  }
9668
- var callStage, REACH_DEPTH, REACH_FUNCTIONS, REACH_WORK, cmp4, pathOf4, byEvidence2, candidateIndexes;
10833
+ var callStage, REACH_DEPTH, REACH_FUNCTIONS, REACH_WORK, cmp6, pathOf4, byEvidence2, candidateIndexes;
9669
10834
  var init_reach = __esm({
9670
10835
  "packages/query-imports/src/reach.ts"() {
9671
10836
  "use strict";
@@ -9675,9 +10840,9 @@ var init_reach = __esm({
9675
10840
  REACH_DEPTH = { default: 8, max: 64 };
9676
10841
  REACH_FUNCTIONS = { default: 500, max: 5e3 };
9677
10842
  REACH_WORK = { default: 5e4, max: 5e5 };
9678
- cmp4 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10843
+ cmp6 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9679
10844
  pathOf4 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9680
- byEvidence2 = (a, b) => cmp4(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
10845
+ byEvidence2 = (a, b) => cmp6(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
9681
10846
  candidateIndexes = /* @__PURE__ */ new WeakMap();
9682
10847
  }
9683
10848
  });
@@ -9756,7 +10921,7 @@ function listExits(engine, args, cwd) {
9756
10921
  return p?.type === "ExternalPackage" ? p.name : id;
9757
10922
  };
9758
10923
  const all2 = [...groups2.entries()].sort(
9759
- ([ka, a], [kb, b]) => b.calls.length - a.calls.length || cmp5(ka, kb)
10924
+ ([ka, a], [kb, b]) => b.calls.length - a.calls.length || cmp7(ka, kb)
9760
10925
  );
9761
10926
  let calls = 0;
9762
10927
  let refs = 0;
@@ -9841,7 +11006,7 @@ function listStartCandidates(engine, args, cwd) {
9841
11006
  }))
9842
11007
  };
9843
11008
  }).sort(
9844
- (a, b) => cmp5(a.group?.name ?? "", b.group?.name ?? "") || cmp5(a.function.path, b.function.path) || a.function.line - b.function.line || cmp5(a.function.id, b.function.id)
11009
+ (a, b) => cmp7(a.group?.name ?? "", b.group?.name ?? "") || cmp7(a.function.path, b.function.path) || a.function.line - b.function.line || cmp7(a.function.id, b.function.id)
9845
11010
  );
9846
11011
  return {
9847
11012
  ...meta3,
@@ -9849,11 +11014,11 @@ function listStartCandidates(engine, args, cwd) {
9849
11014
  offset,
9850
11015
  truncated: offset + limit < rows.length,
9851
11016
  byBasis,
9852
- byGroup: [...counts.values()].sort((a, b) => b.count - a.count || cmp5(a.name, b.name)),
11017
+ byGroup: [...counts.values()].sort((a, b) => b.count - a.count || cmp7(a.name, b.name)),
9853
11018
  candidates: rows.slice(offset, offset + limit)
9854
11019
  };
9855
11020
  }
9856
- var EXITS_MAX, EXIT_SITES_MAX, START_CANDIDATES_MAX, cmp5, pathOf5, sourceOf3, exitKey, byPosition2;
11021
+ var EXITS_MAX, EXIT_SITES_MAX, START_CANDIDATES_MAX, cmp7, pathOf5, sourceOf3, exitKey, byPosition2;
9857
11022
  var init_exits = __esm({
9858
11023
  "packages/query-imports/src/exits.ts"() {
9859
11024
  "use strict";
@@ -9862,11 +11027,11 @@ var init_exits = __esm({
9862
11027
  EXITS_MAX = 500;
9863
11028
  EXIT_SITES_MAX = 100;
9864
11029
  START_CANDIDATES_MAX = 500;
9865
- cmp5 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11030
+ cmp7 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9866
11031
  pathOf5 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
9867
11032
  sourceOf3 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
9868
11033
  exitKey = (x) => `${x.package ?? "runtime"}|${x.name ?? ""}|${x.member ?? ""}|${x.instance ? 1 : 0}`;
9869
- byPosition2 = (a, b) => cmp5(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
11034
+ byPosition2 = (a, b) => cmp7(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset;
9870
11035
  }
9871
11036
  });
9872
11037
 
@@ -10338,9 +11503,9 @@ function tallies(engine, s) {
10338
11503
  for (const g of reader.facts("Group")) for (const f of g.files) if (!groupOf.has(f)) groupOf.set(f, g);
10339
11504
  const own2 = ownCodeTest(engine.pendingLibraries(s.meta.project, s.run));
10340
11505
  for (const t of out.values()) {
10341
- t.row.ids.sort(cmp6);
10342
- t.row.versions.sort(cmp6);
10343
- t.row.sources.sort(cmp6);
11506
+ t.row.ids.sort(cmp8);
11507
+ t.row.versions.sort(cmp8);
11508
+ t.row.sources.sort(cmp8);
10344
11509
  t.row.files = t.importers.size;
10345
11510
  const groups2 = /* @__PURE__ */ new Set();
10346
11511
  for (const id of t.importers.keys()) {
@@ -10380,8 +11545,8 @@ function listLibraries(engine, args, cwd) {
10380
11545
  for (const d of src.defaultExcluded ?? [])
10381
11546
  if (d.origin === "library") leftOut.push({ source: src.sourceId, path: d.path, files: d.files });
10382
11547
  }
10383
- copied.sort((a, b) => cmp6(a.source, b.source) || cmp6(a.path, b.path));
10384
- leftOut.sort((a, b) => cmp6(a.source, b.source) || cmp6(a.path, b.path));
11548
+ copied.sort((a, b) => cmp8(a.source, b.source) || cmp8(a.path, b.path));
11549
+ leftOut.sort((a, b) => cmp8(a.source, b.source) || cmp8(a.path, b.path));
10385
11550
  return {
10386
11551
  ...s.meta,
10387
11552
  stage2: s.stage2,
@@ -10422,11 +11587,11 @@ function getLibrary(engine, args, cwd) {
10422
11587
  path: pathOf6(id),
10423
11588
  source: sourceOf4(id),
10424
11589
  group: g ? { id: g.id, name: g.name } : null,
10425
- forms: [...forms].sort(cmp6),
11590
+ forms: [...forms].sort(cmp8),
10426
11591
  own: f?.type === "File" ? own2(f) : false
10427
11592
  };
10428
- }).sort((a, b) => Number(b.own) - Number(a.own) || cmp6(a.source, b.source) || cmp6(a.path, b.path));
10429
- const members2 = [...t.exits.entries()].sort(([ka, a], [kb, b]) => b.calls + b.references - (a.calls + a.references) || cmp6(ka, kb)).map(([, m]) => ({
11593
+ }).sort((a, b) => Number(b.own) - Number(a.own) || cmp8(a.source, b.source) || cmp8(a.path, b.path));
11594
+ const members2 = [...t.exits.entries()].sort(([ka, a], [kb, b]) => b.calls + b.references - (a.calls + a.references) || cmp8(ka, kb)).map(([, m]) => ({
10430
11595
  name: m.exit.name,
10431
11596
  member: m.exit.member,
10432
11597
  instance: !!m.exit.instance,
@@ -10443,7 +11608,7 @@ function getLibrary(engine, args, cwd) {
10443
11608
  membersTruncated: members2.length > LIBRARY_MEMBERS_MAX
10444
11609
  };
10445
11610
  }
10446
- var LIBRARIES_MAX, LIBRARY_IMPORTERS_MAX, LIBRARY_MEMBERS_MAX, STAGE22, cmp6, sourceOf4, pathOf6, keyOf, byUse;
11611
+ var LIBRARIES_MAX, LIBRARY_IMPORTERS_MAX, LIBRARY_MEMBERS_MAX, STAGE22, cmp8, sourceOf4, pathOf6, keyOf, byUse;
10447
11612
  var init_libraries2 = __esm({
10448
11613
  "packages/query-imports/src/libraries.ts"() {
10449
11614
  "use strict";
@@ -10453,11 +11618,11 @@ var init_libraries2 = __esm({
10453
11618
  LIBRARY_IMPORTERS_MAX = 1e3;
10454
11619
  LIBRARY_MEMBERS_MAX = 500;
10455
11620
  STAGE22 = "stage2";
10456
- cmp6 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11621
+ cmp8 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10457
11622
  sourceOf4 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
10458
11623
  pathOf6 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
10459
11624
  keyOf = (p) => `${p.ecosystem}:${p.name}`;
10460
- byUse = (a, b) => b.files - a.files || b.calls + b.references - (a.calls + a.references) || cmp6(a.name, b.name) || cmp6(a.ecosystem, b.ecosystem);
11625
+ byUse = (a, b) => b.files - a.files || b.calls + b.references - (a.calls + a.references) || cmp8(a.name, b.name) || cmp8(a.ecosystem, b.ecosystem);
10461
11626
  }
10462
11627
  });
10463
11628
 
@@ -10486,13 +11651,15 @@ function crossFileCalls(engine, args, cwd) {
10486
11651
  const offset = args.offset ?? 0;
10487
11652
  if (!Number.isInteger(offset) || offset < 0)
10488
11653
  throw new VeoError("invalid-arguments", "offset must be 0 or more", { fields: ["offset"] });
11654
+ const grouping = groupingOf(args.grouping);
10489
11655
  const { meta: meta3, reader } = engine.readAllStages(args, cwd);
10490
11656
  const end2 = ender(engine, meta3.project, reader);
10491
11657
  let edges;
10492
11658
  let pair;
10493
11659
  if (args.from !== void 0) {
10494
11660
  const list = (v) => Array.isArray(v) ? v : [v];
10495
- const p = pairOf(reader, end2, list(args.from), list(args.to));
11661
+ const groups2 = groupsView(engine, meta3, reader, args.run ?? meta3.committedRun, grouping).groups;
11662
+ const p = pairOf(reader, end2, list(args.from), list(args.to), groups2);
10496
11663
  edges = p.edges;
10497
11664
  pair = p.pair;
10498
11665
  } else if (args.function !== void 0) {
@@ -10519,7 +11686,7 @@ function crossFileCalls(engine, args, cwd) {
10519
11686
  })();
10520
11687
  }
10521
11688
  edges.sort(
10522
- (a, b) => cmp7(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp7(a.id, b.id)
11689
+ (a, b) => cmp9(a.evidence.file, b.evidence.file) || a.evidence.span.start.offset - b.evidence.span.start.offset || cmp9(a.id, b.id)
10523
11690
  );
10524
11691
  const shown = edges.slice(offset, offset + limit);
10525
11692
  const provenance = reader.provenance(shown.map((e) => e.id));
@@ -10538,7 +11705,8 @@ function crossFileCalls(engine, args, cwd) {
10538
11705
  ...pair ? { pair } : {}
10539
11706
  };
10540
11707
  }
10541
- function pairOf(reader, end2, from, to) {
11708
+ function pairOf(reader, end2, from, to, groups2) {
11709
+ const groupById = new Map(groups2.map((g) => [g.id, g]));
10542
11710
  const side = (ids2, field) => {
10543
11711
  const files = /* @__PURE__ */ new Set();
10544
11712
  const kinds = /* @__PURE__ */ new Set();
@@ -10546,18 +11714,18 @@ function pairOf(reader, end2, from, to) {
10546
11714
  for (const id of ids2) {
10547
11715
  if (id.startsWith("folder|")) {
10548
11716
  const rest = id.slice("folder|".length);
10549
- let g;
11717
+ let g2;
10550
11718
  let path = "";
10551
11719
  for (let at = rest.indexOf("|"); at !== -1; at = rest.indexOf("|", at + 1)) {
10552
- const f2 = reader.fact(rest.slice(0, at));
10553
- if (f2?.type === "Group") {
10554
- g = f2;
11720
+ const f2 = groupById.get(rest.slice(0, at));
11721
+ if (f2) {
11722
+ g2 = f2;
10555
11723
  path = rest.slice(at + 1);
10556
11724
  }
10557
11725
  }
10558
- if (!g || !path) throw bad(field);
11726
+ if (!g2 || !path) throw bad(field);
10559
11727
  let found = 0;
10560
- for (const fileId of g.files) {
11728
+ for (const fileId of g2.files) {
10561
11729
  const f2 = reader.fact(fileId);
10562
11730
  if (f2?.type === "File" && f2.path.startsWith(`${path}/`)) {
10563
11731
  files.add(fileId);
@@ -10574,21 +11742,22 @@ function pairOf(reader, end2, from, to) {
10574
11742
  const at = rest.indexOf("|");
10575
11743
  const source = at < 0 ? rest : rest.slice(0, at);
10576
11744
  const path = at < 0 ? "" : rest.slice(at + 1);
10577
- const inside3 = (root) => path === "" || root === path || root.startsWith(`${path}/`);
10578
- const members2 = allGroups().filter(
10579
- (g) => g.source !== source ? false : id.startsWith("area|") ? inside3(g.root) : g.kind === "cluster" && g.files.length === 1 && g.root === path
11745
+ const inside4 = (root) => path === "" || root === path || root.startsWith(`${path}/`);
11746
+ const members2 = groups2.filter(
11747
+ (g2) => g2.source !== source ? false : id.startsWith("area|") ? inside4(g2.root) : (g2.kind === "cluster" || g2.kind === "module") && g2.files.length === 1 && g2.root === path
10580
11748
  );
10581
11749
  if (members2.length === 0) throw bad(field);
10582
- for (const g of members2) for (const f2 of g.files) files.add(f2);
11750
+ for (const g2 of members2) for (const f2 of g2.files) files.add(f2);
10583
11751
  kinds.add("group");
10584
11752
  names.push(id.startsWith("area|") ? `${path || source}/` : `${path || "(top)"}/ single files`);
10585
11753
  continue;
10586
11754
  }
10587
- const f = reader.fact(id);
10588
- if (f?.type === "Group") {
10589
- for (const x of f.files) files.add(x);
11755
+ const g = groupById.get(id);
11756
+ const f = g ? void 0 : reader.fact(id);
11757
+ if (g) {
11758
+ for (const x of g.files) files.add(x);
10590
11759
  kinds.add("group");
10591
- names.push(f.name);
11760
+ names.push(g.name);
10592
11761
  } else if (f?.type === "File") {
10593
11762
  files.add(f.id);
10594
11763
  kinds.add("file");
@@ -10599,8 +11768,6 @@ function pairOf(reader, end2, from, to) {
10599
11768
  const name = names.length <= 3 ? names.join(", ") : `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
10600
11769
  return { files, kinds, name, id: ids2.length === 1 ? ids2[0] : ids2.join(",") };
10601
11770
  };
10602
- let groupsRead;
10603
- const allGroups = () => groupsRead ??= reader.facts("Group");
10604
11771
  const bad = (field) => new VeoError("invalid-arguments", `${field} must be groups, files or a group's folders`, {
10605
11772
  fields: [field]
10606
11773
  });
@@ -10616,10 +11783,10 @@ function pairOf(reader, end2, from, to) {
10616
11783
  const bs = b.files;
10617
11784
  const edges = as.flatMap((f) => reader.facts("CALLS_CROSS_FILE", f)).filter((e) => bs.has(fileOfFn(e.to)));
10618
11785
  const references = as.flatMap((f) => reader.facts("REFERENCES", f)).filter((r) => !r.exit && bs.has(fileOfFn(r.to))).sort(
10619
- (x, y) => cmp7(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
11786
+ (x, y) => cmp9(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
10620
11787
  );
10621
11788
  const imports = as.flatMap((f) => reader.facts("IMPORTS", f)).filter((e) => bs.has(e.to)).sort(
10622
- (x, y) => cmp7(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
11789
+ (x, y) => cmp9(x.evidence.file, y.evidence.file) || x.evidence.span.start.offset - y.evidence.span.start.offset
10623
11790
  );
10624
11791
  return {
10625
11792
  edges,
@@ -10652,7 +11819,7 @@ function pairOf(reader, end2, from, to) {
10652
11819
  }
10653
11820
  };
10654
11821
  }
10655
- function cmp7(a, b) {
11822
+ function cmp9(a, b) {
10656
11823
  return a < b ? -1 : a > b ? 1 : 0;
10657
11824
  }
10658
11825
  function ender(engine, project2, reader) {
@@ -10714,10 +11881,12 @@ var init_src7 = __esm({
10714
11881
  init_src();
10715
11882
  init_nesting();
10716
11883
  init_reads();
11884
+ init_reads();
10717
11885
  init_explain();
10718
11886
  init_reach();
10719
11887
  init_exits();
10720
11888
  init_check();
11889
+ init_connected();
10721
11890
  init_totals();
10722
11891
  init_file_summary();
10723
11892
  init_impact();
@@ -11489,7 +12658,7 @@ var require_cmp = __commonJS({
11489
12658
  var gte = require_gte();
11490
12659
  var lt = require_lt();
11491
12660
  var lte = require_lte();
11492
- var cmp9 = (a, op, b, loose) => {
12661
+ var cmp11 = (a, op, b, loose) => {
11493
12662
  switch (op) {
11494
12663
  case "===":
11495
12664
  if (typeof a === "object") {
@@ -11525,7 +12694,7 @@ var require_cmp = __commonJS({
11525
12694
  throw new TypeError(`Invalid operator: ${op}`);
11526
12695
  }
11527
12696
  };
11528
- module.exports = cmp9;
12697
+ module.exports = cmp11;
11529
12698
  }
11530
12699
  });
11531
12700
 
@@ -12100,7 +13269,7 @@ var require_comparator = __commonJS({
12100
13269
  return false;
12101
13270
  }
12102
13271
  }
12103
- return cmp9(version3, this.operator, this.semver, this.options);
13272
+ return cmp11(version3, this.operator, this.semver, this.options);
12104
13273
  }
12105
13274
  intersects(comp, options2) {
12106
13275
  if (!(comp instanceof _Comparator)) {
@@ -12133,10 +13302,10 @@ var require_comparator = __commonJS({
12133
13302
  if (this.semver.version === comp.semver.version && this.operator.includes("=") && comp.operator.includes("=")) {
12134
13303
  return true;
12135
13304
  }
12136
- if (cmp9(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
13305
+ if (cmp11(this.semver, "<", comp.semver, options2) && this.operator.startsWith(">") && comp.operator.startsWith("<")) {
12137
13306
  return true;
12138
13307
  }
12139
- if (cmp9(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
13308
+ if (cmp11(this.semver, ">", comp.semver, options2) && this.operator.startsWith("<") && comp.operator.startsWith(">")) {
12140
13309
  return true;
12141
13310
  }
12142
13311
  return false;
@@ -12145,7 +13314,7 @@ var require_comparator = __commonJS({
12145
13314
  module.exports = Comparator;
12146
13315
  var parseOptions = require_parse_options();
12147
13316
  var { safeRe: re, t } = require_re();
12148
- var cmp9 = require_cmp();
13317
+ var cmp11 = require_cmp();
12149
13318
  var debug = require_debug();
12150
13319
  var SemVer = require_semver();
12151
13320
  var Range = require_range();
@@ -12656,7 +13825,7 @@ var require_semver2 = __commonJS({
12656
13825
  var neq = require_neq();
12657
13826
  var gte = require_gte();
12658
13827
  var lte = require_lte();
12659
- var cmp9 = require_cmp();
13828
+ var cmp11 = require_cmp();
12660
13829
  var coerce = require_coerce();
12661
13830
  var truncate = require_truncate();
12662
13831
  var Comparator = require_comparator();
@@ -12695,7 +13864,7 @@ var require_semver2 = __commonJS({
12695
13864
  neq,
12696
13865
  gte,
12697
13866
  lte,
12698
- cmp: cmp9,
13867
+ cmp: cmp11,
12699
13868
  coerce,
12700
13869
  truncate,
12701
13870
  Comparator,
@@ -12725,7 +13894,7 @@ var require_semver2 = __commonJS({
12725
13894
  });
12726
13895
 
12727
13896
  // packages/stage2/src/gitignore.ts
12728
- import { posix as posix2 } from "node:path";
13897
+ import { posix as posix4 } from "node:path";
12729
13898
  function toRegExp(pattern, anchored) {
12730
13899
  let re = "";
12731
13900
  for (let i = 0; i < pattern.length; i++) {
@@ -12759,7 +13928,7 @@ function gitignoreMatcher(files) {
12759
13928
  const depth = (p) => p.split("/").length;
12760
13929
  const sorted = [...files].sort((a, b) => depth(a.path) - depth(b.path) || (a.path < b.path ? -1 : 1));
12761
13930
  for (const f of sorted) {
12762
- const dir = posix2.dirname(f.path) === "." ? "" : posix2.dirname(f.path);
13931
+ const dir = posix4.dirname(f.path) === "." ? "" : posix4.dirname(f.path);
12763
13932
  for (const raw of f.content.split(/\r?\n/)) {
12764
13933
  let line = raw.replace(/(?<!\\)\s+$/, "");
12765
13934
  if (!line || line.startsWith("#")) continue;
@@ -12816,7 +13985,7 @@ var init_gitignore = __esm({
12816
13985
 
12817
13986
  // packages/stage2/src/imports.ts
12818
13987
  import { builtinModules } from "node:module";
12819
- import { isAbsolute as isAbsolute2, posix as posix3, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
13988
+ import { isAbsolute as isAbsolute2, posix as posix5, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
12820
13989
  function packageName(specifier) {
12821
13990
  const parts = specifier.split("/");
12822
13991
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
@@ -12900,7 +14069,7 @@ function declared(pkg, name) {
12900
14069
  }
12901
14070
  function lockedVersions(path, text) {
12902
14071
  const out = /* @__PURE__ */ new Map();
12903
- const base2 = posix3.basename(path);
14072
+ const base2 = posix5.basename(path);
12904
14073
  if (base2 === "package-lock.json") {
12905
14074
  const lock = parseJson(text);
12906
14075
  for (const [key, v] of Object.entries(lock?.packages ?? {})) {
@@ -13021,8 +14190,8 @@ function resolveImports2(plans, files) {
13021
14190
  const links = /* @__PURE__ */ new Map();
13022
14191
  for (const tree of trees) {
13023
14192
  for (const [path, json2] of tree.manifests) {
13024
- if (posix3.basename(path) !== "package.json") continue;
13025
- const dir = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
14193
+ if (posix5.basename(path) !== "package.json") continue;
14194
+ const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
13026
14195
  const name = json2?.name;
13027
14196
  if (typeof name === "string" && name && !links.has(name) && (dir === "" || sourceMembers.get(tree)(dir)))
13028
14197
  links.set(name, { tree, dir });
@@ -13082,10 +14251,10 @@ function resolveImports2(plans, files) {
13082
14251
  const escapes = /* @__PURE__ */ new Map();
13083
14252
  for (const s of toResolve) {
13084
14253
  if (!isRelative(s.specifier)) continue;
13085
- const inside3 = posix3.normalize(posix3.join(posix3.dirname(s.path), s.specifier));
13086
- if (inside3 !== ".." && !inside3.startsWith("../")) continue;
14254
+ const inside4 = posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
14255
+ if (inside4 !== ".." && !inside4.startsWith("../")) continue;
13087
14256
  const plan = treeOf.get(s.source).plan;
13088
- const abs = resolvePath(plan.root, ...posix3.dirname(s.path).split("/"), ...s.specifier.split("/"));
14257
+ const abs = resolvePath(plan.root, ...posix5.dirname(s.path).split("/"), ...s.specifier.split("/"));
13089
14258
  const within = (root) => {
13090
14259
  const r = relativePath(root, abs);
13091
14260
  return r === "" || !(r === ".." || r.startsWith(`..${sep7}`) || isAbsolute2(r)) ? r.split(sep7).join("/") : null;
@@ -13133,7 +14302,7 @@ function resolveImports2(plans, files) {
13133
14302
  };
13134
14303
  const versions = /* @__PURE__ */ new Map();
13135
14304
  const lockfileVersion = (tree, from, name) => {
13136
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14305
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13137
14306
  for (const lock of ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"]) {
13138
14307
  const path = dir === "." ? lock : `${dir}/${lock}`;
13139
14308
  const m = tree.plan.manifests.find((x) => x.path === path);
@@ -13147,7 +14316,7 @@ function resolveImports2(plans, files) {
13147
14316
  }
13148
14317
  };
13149
14318
  const nearest = (tree, from, base2) => {
13150
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14319
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13151
14320
  const path = dir === "." ? base2 : `${dir}/${base2}`;
13152
14321
  if (tree.plan.manifests.some((m) => m.path === path)) return path;
13153
14322
  if (dir === "." || dir === "") return null;
@@ -13155,7 +14324,7 @@ function resolveImports2(plans, files) {
13155
14324
  };
13156
14325
  const packageJsons = (tree, from) => {
13157
14326
  const out2 = [];
13158
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14327
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13159
14328
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
13160
14329
  const json2 = tree.manifests.get(path);
13161
14330
  if (json2 && typeof json2 === "object") out2.push(json2);
@@ -13193,7 +14362,7 @@ function resolveImports2(plans, files) {
13193
14362
  if (variants.some((v) => exclude.some((re) => re.test(v))) || variants.some((v) => !filter.matches(v) && include.length === 0) || filter.excludesDir(path))
13194
14363
  return "excluded-by-rule";
13195
14364
  if (include.length > 0) {
13196
- const candidates = [...posix3.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
14365
+ const candidates = [...posix5.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
13197
14366
  if (candidates.every((v) => !include.some((re) => re.test(v)))) return "excluded-by-rule";
13198
14367
  }
13199
14368
  return null;
@@ -13227,7 +14396,7 @@ function resolveImports2(plans, files) {
13227
14396
  );
13228
14397
  const probe = (t, base2) => {
13229
14398
  const set2 = pathSets.get(t);
13230
- const clean = posix3.normalize(base2).replace(/^\.\/?/, "");
14399
+ const clean = posix5.normalize(base2).replace(/^\.\/?/, "");
13231
14400
  const js = /\.(m|c)?jsx?$/.exec(clean);
13232
14401
  const ts = js ? [".ts", ".tsx", ".mts", ".cts"].map(
13233
14402
  (e) => clean.slice(0, -js[0].length) + (js[0] === ".jsx" ? ".tsx" : js[1] ? `.${js[1]}ts` : e)
@@ -13242,7 +14411,7 @@ function resolveImports2(plans, files) {
13242
14411
  return null;
13243
14412
  };
13244
14413
  const nearestPackage = (t, from) => {
13245
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14414
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13246
14415
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
13247
14416
  const json2 = t.manifests.get(path);
13248
14417
  if (json2 && typeof json2 === "object")
@@ -13274,7 +14443,7 @@ function resolveImports2(plans, files) {
13274
14443
  };
13275
14444
  const siteDir = (t, from) => {
13276
14445
  const set2 = pathSets.get(t);
13277
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14446
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13278
14447
  const d = dir === "." ? "" : dir;
13279
14448
  if (["js", "ts", "mjs", "cjs", "mts"].some((e) => set2.has(join14(d, `docusaurus.config.${e}`)))) return d;
13280
14449
  if (d === "") return null;
@@ -13282,18 +14451,18 @@ function resolveImports2(plans, files) {
13282
14451
  };
13283
14452
  const bundlerCache = /* @__PURE__ */ new Map();
13284
14453
  const bundlerAliases = (t, from) => {
13285
- const key = `${t.plan.sourceId}\0${posix3.dirname(from)}`;
14454
+ const key = `${t.plan.sourceId}\0${posix5.dirname(from)}`;
13286
14455
  const cached2 = bundlerCache.get(key);
13287
14456
  if (cached2) return cached2;
13288
14457
  const files2 = fileContent.get(t);
13289
14458
  const out2 = [];
13290
14459
  for (const kind of ["vite", "webpack"]) {
13291
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14460
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13292
14461
  const d = dir === "." ? "" : dir;
13293
14462
  const config2 = ["ts", "js", "mjs", "mts", "cjs", "cts"].map((e) => join14(d, `${kind}.config.${e}`)).find((p) => files2.get(p) !== void 0);
13294
14463
  if (config2) {
13295
14464
  const aliases = parseAliases(files2.get(config2)).map(
13296
- ([k, v]) => [k, posix3.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
14465
+ ([k, v]) => [k, posix5.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
13297
14466
  );
13298
14467
  if (aliases.length)
13299
14468
  out2.push({ config: config2, aliases: aliases.sort((a, b) => b[0].length - a[0].length) });
@@ -13398,7 +14567,7 @@ function resolveImports2(plans, files) {
13398
14567
  for (const { config: config2, aliases } of bundlerAliases(t, from)) {
13399
14568
  for (const [key, value] of aliases) {
13400
14569
  if (specifier !== key && !specifier.startsWith(`${key}/`)) continue;
13401
- const target2 = posix3.normalize(join14(value, specifier.slice(key.length + 1)));
14570
+ const target2 = posix5.normalize(join14(value, specifier.slice(key.length + 1)));
13402
14571
  if (target2 === ".." || target2.startsWith("../")) {
13403
14572
  const abs = resolvePath(t.plan.root, ...target2.split("/"));
13404
14573
  let holder = null;
@@ -13656,8 +14825,8 @@ function resolveImports2(plans, files) {
13656
14825
  for (const u of trees) {
13657
14826
  if (u !== t && (ws === null || workspaceOf.get(u) !== ws)) continue;
13658
14827
  for (const [path, json2] of u.manifests) {
13659
- if (posix3.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
13660
- const dir = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
14828
+ if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
14829
+ const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
13661
14830
  const member = dir === "" && u === t ? true : sourceMembers.get(u)(dir) || dir === "" && coversAbove(u.plan, "");
13662
14831
  if (member && declared(json2, name) !== void 0)
13663
14832
  out2.push(u === t ? path : `${u.plan.sourceId}:${path}`);
@@ -13698,14 +14867,14 @@ function resolveImports2(plans, files) {
13698
14867
  return { pick: "npm", detail: `${name} is declared as ${spec}, not as a workspace package` };
13699
14868
  };
13700
14869
  const baseUrlMiss = (t, from, specifier) => {
13701
- for (let dir = posix3.dirname(from); ; dir = posix3.dirname(dir)) {
14870
+ for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
13702
14871
  const d = dir === "." ? "" : dir;
13703
14872
  for (const c of ["tsconfig.json", "jsconfig.json"]) {
13704
14873
  const json2 = t.manifests.get(join14(d, c));
13705
14874
  if (!json2) continue;
13706
14875
  const baseUrl = json2.compilerOptions?.baseUrl;
13707
14876
  if (typeof baseUrl !== "string") return null;
13708
- const base2 = posix3.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
14877
+ const base2 = posix5.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
13709
14878
  const folder = `${join14(base2, specifier.split("/")[0])}/`;
13710
14879
  for (const p of pathSets.get(t)) if (p.startsWith(folder)) return join14(d, c);
13711
14880
  return null;
@@ -13717,7 +14886,7 @@ function resolveImports2(plans, files) {
13717
14886
  for (const s of all2) {
13718
14887
  const tree = treeOf.get(s.source);
13719
14888
  const plan = tree.plan;
13720
- const rel = (p) => posix3.relative(posix3.dirname(s.path), p) || ".";
14889
+ const rel = (p) => posix5.relative(posix5.dirname(s.path), p) || ".";
13721
14890
  let target2;
13722
14891
  if (isUrl(s.specifier)) {
13723
14892
  const { name, version: version3 } = urlPackage(s.specifier);
@@ -13738,7 +14907,7 @@ function resolveImports2(plans, files) {
13738
14907
  };
13739
14908
  } else {
13740
14909
  const answer = answers.get(s);
13741
- const ownExt = posix3.extname(s.specifier.replace(/\?[^/]*$/, ""));
14910
+ const ownExt = posix5.extname(s.specifier.replace(/\?[^/]*$/, ""));
13742
14911
  const shown = OWN_EXTENSIONS.has(ownExt) ? answer.tried.filter(
13743
14912
  (t) => ![...PROBE_EXTENSIONS, ".d.ts", ".node"].some((e) => t.endsWith(`${ownExt}${e}`))
13744
14913
  ) : answer.tried;
@@ -13889,7 +15058,7 @@ function resolveImports2(plans, files) {
13889
15058
  };
13890
15059
  } else if (isRelative(s.specifier) || s.specifier.startsWith("/")) {
13891
15060
  const holder = escape2?.holder ?? tree;
13892
- const candidate = escape2?.holder ? escape2.rel : posix3.normalize(posix3.join(posix3.dirname(s.path), s.specifier));
15061
+ const candidate = escape2?.holder ? escape2.rel : posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
13893
15062
  const ignored = holder.plan.unpinned.some(
13894
15063
  (u) => u.reason === "gitignored" && (u.path.endsWith("/") ? `${candidate}/`.startsWith(u.path) : [
13895
15064
  candidate,
@@ -14113,7 +15282,7 @@ function resolveImports2(plans, files) {
14113
15282
  }
14114
15283
  if (target2.kind === "unresolved")
14115
15284
  for (const n2 of notes) {
14116
- const base2 = posix3.basename(n2.path);
15285
+ const base2 = posix5.basename(n2.path);
14117
15286
  if (n2.source !== s.source || !["package.json", "tsconfig.json", "jsconfig.json"].includes(base2))
14118
15287
  continue;
14119
15288
  if (nearest(tree, s.path, base2) === n2.path) target2.steps.push(n2.step);
@@ -14151,14 +15320,14 @@ function parseAliases(source) {
14151
15320
  const tpl = /^`\$\{([\s\S]+)\}([^`$]*)`$/.exec(e);
14152
15321
  if (tpl) {
14153
15322
  const base2 = path(tpl[1]);
14154
- return base2 === null ? null : posix3.join(base2, tpl[2] || ".");
15323
+ return base2 === null ? null : posix5.join(base2, tpl[2] || ".");
14155
15324
  }
14156
15325
  const lit = /^(['"`])([^'"`]*)\1$/.exec(e);
14157
15326
  if (lit)
14158
15327
  return lit[2].includes("${") || !/^(\.\.?\/|\/|\.$)/.test(lit[2]) ? null : lit[2].replace(/^\//, "");
14159
15328
  const dirname10 = /^(?:path\.)?(?:resolve|join)\(\s*__dirname\s*((?:,\s*(['"`])[^'"`]*\2\s*)*)\)$/.exec(e);
14160
15329
  if (dirname10)
14161
- return posix3.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
15330
+ return posix5.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
14162
15331
  const url2 = /^(?:fileURLToPath\(\s*)?new URL\(\s*(['"`])([^'"`]*)\1\s*,\s*import\.meta\.url\s*\)(?:\s*\)|\.pathname)?$/.exec(
14163
15332
  e
14164
15333
  );
@@ -14259,13 +15428,13 @@ function coversAbove(plan, dir) {
14259
15428
  );
14260
15429
  aboveCache.set(ws, members2);
14261
15430
  }
14262
- return members2(posix3.join(ws.prefix, dir).replace(/\/$/, ""));
15431
+ return members2(posix5.join(ws.prefix, dir).replace(/\/$/, ""));
14263
15432
  }
14264
15433
  function workspaceMembers(raw, parsed) {
14265
15434
  const include = [];
14266
15435
  const exclude = [];
14267
15436
  const anchored = (base2, glob) => {
14268
- const p = posix3.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
15437
+ const p = posix5.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
14269
15438
  let re = "";
14270
15439
  for (let i = 0; i < p.length; i++) {
14271
15440
  const c = p[i];
@@ -14288,14 +15457,14 @@ function workspaceMembers(raw, parsed) {
14288
15457
  (g.startsWith("!") ? exclude : include).push(anchored(base2, g.replace(/^!/, "")));
14289
15458
  };
14290
15459
  for (const [path, json2] of parsed) {
14291
- if (posix3.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
14292
- const base2 = posix3.dirname(path) === "." ? "" : posix3.dirname(path);
15460
+ if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
15461
+ const base2 = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
14293
15462
  const ws = json2.workspaces;
14294
15463
  add2(base2, Array.isArray(ws) ? ws : ws?.packages);
14295
15464
  }
14296
15465
  for (const m of raw) {
14297
- if (posix3.basename(m.path) !== "pnpm-workspace.yaml") continue;
14298
- add2(posix3.dirname(m.path) === "." ? "" : posix3.dirname(m.path), pnpmWorkspacePackages(m.content));
15466
+ if (posix5.basename(m.path) !== "pnpm-workspace.yaml") continue;
15467
+ add2(posix5.dirname(m.path) === "." ? "" : posix5.dirname(m.path), pnpmWorkspacePackages(m.content));
14299
15468
  }
14300
15469
  return (dir) => include.some((re) => re.test(dir)) && !exclude.some((re) => re.test(dir));
14301
15470
  }
@@ -14490,10 +15659,10 @@ function typeGraph(input2) {
14490
15659
  return via?.target.kind === "file" ? exportedAt(via.target.file.id, e.sourceName ?? name, depth + 1) : null;
14491
15660
  }
14492
15661
  if (e.kind === "default" && !e.localName && !e.sourceName) {
14493
- const inside3 = result2.types.find(
15662
+ const inside4 = result2.types.find(
14494
15663
  (t) => t.span.start.offset >= e.span.start.offset && t.span.end.offset <= e.span.end.offset
14495
15664
  );
14496
- return inside3 ? { file: file2, name: inside3.name } : null;
15665
+ return inside4 ? { file: file2, name: inside4.name } : null;
14497
15666
  }
14498
15667
  if (e.kind === "named" || e.kind === "default") {
14499
15668
  const local = e.localName ?? e.sourceName ?? name;
@@ -17592,7 +18761,7 @@ var init_closed = __esm({
17592
18761
  });
17593
18762
 
17594
18763
  // packages/stage2/src/components.ts
17595
- import { posix as posix4 } from "node:path";
18764
+ import { posix as posix6 } from "node:path";
17596
18765
  function linkComponents(input2) {
17597
18766
  const fn = new Map(input2.functions.map((f) => [`${f.file}\0${f.qualifiedName}`, f.id]));
17598
18767
  const statementsByFile = /* @__PURE__ */ new Map();
@@ -17669,7 +18838,7 @@ function linkComponents(input2) {
17669
18838
  if (inline) return inline;
17670
18839
  const declared2 = input2.templates.find((t) => t.file === fileId && t.component === cls && t.specifier);
17671
18840
  if (!declared2) return null;
17672
- const target2 = `${sourceOf5(fileId)}:${posix4.normalize(posix4.join(posix4.dirname(pathOf7(fileId)), declared2.specifier))}`;
18841
+ const target2 = `${sourceOf5(fileId)}:${posix6.normalize(posix6.join(posix6.dirname(pathOf7(fileId)), declared2.specifier))}`;
17673
18842
  return fn.get(`${target2}\0<template>`) ?? null;
17674
18843
  };
17675
18844
  const usingClasses = (site) => {
@@ -17680,7 +18849,7 @@ function linkComponents(input2) {
17680
18849
  return [{ file: site.file, cls: caller.slice(0, -".<template>".length) }];
17681
18850
  const path = pathOf7(site.file);
17682
18851
  return input2.templates.filter(
17683
- (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix4.normalize(posix4.join(posix4.dirname(pathOf7(t.file)), t.specifier)) === path
18852
+ (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix6.normalize(posix6.join(posix6.dirname(pathOf7(t.file)), t.specifier)) === path
17684
18853
  ).map((t) => ({ file: t.file, cls: t.component }));
17685
18854
  };
17686
18855
  const modules = fileIds.flatMap(
@@ -17952,7 +19121,7 @@ var init_components = __esm({
17952
19121
  });
17953
19122
 
17954
19123
  // packages/stage2/src/exits.ts
17955
- import { posix as posix5 } from "node:path";
19124
+ import { posix as posix7 } from "node:path";
17956
19125
  function renderPath(segs) {
17957
19126
  let out = "";
17958
19127
  for (const s of segs) {
@@ -18745,8 +19914,8 @@ function startCandidates(input2, s, exitAt, nodeAt) {
18745
19914
  for (const plan of input2.plans) {
18746
19915
  const parsed = new Map(plan.manifests.map((m) => [m.path, parseManifest(m.content)]));
18747
19916
  for (const m of plan.manifests) {
18748
- if (posix5.basename(m.path) !== "package.json") continue;
18749
- const dir = posix5.dirname(m.path) === "." ? "" : posix5.dirname(m.path);
19917
+ if (posix7.basename(m.path) !== "package.json") continue;
19918
+ const dir = posix7.dirname(m.path) === "." ? "" : posix7.dirname(m.path);
18750
19919
  const json2 = parsed.get(m.path);
18751
19920
  if (!json2 || typeof json2 !== "object") continue;
18752
19921
  const pkg = typeof json2.name === "string" && json2.name ? json2.name : dir || plan.sourceId;
@@ -18879,7 +20048,7 @@ function scriptFiles(command, depth = 0) {
18879
20048
  const tokens = [...command.matchAll(/"([^"]*)"|'([^']*)'|(&&|\|\||[;|&])|([^\s"';|&]+)/g)];
18880
20049
  let part = [];
18881
20050
  const end2 = () => {
18882
- const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix5.basename(t.text)));
20051
+ const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix7.basename(t.text)));
18883
20052
  if (at !== -1)
18884
20053
  for (let i = at + 1; i < part.length; i++) {
18885
20054
  const t = part[i].text;
@@ -18913,7 +20082,7 @@ function stringLeaves(v) {
18913
20082
  return [];
18914
20083
  }
18915
20084
  function sourceFile(files, source, dir, p, json2) {
18916
- const rel = posix5.normalize(posix5.join(dir, p));
20085
+ const rel = posix7.normalize(posix7.join(dir, p));
18917
20086
  if (rel.startsWith("..")) return void 0;
18918
20087
  const exts = [
18919
20088
  "",
@@ -18939,10 +20108,10 @@ function sourceFile(files, source, dir, p, json2) {
18939
20108
  const hit = probe(rel) ?? probe(noExt);
18940
20109
  if (hit) return hit;
18941
20110
  const built = /^(dist|build|lib|out)\//;
18942
- const inside3 = dir ? noExt.slice(dir.length + 1) : noExt;
18943
- if (!built.test(inside3)) return void 0;
18944
- const srcRel = posix5.join(dir, inside3.replace(built, "src/"));
18945
- return probe(srcRel) ?? (typeof json2.source === "string" ? probe(posix5.join(dir, json2.source).replace(/\.(m?[jt]sx?)$/, "")) : void 0) ?? probe(posix5.join(dir, "src/index"));
20111
+ const inside4 = dir ? noExt.slice(dir.length + 1) : noExt;
20112
+ if (!built.test(inside4)) return void 0;
20113
+ const srcRel = posix7.join(dir, inside4.replace(built, "src/"));
20114
+ return probe(srcRel) ?? (typeof json2.source === "string" ? probe(posix7.join(dir, json2.source).replace(/\.(m?[jt]sx?)$/, "")) : void 0) ?? probe(posix7.join(dir, "src/index"));
18946
20115
  }
18947
20116
  function exportedFunctions(input2, file2) {
18948
20117
  const result2 = input2.results.get(`${file2.source}\0${file2.path}`);
@@ -19036,7 +20205,7 @@ var init_exits2 = __esm({
19036
20205
  });
19037
20206
 
19038
20207
  // packages/stage2/src/groups.ts
19039
- import { posix as posix6 } from "node:path";
20208
+ import { posix as posix8 } from "node:path";
19040
20209
  function groups(input2) {
19041
20210
  const threshold = input2.clusterThreshold ?? DEFAULT_CLUSTER_THRESHOLD;
19042
20211
  const fnFile = new Map(input2.functions.map((f) => [f.id, f.file]));
@@ -19048,16 +20217,16 @@ function groups(input2) {
19048
20217
  const rootName = manifests.get("package.json")?.name;
19049
20218
  const packages = [];
19050
20219
  for (const [path, json2] of manifests) {
19051
- if (posix6.basename(path) !== "package.json" || path === "package.json") continue;
19052
- const dir = posix6.dirname(path);
20220
+ if (posix8.basename(path) !== "package.json" || path === "package.json") continue;
20221
+ const dir = posix8.dirname(path);
19053
20222
  const name = json2?.name;
19054
20223
  if (typeof name === "string" && name && members2(dir)) packages.push({ dir, name });
19055
20224
  }
19056
- packages.sort((a, b) => b.dir.length - a.dir.length || cmp8(a.dir, b.dir));
20225
+ packages.sort((a, b) => b.dir.length - a.dir.length || cmp10(a.dir, b.dir));
19057
20226
  const named = /* @__PURE__ */ new Map();
19058
20227
  for (const p of packages) named.set(p.name, (named.get(p.name) ?? 0) + 1);
19059
20228
  for (const p of packages) if (named.get(p.name) > 1) p.name = `${p.name} (${p.dir})`;
19060
- const files = input2.files.filter((f) => f.source === plan.sourceId).sort((a, b) => cmp8(a.path, b.path));
20229
+ const files = input2.files.filter((f) => f.source === plan.sourceId).sort((a, b) => cmp10(a.path, b.path));
19061
20230
  const boundaries = /* @__PURE__ */ new Map();
19062
20231
  for (const f of files) {
19063
20232
  const pkg = packages.find((p) => f.path.startsWith(`${p.dir}/`));
@@ -19078,7 +20247,10 @@ function groups(input2) {
19078
20247
  out.push({ type: "Group", ...g, externalPackages: [] });
19079
20248
  for (const f of g.files) groupOf.set(f, g.id);
19080
20249
  };
19081
- const asClusters = (files2) => {
20250
+ const within = (b, split) => ({
20251
+ boundary: { kind: b.kind, name: b.name, root: b.root, split }
20252
+ });
20253
+ const asClusters = (files2, b) => {
19082
20254
  for (const c of clusters(files2, input2.imports, input2.calls, fnFile))
19083
20255
  push({
19084
20256
  id: ids.cluster(plan.sourceId, c.key),
@@ -19086,14 +20258,16 @@ function groups(input2) {
19086
20258
  kind: "cluster",
19087
20259
  source: plan.sourceId,
19088
20260
  root: c.root,
19089
- files: c.files.map((f) => f.id)
20261
+ files: c.files.map((f) => f.id),
20262
+ ...within(b, "connections")
19090
20263
  });
19091
20264
  };
19092
- for (const b of [...boundaries.values()].sort((x, y) => cmp8(x.root, y.root))) {
20265
+ for (const b of [...boundaries.values()].sort((x, y) => cmp10(x.root, y.root))) {
19093
20266
  const units = b.kind === "repository" && packages.length === 0 ? folderUnits(b.files) : null;
20267
+ const repo = { kind: "repository", name: b.name, root: b.root };
19094
20268
  if (units) {
19095
20269
  for (const u of units) {
19096
- if (u.root === "" && u.files.length > threshold) asClusters(u.files);
20270
+ if (u.root === "" && u.files.length > threshold) asClusters(u.files, repo);
19097
20271
  else if (u.root === "") {
19098
20272
  push({
19099
20273
  id: ids.group(plan.sourceId, ""),
@@ -19103,7 +20277,8 @@ function groups(input2) {
19103
20277
  root: "",
19104
20278
  files: u.files.map((f) => f.id)
19105
20279
  });
19106
- } else if (u.files.length > threshold) asClusters(u.files);
20280
+ } else if (u.files.length > threshold)
20281
+ asClusters(u.files, { kind: "folder", name: u.root, root: u.root });
19107
20282
  else
19108
20283
  push({
19109
20284
  id: ids.cluster(plan.sourceId, u.root),
@@ -19111,13 +20286,14 @@ function groups(input2) {
19111
20286
  kind: "cluster",
19112
20287
  source: plan.sourceId,
19113
20288
  root: u.root,
19114
- files: u.files.map((f) => f.id)
20289
+ files: u.files.map((f) => f.id),
20290
+ ...within({ kind: "folder", name: u.root, root: u.root }, "folders")
19115
20291
  });
19116
20292
  }
19117
20293
  continue;
19118
20294
  }
19119
20295
  if (b.files.length > threshold) {
19120
- asClusters(b.files);
20296
+ asClusters(b.files, { kind: b.kind, name: b.name, root: b.root });
19121
20297
  continue;
19122
20298
  }
19123
20299
  push({
@@ -19130,64 +20306,7 @@ function groups(input2) {
19130
20306
  });
19131
20307
  }
19132
20308
  }
19133
- const byId = new Map(out.map((g) => [g.id, g]));
19134
- const roll = /* @__PURE__ */ new Map();
19135
- const rollOf = (from, to) => {
19136
- const key = `${from}\0${to}`;
19137
- let r = roll.get(key);
19138
- if (!r) roll.set(key, r = { imports: [], calls: [], references: [] });
19139
- return r;
19140
- };
19141
- for (const e of input2.imports) {
19142
- const from = groupOf.get(e.from);
19143
- if (!from) continue;
19144
- if (e.to.startsWith("package|")) {
19145
- const g = byId.get(from);
19146
- if (!g.externalPackages.includes(e.to)) g.externalPackages.push(e.to);
19147
- continue;
19148
- }
19149
- const to = groupOf.get(e.to);
19150
- if (to && to !== from) rollOf(from, to).imports.push(e);
19151
- }
19152
- for (const c of input2.calls) {
19153
- const fromFile = fnFile.get(c.from);
19154
- const toFile = fnFile.get(c.to);
19155
- const from = fromFile ? groupOf.get(fromFile) : void 0;
19156
- const to = toFile ? groupOf.get(toFile) : void 0;
19157
- if (from && to && from !== to) rollOf(from, to).calls.push(c);
19158
- }
19159
- for (const c of input2.references ?? []) {
19160
- const fromFile = fnFile.get(c.from);
19161
- const toFile = fnFile.get(c.to);
19162
- const from = fromFile ? groupOf.get(fromFile) : void 0;
19163
- const to = toFile ? groupOf.get(toFile) : void 0;
19164
- if (from && to && from !== to) rollOf(from, to).references.push(c);
19165
- }
19166
- for (const g of out) g.externalPackages.sort(cmp8);
19167
- const carries = /* @__PURE__ */ new Map();
19168
- for (const s of input2.symbols ?? []) {
19169
- const key = s.id.slice("IMPORTS_SYMBOL|".length, s.id.lastIndexOf("|"));
19170
- const u = s.uses;
19171
- const yes = u === null || u.calls + u.jsx + u.extends > 0;
19172
- carries.set(key, (carries.get(key) ?? false) || yes);
19173
- }
19174
- const carrying = (e) => carries.get(e.id.slice("IMPORTS|".length)) ?? true;
19175
- const dependsOn = [...roll].map(([key, r]) => {
19176
- const [from, to] = key.split("\0");
19177
- const first = (xs) => [...xs].sort((a, b) => cmp8(a.id, b.id))[0];
19178
- const evidence = (first(r.imports) ?? first(r.calls) ?? first(r.references)).evidence;
19179
- return {
19180
- type: "DEPENDS_ON",
19181
- id: ids.dependsOn(from, to),
19182
- from,
19183
- to,
19184
- imports: r.imports.length,
19185
- calls: r.calls.length,
19186
- ...r.references.length ? { references: r.references.length } : {},
19187
- carrying: r.imports.filter(carrying).length,
19188
- evidence
19189
- };
19190
- }).sort((a, b) => cmp8(a.id, b.id));
20309
+ const dependsOn = rollUp(out, groupOf, input2, fnFile);
19191
20310
  return { groups: out, dependsOn };
19192
20311
  }
19193
20312
  function folderUnits(files) {
@@ -19199,10 +20318,10 @@ function folderUnits(files) {
19199
20318
  roots.add("");
19200
20319
  continue;
19201
20320
  }
19202
- const inside3 = analyzed.filter((f) => top(f) === dir);
19203
- const direct = inside3.filter((f) => f.path.split("/").length === 2);
20321
+ const inside4 = analyzed.filter((f) => top(f) === dir);
20322
+ const direct = inside4.filter((f) => f.path.split("/").length === 2);
19204
20323
  const children = new Set(
19205
- inside3.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
20324
+ inside4.filter((f) => f.path.split("/").length > 2).map((f) => f.path.split("/")[1])
19206
20325
  );
19207
20326
  if (direct.length === 0 && children.size >= 2) for (const c of children) roots.add(`${dir}/${c}`);
19208
20327
  else roots.add(dir);
@@ -19216,7 +20335,7 @@ function folderUnits(files) {
19216
20335
  list.push(f);
19217
20336
  units.set(root, list);
19218
20337
  }
19219
- return [...units].map(([root, list]) => ({ root, files: list })).sort((a, b) => cmp8(a.root, b.root));
20338
+ return [...units].map(([root, list]) => ({ root, files: list })).sort((a, b) => cmp10(a.root, b.root));
19220
20339
  }
19221
20340
  function clusters(files, imports, calls, fnFile) {
19222
20341
  const index = new Map(files.map((f, i) => [f.id, i]));
@@ -19239,7 +20358,7 @@ function clusters(files, imports, calls, fnFile) {
19239
20358
  });
19240
20359
  let community = louvain(n2, edges);
19241
20360
  const touched = new Set(edges.flatMap((e) => [e.a, e.b]));
19242
- const dir = (i) => posix6.dirname(files[i].path);
20361
+ const dir = (i) => posix8.dirname(files[i].path);
19243
20362
  const folderCommunity = /* @__PURE__ */ new Map();
19244
20363
  for (let i = 0; i < n2; i++)
19245
20364
  if (touched.has(i) && !folderCommunity.has(dir(i))) folderCommunity.set(dir(i), community[i]);
@@ -19260,150 +20379,16 @@ function clusters(files, imports, calls, fnFile) {
19260
20379
  });
19261
20380
  return [...members2.values()].map(nameCluster).sort(byKey).map(disambiguate());
19262
20381
  }
19263
- function ancestors(dir) {
19264
- if (!dir) return [""];
19265
- const parts = dir.split("/");
19266
- return ["", ...parts.map((_, i) => parts.slice(0, i + 1).join("/"))];
19267
- }
19268
- function nameCluster(list) {
19269
- const dirs = list.map((f) => {
19270
- const d = posix6.dirname(f.path);
19271
- return d === "." ? "" : d;
19272
- });
19273
- const counts = /* @__PURE__ */ new Map();
19274
- for (const d of dirs) for (const a of ancestors(d)) counts.set(a, (counts.get(a) ?? 0) + 1);
19275
- const root = [...counts].filter(([, n2]) => n2 === list.length).sort((x, y) => y[0].length - x[0].length)[0][0];
19276
- const need = Math.ceil(list.length * 0.75);
19277
- const main2 = [...counts].filter(([dir, n2]) => n2 >= need && inside2(`${dir}/x`, root)).sort((x, y) => y[0].length - x[0].length || y[1] - x[1] || cmp8(x[0], y[0]))[0][0];
19278
- const outside = list.length - counts.get(main2);
19279
- const roles = /* @__PURE__ */ new Map();
19280
- for (const f of list) {
19281
- const parts = posix6.basename(f.path).split(".");
19282
- if (parts.length >= 3)
19283
- roles.set(parts[parts.length - 2], (roles.get(parts[parts.length - 2]) ?? 0) + 1);
19284
- }
19285
- const [role, shared] = [...roles].sort((x, y) => y[1] - x[1] || cmp8(x[0], y[0]))[0] ?? ["", 0];
19286
- const base2 = `${main2 || "(root)"}${list.length > 1 && shared >= Math.ceil(list.length * 0.6) ? ` \xB7 ${role} files` : ""}`;
19287
- const name = outside > 0 ? `${base2} (+${outside} elsewhere in ${root || "the repository"})` : base2;
19288
- return { name, root, main: main2, files: list };
19289
- }
19290
- function disambiguate() {
19291
- const seen = /* @__PURE__ */ new Set();
19292
- return (c) => {
19293
- const key = c.main || "(root)";
19294
- const taken = seen.has(key);
19295
- seen.add(key);
19296
- if (!taken) return { key, name: c.name, root: c.root, files: c.files };
19297
- const first = [...c.files].map((f) => f.path).sort(cmp8).find((p) => inside2(p, c.main));
19298
- const within = c.main ? first.slice(c.main.length + 1) : first;
19299
- const counts = /* @__PURE__ */ new Map();
19300
- for (const f of c.files) {
19301
- if (!inside2(f.path, c.main)) continue;
19302
- const rel = posix6.dirname(c.main ? f.path.slice(c.main.length + 1) : f.path);
19303
- if (rel === ".") continue;
19304
- const parts = rel.split("/");
19305
- for (let i = 1; i <= parts.length; i++) {
19306
- const d = parts.slice(0, i).join("/");
19307
- counts.set(d, (counts.get(d) ?? 0) + 1);
19308
- }
19309
- }
19310
- const [folder, n2] = [...counts].sort(
19311
- (a, b) => b[1] - a[1] || b[0].split("/").length - a[0].split("/").length || cmp8(a[0], b[0])
19312
- )[0] ?? ["", 0];
19313
- const name = n2 >= 2 ? `${c.name} \xB7 mostly ${folder} (${n2} of ${c.files.length})` : `${c.name} (${within})`;
19314
- return { key: `${key} (${within})`, name, root: c.root, files: c.files };
19315
- };
19316
- }
19317
- function louvain(n2, edges) {
19318
- let assignment = Array.from({ length: n2 }, (_, i) => i);
19319
- let nodes = n2;
19320
- let graph = edges;
19321
- for (let level = 0; level < 10; level++) {
19322
- const { community, moved } = localMoves(nodes, graph);
19323
- if (!moved) break;
19324
- const renumber2 = /* @__PURE__ */ new Map();
19325
- for (let i = 0; i < nodes; i++)
19326
- if (!renumber2.has(community[i])) renumber2.set(community[i], renumber2.size);
19327
- assignment = assignment.map((c) => renumber2.get(community[c]));
19328
- const agg = /* @__PURE__ */ new Map();
19329
- for (const e of graph) {
19330
- const a = renumber2.get(community[e.a]);
19331
- const b = renumber2.get(community[e.b]);
19332
- const key = a < b ? `${a} ${b}` : `${b} ${a}`;
19333
- agg.set(key, (agg.get(key) ?? 0) + e.w);
19334
- }
19335
- nodes = renumber2.size;
19336
- graph = [...agg].map(([k, w]) => {
19337
- const [a, b] = k.split(" ").map(Number);
19338
- return { a, b, w };
19339
- });
19340
- }
19341
- const refined = localMoves(n2, edges, assignment).community;
19342
- const renumber = /* @__PURE__ */ new Map();
19343
- return refined.map((c) => {
19344
- if (!renumber.has(c)) renumber.set(c, renumber.size);
19345
- return renumber.get(c);
19346
- });
19347
- }
19348
- function localMoves(n2, edges, initial) {
19349
- const adj = Array.from({ length: n2 }, () => /* @__PURE__ */ new Map());
19350
- const selfLoop = new Array(n2).fill(0);
19351
- let total = 0;
19352
- for (const e of edges) {
19353
- if (e.a === e.b) selfLoop[e.a] += e.w;
19354
- else {
19355
- adj[e.a].set(e.b, (adj[e.a].get(e.b) ?? 0) + e.w);
19356
- adj[e.b].set(e.a, (adj[e.b].get(e.a) ?? 0) + e.w);
19357
- }
19358
- total += e.w;
19359
- }
19360
- const community = initial ? [...initial] : Array.from({ length: n2 }, (_, i) => i);
19361
- if (total === 0) return { community, moved: false };
19362
- const m2 = 2 * total;
19363
- const degree = adj.map((m, i) => [...m.values()].reduce((s, w) => s + w, 0) + 2 * selfLoop[i]);
19364
- let size = n2;
19365
- for (const c of community) if (c + 1 > size) size = c + 1;
19366
- const communityDegree = new Array(size).fill(0);
19367
- for (let i = 0; i < n2; i++) communityDegree[community[i]] += degree[i];
19368
- let moved = false;
19369
- for (let pass = 0; pass < 50; pass++) {
19370
- let changed = false;
19371
- for (let i = 0; i < n2; i++) {
19372
- const own2 = community[i];
19373
- const links = /* @__PURE__ */ new Map();
19374
- for (const [j, w] of adj[i]) links.set(community[j], (links.get(community[j]) ?? 0) + w);
19375
- communityDegree[own2] -= degree[i];
19376
- const gain = (c) => (links.get(c) ?? 0) - communityDegree[c] * degree[i] / m2;
19377
- let best = own2;
19378
- let bestGain = gain(own2);
19379
- for (const c of [...links.keys()].sort((x, y) => x - y)) {
19380
- const g = gain(c);
19381
- if (g > bestGain + 1e-12 || Math.abs(g - bestGain) <= 1e-12 && c < best) {
19382
- best = c;
19383
- bestGain = g;
19384
- }
19385
- }
19386
- communityDegree[best] += degree[i];
19387
- if (best !== own2) {
19388
- community[i] = best;
19389
- changed = true;
19390
- moved = true;
19391
- }
19392
- }
19393
- if (!changed) break;
19394
- }
19395
- return { community, moved };
19396
- }
19397
- var DEFAULT_CLUSTER_THRESHOLD, cmp8, inside2, byKey;
20382
+ var DEFAULT_CLUSTER_THRESHOLD, cmp10;
19398
20383
  var init_groups = __esm({
19399
20384
  "packages/stage2/src/groups.ts"() {
19400
20385
  "use strict";
19401
20386
  init_src();
20387
+ init_cluster();
19402
20388
  init_imports();
20389
+ init_cluster();
19403
20390
  DEFAULT_CLUSTER_THRESHOLD = 200;
19404
- cmp8 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
19405
- inside2 = (path, dir) => dir === "" || path.startsWith(`${dir}/`);
19406
- byKey = (a, b) => cmp8(a.main, b.main) || b.files.length - a.files.length || cmp8(a.files[0].path, b.files[0].path);
20391
+ cmp10 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
19407
20392
  }
19408
20393
  });
19409
20394
 
@@ -21172,7 +22157,7 @@ function folderOf(fileId, head) {
21172
22157
  }
21173
22158
  function aliasesOf(plans) {
21174
22159
  const out = [];
21175
- const dirOf = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
22160
+ const dirOf2 = (path) => path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
21176
22161
  const under = (dir, rel) => {
21177
22162
  const parts = dir ? dir.split("/") : [];
21178
22163
  for (const r of rel.split("/")) {
@@ -21190,7 +22175,7 @@ function aliasesOf(plans) {
21190
22175
  } catch {
21191
22176
  continue;
21192
22177
  }
21193
- const base2 = under(dirOf(m.path), json2?.compilerOptions?.baseUrl ?? ".");
22178
+ const base2 = under(dirOf2(m.path), json2?.compilerOptions?.baseUrl ?? ".");
21194
22179
  for (const [key, targets] of Object.entries(json2?.compilerOptions?.paths ?? {}))
21195
22180
  for (const target2 of targets ?? [])
21196
22181
  out.push([p.sourceId, key.replace(/\*$/, ""), under(base2, target2.replace(/\*.*$/, ""))]);
@@ -21200,11 +22185,11 @@ function aliasesOf(plans) {
21200
22185
  const name = f.path.slice(f.path.lastIndexOf("/") + 1);
21201
22186
  if (/^(vite|webpack)\.config\.[cm]?[jt]s$/.test(name))
21202
22187
  for (const [key, folder] of parseAliases(f.content))
21203
- out.push([p.sourceId, key, under(dirOf(f.path), folder)]);
22188
+ out.push([p.sourceId, key, under(dirOf2(f.path), folder)]);
21204
22189
  else if (/^svelte\.config\.[cm]?[jt]s$/.test(name)) {
21205
22190
  const block = /alias\s*:\s*\{([^}]*)\}/.exec(f.content)?.[1] ?? "";
21206
22191
  for (const m of block.matchAll(/['"]?([$@~\w/-]+)['"]?\s*:\s*['"]([^'"*]+)\/?\*?['"]/g))
21207
- out.push([p.sourceId, m[1].replace(/\/\*$/, ""), under(dirOf(f.path), m[2].replace(/\/$/, ""))]);
22192
+ out.push([p.sourceId, m[1].replace(/\/\*$/, ""), under(dirOf2(f.path), m[2].replace(/\/$/, ""))]);
21208
22193
  }
21209
22194
  }
21210
22195
  }
@@ -21523,7 +22508,7 @@ var init_src8 = __esm({
21523
22508
  symbolsScope = (fileId) => `${STAGE23}:symbols:${fileId}`;
21524
22509
  groupSource = (groupId) => groupId.split("|")[1];
21525
22510
  STEPS = 5;
21526
- STAGE2_VERSION = 5;
22511
+ STAGE2_VERSION = 6;
21527
22512
  stage2 = createStage2();
21528
22513
  }
21529
22514
  });
@@ -59478,7 +60463,8 @@ var init_server3 = __esm({
59478
60463
  from: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe("With to: the calling groups, files or a group's folders (folder|<group>|<path>)"),
59479
60464
  to: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe("With from: the called groups, files or a group's folders"),
59480
60465
  offset: external_exports.number().int().optional().describe("Skip this many first (default 0)"),
59481
- limit: external_exports.number().int().optional().describe(`At most this many calls (1 to ${CROSS_FILE_CALLS_MAX}; default 100)`)
60466
+ limit: external_exports.number().int().optional().describe(`At most this many calls (1 to ${CROSS_FILE_CALLS_MAX}; default 100)`),
60467
+ grouping: external_exports.enum(GROUPINGS).optional().describe("The grouping the group ids are of: declared (default) or connected (#304)")
59482
60468
  },
59483
60469
  call: (e, a, cwd) => crossFileCalls(e, a, cwd)
59484
60470
  },
@@ -59496,13 +60482,16 @@ var init_server3 = __esm({
59496
60482
  call: (e, a, cwd) => projectTotals(e, a, cwd)
59497
60483
  },
59498
60484
  list_groups: {
59499
- description: "The project map (R2): groups of files (workspace packages, repositories, and clusters inside large ones), each with file, function and external-package counts and finding counts; DEPENDS_ON edges between them (imports, cross-file calls, references, and `carrying`: imports whose names are called, rendered or extended; with one as evidence; A calls into B when calls, references or carrying are above zero, else the link is type-only, value-only or unused imports); the external packages (how many, and the most imported); and project totals. `stage2: false` means Stage 2 hasn't run.",
60485
+ description: "The project map (R2): groups of files (workspace packages, repositories, and clusters inside large ones), each with file, function and external-package counts and finding counts; DEPENDS_ON edges between them (imports, cross-file calls, references, and `carrying`: imports whose names are called, rendered or extended; with one as evidence; A calls into B when calls, references or carrying are above zero, else the link is type-only, value-only or unused imports); the external packages (how many, and the most imported); and project totals. Each group says `why` its files are together; with grouping connected, `differences` lists the declared and connected groups that map onto each other other than one to one (a split, a merge). `stage2: false` means Stage 2 hasn't run.",
59500
60486
  input: {
59501
60487
  project,
59502
60488
  run,
59503
60489
  source: external_exports.string().optional().describe("One source only"),
59504
60490
  limit: external_exports.number().int().optional().describe(`At most this many groups (1 to ${GROUPS_MAX}; default ${GROUPS_MAX})`),
59505
- offset: external_exports.number().int().optional().describe("Skip this many groups first (paging; default 0)")
60491
+ offset: external_exports.number().int().optional().describe("Skip this many groups first (paging; default 0)"),
60492
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60493
+ "declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60494
+ )
59506
60495
  },
59507
60496
  call: (e, a, cwd) => listGroups(e, a, cwd)
59508
60497
  },
@@ -59513,13 +60502,21 @@ var init_server3 = __esm({
59513
60502
  run,
59514
60503
  group: external_exports.string().describe("A group id, as returned by list_groups"),
59515
60504
  expand: external_exports.array(external_exports.string()).optional().describe("Folder paths to show open"),
59516
- pending: external_exports.boolean().optional().describe("Include imports waiting for another source")
60505
+ pending: external_exports.boolean().optional().describe("Include imports waiting for another source"),
60506
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60507
+ "The grouping the group id is of: declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60508
+ )
59517
60509
  },
59518
60510
  call: (e, a, cwd) => getGroup(e, a, cwd)
59519
60511
  },
59520
60512
  resolve_imports: {
59521
60513
  description: "A file's imports (R2), each with its outcome (a file, an external package, or broken, not analyzed or pending with the reason) and how it was resolved; and the files importing it.",
59522
- input: { project, run, file: external_exports.string().describe("A file id") },
60514
+ input: {
60515
+ project,
60516
+ run,
60517
+ file: external_exports.string().describe("A file id"),
60518
+ grouping: external_exports.enum(GROUPINGS).optional().describe("The grouping each end's group is of: declared (default) or connected (#304)")
60519
+ },
59523
60520
  call: (e, a, cwd) => resolveImports(e, a, cwd)
59524
60521
  },
59525
60522
  file_summary: {
@@ -59652,7 +60649,10 @@ var init_server3 = __esm({
59652
60649
  "impact (default): by what resolving each would open, the own-code functions whose paths stop at it (#307), most first; place: by file and line"
59653
60650
  ),
59654
60651
  limit: external_exports.number().int().optional().describe(`At most this many (1 to ${FINDINGS_MAX}; default 100)`),
59655
- offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all")
60652
+ offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all"),
60653
+ grouping: external_exports.enum(GROUPINGS).optional().describe(
60654
+ "The grouping `group` and each row's group are of: declared (default): workspace packages, repositories and folders; connected: how files connect (#304): modules joined by calls within their packages, a shared layer apart, packages calling into each other merged"
60655
+ )
59656
60656
  },
59657
60657
  call: (e, a, cwd) => listFindings(e, a, cwd)
59658
60658
  },
@@ -102083,6 +103083,12 @@ async function createServer(engine, options2 = {}) {
102083
103083
  const run2 = pinned.get(req);
102084
103084
  if (run2 !== void 0 && req.params && typeof req.params === "object")
102085
103085
  req.params.run = run2;
103086
+ const project2 = req.params?.project;
103087
+ const route = req.routeOptions.url ?? "";
103088
+ const reads = req.method === "GET" ? !route.endsWith("/status") : route.endsWith("/ask");
103089
+ const connected = req.query?.grouping === "connected";
103090
+ if (typeof project2 === "string" && reads)
103091
+ await engine.finishing(project2, void 0, connected).catch(() => void 0);
102086
103092
  });
102087
103093
  app.addHook("onClose", async () => {
102088
103094
  engine.events.off("event", forward);
@@ -102464,7 +103470,12 @@ async function createServer(engine, options2 = {}) {
102464
103470
  querystring: {
102465
103471
  type: "object",
102466
103472
  additionalProperties: false,
102467
- properties: { source: str2, limit: positive2, offset: count2 }
103473
+ properties: {
103474
+ source: str2,
103475
+ limit: positive2,
103476
+ offset: count2,
103477
+ grouping: { type: "string", enum: [...GROUPINGS] }
103478
+ }
102468
103479
  }
102469
103480
  }
102470
103481
  },
@@ -102472,7 +103483,8 @@ async function createServer(engine, options2 = {}) {
102472
103483
  ...req.params,
102473
103484
  ...req.query.source !== void 0 ? { source: req.query.source } : {},
102474
103485
  ...req.query.limit ? { limit: Number(req.query.limit) } : {},
102475
- ...req.query.offset ? { offset: Number(req.query.offset) } : {}
103486
+ ...req.query.offset ? { offset: Number(req.query.offset) } : {},
103487
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
102476
103488
  })
102477
103489
  );
102478
103490
  app.get(
@@ -102487,7 +103499,8 @@ async function createServer(engine, options2 = {}) {
102487
103499
  properties: {
102488
103500
  group: str2,
102489
103501
  expand: oneOrMore(str2),
102490
- pending: { type: "string", enum: ["true", "false"] }
103502
+ pending: { type: "string", enum: ["true", "false"] },
103503
+ grouping: { type: "string", enum: [...GROUPINGS] }
102491
103504
  }
102492
103505
  }
102493
103506
  }
@@ -102496,7 +103509,8 @@ async function createServer(engine, options2 = {}) {
102496
103509
  ...req.params,
102497
103510
  group: req.query.group,
102498
103511
  ...req.query.expand !== void 0 ? { expand: list(req.query.expand) } : {},
102499
- ...req.query.pending === "true" ? { pending: true } : {}
103512
+ ...req.query.pending === "true" ? { pending: true } : {},
103513
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
102500
103514
  })
102501
103515
  );
102502
103516
  app.get(
@@ -102508,11 +103522,15 @@ async function createServer(engine, options2 = {}) {
102508
103522
  type: "object",
102509
103523
  additionalProperties: false,
102510
103524
  required: ["file"],
102511
- properties: { file: str2 }
103525
+ properties: { file: str2, grouping: { type: "string", enum: [...GROUPINGS] } }
102512
103526
  }
102513
103527
  }
102514
103528
  },
102515
- async (req) => resolveImports(engine, { ...req.params, file: req.query.file })
103529
+ async (req) => resolveImports(engine, {
103530
+ ...req.params,
103531
+ file: req.query.file,
103532
+ ...req.query.grouping !== void 0 ? { grouping: req.query.grouping } : {}
103533
+ })
102516
103534
  );
102517
103535
  app.get(
102518
103536
  "/api/projects/:project/file-summary",
@@ -102545,7 +103563,8 @@ async function createServer(engine, options2 = {}) {
102545
103563
  own: { type: "string", enum: ["true", "false"] },
102546
103564
  sort: { type: "string", enum: ["impact", "place"] },
102547
103565
  limit: positive2,
102548
- offset: count2
103566
+ offset: count2,
103567
+ grouping: { type: "string", enum: [...GROUPINGS] }
102549
103568
  }
102550
103569
  }
102551
103570
  }
@@ -102577,7 +103596,8 @@ async function createServer(engine, options2 = {}) {
102577
103596
  from: oneOrMore(str2),
102578
103597
  to: oneOrMore(str2),
102579
103598
  limit: positive2,
102580
- offset: { type: "string", pattern: "^[0-9]+$" }
103599
+ offset: { type: "string", pattern: "^[0-9]+$" },
103600
+ grouping: { type: "string", enum: [...GROUPINGS] }
102581
103601
  }
102582
103602
  }
102583
103603
  }
@@ -103545,6 +104565,8 @@ async function serveRun(io) {
103545
104565
  const engine = new Engine(io.home, {
103546
104566
  stages: request.stages.map((n2) => known[n2]),
103547
104567
  afterCommit: summarizeFindings,
104568
+ // The connected grouping kept with each run, once its counts are (#374).
104569
+ afterSummaries: keepConnectedGrouping,
103548
104570
  ...request.retention ? { retention: request.retention } : {},
103549
104571
  license: request.license,
103550
104572
  killableRuns: true
@@ -103559,12 +104581,12 @@ async function serveRun(io) {
103559
104581
  }
103560
104582
  function usageFor(command) {
103561
104583
  const out = [];
103562
- let inside3 = false;
104584
+ let inside4 = false;
103563
104585
  for (const line of USAGE.split("\n")) {
103564
104586
  if (/^ {2}veoflow /.test(line))
103565
- inside3 = line.startsWith(` veoflow ${command} `) || line === ` veoflow ${command}`;
103566
- else if (!/^ {3,}/.test(line)) inside3 = false;
103567
- if (inside3) out.push(line);
104587
+ inside4 = line.startsWith(` veoflow ${command} `) || line === ` veoflow ${command}`;
104588
+ else if (!/^ {3,}/.test(line)) inside4 = false;
104589
+ if (inside4) out.push(line);
103568
104590
  }
103569
104591
  return out.length ? out.join("\n") : null;
103570
104592
  }
@@ -103601,6 +104623,7 @@ async function main(argv, io) {
103601
104623
  const engine2 = new Engine(io.home);
103602
104624
  try {
103603
104625
  summarizeFindings(engine2, project2, Number(run2));
104626
+ keepConnectedGrouping(engine2, project2, Number(run2));
103604
104627
  } finally {
103605
104628
  engine2.close();
103606
104629
  }
@@ -103615,6 +104638,8 @@ async function main(argv, io) {
103615
104638
  stages: [stage2],
103616
104639
  // Finding counts kept with each run, so the projects home never scans findings (#249).
103617
104640
  afterCommit: summarizeFindings,
104641
+ // The connected grouping kept with each run, once its counts are (#374).
104642
+ afterSummaries: keepConnectedGrouping,
103618
104643
  ...command === "serve" ? { runner: { command: self2 } } : ["run", "add", "include", "exclude"].includes(command) ? { killableRuns: true } : {}
103619
104644
  });
103620
104645
  let keepOpen = false;