veoflow 0.5.6 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/veo.mjs CHANGED
@@ -504,6 +504,8 @@ var init_classify = __esm({
504
504
  "tsx",
505
505
  "vue",
506
506
  "svelte",
507
+ // Python (#415, R3).
508
+ "python",
507
509
  "angular-template"
508
510
  ]);
509
511
  UNSUPPORTED = {
@@ -1246,7 +1248,7 @@ function unreadNotice(files) {
1246
1248
  const parts = [...by].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).map(([name, n2]) => `${n2.toLocaleString("en-US")} ${name} ${n2 === 1 ? "file" : "files"}`);
1247
1249
  const list = parts.length === 1 ? parts[0] : `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
1248
1250
  const total = [...by.values()].reduce((a, b) => a + b, 0);
1249
- return `${list} ${total === 1 ? "is" : "are"} listed but not analyzed yet: veoflow analyzes JavaScript and TypeScript (with Vue, Svelte and Angular components) today.`;
1251
+ return `${list} ${total === 1 ? "is" : "are"} listed but not analyzed yet: veoflow analyzes JavaScript and TypeScript (with Vue, Svelte and Angular components) and Python today.`;
1250
1252
  }
1251
1253
  function ignoredSourceFolders(root, unpinned) {
1252
1254
  const out = [];
@@ -1869,7 +1871,7 @@ var init_plan = __esm({
1869
1871
  };
1870
1872
  DEFAULT_MAX_FILE_BYTES = 10 * 1024 * 1024;
1871
1873
  HARD_MAX_FILE_BYTES = 64 * 1024 * 1024;
1872
- RESOLVER_MANIFEST = /(^|\/)(package\.json|(ts|js)config[^/]*\.json|package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|\.npmrc|\.yarnrc\.yml)$/;
1874
+ RESOLVER_MANIFEST = /(^|\/)(package\.json|project\.json|nx\.json|pyproject\.toml|setup\.cfg|requirements[^/]*\.txt|uv\.lock|poetry\.lock|(ts|js)config[^/]*\.json|package-lock\.json|pnpm-lock\.yaml|pnpm-workspace\.yaml|yarn\.lock|\.npmrc|\.yarnrc\.yml)$/;
1873
1875
  RESOLVER_INPUT = /\.(json|jsonc|lock|ya?ml|toml|mod|sum)$|(^|\/)(\.npmrc|\.nvmrc|\.babelrc)$/i;
1874
1876
  MINIFIED_MIN_BYTES = 2e4;
1875
1877
  count = (n2, noun) => `${n2.toLocaleString("en-US")} ${noun}${n2 === 1 ? "" : "s"}`;
@@ -3791,6 +3793,7 @@ var init_src2 = __esm({
3791
3793
  // packages/extract-client/src/index.ts
3792
3794
  var src_exports = {};
3793
3795
  __export(src_exports, {
3796
+ SUPPORTED: () => SUPPORTED,
3794
3797
  acceptsTestLicenses: () => acceptsTestLicenses,
3795
3798
  adapterVersion: () => adapterVersion,
3796
3799
  cacheSize: () => cacheSize,
@@ -3798,6 +3801,9 @@ __export(src_exports, {
3798
3801
  extract: () => extract,
3799
3802
  isAvailable: () => isAvailable,
3800
3803
  languageForPath: () => languageForPath,
3804
+ phaseTimings: () => phaseTimings,
3805
+ platformName: () => platformName,
3806
+ resetPhaseTimings: () => resetPhaseTimings,
3801
3807
  resolve: () => resolve3,
3802
3808
  runQueries: () => runQueries,
3803
3809
  verifyLicense: () => verifyLicense
@@ -3813,12 +3819,17 @@ function native() {
3813
3819
  return binding;
3814
3820
  } catch (e) {
3815
3821
  loadError = new Error(
3816
- "The veo-extract native module is not built for this platform. Run: pnpm --filter @veo/extract-client build:native",
3822
+ process.env.VEO_NATIVE_DIR ? `veoflow has no prebuilt engine for ${platformName()}. ${SUPPORTED}` : `The veo-extract native module is not built for ${platformName()}. Run: pnpm --filter @veo/extract-client build:native`,
3817
3823
  { cause: e }
3818
3824
  );
3819
3825
  throw loadError;
3820
3826
  }
3821
3827
  }
3828
+ function platformName() {
3829
+ const report = process.report?.getReport();
3830
+ const musl = process.platform === "linux" && !report?.header?.glibcVersionRuntime;
3831
+ return `${process.platform}-${process.arch}${musl ? " (musl)" : ""}`;
3832
+ }
3822
3833
  function isAvailable() {
3823
3834
  try {
3824
3835
  native();
@@ -3857,10 +3868,17 @@ function languageForPath(path) {
3857
3868
  const ext = path.slice(path.lastIndexOf(".") + 1).toLowerCase();
3858
3869
  return LANGUAGES[ext];
3859
3870
  }
3860
- var binding, loadError, LANGUAGES;
3871
+ function phaseTimings() {
3872
+ return JSON.parse(native().phaseTimings());
3873
+ }
3874
+ function resetPhaseTimings() {
3875
+ native().resetPhaseTimings();
3876
+ }
3877
+ var binding, loadError, SUPPORTED, LANGUAGES;
3861
3878
  var init_src3 = __esm({
3862
3879
  "packages/extract-client/src/index.ts"() {
3863
3880
  "use strict";
3881
+ SUPPORTED = "It runs on macOS (Apple silicon and Intel), Linux with glibc (x64 and arm64) and Windows (x64), with Node.js 22.13 or newer.";
3864
3882
  LANGUAGES = {
3865
3883
  js: "javascript",
3866
3884
  mjs: "javascript",
@@ -3871,7 +3889,8 @@ var init_src3 = __esm({
3871
3889
  cts: "typescript",
3872
3890
  tsx: "tsx",
3873
3891
  vue: "vue",
3874
- svelte: "svelte"
3892
+ svelte: "svelte",
3893
+ py: "python"
3875
3894
  };
3876
3895
  }
3877
3896
  });
@@ -4893,7 +4912,7 @@ var init_stage1 = __esm({
4893
4912
  byOffset = (a, b) => a.site.start.offset - b.site.start.offset || a.site.end.offset - b.site.end.offset;
4894
4913
  BATCH_BYTES2 = 32 << 20;
4895
4914
  BATCH_FILES = 200;
4896
- STAGE1_VERSION = 1;
4915
+ STAGE1_VERSION = 2;
4897
4916
  stage1 = {
4898
4917
  name: STAGE1,
4899
4918
  version: () => `${STAGE1_VERSION}+${adapterVersion()}`,
@@ -7270,7 +7289,9 @@ var init_view = __esm({
7270
7289
  reach: null,
7271
7290
  grouping: "declared",
7272
7291
  differences: false,
7273
- reveal: []
7292
+ reveal: [],
7293
+ unfold: [],
7294
+ allCallbacks: false
7274
7295
  };
7275
7296
  str = (field, optional2 = false) => (a) => optional2 && a[field] === void 0 || typeof a[field] === "string" && a[field].length > 0 ? [] : [field];
7276
7297
  oneOf = (field, values) => (a) => values.includes(a[field]) ? [] : [field];
@@ -7459,17 +7480,39 @@ var init_view = __esm({
7459
7480
  })
7460
7481
  },
7461
7482
  revealFile: {
7462
- 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)",
7483
+ description: `On a file's Imports level, show another file's imports and calls in place, or with side "left" its callers and importers (or hide them again, with what was revealed from it)`,
7463
7484
  control: { kind: "canvas", testId: "reveal-file" },
7464
- check: all(str("file"), str("from", true)),
7485
+ check: all(str("file"), str("from", true), str("side", true)),
7465
7486
  apply: (s, a) => s.reveal.some((r) => r.file === a.file) ? { ...s, reveal: hideReveal(s.reveal, a.file) } : (
7466
7487
  // Only at a file's Imports level, and never the open file itself.
7467
7488
  a.file === s.file || !s.file || s.tab !== "imports" || !s.fileLevel ? s : {
7468
7489
  ...s,
7469
- reveal: [...s.reveal, { file: a.file, from: a.from ?? s.file }]
7490
+ reveal: [
7491
+ ...s.reveal,
7492
+ {
7493
+ file: a.file,
7494
+ from: a.from ?? s.file,
7495
+ ...a.side === "left" ? { side: "left" } : {}
7496
+ }
7497
+ ]
7470
7498
  }
7471
7499
  )
7472
7500
  },
7501
+ toggleCallbacks: {
7502
+ description: "On the File tab, show a function's callbacks (the unnamed functions written inside it), or fold them into it again",
7503
+ control: { kind: "button", testId: "toggle-callbacks" },
7504
+ check: str("fn"),
7505
+ apply: (s, a) => ({
7506
+ ...s,
7507
+ unfold: s.unfold.includes(a.fn) ? s.unfold.filter((f) => f !== a.fn) : [...s.unfold, a.fn]
7508
+ })
7509
+ },
7510
+ setAllCallbacks: {
7511
+ description: "On the File tab, show every function's callbacks, or fold them all",
7512
+ control: { kind: "toggle", testId: "all-callbacks" },
7513
+ check: (a) => typeof a.all === "boolean" ? [] : ["all"],
7514
+ apply: (s, a) => ({ ...s, allCallbacks: a.all, unfold: [] })
7515
+ },
7473
7516
  resetReveal: {
7474
7517
  description: "On a file's Imports level, hide every file revealed in place: the open file's own imports and calls only",
7475
7518
  control: { kind: "button", testId: "reset-reveal" },
@@ -8096,9 +8139,13 @@ function declaredWhy(g) {
8096
8139
  if (g.kind === "repository") return `Declared: the repository ${g.name}`;
8097
8140
  if (g.kind === "workspace-package")
8098
8141
  return `Declared: the workspace package ${g.name} (${g.root || "its root"})`;
8099
- if (g.boundary?.split === "folders") return `Declared: the folder ${g.root}`;
8100
- if (g.boundary)
8101
- return `Declared: part of ${g.boundary.kind === "folder" ? `the folder ${g.boundary.name}` : g.boundary.name}, split by how its files connect`;
8142
+ const of = g.boundary && (g.boundary.kind === "folder" ? `the folder ${g.boundary.name}` : g.boundary.name);
8143
+ if (g.boundary?.split === "folders") {
8144
+ if (g.boundary.rest)
8145
+ return `Declared: the files of ${g.root || "the root"} outside its larger folders, part of ${of}`;
8146
+ return g.boundary.root === g.root ? `Declared: the folder ${g.root}` : `Declared: the folder ${g.root}, part of ${of}`;
8147
+ }
8148
+ if (g.boundary) return `Declared: part of ${of}, split by how its files connect`;
8102
8149
  return `Declared: a cluster of ${g.root || "the repository"}, split by how its files connect`;
8103
8150
  }
8104
8151
  function connectedGrouping(input2) {
@@ -9163,6 +9210,7 @@ var init_totals = __esm({
9163
9210
  });
9164
9211
 
9165
9212
  // packages/query-imports/src/reads.ts
9213
+ import { posix as posix4 } from "node:path";
9166
9214
  function cmp4(a, b) {
9167
9215
  return a < b ? -1 : a > b ? 1 : 0;
9168
9216
  }
@@ -9285,6 +9333,13 @@ function groupIndex(groups2) {
9285
9333
  for (const g of groups2) for (const f of g.files) if (!byFile.has(f)) byFile.set(f, g);
9286
9334
  return byFile;
9287
9335
  }
9336
+ function causeOf(f) {
9337
+ const source = sourceOf2(f.file);
9338
+ if (f.kind === "open-call") return { key: `open-call|${source}|${f.text}`, target: f.text, source };
9339
+ const relative5 = f.text.startsWith("./") || f.text.startsWith("../") || f.text === "." || f.text === "..";
9340
+ const target2 = relative5 ? posix4.normalize(posix4.join(posix4.dirname(f.path), f.text)) : f.text;
9341
+ return { key: `${f.kind}|${f.reason}|${source}|${target2}`, target: target2, source };
9342
+ }
9288
9343
  function findingsIn(reader, groupOf, files, plain2 = false) {
9289
9344
  const each = (type) => files === null ? reader.facts(type) : files.flatMap((f) => reader.facts(type, f));
9290
9345
  const rows = [];
@@ -9730,14 +9785,14 @@ function resolveImports(engine, args, cwd) {
9730
9785
  evidence: u.evidence
9731
9786
  }))
9732
9787
  ].sort(byEvidence);
9733
- const statementKey = (id) => id.replace(/^(IMPORTS|unresolved-import)\|/, "");
9788
+ const statementKey2 = (id) => id.replace(/^(IMPORTS|unresolved-import)\|/, "");
9734
9789
  const namesOf = /* @__PURE__ */ new Map();
9735
9790
  for (const n2 of importedNames(reader, file2.id)) {
9736
9791
  const key = n2.id.replace(/^IMPORTS_SYMBOL\|/, "").replace(/\|[^|]*$/, "");
9737
9792
  namesOf.set(key, [...namesOf.get(key) ?? [], n2]);
9738
9793
  }
9739
9794
  for (const i of imports) {
9740
- const names = namesOf.get(statementKey(i.id));
9795
+ const names = namesOf.get(statementKey2(i.id));
9741
9796
  if (names) i.names = names;
9742
9797
  }
9743
9798
  const importers = reader.factsTo("IMPORTS", file2.id).sort(byEvidence);
@@ -9785,6 +9840,10 @@ function listFindings(engine, args, cwd) {
9785
9840
  throw new VeoError("invalid-arguments", `kind must be one of ${FINDING_KINDS.join(", ")}`, {
9786
9841
  fields: ["kind"]
9787
9842
  });
9843
+ if (args.groupBy !== void 0 && args.groupBy !== "cause")
9844
+ throw new VeoError("invalid-arguments", "groupBy must be cause", { fields: ["groupBy"] });
9845
+ if (args.cause !== void 0 && (typeof args.cause !== "string" || args.cause === ""))
9846
+ throw new VeoError("invalid-arguments", "cause must be a non-empty cause key", { fields: ["cause"] });
9788
9847
  if (args.own !== void 0 && typeof args.own !== "boolean")
9789
9848
  throw new VeoError("invalid-arguments", "own must be true or false", { fields: ["own"] });
9790
9849
  const limit = positiveLimit(args.limit, 100, FINDINGS_MAX);
@@ -9839,6 +9898,108 @@ function listFindings(engine, args, cwd) {
9839
9898
  } : r;
9840
9899
  });
9841
9900
  };
9901
+ if (args.groupBy === "cause" || args.cause !== void 0) {
9902
+ const inGroup = files ? new Set(files) : null;
9903
+ const scoped = (file2) => (!inGroup || inGroup.has(file2)) && (args.source === void 0 || sourceOf2(file2) === args.source) && (!ownFiles || ownFiles.has(file2));
9904
+ const counts2 = zero();
9905
+ let entries;
9906
+ let rowsOf;
9907
+ if (keptImpact && run2 !== null) {
9908
+ const causes2 = keptCauses(engine, meta3.project, run2, reader, groupOf);
9909
+ const order = [];
9910
+ for (const [id, k] of Object.entries(keptImpact)) {
9911
+ if (!scoped(k.file)) continue;
9912
+ tally(counts2, k.kind);
9913
+ if (kinds.has(k.kind)) order.push([id, k]);
9914
+ }
9915
+ order.sort(
9916
+ sort === "impact" ? ([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) : ([ia, a], [ib, b]) => cmp4(a.file, b.file) || a.offset - b.offset || cmp4(ia, ib)
9917
+ );
9918
+ entries = order.map(([id, k]) => ({
9919
+ id,
9920
+ file: k.file,
9921
+ cause: causes2[id] ?? id,
9922
+ opens: sort === "impact" ? k.opens : 0,
9923
+ last: !!k.last
9924
+ }));
9925
+ rowsOf = (ids2) => {
9926
+ const wanted2 = new Set(ids2);
9927
+ const files2 = [...new Set(entries.filter((e) => wanted2.has(e.id)).map((e) => e.file))];
9928
+ const found = new Map(
9929
+ findingsIn(reader, groupOf, files2).filter((f) => wanted2.has(f.id)).map((f) => [f.id, f])
9930
+ );
9931
+ return withImpact(ids2.map((id) => found.get(id)).filter((f) => !!f));
9932
+ };
9933
+ } else {
9934
+ const rows3 = [];
9935
+ for (const f of findingsIn(reader, groupOf, files)) {
9936
+ if (!inScope(f) || ownFiles && !ownFiles.has(f.file)) continue;
9937
+ tally(counts2, f.kind);
9938
+ if (kinds.has(f.kind)) rows3.push(f);
9939
+ }
9940
+ const all2 = withImpact(rows3).sort(
9941
+ sort === "impact" ? (a, b) => Number(listedLast(a)) - Number(listedLast(b)) || (b.impact?.opens ?? 0) - (a.impact?.opens ?? 0) || byEvidence(a, b) || cmp4(a.id, b.id) : (a, b) => byEvidence(a, b) || cmp4(a.id, b.id)
9942
+ );
9943
+ const byId = new Map(all2.map((f) => [f.id, f]));
9944
+ entries = all2.map((f) => ({
9945
+ id: f.id,
9946
+ file: f.file,
9947
+ cause: causeOf(f).key,
9948
+ opens: f.impact?.opens ?? 0,
9949
+ last: listedLast(f)
9950
+ }));
9951
+ rowsOf = (ids2) => ids2.map((id) => byId.get(id));
9952
+ }
9953
+ if (args.cause !== void 0) {
9954
+ const of = entries.filter((e) => e.cause === args.cause);
9955
+ return {
9956
+ ...meta3,
9957
+ stage2: stage22,
9958
+ counts: counts2,
9959
+ total: of.length,
9960
+ offset,
9961
+ truncated: of.length > offset + limit,
9962
+ findings: rowsOf(of.slice(offset, offset + limit).map((e) => e.id))
9963
+ };
9964
+ }
9965
+ const causes = /* @__PURE__ */ new Map();
9966
+ for (const e of entries) {
9967
+ const c = causes.get(e.cause);
9968
+ if (!c)
9969
+ causes.set(e.cause, {
9970
+ first: e.id,
9971
+ count: 1,
9972
+ files: /* @__PURE__ */ new Set([e.file]),
9973
+ opens: e.opens,
9974
+ last: e.last
9975
+ });
9976
+ else {
9977
+ c.count++;
9978
+ c.files.add(e.file);
9979
+ c.opens = Math.max(c.opens, e.opens);
9980
+ c.last &&= e.last;
9981
+ }
9982
+ }
9983
+ const calls = (key) => key.startsWith("open-call|");
9984
+ const listed = [...causes].sort(
9985
+ ([ka, a], [kb, b]) => Number(calls(ka)) - Number(calls(kb)) || Number(a.last) - Number(b.last) || (calls(ka) ? b.opens - a.opens || b.count - a.count : b.count - a.count || b.opens - a.opens) || cmp4(ka, kb)
9986
+ ).slice(offset, offset + limit);
9987
+ const rows2 = rowsOf(listed.map(([, c]) => c.first));
9988
+ return {
9989
+ ...meta3,
9990
+ stage2: stage22,
9991
+ counts: counts2,
9992
+ total: causes.size,
9993
+ offset,
9994
+ truncated: causes.size > offset + limit,
9995
+ // Each row with its own cause, by id (a row not read would otherwise shift the rest).
9996
+ findings: rows2.map((r) => {
9997
+ const [key, c] = listed.find(([, c2]) => c2.first === r.id);
9998
+ const { target: target2, source } = causeOf(r);
9999
+ return { ...r, cause: { key, target: target2, source, count: c.count, files: c.files.size } };
10000
+ })
10001
+ };
10002
+ }
9842
10003
  if (sort === "impact") {
9843
10004
  const inGroup = files ? new Set(files) : null;
9844
10005
  const scoped = (file2) => (!inGroup || inGroup.has(file2)) && (args.source === void 0 || sourceOf2(file2) === args.source) && (!ownFiles || ownFiles.has(file2));
@@ -10022,6 +10183,9 @@ function summarizeFindings(engine, project2, run2) {
10022
10183
  ...listedLast(r) ? { last: true } : {}
10023
10184
  };
10024
10185
  engine.setRunSummary(project2, run2, IMPACT_SUMMARY, { pending: pendingNow, items });
10186
+ engine.setRunSummary(project2, run2, CAUSE_SUMMARY, {
10187
+ items: Object.fromEntries(rows.map((r) => [r.id, causeOf(r).key]))
10188
+ });
10025
10189
  if (reader.count("Group") > 0) {
10026
10190
  const within = reader.countByFile("CALLS");
10027
10191
  const across = reader.countByFile("CALLS_CROSS_FILE");
@@ -10041,6 +10205,18 @@ function summarizeFindings(engine, project2, run2) {
10041
10205
  function pendingKey(pending) {
10042
10206
  return JSON.stringify([...pending].map(([s, paths]) => [s, [...paths].sort()]).sort());
10043
10207
  }
10208
+ function keptCauses(engine, project2, run2, reader, groupOf) {
10209
+ const kept = engine.runSummary(project2, run2, CAUSE_SUMMARY);
10210
+ if (kept) return kept.items;
10211
+ const items = Object.fromEntries(
10212
+ findingsIn(reader, groupOf, null, true).map((f) => [f.id, causeOf(f).key])
10213
+ );
10214
+ try {
10215
+ engine.setRunSummary(project2, run2, CAUSE_SUMMARY, { items });
10216
+ } catch {
10217
+ }
10218
+ return items;
10219
+ }
10044
10220
  function keptImpacts(engine, project2, run2, pending) {
10045
10221
  const kept = engine.runSummary(project2, run2, IMPACT_SUMMARY);
10046
10222
  return kept && kept.pending === pending ? kept.items : void 0;
@@ -10060,7 +10236,7 @@ function ownCounts(summary2, pending) {
10060
10236
  const own2 = ownBySource(summary2, pending);
10061
10237
  return own2 ? Object.values(own2).reduce(add, zero()) : void 0;
10062
10238
  }
10063
- 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;
10239
+ 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, CAUSE_SUMMARY;
10064
10240
  var init_reads = __esm({
10065
10241
  "packages/query-imports/src/reads.ts"() {
10066
10242
  "use strict";
@@ -10103,6 +10279,7 @@ var init_reads = __esm({
10103
10279
  });
10104
10280
  FINDINGS_SUMMARY = "findings/v8";
10105
10281
  IMPACT_SUMMARY = "impact/v3";
10282
+ CAUSE_SUMMARY = "cause/v2";
10106
10283
  }
10107
10284
  });
10108
10285
 
@@ -11116,7 +11293,7 @@ async function loadCheckers() {
11116
11293
  } catch (e) {
11117
11294
  throw new VeoError(
11118
11295
  "checker-failed",
11119
- `the TypeScript reference checker isn't available here (${e.message}); reinstall veoflow with its dependencies`,
11296
+ `the reference checkers aren't available here (${e.message}); reinstall veoflow with its dependencies`,
11120
11297
  { reason: "unavailable" }
11121
11298
  );
11122
11299
  }
@@ -11137,13 +11314,17 @@ async function checkCode(engine, args, cwd = process.cwd()) {
11137
11314
  const scope2 = relative3(source.root, abs).split(sep6).join("/");
11138
11315
  const inScope = (path) => scope2 === "" || path === scope2 || path.startsWith(`${scope2}/`);
11139
11316
  const { reader } = engine.readAllStages({ project: projectId });
11140
- const analyzed = reader.facts("File").filter(
11141
- (f) => f.source === source.id && (f.status === "analyzed" || f.status === "degraded") && f.language !== null && CHECKED.has(f.language) && !f.path.endsWith(".d.ts")
11317
+ const checkable = (set2) => reader.facts("File").filter(
11318
+ (f) => f.source === source.id && (f.status === "analyzed" || f.status === "degraded") && f.language !== null && set2.has(f.language) && !f.path.endsWith(".d.ts")
11142
11319
  );
11320
+ const script = checkable(CHECKED);
11321
+ const pythonFiles = checkable(CHECKED_PYTHON);
11322
+ const python = pythonFiles.some((f) => inScope(f.path)) && !script.some((f) => inScope(f.path));
11323
+ const analyzed = python ? pythonFiles : script;
11143
11324
  if (!analyzed.some((f) => inScope(f.path)))
11144
11325
  throw new VeoError(
11145
11326
  "invalid-arguments",
11146
- `no analyzed JavaScript or TypeScript files under ${args.path} (the checker reads those; analyze the project first)`,
11327
+ `no analyzed JavaScript, TypeScript or Python files under ${args.path} (the checkers read those; analyze the project first)`,
11147
11328
  { fields: ["path"] }
11148
11329
  );
11149
11330
  const texts = /* @__PURE__ */ new Map();
@@ -11166,11 +11347,11 @@ async function checkCode(engine, args, cwd = process.cwd()) {
11166
11347
  const { extract: extract2 } = await Promise.resolve().then(() => (init_src3(), src_exports));
11167
11348
  let index;
11168
11349
  try {
11169
- index = checkers.indexFolder(source.root, { files: [...texts.keys()] });
11350
+ index = python ? checkers.indexPython(source.root, [...texts.keys()]) : checkers.indexFolder(source.root, { files: [...texts.keys()] });
11170
11351
  } catch (e) {
11171
11352
  throw new VeoError(
11172
11353
  "checker-failed",
11173
- `the TypeScript compiler couldn't index ${source.root}: ${e.message}`,
11354
+ `${python ? "scip-python" : "the TypeScript compiler"} couldn't index ${source.root}: ${e.message}`,
11174
11355
  {
11175
11356
  reason: "index"
11176
11357
  }
@@ -11184,7 +11365,7 @@ async function checkCode(engine, args, cwd = process.cwd()) {
11184
11365
  manifests: [],
11185
11366
  files
11186
11367
  }).files;
11187
- const { calls, candidates, references } = checkers.translate(index, texts);
11368
+ const { calls, candidates, references } = python ? { calls: checkers.translatePython(index, adapter, texts), candidates: [], references: 0 } : checkers.translate(index, texts);
11188
11369
  const report = checkers.compare(adapter, calls, references, candidates.length, inScope);
11189
11370
  const fileId = (path) => ids.file(source.id, path);
11190
11371
  const adapterFiles = new Map(adapter.map((f) => [f.path, f]));
@@ -11305,7 +11486,7 @@ async function checkCode(engine, args, cwd = process.cwd()) {
11305
11486
  source: source.id,
11306
11487
  root: source.root,
11307
11488
  path: scope2,
11308
- checker: "scip-typescript",
11489
+ checker: python ? "scip-python" : "scip-typescript",
11309
11490
  files: [...texts.keys()].filter(inScope).length,
11310
11491
  changed: [...changed].filter(inScope).sort(),
11311
11492
  stage2: stage22,
@@ -11329,7 +11510,7 @@ function stage2Answer(facts, at, stage22, reader) {
11329
11510
  if (r.importOutcome) return `open: ${reasonWords(r.importOutcome)}`;
11330
11511
  return `open: ${reasonWords(r.steps.at(-1)?.kind ?? "unresolved")}`;
11331
11512
  }
11332
- var CHECKED, DISAGREE;
11513
+ var CHECKED, CHECKED_PYTHON, DISAGREE;
11333
11514
  var init_check = __esm({
11334
11515
  "packages/query-imports/src/check.ts"() {
11335
11516
  "use strict";
@@ -11337,6 +11518,7 @@ var init_check = __esm({
11337
11518
  init_protocol();
11338
11519
  init_src2();
11339
11520
  CHECKED = /* @__PURE__ */ new Set(["typescript", "tsx", "javascript", "jsx"]);
11521
+ CHECKED_PYTHON = /* @__PURE__ */ new Set(["python"]);
11340
11522
  DISAGREE = /* @__PURE__ */ new Set(["different-callee", "adapter-only", "checker-only"]);
11341
11523
  }
11342
11524
  });
@@ -13972,7 +14154,7 @@ var require_semver2 = __commonJS({
13972
14154
  });
13973
14155
 
13974
14156
  // packages/stage2/src/gitignore.ts
13975
- import { posix as posix4 } from "node:path";
14157
+ import { posix as posix5 } from "node:path";
13976
14158
  function toRegExp(pattern, anchored) {
13977
14159
  let re = "";
13978
14160
  for (let i = 0; i < pattern.length; i++) {
@@ -14006,7 +14188,7 @@ function gitignoreMatcher(files) {
14006
14188
  const depth = (p) => p.split("/").length;
14007
14189
  const sorted = [...files].sort((a, b) => depth(a.path) - depth(b.path) || (a.path < b.path ? -1 : 1));
14008
14190
  for (const f of sorted) {
14009
- const dir = posix4.dirname(f.path) === "." ? "" : posix4.dirname(f.path);
14191
+ const dir = posix5.dirname(f.path) === "." ? "" : posix5.dirname(f.path);
14010
14192
  for (const raw of f.content.split(/\r?\n/)) {
14011
14193
  let line = raw.replace(/(?<!\\)\s+$/, "");
14012
14194
  if (!line || line.startsWith("#")) continue;
@@ -14063,7 +14245,7 @@ var init_gitignore = __esm({
14063
14245
 
14064
14246
  // packages/stage2/src/imports.ts
14065
14247
  import { builtinModules } from "node:module";
14066
- import { isAbsolute as isAbsolute2, posix as posix5, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
14248
+ import { isAbsolute as isAbsolute2, posix as posix6, relative as relativePath, resolve as resolvePath, sep as sep7 } from "node:path";
14067
14249
  function packageName(specifier) {
14068
14250
  const parts = specifier.split("/");
14069
14251
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
@@ -14147,7 +14329,7 @@ function declared(pkg, name) {
14147
14329
  }
14148
14330
  function lockedVersions(path, text) {
14149
14331
  const out = /* @__PURE__ */ new Map();
14150
- const base2 = posix5.basename(path);
14332
+ const base2 = posix6.basename(path);
14151
14333
  if (base2 === "package-lock.json") {
14152
14334
  const lock = parseJson(text);
14153
14335
  for (const [key, v] of Object.entries(lock?.packages ?? {})) {
@@ -14279,8 +14461,8 @@ function resolveImports2(plans, files) {
14279
14461
  const links = /* @__PURE__ */ new Map();
14280
14462
  for (const tree of trees) {
14281
14463
  for (const [path, json2] of tree.manifests) {
14282
- if (posix5.basename(path) !== "package.json") continue;
14283
- const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
14464
+ if (posix6.basename(path) !== "package.json") continue;
14465
+ const dir = posix6.dirname(path) === "." ? "" : posix6.dirname(path);
14284
14466
  const name = json2?.name;
14285
14467
  if (typeof name === "string" && name && !links.has(name) && (dir === "" || sourceMembers.get(tree)(dir)))
14286
14468
  links.set(name, { tree, dir });
@@ -14340,10 +14522,10 @@ function resolveImports2(plans, files) {
14340
14522
  const escapes = /* @__PURE__ */ new Map();
14341
14523
  for (const s of toResolve) {
14342
14524
  if (!isRelative(s.specifier)) continue;
14343
- const inside4 = posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
14525
+ const inside4 = posix6.normalize(posix6.join(posix6.dirname(s.path), s.specifier));
14344
14526
  if (inside4 !== ".." && !inside4.startsWith("../")) continue;
14345
14527
  const plan = treeOf.get(s.source).plan;
14346
- const abs = resolvePath(plan.root, ...posix5.dirname(s.path).split("/"), ...s.specifier.split("/"));
14528
+ const abs = resolvePath(plan.root, ...posix6.dirname(s.path).split("/"), ...s.specifier.split("/"));
14347
14529
  const within = (root) => {
14348
14530
  const r = relativePath(root, abs);
14349
14531
  return r === "" || !(r === ".." || r.startsWith(`..${sep7}`) || isAbsolute2(r)) ? r.split(sep7).join("/") : null;
@@ -14391,7 +14573,7 @@ function resolveImports2(plans, files) {
14391
14573
  };
14392
14574
  const versions = /* @__PURE__ */ new Map();
14393
14575
  const lockfileVersion = (tree, from, name) => {
14394
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14576
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14395
14577
  for (const lock of ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"]) {
14396
14578
  const path = dir === "." ? lock : `${dir}/${lock}`;
14397
14579
  const m = tree.plan.manifests.find((x) => x.path === path);
@@ -14405,7 +14587,7 @@ function resolveImports2(plans, files) {
14405
14587
  }
14406
14588
  };
14407
14589
  const nearest = (tree, from, base2) => {
14408
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14590
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14409
14591
  const path = dir === "." ? base2 : `${dir}/${base2}`;
14410
14592
  if (tree.plan.manifests.some((m) => m.path === path)) return path;
14411
14593
  if (dir === "." || dir === "") return null;
@@ -14413,7 +14595,7 @@ function resolveImports2(plans, files) {
14413
14595
  };
14414
14596
  const packageJsons = (tree, from) => {
14415
14597
  const out2 = [];
14416
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14598
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14417
14599
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
14418
14600
  const json2 = tree.manifests.get(path);
14419
14601
  if (json2 && typeof json2 === "object") out2.push(json2);
@@ -14451,7 +14633,7 @@ function resolveImports2(plans, files) {
14451
14633
  if (variants.some((v) => exclude.some((re) => re.test(v))) || variants.some((v) => !filter.matches(v) && include.length === 0) || filter.excludesDir(path))
14452
14634
  return "excluded-by-rule";
14453
14635
  if (include.length > 0) {
14454
- const candidates = [...posix5.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
14636
+ const candidates = [...posix6.extname(path) ? [path] : [], ...files2.slice(1), ...indexes];
14455
14637
  if (candidates.every((v) => !include.some((re) => re.test(v)))) return "excluded-by-rule";
14456
14638
  }
14457
14639
  return null;
@@ -14485,7 +14667,7 @@ function resolveImports2(plans, files) {
14485
14667
  );
14486
14668
  const probe = (t, base2) => {
14487
14669
  const set2 = pathSets.get(t);
14488
- const clean = posix5.normalize(base2).replace(/^\.\/?/, "");
14670
+ const clean = posix6.normalize(base2).replace(/^\.\/?/, "");
14489
14671
  const js = /\.(m|c)?jsx?$/.exec(clean);
14490
14672
  const ts = js ? [".ts", ".tsx", ".mts", ".cts"].map(
14491
14673
  (e) => clean.slice(0, -js[0].length) + (js[0] === ".jsx" ? ".tsx" : js[1] ? `.${js[1]}ts` : e)
@@ -14500,7 +14682,7 @@ function resolveImports2(plans, files) {
14500
14682
  return null;
14501
14683
  };
14502
14684
  const nearestPackage = (t, from) => {
14503
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14685
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14504
14686
  const path = dir === "." ? "package.json" : `${dir}/package.json`;
14505
14687
  const json2 = t.manifests.get(path);
14506
14688
  if (json2 && typeof json2 === "object")
@@ -14532,7 +14714,7 @@ function resolveImports2(plans, files) {
14532
14714
  };
14533
14715
  const siteDir = (t, from) => {
14534
14716
  const set2 = pathSets.get(t);
14535
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14717
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14536
14718
  const d = dir === "." ? "" : dir;
14537
14719
  if (["js", "ts", "mjs", "cjs", "mts"].some((e) => set2.has(join14(d, `docusaurus.config.${e}`)))) return d;
14538
14720
  if (d === "") return null;
@@ -14540,18 +14722,18 @@ function resolveImports2(plans, files) {
14540
14722
  };
14541
14723
  const bundlerCache = /* @__PURE__ */ new Map();
14542
14724
  const bundlerAliases = (t, from) => {
14543
- const key = `${t.plan.sourceId}\0${posix5.dirname(from)}`;
14725
+ const key = `${t.plan.sourceId}\0${posix6.dirname(from)}`;
14544
14726
  const cached2 = bundlerCache.get(key);
14545
14727
  if (cached2) return cached2;
14546
14728
  const files2 = fileContent.get(t);
14547
14729
  const out2 = [];
14548
14730
  for (const kind of ["vite", "webpack"]) {
14549
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
14731
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14550
14732
  const d = dir === "." ? "" : dir;
14551
14733
  const config2 = ["ts", "js", "mjs", "mts", "cjs", "cts"].map((e) => join14(d, `${kind}.config.${e}`)).find((p) => files2.get(p) !== void 0);
14552
14734
  if (config2) {
14553
14735
  const aliases = parseAliases(files2.get(config2)).map(
14554
- ([k, v]) => [k, posix5.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
14736
+ ([k, v]) => [k, posix6.normalize(join14(d, v)).replace(/^\.\/?$/, "")]
14555
14737
  );
14556
14738
  if (aliases.length)
14557
14739
  out2.push({ config: config2, aliases: aliases.sort((a, b) => b[0].length - a[0].length) });
@@ -14656,7 +14838,7 @@ function resolveImports2(plans, files) {
14656
14838
  for (const { config: config2, aliases } of bundlerAliases(t, from)) {
14657
14839
  for (const [key, value] of aliases) {
14658
14840
  if (specifier !== key && !specifier.startsWith(`${key}/`)) continue;
14659
- const target2 = posix5.normalize(join14(value, specifier.slice(key.length + 1)));
14841
+ const target2 = posix6.normalize(join14(value, specifier.slice(key.length + 1)));
14660
14842
  if (target2 === ".." || target2.startsWith("../")) {
14661
14843
  const abs = resolvePath(t.plan.root, ...target2.split("/"));
14662
14844
  let holder = null;
@@ -14937,8 +15119,8 @@ function resolveImports2(plans, files) {
14937
15119
  for (const u of trees) {
14938
15120
  if (u !== t && (ws === null || workspaceOf.get(u) !== ws)) continue;
14939
15121
  for (const [path, json2] of u.manifests) {
14940
- if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
14941
- const dir = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
15122
+ if (posix6.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
15123
+ const dir = posix6.dirname(path) === "." ? "" : posix6.dirname(path);
14942
15124
  const member = dir === "" && u === t ? true : sourceMembers.get(u)(dir) || dir === "" && coversAbove(u.plan, "");
14943
15125
  if (member && declared(json2, name) !== void 0)
14944
15126
  out2.push(u === t ? path : `${u.plan.sourceId}:${path}`);
@@ -14979,14 +15161,14 @@ function resolveImports2(plans, files) {
14979
15161
  return { pick: "npm", detail: `${name} is declared as ${spec}, not as a workspace package` };
14980
15162
  };
14981
15163
  const baseUrlMiss = (t, from, specifier) => {
14982
- for (let dir = posix5.dirname(from); ; dir = posix5.dirname(dir)) {
15164
+ for (let dir = posix6.dirname(from); ; dir = posix6.dirname(dir)) {
14983
15165
  const d = dir === "." ? "" : dir;
14984
15166
  for (const c of ["tsconfig.json", "jsconfig.json"]) {
14985
15167
  const json2 = t.manifests.get(join14(d, c));
14986
15168
  if (!json2) continue;
14987
15169
  const baseUrl = json2.compilerOptions?.baseUrl;
14988
15170
  if (typeof baseUrl !== "string") return null;
14989
- const base2 = posix5.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
15171
+ const base2 = posix6.normalize(join14(d, baseUrl.replace(/^\.\/?/, ""))).replace(/^\.$/, "");
14990
15172
  const folder = `${join14(base2, specifier.split("/")[0])}/`;
14991
15173
  for (const p of pathSets.get(t)) if (p.startsWith(folder)) return join14(d, c);
14992
15174
  return null;
@@ -14998,7 +15180,7 @@ function resolveImports2(plans, files) {
14998
15180
  for (const s of all2) {
14999
15181
  const tree = treeOf.get(s.source);
15000
15182
  const plan = tree.plan;
15001
- const rel = (p) => posix5.relative(posix5.dirname(s.path), p) || ".";
15183
+ const rel = (p) => posix6.relative(posix6.dirname(s.path), p) || ".";
15002
15184
  let target2;
15003
15185
  if (isUrl(s.specifier)) {
15004
15186
  const { name, version: version3 } = urlPackage(s.specifier);
@@ -15019,7 +15201,7 @@ function resolveImports2(plans, files) {
15019
15201
  };
15020
15202
  } else {
15021
15203
  const answer = answers.get(s);
15022
- const ownExt = posix5.extname(s.specifier.replace(/\?[^/]*$/, ""));
15204
+ const ownExt = posix6.extname(s.specifier.replace(/\?[^/]*$/, ""));
15023
15205
  const shown = OWN_EXTENSIONS.has(ownExt) ? answer.tried.filter(
15024
15206
  (t) => ![...PROBE_EXTENSIONS, ".d.ts", ".node"].some((e) => t.endsWith(`${ownExt}${e}`))
15025
15207
  ) : answer.tried;
@@ -15170,7 +15352,7 @@ function resolveImports2(plans, files) {
15170
15352
  };
15171
15353
  } else if (isRelative(s.specifier) || s.specifier.startsWith("/")) {
15172
15354
  const holder = escape2?.holder ?? tree;
15173
- const candidate = escape2?.holder ? escape2.rel : posix5.normalize(posix5.join(posix5.dirname(s.path), s.specifier));
15355
+ const candidate = escape2?.holder ? escape2.rel : posix6.normalize(posix6.join(posix6.dirname(s.path), s.specifier));
15174
15356
  const ignored = holder.plan.unpinned.some(
15175
15357
  (u) => u.reason === "gitignored" && (u.path.endsWith("/") ? `${candidate}/`.startsWith(u.path) : [
15176
15358
  candidate,
@@ -15395,7 +15577,7 @@ function resolveImports2(plans, files) {
15395
15577
  }
15396
15578
  if (target2.kind === "unresolved")
15397
15579
  for (const n2 of notes) {
15398
- const base2 = posix5.basename(n2.path);
15580
+ const base2 = posix6.basename(n2.path);
15399
15581
  if (n2.source !== s.source || !["package.json", "tsconfig.json", "jsconfig.json"].includes(base2))
15400
15582
  continue;
15401
15583
  if (nearest(tree, s.path, base2) === n2.path) target2.steps.push(n2.step);
@@ -15433,14 +15615,14 @@ function parseAliases(source) {
15433
15615
  const tpl = /^`\$\{([\s\S]+)\}([^`$]*)`$/.exec(e);
15434
15616
  if (tpl) {
15435
15617
  const base2 = path(tpl[1]);
15436
- return base2 === null ? null : posix5.join(base2, tpl[2] || ".");
15618
+ return base2 === null ? null : posix6.join(base2, tpl[2] || ".");
15437
15619
  }
15438
15620
  const lit = /^(['"`])([^'"`]*)\1$/.exec(e);
15439
15621
  if (lit)
15440
15622
  return lit[2].includes("${") || !/^(\.\.?\/|\/|\.$)/.test(lit[2]) ? null : lit[2].replace(/^\//, "");
15441
15623
  const dirname10 = /^(?:path\.)?(?:resolve|join)\(\s*__dirname\s*((?:,\s*(['"`])[^'"`]*\2\s*)*)\)$/.exec(e);
15442
15624
  if (dirname10)
15443
- return posix5.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
15625
+ return posix6.join(".", ...[...dirname10[1].matchAll(/(['"`])([^'"`]*)\1/g)].map((m) => m[2]));
15444
15626
  const url2 = /^(?:fileURLToPath\(\s*)?new URL\(\s*(['"`])([^'"`]*)\1\s*,\s*import\.meta\.url\s*\)(?:\s*\)|\.pathname)?$/.exec(
15445
15627
  e
15446
15628
  );
@@ -15541,13 +15723,13 @@ function coversAbove(plan, dir) {
15541
15723
  );
15542
15724
  aboveCache.set(ws, members2);
15543
15725
  }
15544
- return members2(posix5.join(ws.prefix, dir).replace(/\/$/, ""));
15726
+ return members2(posix6.join(ws.prefix, dir).replace(/\/$/, ""));
15545
15727
  }
15546
15728
  function workspaceMembers(raw, parsed) {
15547
15729
  const include = [];
15548
15730
  const exclude = [];
15549
15731
  const anchored = (base2, glob) => {
15550
- const p = posix5.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
15732
+ const p = posix6.join(base2, glob.replace(/^\.\//, "")).replace(/\/+$/, "");
15551
15733
  let re = "";
15552
15734
  for (let i = 0; i < p.length; i++) {
15553
15735
  const c = p[i];
@@ -15570,14 +15752,14 @@ function workspaceMembers(raw, parsed) {
15570
15752
  (g.startsWith("!") ? exclude : include).push(anchored(base2, g.replace(/^!/, "")));
15571
15753
  };
15572
15754
  for (const [path, json2] of parsed) {
15573
- if (posix5.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
15574
- const base2 = posix5.dirname(path) === "." ? "" : posix5.dirname(path);
15755
+ if (posix6.basename(path) !== "package.json" || !json2 || typeof json2 !== "object") continue;
15756
+ const base2 = posix6.dirname(path) === "." ? "" : posix6.dirname(path);
15575
15757
  const ws = json2.workspaces;
15576
15758
  add2(base2, Array.isArray(ws) ? ws : ws?.packages);
15577
15759
  }
15578
15760
  for (const m of raw) {
15579
- if (posix5.basename(m.path) !== "pnpm-workspace.yaml") continue;
15580
- add2(posix5.dirname(m.path) === "." ? "" : posix5.dirname(m.path), pnpmWorkspacePackages(m.content));
15761
+ if (posix6.basename(m.path) !== "pnpm-workspace.yaml") continue;
15762
+ add2(posix6.dirname(m.path) === "." ? "" : posix6.dirname(m.path), pnpmWorkspacePackages(m.content));
15581
15763
  }
15582
15764
  return (dir) => include.some((re) => re.test(dir)) && !exclude.some((re) => re.test(dir));
15583
15765
  }
@@ -18874,7 +19056,7 @@ var init_closed = __esm({
18874
19056
  });
18875
19057
 
18876
19058
  // packages/stage2/src/components.ts
18877
- import { posix as posix6 } from "node:path";
19059
+ import { posix as posix7 } from "node:path";
18878
19060
  function linkComponents(input2) {
18879
19061
  const fn = new Map(input2.functions.map((f) => [`${f.file}\0${f.qualifiedName}`, f.id]));
18880
19062
  const statementsByFile = /* @__PURE__ */ new Map();
@@ -18951,7 +19133,7 @@ function linkComponents(input2) {
18951
19133
  if (inline) return inline;
18952
19134
  const declared2 = input2.templates.find((t) => t.file === fileId && t.component === cls && t.specifier);
18953
19135
  if (!declared2) return null;
18954
- const target2 = `${sourceOf5(fileId)}:${posix6.normalize(posix6.join(posix6.dirname(pathOf7(fileId)), declared2.specifier))}`;
19136
+ const target2 = `${sourceOf5(fileId)}:${posix7.normalize(posix7.join(posix7.dirname(pathOf7(fileId)), declared2.specifier))}`;
18955
19137
  return fn.get(`${target2}\0<template>`) ?? null;
18956
19138
  };
18957
19139
  const usingClasses = (site) => {
@@ -18962,7 +19144,7 @@ function linkComponents(input2) {
18962
19144
  return [{ file: site.file, cls: caller.slice(0, -".<template>".length) }];
18963
19145
  const path = pathOf7(site.file);
18964
19146
  return input2.templates.filter(
18965
- (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix6.normalize(posix6.join(posix6.dirname(pathOf7(t.file)), t.specifier)) === path
19147
+ (t) => t.specifier && sourceOf5(t.file) === sourceOf5(site.file) && posix7.normalize(posix7.join(posix7.dirname(pathOf7(t.file)), t.specifier)) === path
18966
19148
  ).map((t) => ({ file: t.file, cls: t.component }));
18967
19149
  };
18968
19150
  const modules = fileIds.flatMap(
@@ -19234,7 +19416,7 @@ var init_components = __esm({
19234
19416
  });
19235
19417
 
19236
19418
  // packages/stage2/src/exits.ts
19237
- import { posix as posix7 } from "node:path";
19419
+ import { posix as posix8 } from "node:path";
19238
19420
  function renderPath(segs) {
19239
19421
  let out = "";
19240
19422
  for (const s of segs) {
@@ -20027,8 +20209,8 @@ function startCandidates(input2, s, exitAt, nodeAt) {
20027
20209
  for (const plan of input2.plans) {
20028
20210
  const parsed = new Map(plan.manifests.map((m) => [m.path, parseManifest(m.content)]));
20029
20211
  for (const m of plan.manifests) {
20030
- if (posix7.basename(m.path) !== "package.json") continue;
20031
- const dir = posix7.dirname(m.path) === "." ? "" : posix7.dirname(m.path);
20212
+ if (posix8.basename(m.path) !== "package.json") continue;
20213
+ const dir = posix8.dirname(m.path) === "." ? "" : posix8.dirname(m.path);
20032
20214
  const json2 = parsed.get(m.path);
20033
20215
  if (!json2 || typeof json2 !== "object") continue;
20034
20216
  const pkg = typeof json2.name === "string" && json2.name ? json2.name : dir || plan.sourceId;
@@ -20161,7 +20343,7 @@ function scriptFiles(command, depth = 0) {
20161
20343
  const tokens = [...command.matchAll(/"([^"]*)"|'([^']*)'|(&&|\|\||[;|&])|([^\s"';|&]+)/g)];
20162
20344
  let part = [];
20163
20345
  const end2 = () => {
20164
- const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix7.basename(t.text)));
20346
+ const at = part.findIndex((t) => !t.quoted && RUNNERS.has(posix8.basename(t.text)));
20165
20347
  if (at !== -1)
20166
20348
  for (let i = at + 1; i < part.length; i++) {
20167
20349
  const t = part[i].text;
@@ -20195,7 +20377,7 @@ function stringLeaves(v) {
20195
20377
  return [];
20196
20378
  }
20197
20379
  function sourceFile(files, source, dir, p, json2) {
20198
- const rel = posix7.normalize(posix7.join(dir, p));
20380
+ const rel = posix8.normalize(posix8.join(dir, p));
20199
20381
  if (rel.startsWith("..")) return void 0;
20200
20382
  const exts = [
20201
20383
  "",
@@ -20223,8 +20405,8 @@ function sourceFile(files, source, dir, p, json2) {
20223
20405
  const built = /^(dist|build|lib|out)\//;
20224
20406
  const inside4 = dir ? noExt.slice(dir.length + 1) : noExt;
20225
20407
  if (!built.test(inside4)) return void 0;
20226
- const srcRel = posix7.join(dir, inside4.replace(built, "src/"));
20227
- 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"));
20408
+ const srcRel = posix8.join(dir, inside4.replace(built, "src/"));
20409
+ return probe(srcRel) ?? (typeof json2.source === "string" ? probe(posix8.join(dir, json2.source).replace(/\.(m?[jt]sx?)$/, "")) : void 0) ?? probe(posix8.join(dir, "src/index"));
20228
20410
  }
20229
20411
  function exportedFunctions(input2, file2) {
20230
20412
  const result2 = input2.results.get(`${file2.source}\0${file2.path}`);
@@ -20318,7 +20500,7 @@ var init_exits2 = __esm({
20318
20500
  });
20319
20501
 
20320
20502
  // packages/stage2/src/groups.ts
20321
- import { posix as posix8 } from "node:path";
20503
+ import { posix as posix9 } from "node:path";
20322
20504
  function groups(input2) {
20323
20505
  const threshold = input2.clusterThreshold ?? DEFAULT_CLUSTER_THRESHOLD;
20324
20506
  const fnFile = new Map(input2.functions.map((f) => [f.id, f.file]));
@@ -20330,11 +20512,20 @@ function groups(input2) {
20330
20512
  const rootName = manifests.get("package.json")?.name;
20331
20513
  const packages = [];
20332
20514
  for (const [path, json2] of manifests) {
20333
- if (posix8.basename(path) !== "package.json" || path === "package.json") continue;
20334
- const dir = posix8.dirname(path);
20515
+ if (posix9.basename(path) !== "package.json" || path === "package.json") continue;
20516
+ const dir = posix9.dirname(path);
20335
20517
  const name = json2?.name;
20336
20518
  if (typeof name === "string" && name && members2(dir)) packages.push({ dir, name });
20337
20519
  }
20520
+ const holds = (dir) => input2.files.some((f) => f.source === plan.sourceId && f.path.startsWith(`${dir}/`));
20521
+ if (manifests.has("nx.json"))
20522
+ for (const [path, json2] of manifests) {
20523
+ if (posix9.basename(path) !== "project.json" || path === "project.json") continue;
20524
+ const dir = posix9.dirname(path);
20525
+ if (packages.some((p) => p.dir === dir) || !holds(dir)) continue;
20526
+ const name = json2?.name;
20527
+ packages.push({ dir, name: typeof name === "string" && name ? name : posix9.basename(dir) });
20528
+ }
20338
20529
  packages.sort((a, b) => b.dir.length - a.dir.length || cmp10(a.dir, b.dir));
20339
20530
  const named = /* @__PURE__ */ new Map();
20340
20531
  for (const p of packages) named.set(p.name, (named.get(p.name) ?? 0) + 1);
@@ -20360,8 +20551,8 @@ function groups(input2) {
20360
20551
  out.push({ type: "Group", ...g, externalPackages: [] });
20361
20552
  for (const f of g.files) groupOf.set(f, g.id);
20362
20553
  };
20363
- const within = (b, split) => ({
20364
- boundary: { kind: b.kind, name: b.name, root: b.root, split }
20554
+ const within = (b, split2) => ({
20555
+ boundary: { kind: b.kind, name: b.name, root: b.root, split: split2 }
20365
20556
  });
20366
20557
  const asClusters = (files2, b) => {
20367
20558
  for (const c of clusters(files2, input2.imports, input2.calls, fnFile))
@@ -20375,6 +20566,24 @@ function groups(input2) {
20375
20566
  ...within(b, "connections")
20376
20567
  });
20377
20568
  };
20569
+ const split = (files2, b) => {
20570
+ for (const part of folderParts(files2, b.root, threshold)) {
20571
+ if (part.connect) {
20572
+ asClusters(part.files, b);
20573
+ continue;
20574
+ }
20575
+ const of = part.root || b.name;
20576
+ push({
20577
+ id: ids.cluster(plan.sourceId, part.root),
20578
+ name: part.rest ? `${of} \xB7 other files` : of,
20579
+ kind: "cluster",
20580
+ source: plan.sourceId,
20581
+ root: part.root,
20582
+ files: part.files.map((f) => f.id),
20583
+ boundary: { ...within(b, "folders").boundary, ...part.rest ? { rest: true } : {} }
20584
+ });
20585
+ }
20586
+ };
20378
20587
  for (const b of [...boundaries.values()].sort((x, y) => cmp10(x.root, y.root))) {
20379
20588
  const units = b.kind === "repository" && packages.length === 0 ? folderUnits(b.files) : null;
20380
20589
  const repo = { kind: "repository", name: b.name, root: b.root };
@@ -20391,7 +20600,7 @@ function groups(input2) {
20391
20600
  files: u.files.map((f) => f.id)
20392
20601
  });
20393
20602
  } else if (u.files.length > threshold)
20394
- asClusters(u.files, { kind: "folder", name: u.root, root: u.root });
20603
+ split(u.files, { kind: "folder", name: u.root, root: u.root });
20395
20604
  else
20396
20605
  push({
20397
20606
  id: ids.cluster(plan.sourceId, u.root),
@@ -20406,7 +20615,7 @@ function groups(input2) {
20406
20615
  continue;
20407
20616
  }
20408
20617
  if (b.files.length > threshold) {
20409
- asClusters(b.files, { kind: b.kind, name: b.name, root: b.root });
20618
+ split(b.files, { kind: b.kind, name: b.name, root: b.root });
20410
20619
  continue;
20411
20620
  }
20412
20621
  push({
@@ -20450,6 +20659,33 @@ function folderUnits(files) {
20450
20659
  }
20451
20660
  return [...units].map(([root, list]) => ({ root, files: list })).sort((a, b) => cmp10(a.root, b.root));
20452
20661
  }
20662
+ function folderParts(files, root, threshold) {
20663
+ if (files.length <= threshold) return [{ root, files }];
20664
+ const min = Math.max(3, Math.ceil(threshold / 20));
20665
+ const prefix = root ? `${root}/` : "";
20666
+ const direct = [];
20667
+ const children = /* @__PURE__ */ new Map();
20668
+ for (const f of files) {
20669
+ const rel = f.path.slice(prefix.length);
20670
+ const slash = rel.indexOf("/");
20671
+ if (slash < 0) direct.push(f);
20672
+ else {
20673
+ const child = `${prefix}${rel.slice(0, slash)}`;
20674
+ children.set(child, [...children.get(child) ?? [], f]);
20675
+ }
20676
+ }
20677
+ const large = [...children].filter(([, list]) => list.length >= min).sort(([a], [b]) => cmp10(a, b));
20678
+ if (large.length === 0) return [{ root, files, connect: true }];
20679
+ const out = large.flatMap(([child, list]) => folderParts(list, child, threshold));
20680
+ const big = new Set(large.map(([child]) => child));
20681
+ const small = [...children].filter(([child]) => !big.has(child));
20682
+ const rest = files.filter((f) => !large.some(([child]) => f.path.startsWith(`${child}/`)));
20683
+ if (rest.length === 0) return out;
20684
+ if (direct.length === 0 && small.length === 1) out.push({ root: small[0][0], files: rest });
20685
+ else if (rest.length > threshold) out.push({ root, files: rest, connect: true });
20686
+ else out.push({ root, files: rest, rest: true });
20687
+ return out;
20688
+ }
20453
20689
  function clusters(files, imports, calls, fnFile) {
20454
20690
  const index = new Map(files.map((f, i) => [f.id, i]));
20455
20691
  const n2 = files.length;
@@ -20471,7 +20707,7 @@ function clusters(files, imports, calls, fnFile) {
20471
20707
  });
20472
20708
  let community = louvain(n2, edges);
20473
20709
  const touched = new Set(edges.flatMap((e) => [e.a, e.b]));
20474
- const dir = (i) => posix8.dirname(files[i].path);
20710
+ const dir = (i) => posix9.dirname(files[i].path);
20475
20711
  const folderCommunity = /* @__PURE__ */ new Map();
20476
20712
  for (let i = 0; i < n2; i++)
20477
20713
  if (touched.has(i) && !folderCommunity.has(dir(i))) folderCommunity.set(dir(i), community[i]);
@@ -22321,6 +22557,1048 @@ var init_together = __esm({
22321
22557
  }
22322
22558
  });
22323
22559
 
22560
+ // packages/stage2/src/python.ts
22561
+ import { posix as posix10 } from "node:path";
22562
+ function pythonProject(plan, forPath) {
22563
+ const roots = /* @__PURE__ */ new Set();
22564
+ const dependencies = /* @__PURE__ */ new Set();
22565
+ const dep = (spec) => {
22566
+ if (/^\s*(git\+|hg\+|svn\+|bzr\+|https?:|file:|\.|\/)/.test(spec)) return;
22567
+ const name = /^\s*([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(spec)?.[1];
22568
+ if (name) dependencies.add(normalize(name));
22569
+ };
22570
+ for (const m of plan.manifests) {
22571
+ const base2 = posix10.basename(m.path);
22572
+ const dir = posix10.dirname(m.path) === "." ? "" : posix10.dirname(m.path);
22573
+ if (forPath !== void 0 && dir && !forPath.startsWith(`${dir}/`)) continue;
22574
+ const at = (p) => posix10.normalize(posix10.join(dir, p)).replace(/^\.\/?$/, "").replace(/\/$/, "");
22575
+ if (base2 === "pyproject.toml") {
22576
+ roots.add(dir);
22577
+ let section = "";
22578
+ let inArray = null;
22579
+ const add2 = (kind, value) => {
22580
+ if (kind === "deps") for (const s of quoted(value)) dep(s);
22581
+ else if (kind === "roots") for (const s of quoted(value)) roots.add(at(s));
22582
+ else if (kind === "poetry")
22583
+ for (const from of value.matchAll(/from\s*=\s*["']([^"']+)["']/g)) roots.add(at(from[1]));
22584
+ else if (kind === "hatch") for (const s of quoted(value)) roots.add(at(posix10.dirname(s)));
22585
+ };
22586
+ for (const raw of m.content.split("\n")) {
22587
+ const line = raw.replace(/\s+#.*$/, "").trim();
22588
+ if (!line) continue;
22589
+ const header = /^\[\[?([^\]]+)\]\]?$/.exec(line);
22590
+ if (header) {
22591
+ section = header[1].trim();
22592
+ inArray = null;
22593
+ continue;
22594
+ }
22595
+ if (inArray) {
22596
+ add2(inArray, line);
22597
+ if (closes(line)) inArray = null;
22598
+ continue;
22599
+ }
22600
+ const kv = /^([A-Za-z0-9_.-]+|"[^"]*")\s*=\s*(.*)$/.exec(line);
22601
+ if (!kv) continue;
22602
+ const key = kv[1].replace(/"/g, "");
22603
+ const value = kv[2];
22604
+ const list = (kind) => {
22605
+ add2(kind, value);
22606
+ if (value.startsWith("[") && !closes(value)) inArray = kind;
22607
+ };
22608
+ if (section === "project" && key === "dependencies") list("deps");
22609
+ else if (section === "project.optional-dependencies" || section === "dependency-groups") list("deps");
22610
+ else if (section === "tool.setuptools.packages.find" && key === "where") list("roots");
22611
+ else if (section === "tool.setuptools.package-dir" && key === "")
22612
+ roots.add(at(quoted(value)[0] ?? ""));
22613
+ else if (/^tool\.poetry(\.group\.[^.]+)?\.(dev-)?dependencies$/.test(section) && key !== "python")
22614
+ dependencies.add(normalize(key));
22615
+ else if (section === "tool.poetry" && key === "packages") list("poetry");
22616
+ else if (section === "tool.hatch.build.targets.wheel" && key === "packages") list("hatch");
22617
+ }
22618
+ } else if (base2 === "setup.cfg") {
22619
+ roots.add(dir);
22620
+ let section = "";
22621
+ let key = "";
22622
+ for (const raw of m.content.split("\n")) {
22623
+ const header = /^\s*\[([^\]]+)\]/.exec(raw);
22624
+ if (header) {
22625
+ section = header[1].trim();
22626
+ key = "";
22627
+ continue;
22628
+ }
22629
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/.exec(raw);
22630
+ if (kv) {
22631
+ key = kv[1];
22632
+ if (section === "options" && key === "install_requires") dep(kv[2]);
22633
+ if (section === "options.packages.find" && key === "where" && kv[2].trim())
22634
+ roots.add(at(kv[2].trim()));
22635
+ if (section === "options" && key === "package_dir") {
22636
+ const d = /=\s*(\S+)/.exec(kv[2])?.[1];
22637
+ if (d) roots.add(at(d));
22638
+ }
22639
+ } else if (/^\s+\S/.test(raw) && section === "options" && key === "install_requires") dep(raw.trim());
22640
+ else if (/^\s+=\s*\S/.test(raw) && section === "options" && key === "package_dir")
22641
+ roots.add(at(raw.replace(/^\s+=\s*/, "").trim()));
22642
+ }
22643
+ } else if (base2 === "uv.lock" || base2 === "poetry.lock") {
22644
+ let name = null;
22645
+ let own2 = false;
22646
+ let table = "other";
22647
+ const flush = () => {
22648
+ if (name && !own2) dependencies.add(normalize(name));
22649
+ name = null;
22650
+ own2 = false;
22651
+ };
22652
+ for (const raw of m.content.split("\n")) {
22653
+ const line = raw.trim();
22654
+ if (line === "[[package]]") {
22655
+ flush();
22656
+ table = "package";
22657
+ } else if (line.startsWith("[")) table = line === "[package.source]" ? "source" : "other";
22658
+ else if (table === "package" && name === null && /^name\s*=/.test(line))
22659
+ name = /"([^"]+)"/.exec(line)?.[1] ?? null;
22660
+ else if (table === "package" && /^source\s*=\s*\{\s*(editable|virtual|directory)\s*=/.test(line))
22661
+ own2 = true;
22662
+ else if (table === "source" && /^type\s*=\s*"directory"/.test(line)) own2 = true;
22663
+ }
22664
+ flush();
22665
+ } else if (/^requirements[^/]*\.txt$/.test(base2)) {
22666
+ for (const raw of m.content.split("\n")) {
22667
+ const line = raw.replace(/(^|\s)#.*$/, "").trim();
22668
+ if (line && !line.startsWith("-")) dep(line);
22669
+ }
22670
+ }
22671
+ }
22672
+ roots.add("");
22673
+ return { roots: [...roots].sort((a, b) => b.length - a.length || (a < b ? -1 : 1)), dependencies };
22674
+ }
22675
+ function distribution(top, dependencies) {
22676
+ const plain2 = (d) => d.replace(/-/g, "");
22677
+ const n2 = normalize(top.replace(/^_+/, ""));
22678
+ for (const name of [normalize(DISTRIBUTIONS[top] ?? top), n2, `python-${n2}`])
22679
+ if (dependencies.has(name)) return name;
22680
+ return [...dependencies].find((d) => plain2(d) === plain2(n2)) ?? null;
22681
+ }
22682
+ function distributionByPrefix(top, dependencies) {
22683
+ const n2 = normalize(top);
22684
+ const found = [...dependencies].filter((d) => d.startsWith(`${n2}-`) || d === `${n2}io`).sort((a, b) => a.length - b.length || (a < b ? -1 : 1));
22685
+ return found[0] ?? null;
22686
+ }
22687
+ function moduleIndex(paths) {
22688
+ const files = new Set(paths.filter(isPython));
22689
+ const dirs = /* @__PURE__ */ new Set();
22690
+ for (const p of files)
22691
+ for (let d = posix10.dirname(p); d !== "." && d !== ""; d = posix10.dirname(d)) dirs.add(d);
22692
+ return { files, dirs };
22693
+ }
22694
+ function moduleFile(index, path) {
22695
+ const init = path ? `${path}/__init__.py` : "__init__.py";
22696
+ if (index.files.has(init)) return init;
22697
+ if (path && index.files.has(`${path}.py`)) return `${path}.py`;
22698
+ if (path && index.files.has(`${path}.pyi`)) return `${path}.pyi`;
22699
+ return null;
22700
+ }
22701
+ function moduleVariables(text) {
22702
+ const vars = /* @__PURE__ */ new Map();
22703
+ const code = text.replace(/("""|''')[\s\S]*?\1/g, (m) => m.replace(/[^\n]/g, " "));
22704
+ const set2 = (name, cls) => vars.set(name, vars.has(name) ? "" : cls);
22705
+ let block = null;
22706
+ for (const line of code.split("\n")) {
22707
+ if (!line.trim() || line.trim().startsWith("#")) continue;
22708
+ const indent = /^\s*/.exec(line)[0].length;
22709
+ if (indent === 0) {
22710
+ block = /^(if|elif|else|try|except|finally|with|for|while)\b/.test(line) ? -1 : null;
22711
+ } else if (block === -1) block = indent;
22712
+ const top = indent === 0 || block !== null && block > 0 && indent === block;
22713
+ if (!top) continue;
22714
+ const chain = /^\s*((?:[A-Za-z_]\w*\s*=(?!=)\s*)+)(.*)$/.exec(line);
22715
+ const annotated = /^\s*([A-Za-z_]\w*)\s*:\s*([^=]+?)\s*=(?!=)\s*(.*)$/.exec(line);
22716
+ if (annotated) {
22717
+ const written2 = annotated[2].trim().replace(/^["']|["']$/g, "");
22718
+ set2(annotated[1], indent === 0 && /^[A-Za-z_][\w.]*$/.test(written2) ? written2 : "");
22719
+ } else if (chain) {
22720
+ const names = [...chain[1].matchAll(/([A-Za-z_]\w*)\s*=/g)].map((m) => m[1]);
22721
+ const made = /^([A-Za-z_][\w.]*)\s*\(/.exec(chain[2] ?? "")?.[1];
22722
+ const cls = indent === 0 && made && /^[A-Z]/.test(made.split(".").at(-1)) ? made : "";
22723
+ for (const n2 of names) set2(n2, cls);
22724
+ }
22725
+ }
22726
+ return vars;
22727
+ }
22728
+ function optionalImport(text, line) {
22729
+ const lines = text.split("\n");
22730
+ const indent = (s) => /^\s*/.exec(s)[0].length;
22731
+ let own2 = indent(lines[line - 1] ?? "");
22732
+ for (let i = line - 2; i >= 0 && own2 > 0; i--) {
22733
+ const l = lines[i];
22734
+ if (!l.trim() || l.trim().startsWith("#")) continue;
22735
+ if (indent(l) >= own2) continue;
22736
+ own2 = indent(l);
22737
+ if (/^\s*(def|class|async\s+def)\b/.test(l)) return false;
22738
+ if (!/^\s*try\s*:/.test(l)) continue;
22739
+ for (let j = i + 1; j < lines.length; j++) {
22740
+ const k = lines[j];
22741
+ if (!k.trim() || k.trim().startsWith("#")) continue;
22742
+ if (indent(k) < own2) break;
22743
+ if (indent(k) !== own2) continue;
22744
+ if (!/^\s*except\b/.test(k)) {
22745
+ if (/^\s*(else|finally)\s*:/.test(k)) continue;
22746
+ break;
22747
+ }
22748
+ if (/\b(ImportError|ModuleNotFoundError|Exception|BaseException)\b/.test(k) || /^\s*except\s*:/.test(k))
22749
+ return true;
22750
+ }
22751
+ }
22752
+ return false;
22753
+ }
22754
+ function pythonResults(plans) {
22755
+ const out = /* @__PURE__ */ new Map();
22756
+ for (const plan of plans) {
22757
+ const files = plan.files.filter((f) => f.language === "python" && f.content !== void 0 && !f.skip);
22758
+ if (!files.length) continue;
22759
+ const response = extract({
22760
+ protocolVersion: PROTOCOL_VERSION,
22761
+ root: plan.root,
22762
+ manifests: [],
22763
+ files: files.map((f) => ({ path: f.path, language: f.language, content: f.content }))
22764
+ });
22765
+ for (const r of response.files) out.set(`${plan.sourceId}\0${r.path}`, r);
22766
+ }
22767
+ return out;
22768
+ }
22769
+ function resolvePythonImports(plans, files, results) {
22770
+ const resolved = [];
22771
+ const submodules = /* @__PURE__ */ new Set();
22772
+ const folders = /* @__PURE__ */ new Map();
22773
+ const packagesOf = /* @__PURE__ */ new Map();
22774
+ const packages = /* @__PURE__ */ new Map();
22775
+ const external = (source, ecosystem, name) => {
22776
+ const id = ids.externalPackage(source, ecosystem, name);
22777
+ let pkg = packages.get(id);
22778
+ if (!pkg)
22779
+ packages.set(id, pkg = { type: "ExternalPackage", id, source, ecosystem, name, version: null });
22780
+ return pkg;
22781
+ };
22782
+ for (const plan of plans) {
22783
+ const source = plan.sourceId;
22784
+ const fileNodes = files.filter((f) => f.source === source);
22785
+ const byPath = new Map(fileNodes.map((f) => [f.path, f]));
22786
+ const index = moduleIndex(fileNodes.map((f) => f.path));
22787
+ const projects = /* @__PURE__ */ new Map();
22788
+ const manifestDirs = [
22789
+ ...new Set(plan.manifests.map((m) => posix10.dirname(m.path) === "." ? "" : posix10.dirname(m.path)))
22790
+ ];
22791
+ const projectFor = (path) => {
22792
+ const key = manifestDirs.filter((d) => !d || path.startsWith(`${d}/`)).join("\0");
22793
+ let p = projects.get(key);
22794
+ if (!p) projects.set(key, p = pythonProject(plan, path));
22795
+ return p;
22796
+ };
22797
+ let project2 = projectFor("");
22798
+ const text = new Map(plan.files.filter((f) => f.content !== void 0).map((f) => [f.path, f.content]));
22799
+ const pathIn = (root, dotted) => {
22800
+ const p = posix10.join(root, ...dotted.split("."));
22801
+ return p === "." ? "" : p;
22802
+ };
22803
+ const absoluteFile = (dotted) => {
22804
+ for (const root of project2.roots) {
22805
+ const file2 = moduleFile(index, pathIn(root, dotted));
22806
+ if (file2) return { file: file2, root };
22807
+ }
22808
+ return null;
22809
+ };
22810
+ const absoluteDir = (dotted) => {
22811
+ for (const root of project2.roots) {
22812
+ const dir = pathIn(root, dotted);
22813
+ if (dir && index.dirs.has(dir)) return { dir, root };
22814
+ }
22815
+ return null;
22816
+ };
22817
+ for (const f of fileNodes) {
22818
+ if (f.language !== "python" || f.status === "not_analyzed") continue;
22819
+ const result2 = results.get(`${source}\0${f.path}`);
22820
+ if (!result2) continue;
22821
+ const fileId = f.id;
22822
+ project2 = projectFor(f.path);
22823
+ for (const s of statements(source, f.path, result2)) {
22824
+ let namespaceTarget2 = function(dir) {
22825
+ if (!isFrom) {
22826
+ const local = s.bindings[0]?.[1];
22827
+ if (local) folders.set(`${fileId}\0${local}`, dir);
22828
+ const first = [...index.files].filter((p) => posix10.dirname(p) === dir).sort()[0];
22829
+ return first ? toFile(first, "absolute") : {
22830
+ kind: "unresolved",
22831
+ outcome: "broken",
22832
+ reason: "file-not-found",
22833
+ steps: [
22834
+ ...steps,
22835
+ { kind: "namespace", detail: `${dir} is a namespace package with no module of its own` }
22836
+ ]
22837
+ };
22838
+ }
22839
+ return {
22840
+ kind: "unresolved",
22841
+ outcome: "broken",
22842
+ reason: "file-not-found",
22843
+ steps: [
22844
+ ...steps,
22845
+ {
22846
+ kind: "namespace",
22847
+ detail: `${dir || "the root"} is a namespace package; ${names.join(", ")} isn't a module in it`
22848
+ }
22849
+ ]
22850
+ };
22851
+ };
22852
+ var namespaceTarget = namespaceTarget2;
22853
+ const steps = [];
22854
+ const names = s.bindings.map(([imported]) => imported).filter((n2) => !!n2 && n2 !== "*");
22855
+ const isFrom = s.bindings.some(([imported]) => imported !== "*");
22856
+ const toFile = (path, via) => {
22857
+ const file2 = byPath.get(path);
22858
+ if (file2.status === "not_analyzed")
22859
+ return {
22860
+ kind: "unresolved",
22861
+ outcome: "not-analyzed",
22862
+ reason: file2.reason ?? "not-analyzed",
22863
+ steps: [...steps, { kind: "not-analyzed", detail: `${path} is not analyzed` }]
22864
+ };
22865
+ return { kind: "file", file: file2, via, steps };
22866
+ };
22867
+ const binds = (dir, name) => {
22868
+ const init = results.get(`${source}\0${dir ? `${dir}/` : ""}__init__.py`);
22869
+ return !!init && (init.definitions.some((d) => d.qualifiedName === name) || init.types.some((t) => t.name === name) || init.imports.some(
22870
+ (i) => i.localName === name && !(f.path === `${dir ? `${dir}/` : ""}__init__.py` && i.span.start.offset === s.span.start.offset)
22871
+ ));
22872
+ };
22873
+ const subs = (dir, via, namespace) => {
22874
+ if (!names.length || names.length !== s.bindings.length) return null;
22875
+ const found = names.map(
22876
+ (n2) => namespace || !binds(dir, n2) ? moduleFile(index, dir ? `${dir}/${n2}` : n2) : null
22877
+ );
22878
+ if (found.some((x) => x === null)) return null;
22879
+ if (names.length === 1) submodules.add(statementKey(s));
22880
+ else {
22881
+ folders.set(statementKey(s), dir);
22882
+ names.slice(1).forEach((n2, i) => {
22883
+ const spec = s.specifier.endsWith(".") ? `${s.specifier}${n2}` : `${s.specifier}.${n2}`;
22884
+ const file2 = byPath.get(found[i + 1]);
22885
+ resolved.push({
22886
+ statement: { ...s, specifier: spec, bindings: [[n2, s.bindings[i + 1][1]]], ordinal: 0 },
22887
+ target: file2.status === "not_analyzed" ? {
22888
+ kind: "unresolved",
22889
+ outcome: "not-analyzed",
22890
+ reason: file2.reason ?? "not-analyzed",
22891
+ steps: []
22892
+ } : {
22893
+ kind: "file",
22894
+ file: file2,
22895
+ via,
22896
+ steps: [{ kind: via, detail: `${n2} is the submodule ${found[i + 1]}` }]
22897
+ }
22898
+ });
22899
+ });
22900
+ }
22901
+ steps.push({
22902
+ kind: via,
22903
+ detail: `${names.join(", ")} ${names.length === 1 ? "is the submodule" : "are submodules, the first"} ${found[0]}`
22904
+ });
22905
+ return toFile(found[0], via);
22906
+ };
22907
+ const bindPackage = () => {
22908
+ if (isFrom || !s.specifier.includes(".")) return;
22909
+ const local = s.bindings[0]?.[1];
22910
+ const top = s.specifier.split(".")[0];
22911
+ if (local !== top) return;
22912
+ const file2 = absoluteFile(top);
22913
+ if (file2) packagesOf.set(`${fileId}\0${top}`, byPath.get(file2.file));
22914
+ else {
22915
+ const dir = absoluteDir(top);
22916
+ if (dir) folders.set(`${fileId}\0${top}`, dir.dir);
22917
+ }
22918
+ };
22919
+ let target2;
22920
+ if (s.specifier.startsWith(".")) {
22921
+ const level = /^\.+/.exec(s.specifier)[0].length;
22922
+ const rest = s.specifier.slice(level);
22923
+ let dir = posix10.dirname(f.path) === "." ? "" : posix10.dirname(f.path);
22924
+ for (let i = 1; i < level; i++) dir = posix10.dirname(dir) === "." ? "" : posix10.dirname(dir);
22925
+ const path = rest ? posix10.join(dir, ...rest.split(".")) : dir;
22926
+ steps.push({ kind: "relative", detail: `${s.specifier} from ${f.path} is ${path || "the root"}` });
22927
+ const file2 = moduleFile(index, path);
22928
+ if (file2)
22929
+ target2 = isFrom && file2.endsWith("__init__.py") && subs(path, "relative", false) || toFile(file2, "relative");
22930
+ else if (path === "" || index.dirs.has(path))
22931
+ target2 = isFrom && subs(path, "relative", true) || namespaceTarget2(path);
22932
+ else
22933
+ target2 = {
22934
+ kind: "unresolved",
22935
+ outcome: "broken",
22936
+ reason: "file-not-found",
22937
+ steps: [...steps, { kind: "not-found", detail: `no module ${path}` }]
22938
+ };
22939
+ } else {
22940
+ const top = s.specifier.split(".")[0];
22941
+ const found = absoluteFile(s.specifier);
22942
+ const dist = distribution(top, project2.dependencies);
22943
+ if (found) {
22944
+ steps.push({
22945
+ kind: "absolute",
22946
+ detail: `${s.specifier} is ${found.file}${found.root ? ` (under the root ${found.root})` : ""}`
22947
+ });
22948
+ const dir = pathIn(found.root, s.specifier);
22949
+ target2 = isFrom && found.file.endsWith("__init__.py") && subs(dir, "absolute", false) || toFile(found.file, "absolute");
22950
+ bindPackage();
22951
+ } else if (absoluteFile(top) && !absoluteDir(s.specifier)) {
22952
+ target2 = {
22953
+ kind: "unresolved",
22954
+ outcome: "broken",
22955
+ reason: "file-not-found",
22956
+ steps: [{ kind: "not-found", detail: `${top} is the project's, but it has no ${s.specifier}` }]
22957
+ };
22958
+ } else if (PYTHON_STDLIB.has(top)) {
22959
+ target2 = {
22960
+ kind: "package",
22961
+ pkg: external(source, "python", top),
22962
+ via: "stdlib",
22963
+ steps: [{ kind: "builtin", detail: `${top} is Python's standard library` }]
22964
+ };
22965
+ } else if (dist) {
22966
+ target2 = {
22967
+ kind: "package",
22968
+ pkg: external(source, "pypi", dist),
22969
+ via: "dependency",
22970
+ steps: [{ kind: "dependency", detail: `the project declares ${dist}` }]
22971
+ };
22972
+ } else if (absoluteDir(s.specifier)) {
22973
+ const ns = absoluteDir(s.specifier);
22974
+ steps.push({ kind: "absolute", detail: `${s.specifier} is the namespace package ${ns.dir}` });
22975
+ target2 = isFrom && subs(ns.dir, "absolute", true) || namespaceTarget2(ns.dir);
22976
+ bindPackage();
22977
+ } else if (distributionByPrefix(top, project2.dependencies)) {
22978
+ const name = distributionByPrefix(top, project2.dependencies);
22979
+ target2 = {
22980
+ kind: "package",
22981
+ pkg: external(source, "pypi", name),
22982
+ via: "dependency",
22983
+ steps: [{ kind: "dependency", detail: `the project declares ${name}, named after ${top}` }]
22984
+ };
22985
+ } else if (optionalImport(text.get(f.path) ?? "", s.span.start.line)) {
22986
+ const name = normalize(DISTRIBUTIONS[top] ?? top);
22987
+ target2 = {
22988
+ kind: "package",
22989
+ pkg: external(source, "pypi", name),
22990
+ via: "optional",
22991
+ steps: [{ kind: "optional", detail: `imported in a try whose handler catches ImportError` }]
22992
+ };
22993
+ } else
22994
+ target2 = {
22995
+ kind: "unresolved",
22996
+ outcome: "broken",
22997
+ reason: "unknown-package",
22998
+ steps: [{ kind: "not-found", detail: `nothing in the project or its dependencies is ${top}` }]
22999
+ };
23000
+ }
23001
+ if (target2) resolved.push({ statement: s, target: target2 });
23002
+ }
23003
+ }
23004
+ }
23005
+ return { resolved, submodules, folders, packages: packagesOf };
23006
+ }
23007
+ function linkPython(input2) {
23008
+ const fnByName = new Map(input2.functions.map((f) => [`${f.file}\0${f.qualifiedName}`, f]));
23009
+ const pathOf9 = (fileId) => fileId.slice(fileId.indexOf(":") + 1);
23010
+ const sourceOf7 = (fileId) => fileId.slice(0, fileId.indexOf(":"));
23011
+ const resultOf2 = (fileId) => input2.results.get(`${sourceOf7(fileId)}\0${pathOf9(fileId)}`);
23012
+ const statementsOf = /* @__PURE__ */ new Map();
23013
+ for (const r of input2.imports.resolved) {
23014
+ const list = statementsOf.get(r.statement.fileId) ?? [];
23015
+ list.push(r);
23016
+ statementsOf.set(r.statement.fileId, list);
23017
+ }
23018
+ const fileIds = new Set(input2.imports.resolved.map((r) => r.statement.fileId));
23019
+ for (const r of input2.imports.resolved) if (r.target.kind === "file") fileIds.add(r.target.file.id);
23020
+ const allOf = /* @__PURE__ */ new Map();
23021
+ const dunderAll = (fileId) => {
23022
+ if (allOf.has(fileId)) return allOf.get(fileId);
23023
+ const m = /^__all__\s*(?::[^=]+)?=\s*[[(]([^\])]*)[\])]/m.exec(input2.text(fileId) ?? "");
23024
+ const names = m ? [...m[1].matchAll(/["']([^"']+)["']/g)].map((x) => x[1]) : null;
23025
+ allOf.set(fileId, names);
23026
+ return names;
23027
+ };
23028
+ const step = (kind, detail) => ({ kind, detail });
23029
+ const missing = (stop, detail, hops = [], steps = []) => ({
23030
+ kind: "missing",
23031
+ stop,
23032
+ hops,
23033
+ steps: [...steps, step(stop, detail)]
23034
+ });
23035
+ const variables = /* @__PURE__ */ new Map();
23036
+ const variable = (fileId, name) => {
23037
+ let vars = variables.get(fileId);
23038
+ if (!vars) {
23039
+ vars = moduleVariables(input2.text(fileId) ?? "");
23040
+ variables.set(fileId, vars);
23041
+ }
23042
+ return vars.has(name) ? vars.get(name) : null;
23043
+ };
23044
+ const boundName = (fileId, name, hops) => {
23045
+ const key = `${fileId}\0${name}`;
23046
+ const pkg = input2.imports.packages.get(key);
23047
+ if (pkg)
23048
+ return {
23049
+ kind: "module",
23050
+ file: pkg.id,
23051
+ hops,
23052
+ steps: [step("package", `${name} is the package ${pkg.path}`)]
23053
+ };
23054
+ const dir = input2.imports.folders.get(key);
23055
+ if (dir !== void 0)
23056
+ return {
23057
+ kind: "folder",
23058
+ source: sourceOf7(fileId),
23059
+ dir,
23060
+ hops,
23061
+ steps: [step("namespace", `${name} is the namespace package ${dir || "at the root"}`)]
23062
+ };
23063
+ return null;
23064
+ };
23065
+ const folderMember = (source, dir, name, hops) => {
23066
+ const base2 = dir ? `${dir}/` : "";
23067
+ for (const candidate of [`${base2}${name}/__init__.py`, `${base2}${name}.py`]) {
23068
+ if (input2.results.has(`${source}\0${candidate}`))
23069
+ return {
23070
+ kind: "module",
23071
+ file: `${source}:${candidate}`,
23072
+ hops,
23073
+ steps: [step("submodule", `${name} is the submodule ${candidate}`)]
23074
+ };
23075
+ }
23076
+ return missing("not-exported", `${dir || "the root"} has no module ${name}`, hops);
23077
+ };
23078
+ const lookup = (fileId, name, hops, depth, star) => {
23079
+ const path = pathOf9(fileId);
23080
+ if (depth > MAX_DEPTH3) return missing("cycle", `${path} imports ${name} in a cycle`, hops);
23081
+ const result2 = resultOf2(fileId);
23082
+ if (!result2) return missing("not-found", `${path} was not read`, hops);
23083
+ if (star) {
23084
+ const all2 = dunderAll(fileId);
23085
+ if (all2 ? !all2.includes(name) : name.startsWith("_"))
23086
+ return missing(
23087
+ "not-exported",
23088
+ `${path}'s ${all2 ? "__all__" : "public names"} leave out ${name}`,
23089
+ hops
23090
+ );
23091
+ }
23092
+ const fn = fnByName.get(`${fileId}\0${name}`);
23093
+ if (fn)
23094
+ return { kind: "function", fn: fn.id, hops, steps: [step("definition", `${path} defines ${name}`)] };
23095
+ if (result2.types.some((t) => t.name === name))
23096
+ return {
23097
+ kind: "class",
23098
+ file: fileId,
23099
+ name,
23100
+ hops,
23101
+ steps: [step("definition", `${path} defines the class ${name}`)]
23102
+ };
23103
+ const value = variable(fileId, name);
23104
+ if (value !== null)
23105
+ return {
23106
+ kind: "value",
23107
+ file: fileId,
23108
+ name,
23109
+ cls: value,
23110
+ hops,
23111
+ steps: [step("value", `${path} assigns ${name}${value ? ` (${value})` : ""}`)]
23112
+ };
23113
+ if (hops.includes(fileId)) return missing("cycle", `${path} imports ${name} in a cycle`, hops);
23114
+ const statements2 = statementsOf.get(fileId) ?? [];
23115
+ for (const r of statements2) {
23116
+ const binding2 = r.statement.bindings.find(([, local]) => local === name);
23117
+ if (!binding2) continue;
23118
+ const imported = binding2[0];
23119
+ const via = step("re-export", `${path} imports ${name} from ${r.statement.specifier}`);
23120
+ if (imported === "*") {
23121
+ const ns = bindingAsModule(r);
23122
+ if (ns.kind === "folder") return { ...ns, hops };
23123
+ const t = r.target;
23124
+ if (t.kind === "package") return { kind: "external", pkg: t.pkg.id, hops, steps: [via, ...t.steps] };
23125
+ if (t.kind === "unresolved")
23126
+ return { kind: "unresolved", outcome: t.outcome, hops, steps: [via, ...t.steps] };
23127
+ return { kind: "module", file: t.file.id, hops: [...hops, fileId], steps: [via] };
23128
+ }
23129
+ const e = bindingOf(r, imported, [...hops, fileId], depth + 1);
23130
+ return { ...e, steps: [via, ...e.steps] };
23131
+ }
23132
+ for (const r of statements2) {
23133
+ if (!r.statement.bindings.some(([imported, local]) => imported === "*" && local === null)) continue;
23134
+ if (r.target.kind !== "file") continue;
23135
+ const e = lookup(r.target.file.id, name, [...hops, fileId], depth + 1, true);
23136
+ if (e.kind !== "missing")
23137
+ return {
23138
+ ...e,
23139
+ steps: [step("re-export", `${path} imports everything from ${r.statement.specifier}`), ...e.steps]
23140
+ };
23141
+ }
23142
+ const bound = boundName(fileId, name, hops);
23143
+ if (bound) return bound;
23144
+ if (path.endsWith("__init__.py")) {
23145
+ const dir = posix10.dirname(path);
23146
+ const base2 = dir === "." ? "" : `${dir}/`;
23147
+ for (const candidate of [`${base2}${name}.py`, `${base2}${name}/__init__.py`]) {
23148
+ const id = `${sourceOf7(fileId)}:${candidate}`;
23149
+ if (fileIds.has(id) || input2.results.has(`${sourceOf7(fileId)}\0${candidate}`))
23150
+ return {
23151
+ kind: "module",
23152
+ file: id,
23153
+ hops,
23154
+ steps: [step("submodule", `${name} is the submodule ${candidate}`)]
23155
+ };
23156
+ }
23157
+ }
23158
+ return missing("not-exported", `${path} defines or imports no ${name}`, hops);
23159
+ };
23160
+ const bindingOf = (r, imported, hops, depth) => {
23161
+ const t = r.target;
23162
+ if (t.kind === "package") return { kind: "external", pkg: t.pkg.id, hops, steps: [...t.steps] };
23163
+ if (t.kind === "unresolved") return { kind: "unresolved", outcome: t.outcome, hops, steps: [...t.steps] };
23164
+ if (input2.imports.submodules.has(statementKey(r.statement)))
23165
+ return { kind: "module", file: t.file.id, hops, steps: [...t.steps] };
23166
+ const dir = input2.imports.folders.get(statementKey(r.statement));
23167
+ if (dir !== void 0) return withSteps(folderMember(t.file.source, dir, imported, hops), [...t.steps]);
23168
+ const e = lookup(t.file.id, imported, hops, depth, false);
23169
+ return { ...e, steps: [...t.steps, ...e.steps] };
23170
+ };
23171
+ const classDecl = (c) => resultOf2(c.file)?.types.find((t) => t.name === c.name);
23172
+ const baseMemo = /* @__PURE__ */ new Map();
23173
+ const baseOf2 = (c, base2) => {
23174
+ const key = `${c.file}#${c.name}#${base2}`;
23175
+ let e = baseMemo.get(key);
23176
+ if (!e) baseMemo.set(key, e = baseOfUncached(c, base2));
23177
+ return e;
23178
+ };
23179
+ const baseOfUncached = (c, base2) => {
23180
+ const [head, ...rest] = base2.split(".");
23181
+ if (resultOf2(c.file)?.types.some((t) => t.name === base2))
23182
+ return { kind: "class", file: c.file, name: base2, hops: [], steps: [] };
23183
+ const r = (statementsOf.get(c.file) ?? []).find((s) => s.statement.bindings.some(([, l]) => l === head));
23184
+ let e;
23185
+ if (r) {
23186
+ const imported = r.statement.bindings.find(([, l]) => l === head)[0];
23187
+ e = imported === "*" ? bindingAsModule(r) : bindingOf(r, imported, [], 0);
23188
+ } else
23189
+ e = boundName(c.file, head, []) ?? missing("not-found", `${base2} isn't defined or imported in ${pathOf9(c.file)}`);
23190
+ for (const part of rest) {
23191
+ if (e.kind === "module") e = lookup(e.file, part, [], 0, false);
23192
+ else if (e.kind === "folder") e = folderMember(e.source, e.dir, part, []);
23193
+ else if (e.kind !== "external" && e.kind !== "unresolved")
23194
+ return missing("member", `${base2} can't be followed`);
23195
+ }
23196
+ return e;
23197
+ };
23198
+ const bindingAsModule = (r) => {
23199
+ const local = r.statement.bindings.find(([imported, l]) => imported === "*" && l)?.[1];
23200
+ const ns = local ? input2.imports.folders.get(`${r.statement.fileId}\0${local}`) : void 0;
23201
+ if (ns !== void 0)
23202
+ return {
23203
+ kind: "folder",
23204
+ source: sourceOf7(r.statement.fileId),
23205
+ dir: ns,
23206
+ hops: [],
23207
+ steps: [step("namespace", `${local} is the namespace package ${ns || "at the root"}`)]
23208
+ };
23209
+ const t = r.target;
23210
+ if (t.kind === "package") return { kind: "external", pkg: t.pkg.id, hops: [], steps: [...t.steps] };
23211
+ if (t.kind === "unresolved")
23212
+ return { kind: "unresolved", outcome: t.outcome, hops: [], steps: [...t.steps] };
23213
+ return { kind: "module", file: t.file.id, hops: [], steps: [...t.steps] };
23214
+ };
23215
+ const methodOf = (c, m, seen = /* @__PURE__ */ new Set()) => {
23216
+ const key = `${c.file}#${c.name}`;
23217
+ if (seen.has(key)) return null;
23218
+ seen.add(key);
23219
+ const decl = classDecl(c);
23220
+ if (!decl) return null;
23221
+ const own2 = [...decl.members, ...decl.statics ?? []].find((x) => x.name === m);
23222
+ if (own2?.function) {
23223
+ const fn = fnByName.get(`${c.file}\0${own2.function}`);
23224
+ if (fn) return { fn, definer: c };
23225
+ }
23226
+ if (m === "__init__") {
23227
+ const fn = fnByName.get(`${c.file}\0${c.name}.__init__`);
23228
+ if (fn && !fn.implicit) return { fn, definer: c };
23229
+ }
23230
+ if (own2) return null;
23231
+ let pkg = null;
23232
+ for (const b of decl.bases) {
23233
+ const e = baseOf2(c, b.name);
23234
+ if (e.kind === "class") {
23235
+ const found = methodOf(e, m, seen);
23236
+ if (found && "fn" in found) return found;
23237
+ if (found && "pkg" in found) pkg ??= found.pkg;
23238
+ } else if (e.kind === "external") pkg ??= e.pkg;
23239
+ }
23240
+ return pkg ? { pkg } : null;
23241
+ };
23242
+ const constructorOf = (c) => {
23243
+ const found = methodOf(c, "__init__");
23244
+ if (found && "fn" in found) return found.fn;
23245
+ return fnByName.get(`${c.file}\0${c.name}.__init__`);
23246
+ };
23247
+ let classes = null;
23248
+ const allClasses = () => {
23249
+ if (classes) return classes;
23250
+ const out = [];
23251
+ for (const [key, result2] of input2.results) {
23252
+ if (result2.language !== "python") continue;
23253
+ const fileId = ids.file(key.slice(0, key.indexOf("\0")), key.slice(key.indexOf("\0") + 1));
23254
+ for (const decl of result2.types) out.push({ file: fileId, decl });
23255
+ }
23256
+ return classes = out.sort(
23257
+ (a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : a.decl.span.start.offset - b.decl.span.start.offset
23258
+ );
23259
+ };
23260
+ const ancestors2 = /* @__PURE__ */ new Map();
23261
+ const ancestorsOf = (c) => {
23262
+ const key = `${c.file}#${c.name}`;
23263
+ const known = ancestors2.get(key);
23264
+ if (known) return known;
23265
+ const out = /* @__PURE__ */ new Set([key]);
23266
+ ancestors2.set(key, out);
23267
+ for (const b of classDecl(c)?.bases ?? []) {
23268
+ const e = baseOf2(c, b.name);
23269
+ if (e.kind === "class") for (const a of ancestorsOf(e)) out.add(a);
23270
+ }
23271
+ return out;
23272
+ };
23273
+ const reaches = (c, target2) => ancestorsOf(c).has(`${target2.file}#${target2.name}`);
23274
+ const evidence = (file2, span) => ({
23275
+ file: file2,
23276
+ span,
23277
+ commit: input2.revisions.get(sourceOf7(file2)) ?? ""
23278
+ });
23279
+ const baseClause = (file2, decl, base2) => {
23280
+ const b = decl.bases.find((x) => x.name === base2);
23281
+ if (!b) return null;
23282
+ const text = input2.text(file2);
23283
+ if (!text) return b.span;
23284
+ const bytes = Buffer.from(text, "utf8");
23285
+ const open3 = bytes.lastIndexOf(40, b.span.start.offset);
23286
+ const close = bytes.indexOf(41, decl.bases.at(-1).span.end.offset);
23287
+ if (open3 < decl.span.start.offset || close < 0) return b.span;
23288
+ const pos = (offset) => {
23289
+ const before = bytes.subarray(0, offset).toString("utf8");
23290
+ const line = before.split("\n").length;
23291
+ const column = [...before.slice(before.lastIndexOf("\n") + 1)].length + 1;
23292
+ return { line, column, offset };
23293
+ };
23294
+ return { start: pos(open3), end: pos(close + 1) };
23295
+ };
23296
+ const candidateMemo = /* @__PURE__ */ new Map();
23297
+ const typedCandidates = (c, m) => {
23298
+ const key = `${c.file}#${c.name}#${m}`;
23299
+ let found = candidateMemo.get(key);
23300
+ if (!found) candidateMemo.set(key, found = typedCandidatesOf(c, m));
23301
+ return found;
23302
+ };
23303
+ const typedCandidatesOf = (c, m) => {
23304
+ const bodies = /* @__PURE__ */ new Map();
23305
+ for (const { file: file2, decl } of allClasses()) {
23306
+ const cls = { file: file2, name: decl.name };
23307
+ if (!reaches(cls, c)) continue;
23308
+ const body = methodOf(cls, m);
23309
+ if (!body || !("fn" in body) || bodies.has(body.fn.id)) continue;
23310
+ const own2 = body.definer.file === c.file && body.definer.name === c.name;
23311
+ let basis;
23312
+ if (own2) basis = evidence(body.fn.file, body.fn.evidence.span);
23313
+ else {
23314
+ const definerDecl = classDecl(body.definer);
23315
+ const parent = definerDecl.bases.find((b) => {
23316
+ const e = baseOf2(body.definer, b.name);
23317
+ return e.kind === "class" && reaches(e, c);
23318
+ });
23319
+ const span = parent ? baseClause(body.definer.file, definerDecl, parent.name) : null;
23320
+ basis = evidence(body.definer.file, span ?? definerDecl.span);
23321
+ }
23322
+ bodies.set(body.fn.id, { fn: body.fn, basis });
23323
+ }
23324
+ return [...bodies.values()].sort(
23325
+ (a, b) => a.fn.file < b.fn.file ? -1 : a.fn.file > b.fn.file ? 1 : a.fn.evidence.span.start.offset - b.fn.evidence.span.start.offset
23326
+ );
23327
+ };
23328
+ const memberOf = (e, m) => {
23329
+ const found = methodOf(e, m);
23330
+ return found && "fn" in found ? {
23331
+ kind: "function",
23332
+ fn: found.fn.id,
23333
+ hops: e.hops,
23334
+ steps: [...e.steps, step("instance", `${e.name}'s ${m} is ${found.fn.qualifiedName}`)]
23335
+ } : found && "pkg" in found ? { kind: "external", pkg: found.pkg, hops: e.hops, steps: e.steps } : missing("member", `no class up ${e.name}'s chain declares ${m}`, e.hops, e.steps);
23336
+ };
23337
+ const classNamed = (fileId, name) => {
23338
+ const [head] = name.split(".");
23339
+ if (resultOf2(fileId)?.types.some((t) => t.name === name))
23340
+ return { kind: "class", file: fileId, name, hops: [], steps: [] };
23341
+ const r = (statementsOf.get(fileId) ?? []).find((s) => s.statement.bindings.some(([, l]) => l === head));
23342
+ if (!r) return missing("not-found", `${name} isn't defined or imported here`);
23343
+ return baseOf2({ file: fileId, name: "" }, name);
23344
+ };
23345
+ const resolutions = [];
23346
+ const edges = [];
23347
+ for (const site of input2.sites) {
23348
+ const base2 = {
23349
+ type: "SiteResolution",
23350
+ id: ids.resolution(site.id),
23351
+ site: site.id,
23352
+ file: site.file,
23353
+ evidence: site.evidence
23354
+ };
23355
+ if (site.reason === "dynamic-dispatch") {
23356
+ const table = /^([A-Za-z_]\w*)\[/.exec(site.expression)?.[1];
23357
+ if (table) {
23358
+ const tables = (resultOf2(site.file)?.tables ?? []).filter((t) => t.name === table);
23359
+ if (tables.length === 1) {
23360
+ const t = tables[0];
23361
+ const candidates = t.entries.flatMap((e2) => {
23362
+ const fn = e2.function ? fnByName.get(`${site.file}\0${e2.function}`) : void 0;
23363
+ return fn ? [{ function: fn.id, basis: evidence(site.file, e2.span) }] : [];
23364
+ });
23365
+ if (candidates.length)
23366
+ resolutions.push({
23367
+ ...base2,
23368
+ status: "unresolved",
23369
+ target: null,
23370
+ externalPackage: null,
23371
+ importOutcome: null,
23372
+ steps: [step("table", `${table} is a dict of functions; the call runs one of its values`)],
23373
+ candidates,
23374
+ ...t.exhaustive ? {} : { exhaustive: false }
23375
+ });
23376
+ }
23377
+ continue;
23378
+ }
23379
+ const raw = resultOf2(site.file)?.unresolved.find(
23380
+ (u) => u.site.start.offset === site.evidence.span.start.offset && u.expression === site.expression
23381
+ );
23382
+ if (raw?.receiverType && raw.member) {
23383
+ const c = classNamed(site.file, raw.receiverType);
23384
+ if (c.kind !== "class") continue;
23385
+ const found = typedCandidates(c, raw.member);
23386
+ if (found.length)
23387
+ resolutions.push({
23388
+ ...base2,
23389
+ status: "unresolved",
23390
+ target: null,
23391
+ externalPackage: null,
23392
+ importOutcome: null,
23393
+ steps: [step("typed", `${site.expression}'s receiver is annotated ${raw.receiverType}`)],
23394
+ candidates: found.map((x) => ({ function: x.fn.id, basis: x.basis })),
23395
+ exhaustive: false
23396
+ });
23397
+ }
23398
+ continue;
23399
+ }
23400
+ if (site.reason !== "imported-symbol" || !site.importSpecifier) continue;
23401
+ const local = /^[A-Za-z_]\w*/.exec(site.expression)?.[0] ?? "";
23402
+ const inherited = /^(self|cls)\./.test(site.expression) || site.expression.startsWith("super()");
23403
+ const statements2 = (statementsOf.get(site.file) ?? []).filter(
23404
+ (r) => r.statement.specifier === site.importSpecifier
23405
+ );
23406
+ const statement = inherited ? statements2.find(
23407
+ (r) => r.statement.bindings.some(
23408
+ ([imported, l]) => (imported ?? l) === site.importedName || l === site.importedName
23409
+ )
23410
+ ) ?? statements2.find((r) => r.statement.bindings.some(([imported]) => imported === "*")) : statements2.find((r) => r.statement.bindings.some(([, l]) => l === local)) ?? // A method on an instance of an imported class (`a = A(); a.run()`): the binding of A.
23411
+ statements2.find(
23412
+ (r) => r.statement.bindings.some(
23413
+ ([imported, l]) => l === site.importedName || imported === site.importedName
23414
+ )
23415
+ ) ?? statements2[0];
23416
+ let e;
23417
+ if (inherited) {
23418
+ const name = site.importedName;
23419
+ const b = statement?.statement.bindings.find(
23420
+ ([imported, l]) => (l === name || imported === name) && imported !== "*"
23421
+ );
23422
+ e = !statement ? missing("not-found", `no import of ${site.importSpecifier} in this file`) : b ? bindingOf(statement, b[0], [], 0) : bindingAsModule(statement);
23423
+ if (e.kind === "module") e = withSteps(lookup(e.file, name, e.hops, 0, false), e.steps);
23424
+ else if (e.kind === "folder") e = folderMember(e.source, e.dir, name, e.hops);
23425
+ } else {
23426
+ const dotted = (statementsOf.get(site.file) ?? []).find(
23427
+ (r) => r.statement.specifier.startsWith(`${site.importSpecifier}.`) && r.statement.bindings.some(([imported, l]) => imported === "*" && l === local) && r.target.kind === "package"
23428
+ );
23429
+ if (!statement)
23430
+ e = boundName(site.file, local, []) ?? (dotted ? bindingAsModule(dotted) : missing("not-found", `no import of ${site.importSpecifier} in this file`));
23431
+ else {
23432
+ const binding2 = statement.statement.bindings.find(([, l]) => l === local) ?? statement.statement.bindings.find(
23433
+ ([imported, l]) => l === site.importedName || imported === site.importedName
23434
+ ) ?? statement.statement.bindings[0];
23435
+ e = binding2[0] === "*" ? bindingAsModule(statement) : bindingOf(statement, binding2[0], [], 0);
23436
+ }
23437
+ if (!statement || statement.statement.bindings.some(([imported, l]) => imported === "*" && l === local)) {
23438
+ if (site.importedName && e.kind === "module")
23439
+ e = withSteps(lookup(e.file, site.importedName, e.hops, 0, false), e.steps);
23440
+ else if (site.importedName && e.kind === "folder")
23441
+ e = folderMember(e.source, e.dir, site.importedName, e.hops);
23442
+ }
23443
+ }
23444
+ let called = !site.member;
23445
+ if (site.member && (e.kind === "module" || e.kind === "folder")) {
23446
+ e = e.kind === "module" ? withSteps(lookup(e.file, site.member, e.hops, 0, false), e.steps) : folderMember(e.source, e.dir, site.member, e.hops);
23447
+ called = true;
23448
+ } else if (site.member && e.kind === "value") {
23449
+ const v = e;
23450
+ const cls = v.cls ? classNamed(v.file, v.cls) : null;
23451
+ e = !cls ? missing(
23452
+ "member",
23453
+ `${v.name} is a variable of ${pathOf9(v.file)}; what it holds isn't followed`,
23454
+ v.hops,
23455
+ v.steps
23456
+ ) : cls.kind === "class" || cls.kind === "external" || cls.kind === "unresolved" ? { ...cls, hops: v.hops, steps: [...v.steps, ...cls.steps] } : missing("member", `${v.name} holds a ${v.cls}, which can't be followed`, v.hops, v.steps);
23457
+ if (e.kind === "class") e = memberOf(e, site.member);
23458
+ } else if (site.member && e.kind === "class") e = memberOf(e, site.member);
23459
+ else if (site.member && e.kind === "function")
23460
+ e = missing(
23461
+ "member",
23462
+ `${site.expression} calls a member of what ${local} names, a function`,
23463
+ e.hops,
23464
+ e.steps
23465
+ );
23466
+ if (called) {
23467
+ if (e.kind === "class") {
23468
+ const ctor = constructorOf(e);
23469
+ e = ctor ? {
23470
+ kind: "function",
23471
+ fn: ctor.id,
23472
+ hops: e.hops,
23473
+ steps: [...e.steps, step("constructor", `calling ${e.name} runs ${ctor.qualifiedName}`)]
23474
+ } : missing("not-a-function", `${e.name} has no constructor Stage 2 can follow`, e.hops, e.steps);
23475
+ } else if (e.kind === "module" || e.kind === "folder")
23476
+ e = missing("not-a-function", `${site.expression} is a module`, e.hops, e.steps);
23477
+ else if (e.kind === "value")
23478
+ e = missing(
23479
+ "not-a-function",
23480
+ `${e.name} is a variable of ${pathOf9(e.file)}, not a function Stage 2 follows`,
23481
+ e.hops,
23482
+ e.steps
23483
+ );
23484
+ }
23485
+ const via = inherited ? "inherited" : "import";
23486
+ e = withSteps(e, [
23487
+ step(
23488
+ "import",
23489
+ inherited ? `${site.expression} reaches ${site.importedName}, a base imported from ${site.importSpecifier}` : `${site.expression} goes through the import of ${site.importSpecifier}`
23490
+ )
23491
+ ]);
23492
+ switch (e.kind) {
23493
+ case "function":
23494
+ resolutions.push({
23495
+ ...base2,
23496
+ status: "linked",
23497
+ target: e.fn,
23498
+ externalPackage: null,
23499
+ via,
23500
+ importOutcome: null,
23501
+ steps: e.steps,
23502
+ hops: e.hops
23503
+ });
23504
+ edges.push({
23505
+ type: "CALLS_CROSS_FILE",
23506
+ id: ids.linkedCall(site.id),
23507
+ from: site.enclosingFn,
23508
+ to: e.fn,
23509
+ form: "plain",
23510
+ resolution: "static-exact",
23511
+ confidence: 1,
23512
+ evidence: site.evidence,
23513
+ via: "import"
23514
+ });
23515
+ break;
23516
+ case "external":
23517
+ resolutions.push({
23518
+ ...base2,
23519
+ status: "external",
23520
+ target: null,
23521
+ externalPackage: e.pkg,
23522
+ importOutcome: null,
23523
+ steps: e.steps
23524
+ });
23525
+ break;
23526
+ case "unresolved":
23527
+ resolutions.push({
23528
+ ...base2,
23529
+ status: "unresolved",
23530
+ target: null,
23531
+ externalPackage: null,
23532
+ importOutcome: e.outcome,
23533
+ steps: e.steps
23534
+ });
23535
+ break;
23536
+ default:
23537
+ resolutions.push({
23538
+ ...base2,
23539
+ status: "unresolved",
23540
+ target: null,
23541
+ externalPackage: null,
23542
+ importOutcome: null,
23543
+ steps: e.steps
23544
+ });
23545
+ }
23546
+ }
23547
+ return { resolutions, edges };
23548
+ function withSteps(e, before) {
23549
+ return { ...e, steps: [...before, ...e.steps] };
23550
+ }
23551
+ }
23552
+ var PYTHON_STDLIB, DISTRIBUTIONS, normalize, isPython, quoted, closes, statementKey, MAX_DEPTH3;
23553
+ var init_python = __esm({
23554
+ "packages/stage2/src/python.ts"() {
23555
+ "use strict";
23556
+ init_src();
23557
+ init_src3();
23558
+ init_protocol();
23559
+ init_imports();
23560
+ PYTHON_STDLIB = new Set(
23561
+ "abc aifc argparse array ast asynchat asyncio asyncore atexit audioop base64 bdb binascii bisect builtins bz2 cProfile calendar cgi cgitb chunk cmath cmd code codecs codeop collections colorsys compileall concurrent configparser contextlib contextvars copy copyreg crypt csv ctypes curses dataclasses datetime dbm decimal difflib dis distutils doctest email encodings ensurepip enum errno faulthandler fcntl filecmp fileinput fnmatch fractions ftplib functools gc genericpath getopt getpass gettext glob graphlib grp gzip hashlib heapq hmac html http idlelib imaplib imghdr imp importlib inspect io ipaddress itertools json keyword lib2to3 linecache locale logging lzma mailbox mailcap marshal math mimetypes mmap modulefinder msilib msvcrt multiprocessing netrc nis nntplib ntpath nturl2path numbers opcode operator optparse os ossaudiodev pathlib pdb pickle pickletools pipes pkgutil platform plistlib poplib posix posixpath pprint profile pstats pty pwd py_compile pyclbr pydoc pydoc_data pyexpat queue quopri random re readline reprlib resource rlcompleter runpy sched secrets select selectors shelve shlex shutil signal site smtpd smtplib sndhdr socket socketserver spwd sqlite3 sre_compile sre_constants sre_parse ssl stat statistics string stringprep struct subprocess sunau symtable sys sysconfig syslog tabnanny tarfile telnetlib tempfile termios textwrap this threading time timeit tkinter token tokenize tomllib trace traceback tracemalloc tty turtle turtledemo types typing unicodedata unittest urllib uu uuid venv warnings wave weakref webbrowser winreg winsound wsgiref xdrlib xml xmlrpc zipapp zipfile zipimport zlib zoneinfo __future__ _thread typing_extensions".split(" ")
23562
+ );
23563
+ DISTRIBUTIONS = {
23564
+ yaml: "pyyaml",
23565
+ PIL: "pillow",
23566
+ sklearn: "scikit-learn",
23567
+ bs4: "beautifulsoup4",
23568
+ cv2: "opencv-python",
23569
+ dateutil: "python-dateutil",
23570
+ jwt: "pyjwt",
23571
+ dotenv: "python-dotenv",
23572
+ magic: "python-magic",
23573
+ attr: "attrs",
23574
+ google: "google",
23575
+ jose: "python-jose",
23576
+ multipart: "python-multipart",
23577
+ slugify: "python-slugify",
23578
+ Crypto: "pycryptodome",
23579
+ OpenSSL: "pyopenssl",
23580
+ serial: "pyserial",
23581
+ usb: "pyusb",
23582
+ zmq: "pyzmq",
23583
+ psycopg2: "psycopg2-binary",
23584
+ MySQLdb: "mysqlclient",
23585
+ grpc: "grpcio",
23586
+ qcloud_cos: "cos-python-sdk-v5",
23587
+ baidubce: "bce-python-sdk",
23588
+ obs: "esdk-obs-python",
23589
+ Tea: "alibabacloud-tea",
23590
+ docx: "python-docx",
23591
+ pptx: "python-pptx"
23592
+ };
23593
+ normalize = (name) => name.toLowerCase().replace(/[-_.]+/g, "-");
23594
+ isPython = (path) => path.endsWith(".py") || path.endsWith(".pyi");
23595
+ quoted = (value) => [...value.replace(/\{[^}]*\}/g, "").matchAll(/["']([^"']*)["']/g)].map((m) => m[1]);
23596
+ closes = (line) => line.replace(/"[^"]*"|'[^']*'/g, "").includes("]");
23597
+ statementKey = (s) => `${s.fileId}\0${s.span.start.offset}\0${s.specifier}`;
23598
+ MAX_DEPTH3 = 32;
23599
+ }
23600
+ });
23601
+
22324
23602
  // packages/stage2/src/index.ts
22325
23603
  function scopeOf2(fact) {
22326
23604
  switch (fact.type) {
@@ -22407,14 +23685,31 @@ async function runStage2(ctx, options2 = {}) {
22407
23685
  }
22408
23686
  await step(1, "resolving imports", () => files.length, "files");
22409
23687
  const { resolved, results } = resolveImports2(ctx.plans, files);
22410
- const { edges, unresolved, packages } = importFacts(resolved);
23688
+ const pyResults = pythonResults(ctx.plans);
23689
+ const pyImports = resolvePythonImports(ctx.plans, files, pyResults);
23690
+ const { edges, unresolved, packages } = importFacts([...resolved, ...pyImports.resolved]);
23691
+ const pyFiles = new Set(files.filter((f) => f.language === "python").map((f) => f.id));
23692
+ const allSites = view.facts("UnresolvedCallSite");
22411
23693
  const linkInput = {
22412
23694
  resolved,
22413
23695
  results,
22414
23696
  functions: view.facts("Function"),
22415
- sites: view.facts("UnresolvedCallSite"),
23697
+ sites: allSites.filter((s) => !pyFiles.has(s.file)),
22416
23698
  revisions: new Map(ctx.plans.map((p) => [p.sourceId, p.revision]))
22417
23699
  };
23700
+ const pyText = new Map(
23701
+ ctx.plans.flatMap(
23702
+ (p) => p.files.filter((f) => f.content !== void 0 && f.language === "python").map((f) => [ids.file(p.sourceId, f.path), f.content])
23703
+ )
23704
+ );
23705
+ const pyLinked = linkPython({
23706
+ imports: pyImports,
23707
+ results: pyResults,
23708
+ functions: linkInput.functions,
23709
+ sites: allSites.filter((s) => pyFiles.has(s.file)),
23710
+ revisions: linkInput.revisions,
23711
+ text: (id) => pyText.get(id)
23712
+ });
22418
23713
  await step(2, "linking calls", () => linkInput.sites.length, "call sites");
22419
23714
  const graph = typeGraph(linkInput);
22420
23715
  const linked = link(linkInput, graph);
@@ -22542,6 +23837,7 @@ async function runStage2(ctx, options2 = {}) {
22542
23837
  // Stage 2's links and R1's template links.
22543
23838
  calls: [
22544
23839
  ...linked.edges,
23840
+ ...pyLinked.edges,
22545
23841
  ...typed.edges,
22546
23842
  ...injected.edges,
22547
23843
  ...returned.edges,
@@ -22569,6 +23865,8 @@ async function runStage2(ctx, options2 = {}) {
22569
23865
  ...packages,
22570
23866
  ...kept,
22571
23867
  ...named.resolutions,
23868
+ ...pyLinked.resolutions,
23869
+ ...pyLinked.edges,
22572
23870
  ...typed.edges,
22573
23871
  ...injected.edges,
22574
23872
  ...returned.edges,
@@ -22614,6 +23912,7 @@ var init_src8 = __esm({
22614
23912
  init_types();
22615
23913
  init_typegraph();
22616
23914
  init_together();
23915
+ init_python();
22617
23916
  init_imports();
22618
23917
  init_link();
22619
23918
  init_candidates();
@@ -22627,7 +23926,7 @@ var init_src8 = __esm({
22627
23926
  symbolsScope = (fileId) => `${STAGE23}:symbols:${fileId}`;
22628
23927
  groupSource = (groupId) => groupId.split("|")[1];
22629
23928
  STEPS = 5;
22630
- STAGE2_VERSION = 8;
23929
+ STAGE2_VERSION = 10;
22631
23930
  stage2 = createStage2();
22632
23931
  }
22633
23932
  });
@@ -53576,8 +54875,8 @@ var require_resolve = __commonJS({
53576
54875
  }
53577
54876
  return count2;
53578
54877
  }
53579
- function getFullPath(resolver, id = "", normalize2) {
53580
- if (normalize2 !== false)
54878
+ function getFullPath(resolver, id = "", normalize3) {
54879
+ if (normalize3 !== false)
53581
54880
  id = normalizeId(id);
53582
54881
  const p = resolver.parse(id);
53583
54882
  return _getFullPath(resolver, p);
@@ -55172,7 +56471,7 @@ var require_fast_uri = __commonJS({
55172
56471
  }
55173
56472
  return decodedScheme;
55174
56473
  }
55175
- function normalize2(uri, options2) {
56474
+ function normalize3(uri, options2) {
55176
56475
  if (typeof uri === "string") {
55177
56476
  uri = /** @type {T} */
55178
56477
  normalizeString(uri, options2);
@@ -55550,7 +56849,7 @@ var require_fast_uri = __commonJS({
55550
56849
  }
55551
56850
  var fastUri = {
55552
56851
  SCHEMES,
55553
- normalize: normalize2,
56852
+ normalize: normalize3,
55554
56853
  resolve: resolve9,
55555
56854
  resolveComponent,
55556
56855
  equal,
@@ -60771,7 +62070,11 @@ var init_server3 = __esm({
60771
62070
  offset: external_exports.number().int().optional().describe("Skip this many first (paging; default 0); `total` counts them all"),
60772
62071
  grouping: external_exports.enum(GROUPINGS).optional().describe(
60773
62072
  "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"
60774
- )
62073
+ ),
62074
+ groupBy: external_exports.enum(["cause"]).optional().describe(
62075
+ "cause: one row per cause (#405), the first of its findings with `cause` {key, target, source, count, files}; a cause is one source's: an import's cause is what it failed to reach (a relative one as the path it names), an open call's its text. total, offset and limit then count causes; counts still count findings"
62076
+ ),
62077
+ cause: external_exports.string().optional().describe("Only the findings of this cause: a row's `cause.key` (#405)")
60775
62078
  },
60776
62079
  call: (e, a, cwd) => listFindings(e, a, cwd)
60777
62080
  },
@@ -65540,7 +66843,7 @@ var require_send = __commonJS({
65540
66843
  var { createHttpError } = require_createHttpError();
65541
66844
  var extname = path.extname;
65542
66845
  var join14 = path.join;
65543
- var normalize2 = path.normalize;
66846
+ var normalize3 = path.normalize;
65544
66847
  var resolve9 = path.resolve;
65545
66848
  var sep9 = path.sep;
65546
66849
  var Readable = stream.Readable;
@@ -65619,20 +66922,20 @@ var require_send = __commonJS({
65619
66922
  let parts;
65620
66923
  if (root !== null) {
65621
66924
  if (path2) {
65622
- path2 = normalize2("." + sep9 + path2);
66925
+ path2 = normalize3("." + sep9 + path2);
65623
66926
  }
65624
66927
  if (UP_PATH_REGEXP.test(path2)) {
65625
66928
  debug('malicious path "%s"', path2);
65626
66929
  return { statusCode: 403 };
65627
66930
  }
65628
66931
  parts = path2.split(sep9);
65629
- path2 = normalize2(join14(root, path2));
66932
+ path2 = normalize3(join14(root, path2));
65630
66933
  } else {
65631
66934
  if (UP_PATH_REGEXP.test(path2)) {
65632
66935
  debug('malicious path "%s"', path2);
65633
66936
  return { statusCode: 403 };
65634
66937
  }
65635
- parts = normalize2(path2).split(sep9);
66938
+ parts = normalize3(path2).split(sep9);
65636
66939
  path2 = resolve9(path2);
65637
66940
  }
65638
66941
  return { path: path2, parts };
@@ -84660,11 +85963,11 @@ var require_pino = __commonJS({
84660
85963
  depthLimit: 5,
84661
85964
  edgeLimit: 100
84662
85965
  };
84663
- var normalize2 = createArgsNormalizer(defaultOptions2);
85966
+ var normalize3 = createArgsNormalizer(defaultOptions2);
84664
85967
  var serializers = Object.assign(/* @__PURE__ */ Object.create(null), stdSerializers);
84665
85968
  function pino(...args) {
84666
85969
  const instance = {};
84667
- const { opts, stream } = normalize2(instance, caller(), ...args);
85970
+ const { opts, stream } = normalize3(instance, caller(), ...args);
84668
85971
  if (opts.level && typeof opts.level === "string" && DEFAULT_LEVELS[opts.level.toLowerCase()] !== void 0) opts.level = opts.level.toLowerCase();
84669
85972
  const {
84670
85973
  redact: redact2,
@@ -91100,7 +92403,7 @@ var require_fast_uri2 = __commonJS({
91100
92403
  }
91101
92404
  return decodedScheme;
91102
92405
  }
91103
- function normalize2(uri, options2) {
92406
+ function normalize3(uri, options2) {
91104
92407
  if (typeof uri === "string") {
91105
92408
  uri = /** @type {T} */
91106
92409
  normalizeString(uri, options2);
@@ -91493,7 +92796,7 @@ var require_fast_uri2 = __commonJS({
91493
92796
  }
91494
92797
  var fastUri = {
91495
92798
  SCHEMES,
91496
- normalize: normalize2,
92799
+ normalize: normalize3,
91497
92800
  resolve: resolve9,
91498
92801
  resolveComponent,
91499
92802
  equal,
@@ -101861,7 +103164,7 @@ function unresolvedName(ctx, r, verb) {
101861
103164
  ...r.near.length ? { note: "Functions with similar names are listed." } : {}
101862
103165
  };
101863
103166
  }
101864
- function normalize(question) {
103167
+ function normalize2(question) {
101865
103168
  return question.trim().replace(/\s+/g, " ").replace(/^(?:please\s+|can you\s+|could you\s+)?(?:tell me\s+|show me\s+(?=the\s+))?/i, "").replace(/[?!.\s]+$/, "");
101866
103169
  }
101867
103170
  function repositoryOf(text, sources) {
@@ -101875,7 +103178,7 @@ function repositoryOf(text, sources) {
101875
103178
  return hit ? { source: hit.id, text: m[1] } : null;
101876
103179
  }
101877
103180
  function answerWithGrammar(engine, project2, question, options2 = {}) {
101878
- let text = normalize(question);
103181
+ let text = normalize2(question);
101879
103182
  let sources = [];
101880
103183
  try {
101881
103184
  sources = engine.listSources({ project: project2 }).sources;
@@ -101891,7 +103194,7 @@ function answerWithGrammar(engine, project2, question, options2 = {}) {
101891
103194
  const name = new Map(sources.map((s) => [s.id, s.name ?? s.id]));
101892
103195
  const answer = run2(text, source);
101893
103196
  if (answer !== void 0) return answer;
101894
- return named ? run2(normalize(question), scope2) ?? null : null;
103197
+ return named ? run2(normalize2(question), scope2) ?? null : null;
101895
103198
  function run2(text2, source2) {
101896
103199
  for (const intent of INTENTS)
101897
103200
  for (const pattern of intent.patterns) {
@@ -103118,7 +104421,7 @@ __export(src_exports3, {
103118
104421
  configPath: () => configPath,
103119
104422
  loadSettings: () => loadSettings,
103120
104423
  nameRepositories: () => nameRepositories,
103121
- normalize: () => normalize,
104424
+ normalize: () => normalize2,
103122
104425
  publicSettings: () => publicSettings,
103123
104426
  repositoryOf: () => repositoryOf,
103124
104427
  saveSettings: () => saveSettings,
@@ -103683,7 +104986,9 @@ async function createServer(engine, options2 = {}) {
103683
104986
  sort: { type: "string", enum: ["impact", "place"] },
103684
104987
  limit: positive2,
103685
104988
  offset: count2,
103686
- grouping: { type: "string", enum: [...GROUPINGS] }
104989
+ grouping: { type: "string", enum: [...GROUPINGS] },
104990
+ groupBy: { type: "string", enum: ["cause"] },
104991
+ cause: str2
103687
104992
  }
103688
104993
  }
103689
104994
  }
@@ -104315,7 +105620,8 @@ var USAGE = `veoflow \u2014 a knowledge graph of your code (also runs as \`veo\`
104315
105620
 
104316
105621
  Usage:
104317
105622
  veoflow init <name> create a project
104318
- veoflow add <dir> [--project <id>] add a folder to a project and analyze it
105623
+ veoflow add <dir> [--project <id>] add a folder and analyze it: to a new project named after
105624
+ it, or to --project (or the project whose folder you're in)
104319
105625
  [--id <source-id>] [--include <glob>]... [--exclude <glob>]... [--no-run]
104320
105626
  veoflow run [--project <id>] [--source <id>] [--draft | --commit [--branch <name>] |
104321
105627
  --debug [--until <stage>] | --from <stage>]
@@ -104361,8 +105667,9 @@ Usage:
104361
105667
  the license in force; install a license key (from a file,
104362
105668
  or "-" for stdin); check the installed one again (offline)
104363
105669
  veoflow check [<file|folder>] [--json] [--project <id>]
104364
- the TypeScript compiler's second opinion: each call site
104365
- where it and veoflow disagree, with both answers
105670
+ a reference checker's second opinion (the TypeScript compiler;
105671
+ Pyright for Python): each call site where it and veoflow
105672
+ disagree, with both answers
104366
105673
  veoflow report <file>:<line> [--include-code] [--out <file>] [--force] [--project <id>]
104367
105674
  a bundle to reproduce an analysis bug there (no source code
104368
105675
  unless --include-code); review it before sharing it
@@ -104433,7 +105740,7 @@ function describeCheck(r, cwd, projectFlag) {
104433
105740
  const disagree1 = s1["different-callee"] + s1["adapter-only"] + s1["checker-only"];
104434
105741
  const disagree2 = s2["different-callee"] + s2["checker-only"];
104435
105742
  out.push(
104436
- `checked ${r.source}${r.path ? `:${r.path}` : ""} (${r.files} files) with the TypeScript compiler (scip-typescript)`
105743
+ `checked ${r.source}${r.path ? `:${r.path}` : ""} (${r.files} files) with ${r.checker === "scip-python" ? "Pyright (scip-python)" : "the TypeScript compiler (scip-typescript)"}`
104437
105744
  );
104438
105745
  out.push(
104439
105746
  ` calls within files (Stage 1): ${s1.agree} agree, ${disagree1} disagree; ${s1.outside} resolve outside the source (not compared)`
@@ -104816,12 +106123,8 @@ async function main(argv, io) {
104816
106123
  project2 = found.id;
104817
106124
  }
104818
106125
  if (!project2) {
104819
- const all2 = engine.catalog.listProjects();
104820
- if (all2.length === 1) project2 = all2[0].id;
104821
- else if (all2.length === 0) {
104822
- project2 = engine.createProject({ name: basename3(root) || "project" }).project.id;
104823
- io.out(`created project ${project2}`);
104824
- } else throw new UsageError("several projects exist; pass --project <id>");
106126
+ project2 = engine.createProject({ name: basename3(root) || "project" }).project.id;
106127
+ io.out(`created project ${project2} (to add to another project instead: --project <id|name>)`);
104825
106128
  }
104826
106129
  const { source, sources, notAdded } = engine.addSource({
104827
106130
  project: project2,
@@ -105120,7 +106423,7 @@ try: ${answer.suggestions.join(" \xB7 ")}`);
105120
106423
  throw new UsageError("usage: veoflow check [<file|folder>] [--json] [--project <id>]");
105121
106424
  const project2 = pickProject(engine, values.project, io.cwd);
105122
106425
  const path = positionals[0] ?? ".";
105123
- io.err("running the TypeScript compiler over the source (this can take a while)\u2026");
106426
+ io.err("running the reference checker over the source (this can take a while)\u2026");
105124
106427
  const r = await checkCode(engine, { project: project2, path }, io.cwd);
105125
106428
  if (values.json) io.out(JSON.stringify(r, null, 2));
105126
106429
  else for (const line of describeCheck(r, io.cwd, values.project)) io.out(line);