layermap 0.1.33 → 0.1.35

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/cli.mjs CHANGED
@@ -8,24 +8,24 @@ var __export = (target, all) => {
8
8
 
9
9
  // src/cli.ts
10
10
  import { realpath as realpath4 } from "node:fs/promises";
11
- import path15 from "node:path";
11
+ import path16 from "node:path";
12
12
  import { parseArgs } from "node:util";
13
13
 
14
14
  // src/agent/environment.ts
15
15
  import { execFile } from "node:child_process";
16
- import { createHash as createHash5 } from "node:crypto";
17
- import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
16
+ import { createHash as createHash6 } from "node:crypto";
17
+ import { existsSync as existsSync6, readFileSync as readFileSync5 } from "node:fs";
18
18
  import { mkdir, readdir, readFile as readFile2, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
19
19
  import { createRequire } from "node:module";
20
20
  import { homedir } from "node:os";
21
- import path12 from "node:path";
21
+ import path13 from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
 
24
24
  // src/layermap.ts
25
- import { createHash as createHash4, randomUUID as randomUUID2 } from "node:crypto";
25
+ import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
26
26
  import { mkdirSync, statSync } from "node:fs";
27
27
  import { lstat as lstat3, realpath as realpath2 } from "node:fs/promises";
28
- import path11 from "node:path";
28
+ import path12 from "node:path";
29
29
  import { DatabaseSync } from "@photostructure/sqlite";
30
30
 
31
31
  // src/capture-policy.ts
@@ -1307,10 +1307,10 @@ function mergeDefs(...defs) {
1307
1307
  function cloneDef(schema) {
1308
1308
  return mergeDefs(schema._zod.def);
1309
1309
  }
1310
- function getElementAtPath(obj, path16) {
1311
- if (!path16)
1310
+ function getElementAtPath(obj, path17) {
1311
+ if (!path17)
1312
1312
  return obj;
1313
- return path16.reduce((acc, key) => acc?.[key], obj);
1313
+ return path17.reduce((acc, key) => acc?.[key], obj);
1314
1314
  }
1315
1315
  function promiseAllObject(promisesObj) {
1316
1316
  const keys = Object.keys(promisesObj);
@@ -1719,11 +1719,11 @@ function explicitlyAborted(x, startIndex = 0) {
1719
1719
  }
1720
1720
  return false;
1721
1721
  }
1722
- function prefixIssues(path16, issues) {
1722
+ function prefixIssues(path17, issues) {
1723
1723
  return issues.map((iss) => {
1724
1724
  var _a3;
1725
1725
  (_a3 = iss).path ?? (_a3.path = []);
1726
- iss.path.unshift(path16);
1726
+ iss.path.unshift(path17);
1727
1727
  return iss;
1728
1728
  });
1729
1729
  }
@@ -1870,16 +1870,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
1870
1870
  }
1871
1871
  function formatError(error51, mapper = (issue2) => issue2.message) {
1872
1872
  const fieldErrors = { _errors: [] };
1873
- const processError = (error52, path16 = []) => {
1873
+ const processError = (error52, path17 = []) => {
1874
1874
  for (const issue2 of error52.issues) {
1875
1875
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1876
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1876
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1877
1877
  } else if (issue2.code === "invalid_key") {
1878
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1878
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1879
1879
  } else if (issue2.code === "invalid_element") {
1880
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1880
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1881
1881
  } else {
1882
- const fullpath = [...path16, ...issue2.path];
1882
+ const fullpath = [...path17, ...issue2.path];
1883
1883
  if (fullpath.length === 0) {
1884
1884
  fieldErrors._errors.push(mapper(issue2));
1885
1885
  } else {
@@ -1906,17 +1906,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
1906
1906
  }
1907
1907
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
1908
1908
  const result = { errors: [] };
1909
- const processError = (error52, path16 = []) => {
1909
+ const processError = (error52, path17 = []) => {
1910
1910
  var _a3, _b;
1911
1911
  for (const issue2 of error52.issues) {
1912
1912
  if (issue2.code === "invalid_union" && issue2.errors.length) {
1913
- issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
1913
+ issue2.errors.map((issues) => processError({ issues }, [...path17, ...issue2.path]));
1914
1914
  } else if (issue2.code === "invalid_key") {
1915
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1915
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1916
1916
  } else if (issue2.code === "invalid_element") {
1917
- processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
1917
+ processError({ issues: issue2.issues }, [...path17, ...issue2.path]);
1918
1918
  } else {
1919
- const fullpath = [...path16, ...issue2.path];
1919
+ const fullpath = [...path17, ...issue2.path];
1920
1920
  if (fullpath.length === 0) {
1921
1921
  result.errors.push(mapper(issue2));
1922
1922
  continue;
@@ -1948,8 +1948,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
1948
1948
  }
1949
1949
  function toDotPath(_path) {
1950
1950
  const segs = [];
1951
- const path16 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1952
- for (const seg of path16) {
1951
+ const path17 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
1952
+ for (const seg of path17) {
1953
1953
  if (typeof seg === "number")
1954
1954
  segs.push(`[${seg}]`);
1955
1955
  else if (typeof seg === "symbol")
@@ -14641,13 +14641,13 @@ function resolveRef(ref, ctx) {
14641
14641
  if (!ref.startsWith("#")) {
14642
14642
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
14643
14643
  }
14644
- const path16 = ref.slice(1).split("/").filter(Boolean);
14645
- if (path16.length === 0) {
14644
+ const path17 = ref.slice(1).split("/").filter(Boolean);
14645
+ if (path17.length === 0) {
14646
14646
  return ctx.rootSchema;
14647
14647
  }
14648
14648
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
14649
- if (path16[0] === defsKey) {
14650
- const key = path16[1];
14649
+ if (path17[0] === defsKey) {
14650
+ const key = path17[1];
14651
14651
  if (!key || !ctx.defs[key]) {
14652
14652
  throw new Error(`Reference not found: ${ref}`);
14653
14653
  }
@@ -15268,7 +15268,7 @@ var CodeCommitReader = class _CodeCommitReader {
15268
15268
  const objectHash = createHash2(source.object.length === 64 ? "sha256" : "sha1").update(`blob ${content.byteLength}\0`).update(content).digest("hex");
15269
15269
  if (content.byteLength !== source.bytes || objectHash !== source.object)
15270
15270
  throw new ProjectEvidenceError("PROJECT_CODE_BLOB_INVALID", false);
15271
- const contentDigest = digestValue({ bytesBase64: content.toString("base64") });
15271
+ const contentDigest2 = digestValue({ bytesBase64: content.toString("base64") });
15272
15272
  let text = !content.includes(0);
15273
15273
  try {
15274
15274
  new TextDecoder("utf-8", { fatal: true }).decode(content);
@@ -15280,7 +15280,7 @@ var CodeCommitReader = class _CodeCommitReader {
15280
15280
  path: source.path,
15281
15281
  byteLength: source.bytes,
15282
15282
  state: text ? "TEXT" : "NON_TEXT",
15283
- contentDigest
15283
+ contentDigest: contentDigest2
15284
15284
  },
15285
15285
  content
15286
15286
  };
@@ -15410,14 +15410,14 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15410
15410
  throw new ProjectEvidenceError("PROJECT_FILE_CHANGED", true);
15411
15411
  }
15412
15412
  await this.inspectPath(absolutePath);
15413
- const contentDigest = digestValue({ bytesBase64: bytes.toString("base64") });
15413
+ const contentDigest2 = digestValue({ bytesBase64: bytes.toString("base64") });
15414
15414
  if (bytes.includes(0)) {
15415
15415
  return Object.freeze({
15416
15416
  entry: Object.freeze({
15417
15417
  path: relativePath,
15418
15418
  state: "NON_TEXT",
15419
15419
  byteLength,
15420
- contentDigest
15420
+ contentDigest: contentDigest2
15421
15421
  }),
15422
15422
  content: bytes
15423
15423
  });
@@ -15429,7 +15429,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15429
15429
  path: relativePath,
15430
15430
  state: "NON_TEXT",
15431
15431
  byteLength,
15432
- contentDigest
15432
+ contentDigest: contentDigest2
15433
15433
  }),
15434
15434
  content: bytes
15435
15435
  });
@@ -15439,7 +15439,7 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15439
15439
  path: relativePath,
15440
15440
  state: "TEXT",
15441
15441
  byteLength,
15442
- contentDigest
15442
+ contentDigest: contentDigest2
15443
15443
  }),
15444
15444
  content: bytes
15445
15445
  });
@@ -15506,8 +15506,90 @@ var StableProjectCaptureSession = class _StableProjectCaptureSession {
15506
15506
  }
15507
15507
  };
15508
15508
 
15509
- // src/source-scope.ts
15509
+ // src/project-map-installed.ts
15510
+ import { createHash as createHash3 } from "node:crypto";
15511
+ import { existsSync as existsSync2, readdirSync, readFileSync, realpathSync } from "node:fs";
15512
+ import { isBuiltin } from "node:module";
15510
15513
  import path6 from "node:path";
15514
+ var INSTALL_RECORDS = [
15515
+ ".pnpm/lock.yaml",
15516
+ ".package-lock.json",
15517
+ ".yarn-state.yml",
15518
+ ".yarn-integrity"
15519
+ ];
15520
+ var LOCKFILES = [
15521
+ "pnpm-lock.yaml",
15522
+ "package-lock.json",
15523
+ "npm-shrinkwrap.json",
15524
+ "yarn.lock",
15525
+ "bun.lock",
15526
+ "bun.lockb"
15527
+ ];
15528
+ var MAP_DEPENDENCY_NOT_INSTALLED = "DEPENDENCY_NOT_INSTALLED";
15529
+ function mapPackageOf(specifier) {
15530
+ if (isBuiltin(specifier)) return void 0;
15531
+ return /^(?:@[a-z0-9~][\w.~-]*\/)?[a-z0-9~][\w.~-]*(?=\/|$)/iu.exec(specifier)?.[0];
15532
+ }
15533
+ function mapInstalledPath(realRoot, relative) {
15534
+ try {
15535
+ const real = realpathSync.native(path6.join(realRoot, relative));
15536
+ return real.startsWith(`${realRoot}${path6.sep}`) ? real : void 0;
15537
+ } catch {
15538
+ return void 0;
15539
+ }
15540
+ }
15541
+ var contentDigest = (file2) => createHash3("sha256").update(readFileSync(file2)).digest("hex");
15542
+ var versionOf = (realRoot, relative) => {
15543
+ const manifest = mapInstalledPath(realRoot, `${relative}/package.json`);
15544
+ if (!manifest) return "not in the project";
15545
+ try {
15546
+ return String(JSON.parse(readFileSync(manifest, "utf8")).version);
15547
+ } catch {
15548
+ return "unreadable";
15549
+ }
15550
+ };
15551
+ function installedAt(realRoot, directory, real) {
15552
+ const records = INSTALL_RECORDS.flatMap((name) => {
15553
+ const file2 = mapInstalledPath(realRoot, path6.posix.join(directory, name));
15554
+ return file2 ? [[name, contentDigest(file2)]] : [];
15555
+ });
15556
+ if (records.length) return records;
15557
+ const packages = readdirSync(real).flatMap((name) => {
15558
+ if (name.startsWith(".")) return [];
15559
+ if (!name.startsWith("@")) return [name];
15560
+ const scope = mapInstalledPath(realRoot, path6.posix.join(directory, name));
15561
+ return scope ? readdirSync(scope).map((inner) => `${name}/${inner}`) : [];
15562
+ });
15563
+ const beside = path6.join(realRoot, path6.posix.dirname(directory));
15564
+ return {
15565
+ packages: packages.sort().map((name) => [name, versionOf(realRoot, `${directory}/${name}`)]),
15566
+ lockfiles: LOCKFILES.flatMap((name) => {
15567
+ const file2 = path6.join(beside, name);
15568
+ return existsSync2(file2) ? [[name, contentDigest(file2)]] : [];
15569
+ })
15570
+ };
15571
+ }
15572
+ function mapInstalledDigest(root, paths) {
15573
+ const realRoot = realpathSync.native(root);
15574
+ const directories = /* @__PURE__ */ new Set(["."]);
15575
+ for (const file2 of paths) {
15576
+ let at = path6.posix.dirname(file2);
15577
+ while (at !== "." && !directories.has(at)) {
15578
+ directories.add(at);
15579
+ at = path6.posix.dirname(at);
15580
+ }
15581
+ }
15582
+ const installed = [];
15583
+ for (const directory of [...directories].sort()) {
15584
+ const modules = path6.posix.join(directory, "node_modules");
15585
+ const real = mapInstalledPath(realRoot, modules);
15586
+ if (real) installed.push([modules, installedAt(realRoot, modules, real)]);
15587
+ }
15588
+ return digestValue(installed);
15589
+ }
15590
+
15591
+ // src/source-scope.ts
15592
+ import path7 from "node:path";
15511
15593
  var InitialEvidenceScopeSchema = external_exports.object({
15512
15594
  pathPrefixes: external_exports.array(ProjectEvidenceGrantPathPrefixSchema).min(1).max(64)
15513
15595
  }).strict();
@@ -15595,7 +15677,7 @@ var includesInitialEvidencePath = (relativePath, scope) => {
15595
15677
  if (isProjectEvidenceTraversalExcluded(relativePath) || inExcludedDirectory(relativePath))
15596
15678
  return false;
15597
15679
  const basename = relativePath.toLowerCase().split("/").at(-1) ?? "";
15598
- return extensions.has(path6.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15680
+ return extensions.has(path7.posix.extname(basename)) || SOURCE_POLICY.documentationFiles.includes(basename) || SOURCE_POLICY.configurationFiles.includes(basename) || SOURCE_POLICY.workspaceFiles.includes(relativePath);
15599
15681
  };
15600
15682
 
15601
15683
  // src/code-index-capture.ts
@@ -15698,13 +15780,18 @@ var CodeIndexCapture = class {
15698
15780
  )
15699
15781
  );
15700
15782
  const textEntries = entries.filter((entry) => entry.state === "TEXT");
15783
+ const installedDigest = mapInstalledDigest(
15784
+ session.root,
15785
+ entries.map((entry) => entry.path)
15786
+ );
15701
15787
  return {
15702
15788
  version: {
15703
15789
  version: digestValue({
15704
15790
  projectRef: source.projectRef,
15705
15791
  pathPrefixes,
15706
15792
  entries,
15707
- analyzer: this.analyzer
15793
+ analyzer: this.analyzer,
15794
+ installed: installedDigest
15708
15795
  }),
15709
15796
  projectRef: source.projectRef,
15710
15797
  pathPrefixes,
@@ -15714,6 +15801,7 @@ var CodeIndexCapture = class {
15714
15801
  analyzer: this.analyzer
15715
15802
  },
15716
15803
  entries,
15804
+ installedDigest,
15717
15805
  universeDigest: digestValue(
15718
15806
  [...snapshot?.files ?? commit?.entries.map((entry) => entry.path) ?? []].sort()
15719
15807
  )
@@ -15873,6 +15961,9 @@ var MapRelationSchema = external_exports.object({
15873
15961
  // The full route a decorator registers its declaration under, when it says more than the
15874
15962
  // argument: the HTTP methods, then the class's path joined with the member's.
15875
15963
  route: external_exports.string().min(1).max(256).optional(),
15964
+ // The event a component emits to the handler a template binds to it. The handler runs only
15965
+ // where that template is, which the template's own relation to it says.
15966
+ event: external_exports.string().min(1).max(256).optional(),
15876
15967
  basis: external_exports.enum(["TYPE_RESOLVED", "SYNTAX_DECLARED", "UNRESOLVED"]),
15877
15968
  unresolvedReason: external_exports.enum([
15878
15969
  "SYNTAX_ONLY",
@@ -15906,7 +15997,9 @@ var MapNoteSchema = external_exports.object({
15906
15997
  var MapGapSchema = external_exports.object({
15907
15998
  code: external_exports.string().min(1).max(128),
15908
15999
  path: external_exports.string().optional(),
15909
- count: external_exports.number().int().positive().optional()
16000
+ count: external_exports.number().int().positive().optional(),
16001
+ // The package a gap is about, such as one the code imports that is not installed.
16002
+ package: external_exports.string().min(1).max(256).optional()
15910
16003
  }).strict();
15911
16004
  var MapSearchRankingSignalSchema = external_exports.enum([
15912
16005
  "EXACT_SYMBOL",
@@ -15961,8 +16054,8 @@ var MapAnalysisSchema = external_exports.object({
15961
16054
  var mapPathAllowed = (relative, prefixes) => prefixes.some(
15962
16055
  (prefix) => prefix === "." || relative === prefix || relative.startsWith(`${prefix}/`)
15963
16056
  );
15964
- var mapTestPath = (path16) => /(?:^|\/)(?:__tests__|tests?|fixtures?|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
15965
- path16
16057
+ var mapTestPath = (path17) => /(?:^|\/)(?:__tests__|tests?|fixtures?|e2e|testdata)(?:\/|$)|\.(?:spec|test)\.|_test\.(?:go|py)$|(?:^|\/)(?:test_[^/]*\.py|conftest\.py)$/iu.test(
16058
+ path17
15966
16059
  );
15967
16060
 
15968
16061
  // src/project-map-reference-types.ts
@@ -15978,9 +16071,26 @@ var MapReferenceSchema = external_exports.object({
15978
16071
  anchor: MapAnchorSchema,
15979
16072
  kind: MapReferenceKindSchema
15980
16073
  }).strict();
16074
+ var MapDiagnosticSchema = external_exports.object({
16075
+ path: external_exports.string(),
16076
+ line: external_exports.number().int().positive(),
16077
+ code: external_exports.number().int(),
16078
+ text: external_exports.string(),
16079
+ span: external_exports.string()
16080
+ }).strict();
16081
+ var MapDiagnosticsSchema = external_exports.object({
16082
+ diagnostics: external_exports.array(MapDiagnosticSchema),
16083
+ /** Packages the compile could not find. */
16084
+ missing: external_exports.array(external_exports.string()),
16085
+ requiredFiles: external_exports.array(external_exports.string())
16086
+ }).strict();
16087
+ var MAP_REFERENCES_MAX = 1e3;
15981
16088
  var MapReferencePageSchema = external_exports.object({
15982
- references: external_exports.array(MapReferenceSchema).max(200),
15983
- nextOffset: external_exports.number().int().nonnegative().optional(),
16089
+ references: external_exports.array(MapReferenceSchema).max(MAP_REFERENCES_MAX),
16090
+ nextOffset: external_exports.number().int().nonnegative().optional()
16091
+ }).strict();
16092
+ var MapReferenceBatchSchema = external_exports.object({
16093
+ pages: external_exports.array(MapReferencePageSchema.nullable()),
15984
16094
  requiredFiles: external_exports.array(external_exports.string())
15985
16095
  }).strict();
15986
16096
  var MapReferenceResultSchema = external_exports.object({
@@ -16046,11 +16156,11 @@ var string4 = (value) => {
16046
16156
  var identity = (id2, reconstructed) => id2 === reconstructed ? [] : [JSON.stringify(id2)];
16047
16157
  function encodeMapText(graph) {
16048
16158
  const files = /* @__PURE__ */ new Map();
16049
- const file2 = (path16) => {
16050
- let ref = files.get(path16);
16159
+ const file2 = (path17) => {
16160
+ let ref = files.get(path17);
16051
16161
  if (!ref) {
16052
16162
  ref = `F${files.size + 1}`;
16053
- files.set(path16, ref);
16163
+ files.set(path17, ref);
16054
16164
  }
16055
16165
  return ref;
16056
16166
  };
@@ -16098,7 +16208,7 @@ function encodeMapText(graph) {
16098
16208
  rows2.push(`B ${node(frontier.entityRef)} ${frontier.direction}`);
16099
16209
  return [
16100
16210
  ...header,
16101
- ...[...files].map(([path16, ref]) => `${ref} ${JSON.stringify(path16)}`),
16211
+ ...[...files].map(([path17, ref]) => `${ref} ${JSON.stringify(path17)}`),
16102
16212
  ...rows2
16103
16213
  ].join("\n");
16104
16214
  }
@@ -16118,10 +16228,10 @@ function decodeMapText(text) {
16118
16228
  const at = (value) => {
16119
16229
  const match = /^(F[1-9]\d*):(\d+)-(\d+)@(\d+)-(\d+)$/u.exec(value ?? "");
16120
16230
  if (!match) return failed();
16121
- const path16 = files.get(match[1] ?? "");
16122
- if (path16 === void 0) return failed();
16231
+ const path17 = files.get(match[1] ?? "");
16232
+ if (path17 === void 0) return failed();
16123
16233
  return MapAnchorSchema.parse({
16124
- path: path16,
16234
+ path: path17,
16125
16235
  startLine: Number(match[2]),
16126
16236
  endLine: Number(match[3]),
16127
16237
  start: Number(match[4]),
@@ -16198,8 +16308,8 @@ function decodeMapText(text) {
16198
16308
  var locationSchema = MapAnchorSchema.describe(
16199
16309
  "Source location: start/end are zero-based UTF-16 offsets with an exclusive end; line numbers are one-based."
16200
16310
  );
16201
- var location = ({ path: path16, startLine, endLine, start, end }) => ({
16202
- path: path16,
16311
+ var location = ({ path: path17, startLine, endLine, start, end }) => ({
16312
+ path: path17,
16203
16313
  startLine,
16204
16314
  endLine,
16205
16315
  start,
@@ -16302,11 +16412,11 @@ var MapNavigationObjectsSchema = external_exports.union([
16302
16412
  ),
16303
16413
  external_exports.object({ files: external_exports.array(searchFileSchema) }).passthrough().refine((value) => !("format" in value), "Text navigation must decode through its format.").transform(
16304
16414
  (value) => value.files.flatMap(
16305
- ({ path: path16, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16415
+ ({ path: path17, symbols }) => symbols.map(({ id: id2, name, kind, startLine, endLine, start, end, execution }) => ({
16306
16416
  id: id2,
16307
16417
  name,
16308
16418
  kind,
16309
- anchor: { path: path16, startLine, endLine, start, end },
16419
+ anchor: { path: path17, startLine, endLine, start, end },
16310
16420
  ...execution ? { execution } : {}
16311
16421
  }))
16312
16422
  )
@@ -16319,10 +16429,10 @@ var mapSearchNavigation = (result) => {
16319
16429
  for (const [index, object2] of found.entries()) {
16320
16430
  const ranking = rankings[index];
16321
16431
  if (!ranking) throw new Error("PROJECT_MAP_SEARCH_RANKING_MISSING");
16322
- const path16 = object2.anchor.path;
16432
+ const path17 = object2.anchor.path;
16323
16433
  let file2 = files.at(-1);
16324
- if (file2?.path !== path16) {
16325
- file2 = { path: path16, symbols: [] };
16434
+ if (file2?.path !== path17) {
16435
+ file2 = { path: path17, symbols: [] };
16326
16436
  files.push(file2);
16327
16437
  }
16328
16438
  file2.symbols.push({
@@ -16448,8 +16558,8 @@ var MapViewGraph = class {
16448
16558
  }
16449
16559
  return object2;
16450
16560
  }
16451
- objectsAt(path16) {
16452
- return this.statements.path.all(this.version, path16).map((row) => {
16561
+ objectsAt(path17) {
16562
+ return this.statements.path.all(this.version, path17).map((row) => {
16453
16563
  const object2 = MapObjectSchema.parse(JSON.parse(String(row.object_json)));
16454
16564
  this.objects.set(object2.id, object2);
16455
16565
  return object2;
@@ -16568,8 +16678,8 @@ var MapViewGraph = class {
16568
16678
  );
16569
16679
  }
16570
16680
  };
16571
- function mapSelectDeclarations(graph, path16, name, line) {
16572
- const objects2 = graph.objectsAt(path16).filter((object2) => !mapIsModule(object2));
16681
+ function mapSelectDeclarations(graph, path17, name, line) {
16682
+ const objects2 = graph.objectsAt(path17).filter((object2) => !mapIsModule(object2));
16573
16683
  const matching = name === void 0 ? objects2 : objects2.filter(
16574
16684
  (object2) => object2.name === name || name.includes(".") && graph.qualifiedName(object2.id) === name
16575
16685
  );
@@ -16591,12 +16701,12 @@ function requireMapObject(store, version2, selector, prefixes) {
16591
16701
  if ([entityRef, locator, symbol2].filter((value) => value !== void 0).length !== 1 || entityRef !== void 0 && !entityRef.length)
16592
16702
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16593
16703
  if (symbol2) {
16594
- const path16 = normalizeProjectEvidencePath(symbol2.path);
16595
- if (!mapPathAllowed(path16, prefixes))
16704
+ const path17 = normalizeProjectEvidencePath(symbol2.path);
16705
+ if (!mapPathAllowed(path17, prefixes))
16596
16706
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16597
16707
  const selected = mapSelectDeclarations(
16598
16708
  new MapViewGraph(store, version2),
16599
- path16,
16709
+ path17,
16600
16710
  symbol2.name,
16601
16711
  symbol2.line
16602
16712
  );
@@ -16607,14 +16717,14 @@ function requireMapObject(store, version2, selector, prefixes) {
16607
16717
  }
16608
16718
  let rows2;
16609
16719
  if (locator) {
16610
- const path16 = normalizeProjectEvidencePath(locator.path);
16720
+ const path17 = normalizeProjectEvidencePath(locator.path);
16611
16721
  if (!Number.isSafeInteger(locator.start) || locator.start < 0 || locator.kind !== void 0 && !MapObjectKindSchema.safeParse(locator.kind).success)
16612
16722
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16613
- if (!mapPathAllowed(path16, prefixes))
16723
+ if (!mapPathAllowed(path17, prefixes))
16614
16724
  throw new ProjectEvidenceError("PROJECT_MAP_OBJECT_NOT_FOUND", false);
16615
16725
  rows2 = store.database.prepare(`SELECT object_json FROM project_map_objects
16616
16726
  WHERE version_ref = ? AND path = ? AND json_extract(object_json, '$.anchor.start') = ?
16617
- AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path16, locator.start, locator.kind ?? null, locator.kind ?? null);
16727
+ AND (? IS NULL OR kind = ?) LIMIT 2`).all(version2, path17, locator.start, locator.kind ?? null, locator.kind ?? null);
16618
16728
  } else {
16619
16729
  rows2 = store.database.prepare(
16620
16730
  "SELECT object_json FROM project_map_objects WHERE version_ref = ? AND entity_ref = ?"
@@ -16655,13 +16765,16 @@ function mapQueryPage(count, materialize, navigation, budget) {
16655
16765
 
16656
16766
  // src/project-map-query-selection.ts
16657
16767
  var mapQuerySelection = (input, knownKinds) => {
16658
- const path16 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
16768
+ const path17 = normalizeProjectEvidencePath(input.path ?? ".", true) || ".";
16659
16769
  const kinds = input.kinds ?? knownKinds;
16660
16770
  if (!Array.isArray(kinds) || !kinds.length || kinds.length > knownKinds.length || kinds.some((kind) => !knownKinds.includes(kind)))
16661
16771
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
16662
- return { path: path16, kinds: [...new Set(kinds)].sort() };
16772
+ return { path: path17, kinds: [...new Set(kinds)].sort() };
16663
16773
  };
16664
- var mapQueryPathMatches = (path16, prefix) => prefix === "." || path16 === prefix || path16.startsWith(`${prefix}/`);
16774
+ var mapQueryPathMatches = (path17, prefix) => prefix === "." || path17 === prefix || path17.startsWith(`${prefix}/`);
16775
+ var MAP_RELATION_TARGET_JOIN = `LEFT JOIN project_map_unit_objects t ON t.entity_ref = r.to_ref
16776
+ AND EXISTS (SELECT 1 FROM project_map_version_units target
16777
+ WHERE target.version_ref = r.version_ref AND target.unit_ref = t.unit_ref AND target.path = t.path)`;
16665
16778
  var mapQueryPathSql = (column) => `(? = '.' OR ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/')`;
16666
16779
 
16667
16780
  // src/project-map-search-focus.ts
@@ -16759,7 +16872,7 @@ var declarationKinds = /* @__PURE__ */ new Set([
16759
16872
  "METHOD",
16760
16873
  "TYPE"
16761
16874
  ]);
16762
- var fileStem = (path16) => path16.slice(path16.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16875
+ var fileStem = (path17) => path17.slice(path17.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16763
16876
  var compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
16764
16877
  var compareRows = (left, right) => right.ranking.score - left.ranking.score || compareText(left.object.anchor.path, right.object.anchor.path) || compareText(left.object.id, right.object.id);
16765
16878
  function mapSearchQuery(input) {
@@ -16786,10 +16899,10 @@ function mapSearchQuery(input) {
16786
16899
  }
16787
16900
  function rank(object2, documentation, relationCount, query, focus) {
16788
16901
  const name = object2.name.toLowerCase();
16789
- const path16 = object2.anchor.path.toLowerCase();
16902
+ const path17 = object2.anchor.path.toLowerCase();
16790
16903
  const values = {
16791
16904
  NAME: [name],
16792
- PATH: [path16],
16905
+ PATH: [path17],
16793
16906
  DOCUMENTATION: documentation.map((text) => text.toLowerCase())
16794
16907
  };
16795
16908
  const matched = query.terms.map((term) => ({
@@ -16814,12 +16927,12 @@ function rank(object2, documentation, relationCount, query, focus) {
16814
16927
  score += 7e3;
16815
16928
  signals.push("SYMBOL_CONTAINS");
16816
16929
  } else if (matchedFields.includes("NAME")) signals.push("SYMBOL_CONTAINS");
16817
- if (object2.kind === "FILE" && fileStem(path16) === normalizedQuery) {
16930
+ if (object2.kind === "FILE" && fileStem(path17) === normalizedQuery) {
16818
16931
  score += 11e3;
16819
16932
  signals.push("EXACT_FILE_STEM");
16820
16933
  }
16821
16934
  if (matchedFields.includes("PATH")) {
16822
- score += path16.includes(normalizedQuery) ? 2500 : 0;
16935
+ score += path17.includes(normalizedQuery) ? 2500 : 0;
16823
16936
  signals.push("PATH_CONTAINS");
16824
16937
  }
16825
16938
  if (matchedFields.includes("DOCUMENTATION")) {
@@ -16834,8 +16947,8 @@ function rank(object2, documentation, relationCount, query, focus) {
16834
16947
  score += kindWeight[object2.kind] + Math.min(1200, relationCount * 20) + (focus?.score ?? 0);
16835
16948
  if (declarationKinds.has(object2.kind)) signals.push("DECLARATION");
16836
16949
  if (relationCount > 0) signals.push("GRAPH_CONNECTED");
16837
- const isTest = mapTestPath(path16);
16838
- const isGenerated = generatedPath.test(path16);
16950
+ const isTest = mapTestPath(path17);
16951
+ const isGenerated = generatedPath.test(path17);
16839
16952
  const hasTestIntent = query.terms.some((term) => testQuery.test(term));
16840
16953
  score += isTest ? hasTestIntent ? 1e3 : -5e3 : 300;
16841
16954
  score += isGenerated ? -3e3 : 300;
@@ -16893,7 +17006,7 @@ function mapSearchRows(store, input, query, scope, offset, signal) {
16893
17006
  )
16894
17007
  SELECT object.object_json,
16895
17008
  (SELECT count(*) FROM project_map_relations r
16896
- LEFT JOIN project_map_objects t ON t.version_ref = r.version_ref AND t.entity_ref = r.to_ref
17009
+ ${MAP_RELATION_TARGET_JOIN}
16897
17010
  WHERE r.version_ref = object.version_ref AND r.from_ref = object.entity_ref
16898
17011
  AND ${mapSearchAllowedSql("r.path")}
16899
17012
  AND (r.to_ref IS NULL OR ${mapSearchAllowedSql("t.path")})) +
@@ -17012,25 +17125,17 @@ async function mapExploreTraversal(store, input, signal) {
17012
17125
  assertActive();
17013
17126
  };
17014
17127
  await checkpoint();
17015
- const statement = store.database.prepare(`
17128
+ const relations = (seeded, order) => store.database.prepare(`
17016
17129
  SELECT r.relation_ref, r.from_ref, r.to_ref, json_extract(r.relation_json, '$.kind') AS kind
17017
17130
  FROM project_map_relations r
17018
17131
  JOIN project_map_objects f ON f.version_ref = r.version_ref AND f.entity_ref = r.from_ref
17019
- LEFT JOIN project_map_objects t ON t.version_ref = r.version_ref AND t.entity_ref = r.to_ref
17132
+ ${MAP_RELATION_TARGET_JOIN}
17020
17133
  WHERE r.version_ref = ? AND ${allowed("r.path")} AND ${allowed("f.path")}
17021
17134
  AND (r.to_ref IS NULL OR ${allowed("t.path")})
17022
17135
  AND ${mapQueryPathSql("r.path")}
17023
17136
  AND json_extract(r.relation_json, '$.kind') IN (SELECT value FROM json_each(?))
17024
- ${input.scope === "PROJECT" ? `ORDER BY ${relationOrder}` : ""}`);
17025
- const relationRefs = [];
17026
- const adjacency = /* @__PURE__ */ new Map();
17027
- const connect = (ref, edge) => {
17028
- const existing = adjacency.get(ref);
17029
- if (existing) existing.push(edge);
17030
- else adjacency.set(ref, [edge]);
17031
- };
17032
- let inspected = 0;
17033
- for (const row of statement.iterate(
17137
+ ${seeded} ${order}`);
17138
+ const filters = [
17034
17139
  input.version,
17035
17140
  input.authorizationScope,
17036
17141
  input.authorizationScope,
@@ -17040,29 +17145,22 @@ async function mapExploreTraversal(store, input, signal) {
17040
17145
  input.selection.path,
17041
17146
  input.selection.path,
17042
17147
  canonicalJson(input.selection.kinds)
17043
- )) {
17044
- if (++inspected % 256 === 0) await checkpoint();
17045
- const relation = {
17046
- id: String(row.relation_ref),
17047
- from: String(row.from_ref),
17048
- ...row.to_ref === null ? {} : { to: String(row.to_ref) },
17049
- kind: row.kind
17050
- };
17051
- if (input.scope === "PROJECT") {
17052
- relationRefs.push(relation.id);
17053
- continue;
17054
- }
17055
- if (input.direction !== "INCOMING") connect(relation.from, relation);
17056
- if (input.direction !== "OUTGOING" && relation.to && relation.to !== relation.from)
17057
- connect(relation.to, relation);
17058
- else if (input.direction === "INCOMING" && relation.to === relation.from)
17059
- connect(relation.to, relation);
17060
- }
17148
+ ];
17149
+ const relationRefs = [];
17150
+ let inspected = 0;
17061
17151
  if (input.scope === "PROJECT") {
17152
+ for (const row of relations("", `ORDER BY ${relationOrder}`).iterate(...filters)) {
17153
+ if (++inspected % 256 === 0) await checkpoint();
17154
+ relationRefs.push(String(row.relation_ref));
17155
+ }
17062
17156
  assertActive();
17063
17157
  return { relationRefs, frontier: [] };
17064
17158
  }
17065
17159
  if (!input.entityRef) throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
17160
+ const ends = [
17161
+ ...input.direction === "INCOMING" ? [] : ["r.from_ref"],
17162
+ ...input.direction === "OUTGOING" ? [] : ["r.to_ref"]
17163
+ ].map((end) => relations(`AND ${end} IN (SELECT value FROM json_each(?))`, ""));
17066
17164
  const known = /* @__PURE__ */ new Set([input.entityRef]);
17067
17165
  const seenRelations = /* @__PURE__ */ new Set();
17068
17166
  const frontier = [];
@@ -17072,10 +17170,18 @@ async function mapExploreTraversal(store, input, signal) {
17072
17170
  await checkpoint();
17073
17171
  depth++;
17074
17172
  const candidates = /* @__PURE__ */ new Map();
17075
- for (const ref of seeds) {
17076
- for (const edge of adjacency.get(ref) ?? []) {
17173
+ const seedRefs = canonicalJson(seeds);
17174
+ for (const end of ends) {
17175
+ for (const row of end.iterate(...filters, seedRefs)) {
17077
17176
  if (++inspected % 256 === 0) await checkpoint();
17078
- if (!seenRelations.has(edge.id)) candidates.set(edge.id, edge);
17177
+ const id2 = String(row.relation_ref);
17178
+ if (seenRelations.has(id2)) continue;
17179
+ candidates.set(id2, {
17180
+ id: id2,
17181
+ from: String(row.from_ref),
17182
+ ...row.to_ref === null ? {} : { to: String(row.to_ref) },
17183
+ kind: row.kind
17184
+ });
17079
17185
  }
17080
17186
  }
17081
17187
  const next = [];
@@ -17134,7 +17240,7 @@ function mapPageFrontier(frontier, rows2) {
17134
17240
  }
17135
17241
 
17136
17242
  // src/project-map-language-go.ts
17137
- import { existsSync as existsSync3 } from "node:fs";
17243
+ import { existsSync as existsSync4 } from "node:fs";
17138
17244
 
17139
17245
  // src/project-map-analysis-validation.ts
17140
17246
  function validateMapAnalysis(analysis, input) {
@@ -17297,7 +17403,11 @@ var MapFactsSchema = external_exports.object({
17297
17403
  state: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
17298
17404
  }).strict();
17299
17405
  var MapReferenceFactsSchema = external_exports.object({
17300
- references: external_exports.array(external_exports.object({ ...span, kind: MapReferenceKindSchema }).strict())
17406
+ pages: external_exports.array(
17407
+ external_exports.object({
17408
+ references: external_exports.array(external_exports.object({ ...span, kind: MapReferenceKindSchema }).strict())
17409
+ }).strict().nullable()
17410
+ )
17301
17411
  }).strict();
17302
17412
  var invalid = () => {
17303
17413
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
@@ -17319,13 +17429,13 @@ function utf16Offsets(text) {
17319
17429
  }
17320
17430
  function offsetConverter(files, offsets) {
17321
17431
  const converters = /* @__PURE__ */ new Map();
17322
- return (path16, offset) => {
17323
- let convert = converters.get(path16);
17432
+ return (path17, offset) => {
17433
+ let convert = converters.get(path17);
17324
17434
  if (!convert) {
17325
- const text = files[path16];
17435
+ const text = files[path17];
17326
17436
  if (text === void 0) return invalid();
17327
17437
  convert = offsets === "UTF16" ? (value) => value <= text.length ? value : invalid() : utf16Offsets(text);
17328
- converters.set(path16, convert);
17438
+ converters.set(path17, convert);
17329
17439
  }
17330
17440
  return convert(offset);
17331
17441
  };
@@ -17356,7 +17466,7 @@ function mapFactsAnalysis(facts, input, context) {
17356
17466
  const collect = new MapOutputCollector(output);
17357
17467
  const positions = new MapSourcePositions(input.files);
17358
17468
  const offset = offsetConverter(input.files, context.offsets);
17359
- const anchor = (path16, start, end) => positions.span(path16, offset(path16, start), offset(path16, end));
17469
+ const anchor = (path17, start, end) => positions.span(path17, offset(path17, start), offset(path17, end));
17360
17470
  const located = /* @__PURE__ */ new Map();
17361
17471
  const canonical = /* @__PURE__ */ new Map();
17362
17472
  const bySpan = /* @__PURE__ */ new Map();
@@ -17491,11 +17601,21 @@ function mapFactsAnalysis(facts, input, context) {
17491
17601
  }
17492
17602
  return output;
17493
17603
  }
17494
- function mapReferencesPage(facts, files, reference, offsets) {
17604
+ function mapReferencePages(facts, files, requests, offsets) {
17605
+ if (facts.pages.length !== requests.length) invalid();
17495
17606
  const positions = new MapSourcePositions(files);
17496
17607
  const offset = offsetConverter(files, offsets);
17608
+ return {
17609
+ pages: facts.pages.map((found, at) => {
17610
+ const request = requests[at];
17611
+ return found && referencePage(found, positions, offset, request);
17612
+ }),
17613
+ requiredFiles: []
17614
+ };
17615
+ }
17616
+ function referencePage(found, positions, offset, reference) {
17497
17617
  const references = /* @__PURE__ */ new Map();
17498
- for (const fact of facts.references) {
17618
+ for (const fact of found.references) {
17499
17619
  if (!mapQueryPathMatches(fact.path, reference.path ?? ".")) continue;
17500
17620
  if (reference.kinds && !reference.kinds.includes(fact.kind)) continue;
17501
17621
  const anchor = positions.span(
@@ -17514,15 +17634,14 @@ function mapReferencesPage(facts, files, reference, offsets) {
17514
17634
  const next = reference.offset + selected.length;
17515
17635
  return {
17516
17636
  references: selected,
17517
- ...next < ordered.length ? { nextOffset: next } : {},
17518
- requiredFiles: []
17637
+ ...next < ordered.length ? { nextOffset: next } : {}
17519
17638
  };
17520
17639
  }
17521
17640
 
17522
17641
  // src/project-map-process.ts
17523
17642
  import { execFileSync, spawn as spawn2 } from "node:child_process";
17524
- import { existsSync as existsSync2, readFileSync, realpathSync } from "node:fs";
17525
- import path7 from "node:path";
17643
+ import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
17644
+ import path8 from "node:path";
17526
17645
 
17527
17646
  // src/project-map-failure.ts
17528
17647
  var PhaseSchema = external_exports.enum([
@@ -17648,24 +17767,24 @@ var ProjectMapStopUnconfirmedError = class extends ProjectEvidenceError {
17648
17767
  }
17649
17768
  };
17650
17769
  var installedMapParserResources = () => {
17651
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17770
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17652
17771
  return {
17653
- workerPath: path7.join(directory, "project-map-worker.mjs"),
17654
- compilerPath: path7.join(directory, "project-map-native/tsc")
17772
+ workerPath: path8.join(directory, "project-map-worker.mjs"),
17773
+ compilerPath: path8.join(directory, "project-map-native/tsc")
17655
17774
  };
17656
17775
  };
17657
17776
  var installedPythonMapResources = () => {
17658
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17777
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17659
17778
  return {
17660
- workerPath: path7.join(directory, "project-map-python-worker.mjs"),
17661
- compilerPath: path7.join(directory, "project-map-python/typeshed")
17779
+ workerPath: path8.join(directory, "project-map-python-worker.mjs"),
17780
+ compilerPath: path8.join(directory, "project-map-python/typeshed")
17662
17781
  };
17663
17782
  };
17664
17783
  function discoverJavaRuntime(env = process.env) {
17665
17784
  const homes = [env.LAYERMAP_JAVA_HOME, env.JAVA_HOME];
17666
- for (const directory of (env.PATH ?? env.Path ?? "").split(path7.delimiter)) {
17667
- const java = path7.join(directory, executableName("java"));
17668
- if (directory && existsSync2(java)) homes.push(path7.dirname(path7.dirname(realpathSync(java))));
17785
+ for (const directory of (env.PATH ?? env.Path ?? "").split(path8.delimiter)) {
17786
+ const java = path8.join(directory, executableName("java"));
17787
+ if (directory && existsSync3(java)) homes.push(path8.dirname(path8.dirname(realpathSync2(java))));
17669
17788
  }
17670
17789
  homes.push(
17671
17790
  ...["/opt/homebrew/opt", "/usr/local/opt"].flatMap(
@@ -17673,7 +17792,7 @@ function discoverJavaRuntime(env = process.env) {
17673
17792
  (formula) => `${prefix}/${formula}/libexec/openjdk.jdk/Contents/Home`
17674
17793
  )
17675
17794
  ),
17676
- ...env.HOME ? [path7.join(env.HOME, ".sdkman/candidates/java/current")] : []
17795
+ ...env.HOME ? [path8.join(env.HOME, ".sdkman/candidates/java/current")] : []
17677
17796
  );
17678
17797
  if (process.platform === "darwin")
17679
17798
  try {
@@ -17688,12 +17807,12 @@ function discoverJavaRuntime(env = process.env) {
17688
17807
  }
17689
17808
  for (const home of homes) {
17690
17809
  if (!home) continue;
17691
- const runtimePath = path7.join(home, "bin", executableName("java"));
17692
- if (!existsSync2(runtimePath) || !existsSync2(path7.join(home, "bin", executableName("javac"))))
17810
+ const runtimePath = path8.join(home, "bin", executableName("java"));
17811
+ if (!existsSync3(runtimePath) || !existsSync3(path8.join(home, "bin", executableName("javac"))))
17693
17812
  continue;
17694
17813
  let release = "";
17695
17814
  try {
17696
- release = readFileSync(path7.join(home, "release"), "utf8");
17815
+ release = readFileSync2(path8.join(home, "release"), "utf8");
17697
17816
  } catch {
17698
17817
  continue;
17699
17818
  }
@@ -17704,26 +17823,26 @@ function discoverJavaRuntime(env = process.env) {
17704
17823
  return void 0;
17705
17824
  }
17706
17825
  var installedJavaMapResources = () => {
17707
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17708
- const compilerPath = path7.join(directory, "project-map-java/java-map.jar");
17826
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17827
+ const compilerPath = path8.join(directory, "project-map-java/java-map.jar");
17709
17828
  return {
17710
- workerPath: path7.join(directory, "project-map-java-worker.mjs"),
17829
+ workerPath: path8.join(directory, "project-map-java-worker.mjs"),
17711
17830
  compilerPath,
17712
17831
  // A build without a JDK leaves no analyzer to run, whatever runtime this machine has.
17713
- ...existsSync2(compilerPath) ? discoverJavaRuntime() : {}
17832
+ ...existsSync3(compilerPath) ? discoverJavaRuntime() : {}
17714
17833
  };
17715
17834
  };
17716
17835
  var installedGoMapResources = () => {
17717
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17836
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17718
17837
  return {
17719
- workerPath: path7.join(directory, "project-map-go-worker.mjs"),
17720
- compilerPath: path7.join(directory, "project-map-go/go-map")
17838
+ workerPath: path8.join(directory, "project-map-go-worker.mjs"),
17839
+ compilerPath: path8.join(directory, "project-map-go/go-map")
17721
17840
  };
17722
17841
  };
17723
17842
  function runMapOperation(resources, input, schema, signal, observeTiming) {
17724
17843
  if (signal.aborted)
17725
17844
  return Promise.reject(new ProjectEvidenceError("PROJECT_READ_CANCELLED", true));
17726
- if (!path7.isAbsolute(resources.workerPath) || !path7.isAbsolute(resources.compilerPath)) {
17845
+ if (!path8.isAbsolute(resources.workerPath) || !path8.isAbsolute(resources.compilerPath)) {
17727
17846
  return Promise.reject(
17728
17847
  new ProjectEvidenceError("PROJECT_MAP_PARSER_CONFIGURATION_INVALID", false)
17729
17848
  );
@@ -17923,8 +18042,8 @@ var goModule = /(?:^|\/)go\.mod$/u;
17923
18042
  var codeHosts = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
17924
18043
  var GO_MAP_LANGUAGE = Object.freeze({
17925
18044
  id: "go-1.24-map-v9",
17926
- claims: (path16) => path16.endsWith(".go"),
17927
- reads: (path16) => goModule.test(path16),
18045
+ claims: (path17) => path17.endsWith(".go"),
18046
+ reads: (path17) => goModule.test(path17),
17928
18047
  // A module path, or the standard library, whose first path element has no dot.
17929
18048
  importName: (specifier) => {
17930
18049
  const parts = specifier.split("/");
@@ -17933,7 +18052,7 @@ var GO_MAP_LANGUAGE = Object.freeze({
17933
18052
  return parts.slice(0, size).join("/");
17934
18053
  },
17935
18054
  // Go imports a package: the directory of the file.
17936
- importTarget: (path16) => `${path16.slice(0, path16.lastIndexOf("/") + 1) || "./"}`,
18055
+ importTarget: (path17) => `${path17.slice(0, path17.lastIndexOf("/") + 1) || "./"}`,
17937
18056
  create: () => new GoMapAnalyzer()
17938
18057
  });
17939
18058
  var GO_GAPS = [
@@ -17979,12 +18098,12 @@ var GoMapAnalyzer = class {
17979
18098
  }
17980
18099
  }
17981
18100
  async analyze(session, signal) {
17982
- const modules = session.readable.map((entry) => entry.path).filter((path16) => goModule.test(path16)).sort();
17983
- const moduleOf = (path16) => {
18101
+ const modules = session.readable.map((entry) => entry.path).filter((path17) => goModule.test(path17)).sort();
18102
+ const moduleOf = (path17) => {
17984
18103
  let best;
17985
18104
  for (const modFile of modules) {
17986
18105
  const directory = modFile.slice(0, modFile.lastIndexOf("/") + 1);
17987
- if (path16.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18106
+ if (path17.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
17988
18107
  best = modFile;
17989
18108
  }
17990
18109
  return best;
@@ -18000,11 +18119,11 @@ var GoMapAnalyzer = class {
18000
18119
  for (const modFile of [...groups.keys()].sort()) {
18001
18120
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18002
18121
  const files = /* @__PURE__ */ Object.create(null);
18003
- for (const path16 of [...groups.get(modFile) ?? [], ...modFile ? [modFile] : []]) {
18004
- const text = session.texts[path16];
18122
+ for (const path17 of [...groups.get(modFile) ?? [], ...modFile ? [modFile] : []]) {
18123
+ const text = session.texts[path17];
18005
18124
  if (text === void 0)
18006
18125
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18007
- files[path16] = text;
18126
+ files[path17] = text;
18008
18127
  }
18009
18128
  const input = {
18010
18129
  contextRef: digestValue({
@@ -18016,7 +18135,7 @@ var GoMapAnalyzer = class {
18016
18135
  inventory: Object.keys(files).sort(),
18017
18136
  syntaxOnly: false
18018
18137
  };
18019
- const built = existsSync3(this.resources.compilerPath);
18138
+ const built = existsSync4(this.resources.compilerPath);
18020
18139
  const reused = session.reuse(input.contextRef, { modFile, built }, Object.keys(files));
18021
18140
  if (reused) {
18022
18141
  session.accept(reused);
@@ -18034,34 +18153,33 @@ var GoMapAnalyzer = class {
18034
18153
  session.accept(analysis);
18035
18154
  }
18036
18155
  }
18037
- async references(input, reference, signal, observe) {
18038
- const text = input.files[reference.targetPath];
18039
- if (text === void 0 || !existsSync3(this.resources.compilerPath))
18040
- throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
18156
+ async references(input, references, signal, observe) {
18157
+ if (!existsSync4(this.resources.compilerPath))
18158
+ return { pages: references.map(() => null), requiredFiles: [] };
18041
18159
  const files = /* @__PURE__ */ Object.create(null);
18042
- for (const [path16, value] of Object.entries(input.files))
18043
- if (this.claims(path16) || goModule.test(path16)) files[path16] = value;
18160
+ for (const [path17, value] of Object.entries(input.files))
18161
+ if (this.claims(path17) || goModule.test(path17)) files[path17] = value;
18044
18162
  const facts = await this.operation(
18045
18163
  {
18046
18164
  ...input,
18047
18165
  files,
18048
18166
  operation: "REFERENCES",
18049
18167
  modFile: input.configPath ?? "",
18050
- target: {
18051
- path: reference.targetPath,
18052
- offset: mapFactsOffset(text, reference.symbolStart, "UTF8_BYTES")
18053
- }
18168
+ targets: references.map(({ targetPath, symbolStart }) => ({
18169
+ path: targetPath,
18170
+ offset: mapFactsOffset(input.files[targetPath] ?? "", symbolStart, "UTF8_BYTES")
18171
+ }))
18054
18172
  },
18055
18173
  MapReferenceFactsSchema,
18056
18174
  signal,
18057
18175
  observe
18058
18176
  );
18059
- return mapReferencesPage(facts, files, reference, "UTF8_BYTES");
18177
+ return mapReferencePages(facts, files, references, "UTF8_BYTES");
18060
18178
  }
18061
18179
  };
18062
18180
 
18063
18181
  // src/project-map-language-java.ts
18064
- import { existsSync as existsSync4 } from "node:fs";
18182
+ import { existsSync as existsSync5 } from "node:fs";
18065
18183
  var BUILD_FILES = [
18066
18184
  "settings.gradle.kts",
18067
18185
  "settings.gradle",
@@ -18070,14 +18188,14 @@ var BUILD_FILES = [
18070
18188
  "pom.xml"
18071
18189
  ];
18072
18190
  var buildFile = /(?:^|\/)(?:pom\.xml|(?:build|settings)\.gradle(?:\.kts)?)$/u;
18073
- var directoryOf = (path16) => path16.slice(0, path16.lastIndexOf("/") + 1);
18074
- var nameOf = (path16) => path16.slice(path16.lastIndexOf("/") + 1);
18191
+ var directoryOf = (path17) => path17.slice(0, path17.lastIndexOf("/") + 1);
18192
+ var nameOf = (path17) => path17.slice(path17.lastIndexOf("/") + 1);
18075
18193
  var DEFAULT_RELEASE = 21;
18076
18194
  var platformPackage = /^(?:java|jdk|sun|com\.sun|javax\.(?:annotation\.processing|crypto|imageio|lang\.model|management|naming|net|print|script|security|sound|sql|swing|tools|transaction\.xa|xml))(?:\.|$)/u;
18077
18195
  var JAVA_MAP_LANGUAGE = Object.freeze({
18078
18196
  id: "javac-lombok-1.18.48-map-v8",
18079
- claims: (path16) => path16.endsWith(".java"),
18080
- reads: (path16) => buildFile.test(path16),
18197
+ claims: (path17) => path17.endsWith(".java"),
18198
+ reads: (path17) => buildFile.test(path17),
18081
18199
  // A package of the Java platform, or a library named by its first two package segments.
18082
18200
  importName: (specifier) => platformPackage.test(specifier) ? "Java standard library" : specifier.split(".").slice(0, 2).join("."),
18083
18201
  create: () => new JavaMapAnalyzer()
@@ -18140,7 +18258,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18140
18258
  // The runtime found at startup may be gone since (an upgraded JDK replaces its directory).
18141
18259
  refreshRuntime() {
18142
18260
  const { runtimePath } = this.resources;
18143
- if (runtimePath && !existsSync4(runtimePath)) {
18261
+ if (runtimePath && !existsSync5(runtimePath)) {
18144
18262
  const { runtimePath: _gone, runtimeVersion: _version, ...rest } = this.resources;
18145
18263
  this.resources = { ...rest, ...discoverJavaRuntime() };
18146
18264
  }
@@ -18167,12 +18285,12 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18167
18285
  // The worker's request for a context: the Java sources, the release and which are tests.
18168
18286
  request(input, buildTexts) {
18169
18287
  const files = /* @__PURE__ */ Object.create(null);
18170
- for (const [path16, text] of Object.entries(input.files))
18171
- if (this.claims(path16)) files[path16] = text;
18288
+ for (const [path17, text] of Object.entries(input.files))
18289
+ if (this.claims(path17)) files[path17] = text;
18172
18290
  return {
18173
18291
  files,
18174
18292
  release: javaRelease(buildTexts, this.resources.runtimeVersion),
18175
- tests: Object.keys(files).filter((path16) => mapTestPath(path16))
18293
+ tests: Object.keys(files).filter((path17) => mapTestPath(path17))
18176
18294
  };
18177
18295
  }
18178
18296
  // The build files of a context's root directory, which declare its Java version.
@@ -18184,35 +18302,35 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18184
18302
  }
18185
18303
  async analyze(session, signal) {
18186
18304
  this.refreshRuntime();
18187
- const builds = session.readable.map((entry) => entry.path).filter((path16) => buildFile.test(path16));
18188
- for (const path16 of builds) session.configuration(path16);
18189
- const rank2 = (path16) => BUILD_FILES.indexOf(nameOf(path16));
18305
+ const builds = session.readable.map((entry) => entry.path).filter((path17) => buildFile.test(path17));
18306
+ for (const path17 of builds) session.configuration(path17);
18307
+ const rank2 = (path17) => BUILD_FILES.indexOf(nameOf(path17));
18190
18308
  const roots = /* @__PURE__ */ new Map();
18191
18309
  const modules = /* @__PURE__ */ new Map();
18192
- for (const path16 of builds) {
18193
- const directory = directoryOf(path16);
18310
+ for (const path17 of builds) {
18311
+ const directory = directoryOf(path17);
18194
18312
  const current = modules.get(directory);
18195
- if (current === void 0 || rank2(path16) < rank2(current)) modules.set(directory, path16);
18196
- const text = session.texts[path16] ?? "";
18197
- if (/settings\.gradle(?:\.kts)?$/u.test(path16) || path16.endsWith("pom.xml") && /<modules>/u.test(text)) {
18313
+ if (current === void 0 || rank2(path17) < rank2(current)) modules.set(directory, path17);
18314
+ const text = session.texts[path17] ?? "";
18315
+ if (/settings\.gradle(?:\.kts)?$/u.test(path17) || path17.endsWith("pom.xml") && /<modules>/u.test(text)) {
18198
18316
  const root = roots.get(directory);
18199
- if (root === void 0 || rank2(path16) < rank2(root)) roots.set(directory, path16);
18317
+ if (root === void 0 || rank2(path17) < rank2(root)) roots.set(directory, path17);
18200
18318
  }
18201
18319
  }
18202
- const configOf = (path16) => {
18320
+ const configOf = (path17) => {
18203
18321
  let outer;
18204
18322
  for (const directory of roots.keys())
18205
- if (path16.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18323
+ if (path17.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18206
18324
  outer = directory;
18207
18325
  if (outer !== void 0) return roots.get(outer);
18208
18326
  let nearest;
18209
18327
  for (const directory of modules.keys())
18210
- if (path16.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18328
+ if (path17.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18211
18329
  nearest = directory;
18212
18330
  return nearest === void 0 ? "" : modules.get(nearest);
18213
18331
  };
18214
- const output = (path16) => [...modules.keys()].some(
18215
- (directory) => path16.startsWith(`${directory}build/`) || path16.startsWith(`${directory}target/`)
18332
+ const output = (path17) => [...modules.keys()].some(
18333
+ (directory) => path17.startsWith(`${directory}build/`) || path17.startsWith(`${directory}target/`)
18216
18334
  );
18217
18335
  const groups = /* @__PURE__ */ new Map();
18218
18336
  for (const entry of session.readable) {
@@ -18227,13 +18345,13 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18227
18345
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18228
18346
  const files = /* @__PURE__ */ Object.create(null);
18229
18347
  const rootBuilds = configPath ? BUILD_FILES.map((name) => `${directoryOf(configPath)}${name}`).filter(
18230
- (path16) => builds.includes(path16)
18348
+ (path17) => builds.includes(path17)
18231
18349
  ) : [];
18232
- for (const path16 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18233
- const text = session.texts[path16];
18350
+ for (const path17 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18351
+ const text = session.texts[path17];
18234
18352
  if (text === void 0)
18235
18353
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18236
- files[path16] = text;
18354
+ files[path17] = text;
18237
18355
  }
18238
18356
  const input = {
18239
18357
  contextRef: digestValue({
@@ -18258,7 +18376,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18258
18376
  release: request.release,
18259
18377
  tests: request.tests,
18260
18378
  runtime,
18261
- built: existsSync4(this.resources.compilerPath),
18379
+ built: existsSync5(this.resources.compilerPath),
18262
18380
  lombokConfig
18263
18381
  },
18264
18382
  Object.keys(files)
@@ -18276,7 +18394,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18276
18394
  const prior = JavaStateSchema.safeParse(previous?.state).data;
18277
18395
  const incremental = previous && prior?.basis === basis ? {
18278
18396
  changed: Object.keys(request.files).filter(
18279
- (path16) => digests.get(path16) !== previous.digests.get(path16)
18397
+ (path17) => digests.get(path17) !== previous.digests.get(path17)
18280
18398
  ),
18281
18399
  state: prior.java
18282
18400
  } : void 0;
@@ -18293,7 +18411,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18293
18411
  this.resources.runtimeVersion,
18294
18412
  [
18295
18413
  ...this.resources.runtimePath ? [] : [
18296
- existsSync4(this.resources.compilerPath) ? "JAVA_RUNTIME_UNAVAILABLE" : "JAVA_ANALYZER_NOT_BUILT"
18414
+ existsSync5(this.resources.compilerPath) ? "JAVA_RUNTIME_UNAVAILABLE" : "JAVA_ANALYZER_NOT_BUILT"
18297
18415
  ],
18298
18416
  ...lombokConfig ? ["LOMBOK_CONFIG_NOT_APPLIED"] : []
18299
18417
  ]
@@ -18305,34 +18423,37 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18305
18423
  continue;
18306
18424
  }
18307
18425
  const focus = new Set(facts.focus);
18308
- if (!incremental || facts.focus.some((path16) => !Object.hasOwn(request.files, path16)) || incremental.changed.some((path16) => !focus.has(path16)))
18426
+ if (!incremental || facts.focus.some((path17) => !Object.hasOwn(request.files, path17)) || incremental.changed.some((path17) => !focus.has(path17)))
18309
18427
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18310
18428
  analysis.objects = analysis.objects.filter((object2) => focus.has(object2.anchor.path));
18311
18429
  analysis.relations = analysis.relations.filter((relation) => focus.has(relation.anchor.path));
18312
18430
  analysis.notes = analysis.notes.filter((note) => focus.has(note.anchor.path));
18313
18431
  session.accept(analysis, {
18314
18432
  state,
18315
- linked: analysis.parsedFiles.filter((path16) => !focus.has(path16))
18433
+ linked: analysis.parsedFiles.filter((path17) => !focus.has(path17))
18316
18434
  });
18317
18435
  }
18318
18436
  }
18319
- async references(input, reference, signal, observe) {
18437
+ async references(input, references, signal, observe) {
18320
18438
  this.refreshRuntime();
18321
- if (input.files[reference.targetPath] === void 0 || !this.resources.runtimePath)
18322
- throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
18439
+ if (!this.resources.runtimePath)
18440
+ return { pages: references.map(() => null), requiredFiles: [] };
18323
18441
  const request = this.request(input, _JavaMapAnalyzer.buildTexts(input.files, input.configPath));
18324
18442
  const facts = await this.operation(
18325
18443
  {
18326
18444
  ...input,
18327
18445
  ...request,
18328
18446
  operation: "REFERENCES",
18329
- target: { path: reference.targetPath, offset: reference.symbolStart }
18447
+ targets: references.map(({ targetPath, symbolStart }) => ({
18448
+ path: targetPath,
18449
+ offset: symbolStart
18450
+ }))
18330
18451
  },
18331
18452
  MapReferenceFactsSchema,
18332
18453
  signal,
18333
18454
  observe
18334
18455
  );
18335
- return mapReferencesPage(facts, request.files, reference, "UTF16");
18456
+ return mapReferencePages(facts, request.files, references, "UTF16");
18336
18457
  }
18337
18458
  };
18338
18459
 
@@ -18624,12 +18745,12 @@ var PYTHON_STANDARD_LIBRARY = /* @__PURE__ */ new Set([
18624
18745
  // src/project-map-language-python.ts
18625
18746
  var CONFIGURATION = ["pyrightconfig.json", "pyproject.toml", "setup.cfg"];
18626
18747
  var pythonConfig = /(?:^|\/)(?:pyrightconfig\.json|pyproject\.toml|setup\.cfg)$/u;
18627
- var directoryOf2 = (path16) => path16.slice(0, path16.lastIndexOf("/") + 1);
18748
+ var directoryOf2 = (path17) => path17.slice(0, path17.lastIndexOf("/") + 1);
18628
18749
  var DEFAULT_PYTHON = { major: 3, minor: 13 };
18629
18750
  var PYTHON_MAP_LANGUAGE = Object.freeze({
18630
18751
  id: "pyright-1.1.414-map-v13",
18631
- claims: (path16) => /\.pyi?$/u.test(path16),
18632
- reads: (path16) => pythonConfig.test(path16),
18752
+ claims: (path17) => /\.pyi?$/u.test(path17),
18753
+ reads: (path17) => pythonConfig.test(path17),
18633
18754
  // An absolute import names the standard library or a distribution's top-level package.
18634
18755
  importName: (specifier) => {
18635
18756
  const top = specifier.split(".", 1)[0] ?? specifier;
@@ -18681,21 +18802,21 @@ var PythonMapAnalyzer = class {
18681
18802
  return {
18682
18803
  root: input.configPath ? directoryOf2(input.configPath).replace(/\/$/u, "") : "",
18683
18804
  pythonVersion: pythonVersion(input.files, input.configPath),
18684
- tests: Object.keys(input.files).filter((path16) => this.claims(path16) && mapTestPath(path16))
18805
+ tests: Object.keys(input.files).filter((path17) => this.claims(path17) && mapTestPath(path17))
18685
18806
  };
18686
18807
  }
18687
18808
  async analyze(session, signal) {
18688
18809
  const roots = /* @__PURE__ */ new Map();
18689
- for (const path16 of session.readable.map((entry) => entry.path).filter((path17) => pythonConfig.test(path17))) {
18690
- const directory = directoryOf2(path16);
18810
+ for (const path17 of session.readable.map((entry) => entry.path).filter((path18) => pythonConfig.test(path18))) {
18811
+ const directory = directoryOf2(path17);
18691
18812
  const current = roots.get(directory);
18692
18813
  const rank2 = (file2) => CONFIGURATION.indexOf(file2.slice(directory.length));
18693
- if (current === void 0 || rank2(path16) < rank2(current)) roots.set(directory, path16);
18814
+ if (current === void 0 || rank2(path17) < rank2(current)) roots.set(directory, path17);
18694
18815
  }
18695
- const rootOf = (path16) => {
18816
+ const rootOf = (path17) => {
18696
18817
  let best;
18697
18818
  for (const directory of roots.keys())
18698
- if (path16.startsWith(directory) && (best === void 0 || directory.length > best.length))
18819
+ if (path17.startsWith(directory) && (best === void 0 || directory.length > best.length))
18699
18820
  best = directory;
18700
18821
  return best === void 0 ? "" : roots.get(best);
18701
18822
  };
@@ -18710,11 +18831,11 @@ var PythonMapAnalyzer = class {
18710
18831
  for (const configPath of [...groups.keys()].sort()) {
18711
18832
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18712
18833
  const files = /* @__PURE__ */ Object.create(null);
18713
- for (const path16 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
18714
- const text = session.texts[path16];
18834
+ for (const path17 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
18835
+ const text = session.texts[path17];
18715
18836
  if (text === void 0)
18716
18837
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18717
- files[path16] = text;
18838
+ files[path17] = text;
18718
18839
  }
18719
18840
  const input = {
18720
18841
  contextRef: digestValue({
@@ -18758,30 +18879,31 @@ var PythonMapAnalyzer = class {
18758
18879
  session.accept(analysis);
18759
18880
  }
18760
18881
  }
18761
- async references(input, reference, signal, observe) {
18762
- if (input.files[reference.targetPath] === void 0)
18763
- throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
18882
+ async references(input, references, signal, observe) {
18764
18883
  const files = /* @__PURE__ */ Object.create(null);
18765
- for (const [path16, value] of Object.entries(input.files))
18766
- if (this.claims(path16) || pythonConfig.test(path16)) files[path16] = value;
18884
+ for (const [path17, value] of Object.entries(input.files))
18885
+ if (this.claims(path17) || pythonConfig.test(path17)) files[path17] = value;
18767
18886
  const facts = await this.operation(
18768
18887
  {
18769
18888
  ...input,
18770
18889
  files,
18771
18890
  ...this.request({ ...input, files }),
18772
18891
  operation: "REFERENCES",
18773
- target: { path: reference.targetPath, offset: reference.symbolStart }
18892
+ targets: references.map(({ targetPath, symbolStart }) => ({
18893
+ path: targetPath,
18894
+ offset: symbolStart
18895
+ }))
18774
18896
  },
18775
18897
  MapReferenceFactsSchema,
18776
18898
  signal,
18777
18899
  observe
18778
18900
  );
18779
- return mapReferencesPage(facts, files, reference, "UTF16");
18901
+ return mapReferencePages(facts, files, references, "UTF16");
18780
18902
  }
18781
18903
  };
18782
18904
 
18783
18905
  // src/project-map-miniprogram.ts
18784
- import path8 from "node:path";
18906
+ import path9 from "node:path";
18785
18907
  import {
18786
18908
  isCallExpression,
18787
18909
  isExpressionStatement,
@@ -18799,9 +18921,9 @@ var miniprogramTemplateOf = (script, inventory) => /\.[cm]?[jt]sx?$/u.test(scrip
18799
18921
  function miniprogramConfiguration(template, inventory) {
18800
18922
  const own = template.replace(/\.wxml$/u, ".json");
18801
18923
  const configuration = inventory.has(own) ? { own } : {};
18802
- for (let directory = path8.posix.dirname(template); ; directory = path8.posix.dirname(directory)) {
18924
+ for (let directory = path9.posix.dirname(template); ; directory = path9.posix.dirname(directory)) {
18803
18925
  const root = directory === "." ? "" : directory;
18804
- const app = path8.posix.join(root, "app.json");
18926
+ const app = path9.posix.join(root, "app.json");
18805
18927
  if (inventory.has(app)) return { ...configuration, app, root };
18806
18928
  if (!root) return configuration;
18807
18929
  }
@@ -18813,9 +18935,9 @@ var miniprogramEventOf = (target) => {
18813
18935
 
18814
18936
  // src/project-map-language-typescript.ts
18815
18937
  var TYPESCRIPT_MAP_LANGUAGE = Object.freeze({
18816
- id: "typescript-7.0.2-map-v21",
18817
- claims: (path16) => /\.[cm]?[jt]sx?$/u.test(path16),
18818
- reads: (path16) => path16.endsWith(".json") || path16.endsWith(".wxml") || path16 === "pnpm-workspace.yaml",
18938
+ id: "typescript-7.0.2-map-v24",
18939
+ claims: (path17) => /\.[cm]?[jt]sx?$/u.test(path17),
18940
+ reads: (path17) => path17.endsWith(".json") || path17.endsWith(".wxml") || path17 === "pnpm-workspace.yaml",
18819
18941
  create: () => new TypeScriptMapAnalyzer()
18820
18942
  });
18821
18943
  var CONFIGURATIONS_KEPT = 4;
@@ -18827,8 +18949,8 @@ var TypeScriptMapAnalyzer = class {
18827
18949
  id = TYPESCRIPT_MAP_LANGUAGE.id;
18828
18950
  claims = TYPESCRIPT_MAP_LANGUAGE.claims;
18829
18951
  reads = TYPESCRIPT_MAP_LANGUAGE.reads;
18830
- // Discovery reads the texts of the files the language reads and nothing else, so a result
18831
- // stands while they are the same, as they are when only other languages' files changed.
18952
+ // Discovery reads the texts of the files the language reads and what is installed, nothing else,
18953
+ // so a result stands while they are the same, as they are when only other languages' files changed.
18832
18954
  configurations = /* @__PURE__ */ new Map();
18833
18955
  async operation(input, schema, signal, observe) {
18834
18956
  const start = performance.now();
@@ -18850,16 +18972,24 @@ var TypeScriptMapAnalyzer = class {
18850
18972
  observe?.({ ...event, phase: "FINISHED", elapsedMs: performance.now() - start });
18851
18973
  }
18852
18974
  }
18853
- references(input, reference, signal, observe) {
18975
+ references(input, references, signal, observe, until) {
18854
18976
  return this.operation(
18855
- { ...input, operation: "REFERENCES", reference },
18856
- MapReferencePageSchema,
18977
+ { ...input, operation: "REFERENCES", references, ...until === void 0 ? {} : { until } },
18978
+ MapReferenceBatchSchema,
18979
+ signal,
18980
+ observe
18981
+ );
18982
+ }
18983
+ diagnostics(input, signal, observe) {
18984
+ return this.operation(
18985
+ { ...input, operation: "DIAGNOSTICS" },
18986
+ MapDiagnosticsSchema,
18857
18987
  signal,
18858
18988
  observe
18859
18989
  );
18860
18990
  }
18861
18991
  async analyze(session, signal) {
18862
- const { entries, texts: unitTexts, observe } = session;
18992
+ const { entries, texts: unitTexts, observe, installed } = session;
18863
18993
  const byPath = new Map(session.readable.map((entry) => [entry.path, entry]));
18864
18994
  const inventory = [...byPath.keys()];
18865
18995
  const inventorySet = new Set(inventory);
@@ -18907,9 +19037,14 @@ var TypeScriptMapAnalyzer = class {
18907
19037
  configPath: configPath ?? null,
18908
19038
  rootFiles: rootFiles ?? null,
18909
19039
  inventory,
18910
- workspace: workspace ?? null
19040
+ workspace: workspace ?? null,
19041
+ installed: installed.digest
18911
19042
  },
18912
- Object.keys(texts)
19043
+ [
19044
+ ...workspace?.configurationFiles ?? [],
19045
+ ...configPath ? [configPath] : [],
19046
+ ...rootFiles ?? inventory
19047
+ ]
18913
19048
  );
18914
19049
  if (reused) {
18915
19050
  accept(reused);
@@ -18924,7 +19059,8 @@ var TypeScriptMapAnalyzer = class {
18924
19059
  files: texts,
18925
19060
  inventory,
18926
19061
  syntaxOnly: false,
18927
- ...workspace ? { workspace } : {}
19062
+ ...workspace ? { workspace } : {},
19063
+ dependencies: installed.directory
18928
19064
  };
18929
19065
  const analysis = await this.operation(
18930
19066
  { ...input, operation: "BUILD" },
@@ -18937,9 +19073,9 @@ var TypeScriptMapAnalyzer = class {
18937
19073
  accept(analysis);
18938
19074
  return;
18939
19075
  }
18940
- const required2 = analysis.requiredFiles.map((path16) => {
18941
- const entry = byPath.get(path16);
18942
- if (!entry || Object.hasOwn(texts, path16))
19076
+ const required2 = analysis.requiredFiles.map((path17) => {
19077
+ const entry = byPath.get(path17);
19078
+ if (!entry || Object.hasOwn(texts, path17))
18943
19079
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18944
19080
  return entry;
18945
19081
  });
@@ -18948,7 +19084,8 @@ var TypeScriptMapAnalyzer = class {
18948
19084
  }
18949
19085
  };
18950
19086
  const configurationKey = digestValue({
18951
- files: session.readable.map((entry) => [entry.path, entry.contentDigest ?? null])
19087
+ files: session.readable.map((entry) => [entry.path, entry.contentDigest ?? null]),
19088
+ installed: installed.digest
18952
19089
  });
18953
19090
  const discovered = this.configurations.get(configurationKey) ?? await this.operation(
18954
19091
  {
@@ -18956,7 +19093,8 @@ var TypeScriptMapAnalyzer = class {
18956
19093
  contextRef: digestValue({ entries, purpose: "CONFIGURE" }),
18957
19094
  files: unitTexts,
18958
19095
  inventory,
18959
- syntaxOnly: false
19096
+ syntaxOnly: false,
19097
+ dependencies: installed.directory
18960
19098
  },
18961
19099
  MapConfigurationResultSchema,
18962
19100
  signal,
@@ -18997,16 +19135,16 @@ var MAP_LANGUAGES = Object.freeze([
18997
19135
  ]);
18998
19136
  var mapAnalyzerSuite = (languages) => languages.map((language) => language.id).sort().join("+");
18999
19137
  var PROJECT_MAP_ANALYZER = mapAnalyzerSuite(MAP_LANGUAGES);
19000
- var mapCodePath = (path16) => MAP_LANGUAGES.some((language) => language.claims(path16));
19001
- var languageOf = (path16) => MAP_LANGUAGES.find((language) => language.claims(path16));
19002
- var mapLanguageOf = (path16) => languageOf(path16)?.id;
19138
+ var mapCodePath = (path17) => MAP_LANGUAGES.some((language) => language.claims(path17));
19139
+ var languageOf = (path17) => MAP_LANGUAGES.find((language) => language.claims(path17));
19140
+ var mapLanguageOf = (path17) => languageOf(path17)?.id;
19003
19141
  var npmPackage = (specifier) => {
19004
19142
  if (specifier.startsWith("node:")) return "node:*";
19005
19143
  const parts = specifier.split("/");
19006
19144
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
19007
19145
  };
19008
19146
  var mapExternalImport = (sourcePath, specifier) => languageOf(sourcePath)?.importName?.(specifier) ?? npmPackage(specifier);
19009
- var mapImportTarget = (path16) => languageOf(path16)?.importTarget?.(path16) ?? path16;
19147
+ var mapImportTarget = (path17) => languageOf(path17)?.importTarget?.(path17) ?? path17;
19010
19148
 
19011
19149
  // src/project-map-view.ts
19012
19150
  var MAP_VIEW_FORMAT = "PROJECT_MAP_VIEW_V1";
@@ -19019,6 +19157,7 @@ var MAP_VIEW_LIMITS = Object.freeze({
19019
19157
  members: 40,
19020
19158
  externalPackages: 20,
19021
19159
  unresolvedTargets: 12,
19160
+ notInstalled: 8,
19022
19161
  // Call targets are written text; a long call chain keeps its receiver and its last members.
19023
19162
  targetText: 120,
19024
19163
  // Calls naming a method on an unknown receiver are listed up to this many, else counted.
@@ -19045,10 +19184,10 @@ var notFound = () => {
19045
19184
  };
19046
19185
  var MAP_KINDS_LEGEND = "kinds f function, c class, m method, p property, v variable, t type, i interface, e enum; numbers are 1-based source lines";
19047
19186
  var MAP_DECLARATION_LEGEND = `@n marks where a relationship occurs and +n counts further sites, which project_find_references lists; a quoted path after the sites is the route the call or value is registered under there: its HTTP methods when the registration names them, then its path joined with the prefixes of the routers it is registered on, as far as the same function or file sets them (a prefix added where a router is mounted or passed in is not included); route "\u2026" after a decorator is the full route the decorator maps, its class's path joined with its own. Static relationships are grouped by the declaration that owns them. Callers are direct calls, uses as a value (stored, passed, returned or selected, then usually invoked through that value) and calls through an interface, type or base member that a declaration implements (dispatched from); dispatches to lists the members that implement an interface, type or base member, which a call through it may reach; trace stops names calls whose target is a function value, a member without a mapped implementation or a computed key, which only source reading can follow; possible callers by name are calls elsewhere, in the same language, of a member with a method's name on a receiver of unknown type (an untyped value, or one an unloaded package produced); they may or may not reach that method.`;
19048
- var within = (path16, directory) => directory === "." || path16.startsWith(`${directory}/`);
19049
- var parentDirectory = (path16) => {
19050
- const slash = path16.lastIndexOf("/");
19051
- return slash < 0 ? "." : path16.slice(0, slash);
19187
+ var within = (path17, directory) => directory === "." || path17.startsWith(`${directory}/`);
19188
+ var parentDirectory = (path17) => {
19189
+ const slash = path17.lastIndexOf("/");
19190
+ return slash < 0 ? "." : path17.slice(0, slash);
19052
19191
  };
19053
19192
  var compareText2 = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19054
19193
  var byCount = ([leftName, left], [rightName, right]) => right - left || compareText2(leftName, rightName);
@@ -19122,7 +19261,7 @@ function pageBlocks(view, head, whole, offset, budget) {
19122
19261
  if (offset === blocks.length) return materialize(0);
19123
19262
  return mapQueryPage(blocks.length - offset, materialize, (page) => page, budget);
19124
19263
  }
19125
- var inModule = (path16, module) => module.direct ? parentDirectory(path16) === module.directory : within(path16, module.directory);
19264
+ var inModule = (path17, module) => module.direct ? parentDirectory(path17) === module.directory : within(path17, module.directory);
19126
19265
  var moduleLabel = (module) => module.direct ? `${module.directory === "." ? "" : `${module.directory}/`}* (files directly here)` : `${module.directory}/`;
19127
19266
  function childModules(module, files) {
19128
19267
  if (module.direct) return [];
@@ -19177,9 +19316,9 @@ function mapProjectModules(entries) {
19177
19316
  (entry) => entry.state === "TEXT" && mapCodePath(entry.path) && !mapTestPath(entry.path)
19178
19317
  ).map((entry) => entry.path)
19179
19318
  );
19180
- return (path16) => {
19181
- if (mapTestPath(path16)) return void 0;
19182
- const module = modules.find((candidate) => inModule(path16, candidate));
19319
+ return (path17) => {
19320
+ if (mapTestPath(path17)) return void 0;
19321
+ const module = modules.find((candidate) => inModule(path17, candidate));
19183
19322
  return module && moduleLabel(module);
19184
19323
  };
19185
19324
  }
@@ -19187,7 +19326,7 @@ function loadImports(store, version2) {
19187
19326
  return store.database.prepare(`SELECT r.path AS source, t.path AS target,
19188
19327
  json_extract(r.relation_json, '$.target') AS specifier, count(*) AS count
19189
19328
  FROM project_map_relations r NOT INDEXED
19190
- LEFT JOIN project_map_objects t ON t.version_ref = r.version_ref AND t.entity_ref = r.to_ref
19329
+ ${MAP_RELATION_TARGET_JOIN}
19191
19330
  WHERE r.version_ref = ? AND json_extract(r.relation_json, '$.kind') IN ('IMPORTS', 'TEST_IMPORTS')
19192
19331
  GROUP BY source, target, specifier`).all(version2).map((row) => ({
19193
19332
  source: String(row.source),
@@ -19291,12 +19430,12 @@ function loadMemberCalls(store, version2) {
19291
19430
  FROM project_map_relations
19292
19431
  WHERE version_ref = ? AND to_ref IS NULL AND json_extract(relation_json, '$.kind') = 'CALLS'
19293
19432
  AND json_extract(relation_json, '$.unresolvedReason') IN ('SYMBOL_NOT_RESOLVED', 'SYNTAX_ONLY')`).all(version2)) {
19294
- const path16 = String(row.path);
19433
+ const path17 = String(row.path);
19295
19434
  const target = String(row.target);
19296
19435
  const name = MEMBER_NAME.exec(target)?.[1];
19297
- const language = mapLanguageOf(path16);
19436
+ const language = mapLanguageOf(path17);
19298
19437
  if (!name || !language) continue;
19299
- const call = { from: String(row.from_ref), path: path16, line: Number(row.line), target };
19438
+ const call = { from: String(row.from_ref), path: path17, line: Number(row.line), target };
19300
19439
  const key = memberKey(language, name);
19301
19440
  const known = calls.get(key);
19302
19441
  if (known) known.push(call);
@@ -19332,6 +19471,7 @@ var MAP_LIMITS = {
19332
19471
  GO_ANALYZER_NOT_BUILT: "the Go analyzer was not built (no Go 1.24 at build time), so Go files have no declarations or links",
19333
19472
  LOMBOK_CONFIG_NOT_APPLIED: "lombok.config settings are not applied, so names Lombok generates may differ from the build's",
19334
19473
  NO_JAVA_BUILD: "Java files outside a Gradle or Maven build are analyzed together as one program",
19474
+ STANDARD_LIBRARY_NOT_LOADED: "TypeScript's standard library was not found beside the compiler, so built-in types such as Array and ThisType are missing and calls that depend on them are unresolved",
19335
19475
  NO_ADMITTED_TSCONFIG: "TypeScript and JavaScript files outside a tsconfig use inferred settings",
19336
19476
  NO_PYTHON_CONFIGURATION: "Python files outside a project configuration use inferred settings"
19337
19477
  };
@@ -19340,7 +19480,12 @@ function loadCoverageNotes(store, version2) {
19340
19480
  const gaps = row ? JSON.parse(String(row.coverage_json)).gaps : [];
19341
19481
  const files = /* @__PURE__ */ new Map();
19342
19482
  const limits = /* @__PURE__ */ new Set();
19483
+ const notInstalled = /* @__PURE__ */ new Set();
19343
19484
  for (const gap of gaps) {
19485
+ if (gap.code === MAP_DEPENDENCY_NOT_INSTALLED && gap.package) {
19486
+ notInstalled.add(gap.package);
19487
+ continue;
19488
+ }
19344
19489
  if (gap.path === void 0) {
19345
19490
  const limit = MAP_LIMITS[gap.code];
19346
19491
  if (limit) limits.add(limit);
@@ -19351,13 +19496,18 @@ function loadCoverageNotes(store, version2) {
19351
19496
  if (!codes.includes(gap.code)) codes.push(gap.code);
19352
19497
  files.set(gap.path, codes);
19353
19498
  }
19354
- for (const [path16, codes] of files)
19499
+ for (const [path17, codes] of files)
19355
19500
  if (codes.length > 1 && codes.includes("NOT_IN_PARSED_CONTEXT"))
19356
19501
  files.set(
19357
- path16,
19502
+ path17,
19358
19503
  codes.filter((code) => code !== "NOT_IN_PARSED_CONTEXT")
19359
19504
  );
19360
- return { files, limits: [...limits] };
19505
+ const missing = [...notInstalled].sort();
19506
+ if (missing.length)
19507
+ limits.add(
19508
+ `${missing.slice(0, MAP_VIEW_LIMITS.notInstalled).join(", ")}${missing.length > MAP_VIEW_LIMITS.notInstalled ? ` and ${missing.length - MAP_VIEW_LIMITS.notInstalled} more packages` : ""} are not installed in this directory, so values typed by them have no type to follow and calls through them may be missing`
19509
+ );
19510
+ return { files, limits: [...limits], notInstalled: missing };
19361
19511
  }
19362
19512
  var MapViewCache = class {
19363
19513
  facts = new VersionCache(loadDirectoryFacts);
@@ -19394,9 +19544,9 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19394
19544
  const visiblePaths = new Set(visible.map((entry) => entry.path));
19395
19545
  const code = visible.filter((entry) => entry.state === "TEXT" && mapCodePath(entry.path)).map((entry) => entry.path);
19396
19546
  const modules = mapModules(directory, code);
19397
- const moduleOf = (path16) => modules.find((module) => inModule(path16, module));
19398
- const outside = (path16) => {
19399
- const parts = path16.split("/");
19547
+ const moduleOf = (path17) => modules.find((module) => inModule(path17, module));
19548
+ const outside = (path17) => {
19549
+ const parts = path17.split("/");
19400
19550
  return `${parts.slice(0, Math.min(2, parts.length - 1)).join("/") || "."}/ (outside)`;
19401
19551
  };
19402
19552
  const moduleImports = /* @__PURE__ */ new Map();
@@ -19421,8 +19571,8 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19421
19571
  const blocks = [];
19422
19572
  if (modules.length > 1) {
19423
19573
  const sizes = /* @__PURE__ */ new Map();
19424
- for (const path16 of code) {
19425
- const module = moduleOf(path16);
19574
+ for (const path17 of code) {
19575
+ const module = moduleOf(path17);
19426
19576
  if (module) increment(sizes, moduleLabel(module));
19427
19577
  }
19428
19578
  blocks.push(
@@ -19451,18 +19601,18 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19451
19601
  )}${packages.length > shown.length ? `, +${packages.length - shown.length} more` : ""}`
19452
19602
  );
19453
19603
  }
19454
- const lineCount = (path16) => {
19455
- const file2 = facts.files.get(path16);
19456
- const gaps = coverage.files.get(path16) ?? [];
19604
+ const lineCount = (path17) => {
19605
+ const file2 = facts.files.get(path17);
19606
+ const gaps = coverage.files.get(path17) ?? [];
19457
19607
  if (file2?.parsed === false) return `[not parsed${gaps.length ? `: ${gaps.join("; ")}` : ""}]`;
19458
19608
  return `${file2 ? `${file2.lines}L` : "?L"}${gaps.length ? ` [${gaps.join("; ")}]` : ""}`;
19459
19609
  };
19460
19610
  const codeDirectories = /* @__PURE__ */ new Set();
19461
- for (const path16 of code)
19462
- for (let parent = parentDirectory(path16); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19611
+ for (const path17 of code)
19612
+ for (let parent = parentDirectory(path17); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19463
19613
  codeDirectories.add(parent);
19464
- const groupOf = (path16) => {
19465
- let group = parentDirectory(path16);
19614
+ const groupOf = (path17) => {
19615
+ let group = parentDirectory(path17);
19466
19616
  for (let parent = group; parent !== "." && parent !== directory && !codeDirectories.has(parent); parent = parentDirectory(parent))
19467
19617
  group = parent;
19468
19618
  return group;
@@ -19494,11 +19644,11 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19494
19644
  ]);
19495
19645
  }
19496
19646
  const detailed = [
19497
- ...code.map((path16) => {
19498
- const declarations2 = (facts.exported.get(path16) ?? []).map(({ text: text2 }) => text2);
19647
+ ...code.map((path17) => {
19648
+ const declarations2 = (facts.exported.get(path17) ?? []).map(({ text: text2 }) => text2);
19499
19649
  return [
19500
- path16,
19501
- `${path16} ${lineCount(path16)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19650
+ path17,
19651
+ `${path17} ${lineCount(path17)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19502
19652
  ];
19503
19653
  }),
19504
19654
  ...listedOther.map((entry) => [
@@ -19509,7 +19659,7 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19509
19659
  ];
19510
19660
  const directories = /* @__PURE__ */ new Map();
19511
19661
  for (const entry of [
19512
- ...code.map((path16) => ({ path: path16, item: lineCount(path16) })),
19662
+ ...code.map((path17) => ({ path: path17, item: lineCount(path17) })),
19513
19663
  ...listedOther.map((entry2) => ({
19514
19664
  path: entry2.path,
19515
19665
  item: entry2.state === "TEXT" ? "" : `(${entry2.state})`
@@ -19537,10 +19687,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19537
19687
  );
19538
19688
  const text = visible.filter((entry) => entry.state === "TEXT").length;
19539
19689
  const resolution = /* @__PURE__ */ new Map();
19540
- for (const path16 of code) {
19541
- const counts = facts.calls.get(path16);
19690
+ for (const path17 of code) {
19691
+ const counts = facts.calls.get(path17);
19542
19692
  if (!counts) continue;
19543
- const language = facts.files.get(path16)?.language ?? "unknown";
19693
+ const language = facts.files.get(path17)?.language ?? "unknown";
19544
19694
  const total = resolution.get(language) ?? { resolved: 0, unresolved: 0, external: 0 };
19545
19695
  total.resolved += counts.resolved;
19546
19696
  total.unresolved += counts.unresolved;
@@ -19556,7 +19706,7 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19556
19706
  `PROJECT MAP \xB7 DIRECTORY ${directory} \xB7 ${code.length} code files \xB7 ${text - code.length} other text files${visible.length > text ? ` \xB7 ${visible.length - text} unreadable entries` : ""}${hiddenTests ? ` \xB7 ${hiddenTests} test files hidden (includeTests)` : ""}${prefixes.includes(".") ? "" : " \xB7 limited to authorized paths"}`,
19557
19707
  tier === "DETAILED" ? "Code files list line count and exported declarations; other files show size." : tier === "COMPACT" ? "File lines give a directory, then its files with line counts; join them for a path. Declarations are omitted to keep this overview small: open a file, or a directory with fewer files, to see them." : "Files are omitted because this directory is large: open a module directory to list its files.",
19558
19708
  ...rates.length ? [
19559
- `Static calls linked to project declarations: ${rates.join(", ")}; the rest have a callee of unknown type, such as a value from a package whose types are not loaded. ${externalCalls} calls into the standard library or into packages that are not loaded are not counted.`
19709
+ `Static calls linked to project declarations: ${rates.join(", ")}; the rest have a callee of unknown type, such as a value from a package that is not installed or has no types. ${externalCalls} calls into the standard library or into packages are not counted.`
19560
19710
  ] : [],
19561
19711
  ...directory === "." && coverage.limits.length ? [`Map limits: ${coverage.limits.join("; ")}.`] : []
19562
19712
  ];
@@ -19599,8 +19749,8 @@ var DeclarationGroups = class {
19599
19749
  prefixes;
19600
19750
  showTests;
19601
19751
  memberCalls;
19602
- visible(path16) {
19603
- return mapPathAllowed(path16, this.prefixes) && (this.showTests || !mapTestPath(path16));
19752
+ visible(path17) {
19753
+ return mapPathAllowed(path17, this.prefixes) && (this.showTests || !mapTestPath(path17));
19604
19754
  }
19605
19755
  entry(object2, imported = false) {
19606
19756
  if (mapMiniprogramTemplate(object2.anchor.path)) return "(template)";
@@ -19645,11 +19795,11 @@ var DeclarationGroups = class {
19645
19795
  value.lines.push(line);
19646
19796
  aggregates.set(key, value);
19647
19797
  };
19648
- const dispatch = (arrow, label, ref2, path16, line) => {
19798
+ const dispatch = (arrow, label, ref2, path17, line) => {
19649
19799
  const other = graph.object(graph.owner(ref2));
19650
19800
  if (owned.has(other.id)) return;
19651
- if (!this.visible(path16)) {
19652
- if (mapPathAllowed(path16, this.prefixes)) omittedTests++;
19801
+ if (!this.visible(path17)) {
19802
+ if (mapPathAllowed(path17, this.prefixes)) omittedTests++;
19653
19803
  return;
19654
19804
  }
19655
19805
  add(arrow, label, other, line);
@@ -19713,7 +19863,7 @@ var DeclarationGroups = class {
19713
19863
  else
19714
19864
  add(
19715
19865
  "\u2192",
19716
- shows(relation) ? "shows" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
19866
+ relation.event ? `calls via ${relation.event} event` : shows(relation) ? "shows" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
19717
19867
  other,
19718
19868
  relation.anchor.startLine,
19719
19869
  relation.argument
@@ -19738,7 +19888,7 @@ var DeclarationGroups = class {
19738
19888
  if (mapPathAllowed(relation.anchor.path, this.prefixes)) omittedTests++;
19739
19889
  continue;
19740
19890
  }
19741
- const label = relation.kind === "CALLS" && focus.kind === "CLASS" ? "instantiated by" : shows(relation) ? "shown by" : INCOMING[relation.kind] ?? relation.kind.toLowerCase();
19891
+ const label = relation.event ? `called via ${relation.event} event by` : relation.kind === "CALLS" && focus.kind === "CLASS" ? "instantiated by" : shows(relation) ? "shown by" : INCOMING[relation.kind] ?? relation.kind.toLowerCase();
19742
19892
  add(
19743
19893
  "\u2190",
19744
19894
  label,
@@ -19806,7 +19956,7 @@ var DeclarationGroups = class {
19806
19956
  else files2.set(call.path, [item]);
19807
19957
  }
19808
19958
  lines.push(
19809
- ` \u2190 possible callers by name: ${[...files2].map(([path16, items]) => `${path16}: ${items.join(", ")}`).join("; ")}${inTests}`
19959
+ ` \u2190 possible callers by name: ${[...files2].map(([path17, items]) => `${path17}: ${items.join(", ")}`).join("; ")}${inTests}`
19810
19960
  );
19811
19961
  } else if (possibleInTests)
19812
19962
  lines.push(` \u2190 possible callers by name: ${possibleInTests} in test files (includeTests)`);
@@ -19842,14 +19992,14 @@ var DeclarationGroups = class {
19842
19992
  return { lines, neighbors: [...new Set(neighbors)] };
19843
19993
  }
19844
19994
  };
19845
- function fileView(store, coverage, graph, input, path16, prefixes) {
19846
- const entry = store.getEntry(input.version, path16);
19847
- if (!entry || !mapPathAllowed(path16, prefixes)) return notFound();
19848
- const showTests = input.includeTests === true || mapTestPath(path16);
19849
- const module = mapCodePath(path16) ? graph.objectsAt(path16).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path16) ? graph.objectsAt(path16).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
19850
- const gaps = coverage.files.get(path16) ?? [];
19995
+ function fileView(store, coverage, graph, input, path17, prefixes) {
19996
+ const entry = store.getEntry(input.version, path17);
19997
+ if (!entry || !mapPathAllowed(path17, prefixes)) return notFound();
19998
+ const showTests = input.includeTests === true || mapTestPath(path17);
19999
+ const module = mapCodePath(path17) ? graph.objectsAt(path17).find((object2) => mapIsModule(object2)) : mapMiniprogramTemplate(path17) ? graph.objectsAt(path17).find((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : void 0;
20000
+ const gaps = coverage.files.get(path17) ?? [];
19851
20001
  const head = [
19852
- `PROJECT MAP \xB7 FILE ${path16} \xB7 ${entry.state !== "TEXT" ? entry.state : module ? module.parsing === "NOT_PARSED" ? `not parsed${gaps.length ? ` (${gaps.join("; ")})` : ""}; read it as text` : `${module.anchor.endLine} lines${gaps.length ? ` \xB7 ${gaps.join("; ")}` : ""}` : `${entry.byteLength} bytes, not analyzed; read it as text`}`
20002
+ `PROJECT MAP \xB7 FILE ${path17} \xB7 ${entry.state !== "TEXT" ? entry.state : module ? module.parsing === "NOT_PARSED" ? `not parsed${gaps.length ? ` (${gaps.join("; ")})` : ""}; read it as text` : `${module.anchor.endLine} lines${gaps.length ? ` \xB7 ${gaps.join("; ")}` : ""}` : `${entry.byteLength} bytes, not analyzed; read it as text`}`
19853
20003
  ];
19854
20004
  if (!module || entry.state !== "TEXT")
19855
20005
  return pageBlocks("FILE", head, [], input.offset ?? 0, input.outputBudget);
@@ -19869,7 +20019,7 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19869
20019
  tags.set(relation.from, list);
19870
20020
  }
19871
20021
  const describe3 = (object2) => [
19872
- `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path16 ? "" : ` (${object2.anchor.path})`}`,
20022
+ `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path17 ? "" : ` (${object2.anchor.path})`}`,
19873
20023
  ...tags.get(object2.id) ?? []
19874
20024
  ].join(" ");
19875
20025
  const declarations2 = [];
@@ -19884,11 +20034,11 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19884
20034
  );
19885
20035
  }
19886
20036
  const elsewhere = /* @__PURE__ */ new Map();
19887
- for (const object2 of graph.objectsAt(path16)) {
20037
+ for (const object2 of graph.objectsAt(path17)) {
19888
20038
  const parent = mapIsModule(object2) ? void 0 : graph.parent(object2.id);
19889
20039
  if (parent === void 0 || !graph.isAddressable(object2)) continue;
19890
20040
  const container = graph.object(parent);
19891
- if (mapIsModule(container) || container.anchor.path === path16) continue;
20041
+ if (mapIsModule(container) || container.anchor.path === path17) continue;
19892
20042
  const into = elsewhere.get(parent);
19893
20043
  if (into) into.push(object2);
19894
20044
  else elsewhere.set(parent, [object2]);
@@ -19902,7 +20052,7 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19902
20052
  if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
19903
20053
  const imports2 = /* @__PURE__ */ new Set();
19904
20054
  const external = /* @__PURE__ */ new Set();
19905
- const fileObjects = graph.objectsAt(path16).map((object2) => object2.id);
20055
+ const fileObjects = graph.objectsAt(path17).map((object2) => object2.id);
19906
20056
  for (const relation of graph.relationsFrom(fileObjects)) {
19907
20057
  if (!IMPORT_KINDS.has(relation.kind)) continue;
19908
20058
  if (relation.to === void 0) external.add(relation.target);
@@ -19913,8 +20063,8 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19913
20063
  }
19914
20064
  const importers = /* @__PURE__ */ new Set();
19915
20065
  const testImporters = /* @__PURE__ */ new Set();
19916
- const imported = mapImportTarget(path16);
19917
- const packageModules = imported === path16 ? [module.id] : store.listEntries(input.version).filter((entry2) => mapImportTarget(entry2.path) === imported).flatMap((entry2) => graph.objectsAt(entry2.path).filter((object2) => mapIsModule(object2))).map((object2) => object2.id);
20066
+ const imported = mapImportTarget(path17);
20067
+ const packageModules = imported === path17 ? [module.id] : store.listEntries(input.version).filter((entry2) => mapImportTarget(entry2.path) === imported).flatMap((entry2) => graph.objectsAt(entry2.path).filter((object2) => mapIsModule(object2))).map((object2) => object2.id);
19918
20068
  for (const relation of graph.relationsTo(packageModules)) {
19919
20069
  if (!IMPORT_KINDS.has(relation.kind)) continue;
19920
20070
  const source = relation.anchor.path;
@@ -19942,16 +20092,16 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19942
20092
  if (scope.length) blocks.push(["MODULE SCOPE (top-level statements)", ...scope].join("\n"));
19943
20093
  return pageBlocks("FILE", head, blocks, input.offset ?? 0, input.outputBudget);
19944
20094
  }
19945
- function declarationView(graph, input, path16, prefixes, memberCalls) {
20095
+ function declarationView(graph, input, path17, prefixes, memberCalls) {
19946
20096
  const requested = input.depth ?? 1;
19947
20097
  if (!Number.isSafeInteger(requested) || requested < 1 || requested > MAP_VIEW_LIMITS.directedDepth)
19948
20098
  return invalid2();
19949
20099
  const both = (input.direction ?? "BOTH") === "BOTH";
19950
20100
  const depth = both ? Math.min(requested, MAP_VIEW_LIMITS.bothDepth) : requested;
19951
20101
  const { name, line } = input;
19952
- const selected = mapSelectDeclarations(graph, path16, name, line);
20102
+ const selected = mapSelectDeclarations(graph, path17, name, line);
19953
20103
  if (!selected.length) return notFound();
19954
- const showTests = input.includeTests === true || mapTestPath(path16);
20104
+ const showTests = input.includeTests === true || mapTestPath(path17);
19955
20105
  const groups = new DeclarationGroups(graph, input, prefixes, showTests, memberCalls);
19956
20106
  const blocks = [];
19957
20107
  const seen = /* @__PURE__ */ new Set();
@@ -19999,7 +20149,7 @@ function declarationView(graph, input, path16, prefixes, memberCalls) {
19999
20149
  );
20000
20150
  }
20001
20151
  const head = [
20002
- `PROJECT MAP \xB7 DECLARATION ${path16}${name === void 0 ? "" : ` ${name}`}${line === void 0 ? "" : ` line ${line}`} \xB7 direction ${input.direction ?? "BOTH"} \xB7 depth ${depth}${depth < requested ? ` (BOTH is limited to ${MAP_VIEW_LIMITS.bothDepth})` : ""}${prefixes.includes(".") ? "" : " \xB7 limited to authorized paths"}`,
20152
+ `PROJECT MAP \xB7 DECLARATION ${path17}${name === void 0 ? "" : ` ${name}`}${line === void 0 ? "" : ` line ${line}`} \xB7 direction ${input.direction ?? "BOTH"} \xB7 depth ${depth}${depth < requested ? ` (BOTH is limited to ${MAP_VIEW_LIMITS.bothDepth})` : ""}${prefixes.includes(".") ? "" : " \xB7 limited to authorized paths"}`,
20003
20153
  ...truncated ? [`Expansion stopped at ${MAP_VIEW_LIMITS.declarations} declarations.`] : [],
20004
20154
  ...(input.direction ?? "BOTH") === "OUTGOING" ? [] : [callerCoverage(input.textSearch ?? DEFAULT_TEXT_SEARCH)]
20005
20155
  ];
@@ -20126,10 +20276,10 @@ var ProjectMapQuery = class {
20126
20276
  view(input, signal) {
20127
20277
  this.requireReadableMap(input.version, signal);
20128
20278
  const { offset, prefixes } = admission(input);
20129
- const path16 = normalizeProjectEvidencePath(input.path, true) || ".";
20279
+ const path17 = normalizeProjectEvidencePath(input.path, true) || ".";
20130
20280
  const view = mapView(
20131
20281
  this.store,
20132
- { ...input, path: path16, offset, allowedPathPrefixes: prefixes },
20282
+ { ...input, path: path17, offset, allowedPathPrefixes: prefixes },
20133
20283
  this.views
20134
20284
  );
20135
20285
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -20329,13 +20479,13 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20329
20479
  */
20330
20480
  async readAll(expected) {
20331
20481
  if (this.signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
20332
- const paths = expected.map(({ path: path16 }) => {
20333
- assertProjectEvidencePathNotSensitive(path16);
20334
- if (isProjectEvidenceTraversalExcluded(path16))
20482
+ const paths = expected.map(({ path: path17 }) => {
20483
+ assertProjectEvidencePathNotSensitive(path17);
20484
+ if (isProjectEvidenceTraversalExcluded(path17))
20335
20485
  throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20336
- return path16;
20486
+ return path17;
20337
20487
  });
20338
- const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path16) => this.session.captureFile(path16));
20488
+ const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path17) => this.session.captureFile(path17));
20339
20489
  for (const [index, { entry }] of results.entries()) {
20340
20490
  const wanted = expected[index];
20341
20491
  if (entry.state !== wanted?.state || entry.contentDigest !== wanted.contentDigest || entry.byteLength !== wanted.byteLength)
@@ -20696,7 +20846,7 @@ ${scopeDigest}`;
20696
20846
  throw new ProjectEvidenceError("PROJECT_READ_RANGE_NOT_AVAILABLE", false);
20697
20847
  const entry = this.store.getEntry(input.version, relativePath);
20698
20848
  if (!entry) throw new ProjectEvidenceError("PROJECT_PATH_NOT_READABLE", false);
20699
- const contentDigest = this.requireTextContentDigest(entry);
20849
+ const contentDigest2 = this.requireTextContentDigest(entry);
20700
20850
  const session = new ProjectMapReadSession(this.store, input.version, input.source, signal);
20701
20851
  const content = await session.read(entry);
20702
20852
  await session.assertStable();
@@ -20714,7 +20864,7 @@ ${scopeDigest}`;
20714
20864
  endLine: startLine + Math.max(0, selected.length - 1)
20715
20865
  }),
20716
20866
  text: selected.join("\n"),
20717
- contentDigest,
20867
+ contentDigest: contentDigest2,
20718
20868
  sourceHasMore: endLine < Math.min(declaration?.endLine ?? lines.length, lines.length),
20719
20869
  ...object2 ? {
20720
20870
  symbol: Object.freeze({
@@ -20795,7 +20945,7 @@ ${scopeDigest}`;
20795
20945
  };
20796
20946
 
20797
20947
  // src/code-index-store.ts
20798
- import { createHash as createHash3, randomBytes, randomUUID } from "node:crypto";
20948
+ import { createHash as createHash4, randomBytes, randomUUID } from "node:crypto";
20799
20949
  var CODE_INDEX_SCHEMA = `
20800
20950
  CREATE TABLE project_code_meta (meta_key TEXT PRIMARY KEY, meta_value TEXT NOT NULL);
20801
20951
  CREATE TABLE project_code_versions (
@@ -21043,12 +21193,13 @@ var CodeIndexStore = class {
21043
21193
  discardMapStage(buildRef) {
21044
21194
  this.database.prepare("DELETE FROM project_map_staging WHERE build_ref = ?").run(buildRef);
21045
21195
  }
21046
- publish(version2, entries, buildRef, coverage, linked) {
21196
+ publish(version2, entries, installedDigest, buildRef, coverage, linked) {
21047
21197
  if (version2.version !== digestValue({
21048
21198
  projectRef: version2.projectRef,
21049
21199
  pathPrefixes: version2.pathPrefixes,
21050
21200
  entries,
21051
- analyzer: version2.analyzer
21201
+ analyzer: version2.analyzer,
21202
+ installed: installedDigest
21052
21203
  }) || entries.length !== version2.fileCount || entries.filter((entry) => entry.state === "TEXT").length !== version2.readableTextFileCount || entries.filter((entry) => entry.state === "TEXT").reduce((sum, entry) => sum + entry.byteLength, 0) !== version2.capturedBytes)
21053
21204
  return corrupt2();
21054
21205
  this.database.exec("BEGIN IMMEDIATE");
@@ -21057,7 +21208,7 @@ var CodeIndexStore = class {
21057
21208
  const staged = this.stageUnits(buildRef, paths, linked);
21058
21209
  const reused = linked ? this.database.prepare(`SELECT path, unit_ref FROM project_map_version_units
21059
21210
  WHERE version_ref = ? AND path IN (SELECT value FROM json_each(?))`).all(linked.version, JSON.stringify([...linked.paths])).map((row) => ({ path: String(row.path), unit: String(row.unit_ref) })) : [];
21060
- if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path16 }) => !paths.has(path16)) || staged.some(({ path: path16 }) => linked?.paths.has(path16)))
21211
+ if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path17 }) => !paths.has(path17)) || staged.some(({ path: path17 }) => linked?.paths.has(path17)))
21061
21212
  throw new MapReplayConflict();
21062
21213
  const units = [...staged, ...reused].sort(
21063
21214
  (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
@@ -21108,7 +21259,7 @@ var CodeIndexStore = class {
21108
21259
  const member = this.database.prepare(
21109
21260
  "INSERT INTO project_map_version_units VALUES (?, ?, ?)"
21110
21261
  );
21111
- for (const { path: path16, unit } of reused) member.run(version2.version, path16, unit);
21262
+ for (const { path: path17, unit } of reused) member.run(version2.version, path17, unit);
21112
21263
  this.database.prepare("INSERT INTO project_map_coverage VALUES (?, ?)").run(version2.version, canonicalJson(coverage));
21113
21264
  }
21114
21265
  this.database.exec(`DELETE FROM project_map_publish_objects;
@@ -21163,7 +21314,7 @@ var CodeIndexStore = class {
21163
21314
  corrupt2();
21164
21315
  }
21165
21316
  if (linked) {
21166
- const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path16) => !linked.paths.has(path16));
21317
+ const unlinked = database.prepare("SELECT path FROM project_map_version_units WHERE version_ref = ?").all(linked.version).map((row) => String(row.path)).filter((path17) => !linked.paths.has(path17));
21167
21318
  if (database.prepare(`SELECT 1 FROM project_map_objects gone
21168
21319
  WHERE gone.version_ref = ? AND gone.path IN (SELECT value FROM json_each(?))
21169
21320
  AND gone.entity_ref NOT IN (SELECT entity_ref FROM project_map_publish_objects)
@@ -21185,17 +21336,17 @@ var CodeIndexStore = class {
21185
21336
  const units = [];
21186
21337
  for (const row of database.prepare(`SELECT path FROM project_map_publish_objects
21187
21338
  UNION SELECT path FROM project_map_publish_relations ORDER BY path`).all()) {
21188
- const path16 = String(row.path);
21189
- const hash2 = createHash3("sha256").update(path16).update("\0");
21339
+ const path17 = String(row.path);
21340
+ const hash2 = createHash4("sha256").update(path17).update("\0");
21190
21341
  for (const [mark, statement] of [
21191
21342
  ["object", objects2],
21192
21343
  ["relation", relations],
21193
21344
  ["note", pathNotes]
21194
21345
  ])
21195
- for (const fact of statement.all(path16))
21346
+ for (const fact of statement.all(path17))
21196
21347
  for (const value of Object.values(fact))
21197
21348
  hash2.update(mark).update("\0").update(String(value)).update("\0");
21198
- units.push({ path: path16, unit: hash2.digest("hex") });
21349
+ units.push({ path: path17, unit: hash2.digest("hex") });
21199
21350
  }
21200
21351
  return units;
21201
21352
  }
@@ -21213,13 +21364,13 @@ var CodeIndexStore = class {
21213
21364
  "INSERT INTO project_map_unit_notes SELECT ?, * FROM project_map_publish_notes WHERE path = ?"
21214
21365
  );
21215
21366
  const member = database.prepare("INSERT INTO project_map_version_units VALUES (?, ?, ?)");
21216
- for (const { path: path16, unit } of units) {
21217
- if (insertUnit.run(unit, path16).changes) {
21218
- unitObjects.run(unit, path16);
21219
- unitRelations.run(unit, path16);
21220
- unitNotes.run(unit, path16);
21367
+ for (const { path: path17, unit } of units) {
21368
+ if (insertUnit.run(unit, path17).changes) {
21369
+ unitObjects.run(unit, path17);
21370
+ unitRelations.run(unit, path17);
21371
+ unitNotes.run(unit, path17);
21221
21372
  }
21222
- member.run(version2, path16, unit);
21373
+ member.run(version2, path17, unit);
21223
21374
  }
21224
21375
  }
21225
21376
  /**
@@ -21472,27 +21623,30 @@ var contextFiles = (context) => [
21472
21623
  ...context.configurationFiles,
21473
21624
  ...context.workspace?.configurationFiles ?? []
21474
21625
  ];
21475
- function replayableContexts(parent, digests) {
21626
+ var codeFiles = (context, parsedFiles, claims) => [...context.inputFiles.filter(claims), ...parsedFiles];
21627
+ function replayableContexts(parent, digests, claims) {
21628
+ const factFiles = /* @__PURE__ */ new Map();
21476
21629
  const sharing = /* @__PURE__ */ new Map();
21477
- for (const [ref, { context }] of parent.contexts)
21478
- for (const path16 of contextFiles(context)) {
21479
- const refs = sharing.get(path16) ?? /* @__PURE__ */ new Set();
21630
+ const analyzed = /* @__PURE__ */ new Set();
21631
+ for (const [ref, { context }] of parent.contexts) {
21632
+ const { analysis, paths } = parent.shell(ref);
21633
+ const files = /* @__PURE__ */ new Set([...codeFiles(context, analysis.parsedFiles, claims), ...paths ?? []]);
21634
+ factFiles.set(ref, files);
21635
+ for (const path17 of files) {
21636
+ const refs = sharing.get(path17) ?? /* @__PURE__ */ new Set();
21480
21637
  refs.add(ref);
21481
- sharing.set(path16, refs);
21638
+ sharing.set(path17, refs);
21482
21639
  }
21483
- const unchanged = /* @__PURE__ */ new Set();
21484
- for (const [ref, { context }] of parent.contexts)
21485
- if (contextFiles(context).every(
21486
- (path16) => digests.get(path16) !== void 0 && digests.get(path16) === parent.entries.get(path16)
21487
- ))
21488
- unchanged.add(ref);
21489
- const replayable = /* @__PURE__ */ new Set();
21490
- for (const [ref, { context }] of parent.contexts)
21491
- if (unchanged.has(ref) && contextFiles(context).every(
21492
- (path16) => [...sharing.get(path16) ?? []].every((other) => unchanged.has(other))
21640
+ if (!paths || !contextFiles(context).every(
21641
+ (path17) => digests.get(path17) !== void 0 && digests.get(path17) === parent.entries.get(path17)
21493
21642
  ))
21494
- replayable.add(ref);
21495
- return { replayable, sharing };
21643
+ analyzed.add(ref);
21644
+ }
21645
+ for (const ref of analyzed)
21646
+ for (const path17 of factFiles.get(ref) ?? [])
21647
+ for (const other of sharing.get(path17) ?? []) analyzed.add(other);
21648
+ const replayable = new Set([...parent.contexts.keys()].filter((ref) => !analyzed.has(ref)));
21649
+ return { replayable, sharing, factFiles };
21496
21650
  }
21497
21651
  var invalidParent = () => {
21498
21652
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
@@ -21522,16 +21676,20 @@ var ProjectMapAnalyzer = class {
21522
21676
  languages;
21523
21677
  observe;
21524
21678
  id;
21525
- claims(path16) {
21526
- return this.languages.some((language) => language.claims(path16));
21679
+ claims(path17) {
21680
+ return this.languages.some((language) => language.claims(path17));
21527
21681
  }
21528
- references(input, reference, signal) {
21529
- const language = this.languages.find((language2) => language2.claims(reference.targetPath));
21530
- if (!language?.references)
21531
- throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
21532
- return language.references(input, reference, signal, this.observe);
21682
+ // A context holds one language's code, so its requests are that language's.
21683
+ async references(input, references, signal, until) {
21684
+ const [first] = references;
21685
+ const language = first && this.languages.find((item) => item.claims(first.targetPath));
21686
+ return language?.references ? language.references(input, references, signal, this.observe, until) : { pages: references.map(() => null), requiredFiles: [] };
21687
+ }
21688
+ // A context's compiler diagnostics, undefined for a language without a compiler to ask.
21689
+ diagnostics(input, path17, signal) {
21690
+ return this.languages.find((language) => language.claims(path17))?.diagnostics?.(input, signal, this.observe);
21533
21691
  }
21534
- async analyze(reader, entries, signal, consume, parent) {
21692
+ async analyze(reader, entries, installed, signal, consume, parent) {
21535
21693
  const result = {
21536
21694
  gaps: [{ code: "MAP_COVERS_ADMITTED_SCOPE_AND_POLICY_ONLY" }],
21537
21695
  parsedFiles: []
@@ -21553,7 +21711,12 @@ var ProjectMapAnalyzer = class {
21553
21711
  const digests = /* @__PURE__ */ new Map();
21554
21712
  for (const entry of entries)
21555
21713
  if (entry.contentDigest) digests.set(entry.path, entry.contentDigest);
21556
- const { replayable, sharing } = parent ? replayableContexts(parent, digests) : { replayable: /* @__PURE__ */ new Set(), sharing: /* @__PURE__ */ new Map() };
21714
+ const claims = (path17) => this.claims(path17);
21715
+ const { replayable, sharing, factFiles } = parent ? replayableContexts(parent, digests, claims) : {
21716
+ replayable: /* @__PURE__ */ new Set(),
21717
+ sharing: /* @__PURE__ */ new Map(),
21718
+ factFiles: /* @__PURE__ */ new Map()
21719
+ };
21557
21720
  const requests = /* @__PURE__ */ new Map();
21558
21721
  const states = /* @__PURE__ */ new Map();
21559
21722
  const replayed = /* @__PURE__ */ new Map();
@@ -21563,13 +21726,13 @@ var ProjectMapAnalyzer = class {
21563
21726
  const reuse = (contextRef2, request, files2) => {
21564
21727
  const digest = digestValue({
21565
21728
  request,
21566
- files: files2.map((path16) => [path16, digests.get(path16) ?? null])
21729
+ files: files2.map((path17) => [path17, digests.get(path17) ?? null])
21567
21730
  });
21568
21731
  requests.set(contextRef2, digest);
21569
21732
  if (!parent || !replayable.has(contextRef2)) return void 0;
21570
21733
  if (parent.contexts.get(contextRef2)?.requestDigest !== digest) return void 0;
21571
21734
  const { analysis, state, paths } = parent.shell(contextRef2);
21572
- if (!paths) return void 0;
21735
+ if (!paths) return invalidParent();
21573
21736
  if (state !== void 0) states.set(contextRef2, state);
21574
21737
  replayed.set(contextRef2, paths);
21575
21738
  this.observe?.({
@@ -21602,7 +21765,7 @@ var ProjectMapAnalyzer = class {
21602
21765
  const ref = analysis.contexts[0]?.ref ?? "";
21603
21766
  if (options?.linked?.length) {
21604
21767
  if (!parent || analysis.contexts.length !== 1) return invalidParent();
21605
- for (const path16 of options.linked) linked.add(path16);
21768
+ for (const path17 of options.linked) linked.add(path17);
21606
21769
  this.observe?.({
21607
21770
  operation: "LINK",
21608
21771
  phase: "FINISHED",
@@ -21629,11 +21792,11 @@ var ProjectMapAnalyzer = class {
21629
21792
  });
21630
21793
  for (const file2 of analysis.parsedFiles) parsed.add(file2);
21631
21794
  const staged = factPaths(analysis);
21632
- for (const path16 of staged) stagedPaths.add(path16);
21795
+ for (const path17 of staged) stagedPaths.add(path17);
21633
21796
  for (const context of analysis.contexts) {
21634
21797
  for (const file2 of context.configurationFiles) configurationInputs.add(file2);
21635
21798
  if (!replayed.has(context.ref))
21636
- for (const file2 of options?.linked?.length ? staged : contextFiles(context))
21799
+ for (const file2 of options?.linked?.length ? staged : codeFiles(context, analysis.parsedFiles, claims))
21637
21800
  analyzedFiles.add(file2);
21638
21801
  }
21639
21802
  for (const gap of analysis.gaps) result.gaps.push(gap);
@@ -21652,13 +21815,14 @@ var ProjectMapAnalyzer = class {
21652
21815
  await language.analyze(
21653
21816
  {
21654
21817
  entries,
21818
+ installed,
21655
21819
  readable: own,
21656
21820
  texts,
21657
21821
  read,
21658
21822
  accept,
21659
21823
  reuse,
21660
21824
  previous,
21661
- configuration: (path16) => configurationInputs.add(path16),
21825
+ configuration: (path17) => configurationInputs.add(path17),
21662
21826
  observe: this.observe
21663
21827
  },
21664
21828
  signal
@@ -21695,12 +21859,12 @@ var ProjectMapAnalyzer = class {
21695
21859
  if (files.objects.length) accept(files);
21696
21860
  if (parent && (replayed.size || linked.size)) {
21697
21861
  for (const ref of replayed.keys())
21698
- for (const path16 of contextFiles(parent.contexts.get(ref)?.context ?? invalidParent()))
21699
- if (analyzedFiles.has(path16) || [...sharing.get(path16) ?? []].some((other) => !replayed.has(other)))
21862
+ for (const path17 of factFiles.get(ref) ?? invalidParent())
21863
+ if (analyzedFiles.has(path17) || [...sharing.get(path17) ?? []].some((other) => !replayed.has(other)))
21700
21864
  throw new MapReplayConflict();
21701
- for (const paths of replayed.values()) for (const path16 of paths) linked.add(path16);
21702
- for (const path16 of linked)
21703
- if (analyzedFiles.has(path16) || stagedPaths.has(path16)) throw new MapReplayConflict();
21865
+ for (const paths of replayed.values()) for (const path17 of paths) linked.add(path17);
21866
+ for (const path17 of linked)
21867
+ if (analyzedFiles.has(path17) || stagedPaths.has(path17)) throw new MapReplayConflict();
21704
21868
  parent.link([...linked]);
21705
21869
  }
21706
21870
  result.parsedFiles = [...parsed].sort();
@@ -21709,6 +21873,11 @@ var ProjectMapAnalyzer = class {
21709
21873
  };
21710
21874
 
21711
21875
  // src/project-map-reference-query.ts
21876
+ var invalidProtocol = () => new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
21877
+ var anchored = ({ anchor }, files) => {
21878
+ const text = files[anchor.path];
21879
+ return text !== void 0 && anchor.start >= 0 && anchor.end >= anchor.start && anchor.end <= text.length;
21880
+ };
21712
21881
  var ProjectMapReferenceQuery = class {
21713
21882
  constructor(store, analyzer) {
21714
21883
  this.store = store;
@@ -21716,18 +21885,186 @@ var ProjectMapReferenceQuery = class {
21716
21885
  }
21717
21886
  store;
21718
21887
  analyzer;
21719
- async query(input, signal) {
21888
+ // The source to read a complete map version from, once that version is this source's to read.
21889
+ readable(version2, input) {
21720
21890
  const source = Object.freeze({
21721
- ...input.source,
21722
- directory: Object.freeze({ ...input.source.directory })
21891
+ ...input,
21892
+ directory: Object.freeze({ ...input.directory })
21723
21893
  });
21724
- const version2 = this.store.requireVersion(input.version);
21725
- if (version2.analyzer !== this.analyzer.id)
21894
+ const stored = this.store.requireVersion(version2);
21895
+ if (stored.analyzer !== this.analyzer.id)
21726
21896
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
21727
- if (version2.projectRef !== source.projectRef)
21897
+ if (stored.projectRef !== source.projectRef)
21728
21898
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_ACCESS_REVOKED", false);
21729
- if (!this.store.getIndexProgress(input.version).complete)
21899
+ if (!this.store.getIndexProgress(version2).complete)
21730
21900
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
21901
+ return source;
21902
+ }
21903
+ // The compiler contexts a file is in.
21904
+ contexts(version2, path17) {
21905
+ return this.store.database.prepare(`SELECT DISTINCT c.context_ref, c.context_json
21906
+ FROM project_map_contexts c, json_each(c.context_json, '$.inputFiles') f
21907
+ WHERE c.version_ref = ? AND f.value = ?
21908
+ AND json_extract(c.context_json, '$.mode') != 'SYNTAX_ONLY'
21909
+ ORDER BY c.context_ref`).all(version2, path17).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
21910
+ }
21911
+ // A context's sources, and the request for its compile.
21912
+ async open(version2, source, context, signal) {
21913
+ const entries = context.inputFiles.map((file2) => {
21914
+ const entry = this.store.getEntry(version2, file2);
21915
+ if (entry?.state !== "TEXT")
21916
+ throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
21917
+ return entry;
21918
+ });
21919
+ const reader = await ProjectMapSourceReader.open(source, signal, false);
21920
+ const files = /* @__PURE__ */ Object.create(null);
21921
+ const contents = await reader.readAll(entries);
21922
+ for (const [index, entry] of entries.entries()) {
21923
+ const value = contents[index];
21924
+ if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
21925
+ files[entry.path] = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
21926
+ value.content
21927
+ );
21928
+ }
21929
+ return {
21930
+ reader,
21931
+ files,
21932
+ request: {
21933
+ contextRef: context.ref,
21934
+ configPath: context.configPath,
21935
+ rootFiles: context.rootFiles,
21936
+ files,
21937
+ inventory: context.inputFiles,
21938
+ syntaxOnly: false,
21939
+ workspace: context.workspace,
21940
+ dependencies: source.directory.canonicalPath
21941
+ }
21942
+ };
21943
+ }
21944
+ /** The configurations of the contexts a version's files are in. */
21945
+ contextConfigurations(version2, paths) {
21946
+ return paths.flatMap(
21947
+ (path17) => this.contexts(version2, path17).flatMap((context) => context.configPath ?? [])
21948
+ );
21949
+ }
21950
+ /**
21951
+ * What the compiler says is wrong in each context of the given configurations, for as long as
21952
+ * the deadline leaves; a context started is compiled to the end, so what each holds is whole. A
21953
+ * context without a configuration was given options of ours, so its errors say nothing of how
21954
+ * the project compiles. Contexts of a language without a compiler to ask are not counted.
21955
+ */
21956
+ async diagnostics(input, signal) {
21957
+ const source = this.readable(input.version, input.source);
21958
+ const contexts = /* @__PURE__ */ new Map();
21959
+ for (const row of this.store.database.prepare(`SELECT DISTINCT context_ref, context_json FROM project_map_contexts
21960
+ WHERE version_ref = ? AND json_extract(context_json, '$.mode') != 'SYNTAX_ONLY'
21961
+ ORDER BY context_ref`).all(input.version)) {
21962
+ const context = MapContextSchema.parse(JSON.parse(String(row.context_json)));
21963
+ if (context.configPath && input.configurations.includes(context.configPath))
21964
+ contexts.set(context.configPath, context);
21965
+ }
21966
+ const compiled = [];
21967
+ const unchecked = [];
21968
+ for (const [configPath, context] of contexts) {
21969
+ if (Date.now() > input.until) {
21970
+ unchecked.push(configPath);
21971
+ continue;
21972
+ }
21973
+ const [path17] = context.rootFiles ?? context.inputFiles;
21974
+ const { reader, request } = await this.open(input.version, source, context, signal);
21975
+ const result = path17 === void 0 ? void 0 : await this.analyzer.diagnostics(request, path17, signal);
21976
+ await reader.assertStable();
21977
+ if (!result) continue;
21978
+ if (result.requiredFiles.length)
21979
+ throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
21980
+ const found = new Map(
21981
+ result.diagnostics.map((item) => [
21982
+ `${item.path}:${item.line}:${item.code}:${item.text}`,
21983
+ item
21984
+ ])
21985
+ );
21986
+ compiled.push({ configPath, errors: [...found.values()], missing: result.missing });
21987
+ }
21988
+ return { contexts: compiled, unchecked };
21989
+ }
21990
+ // The innermost object around a location.
21991
+ owner(version2, anchor) {
21992
+ const row = this.store.database.prepare(`SELECT object_json FROM project_map_objects
21993
+ WHERE version_ref = ? AND path = ?
21994
+ AND json_extract(object_json, '$.anchor.start') <= ? AND json_extract(object_json, '$.anchor.end') >= ?
21995
+ ORDER BY json_extract(object_json, '$.anchor.end') - json_extract(object_json, '$.anchor.start'), entity_ref LIMIT 1`).get(version2, anchor.path, anchor.start, anchor.end);
21996
+ return row ? MapObjectSchema.parse(JSON.parse(String(row.object_json))) : void 0;
21997
+ }
21998
+ /**
21999
+ * The uses of many declarations of one version, each context they are in compiled once, for as
22000
+ * long as the deadline leaves. A declaration not read to the end says so, with what was found.
22001
+ */
22002
+ async uses(input, signal) {
22003
+ const source = this.readable(input.version, input.source);
22004
+ const found = /* @__PURE__ */ new Map();
22005
+ const contextsOf = /* @__PURE__ */ new Map();
22006
+ const compiles = /* @__PURE__ */ new Map();
22007
+ for (const ref of input.refs) {
22008
+ const object2 = requireMapObject(this.store, input.version, { entityRef: ref }, ["."]);
22009
+ const path17 = object2.anchor.path;
22010
+ const contexts = contextsOf.get(path17) ?? this.contexts(input.version, path17);
22011
+ contextsOf.set(path17, contexts);
22012
+ const readable = object2.symbolStart === void 0 ? [] : contexts;
22013
+ found.set(ref, {
22014
+ uses: [],
22015
+ locations: /* @__PURE__ */ new Set(),
22016
+ waiting: readable.length,
22017
+ complete: readable.length > 0
22018
+ });
22019
+ for (const context of readable) {
22020
+ const compile = compiles.get(context.ref) ?? { context, targets: [] };
22021
+ compile.targets.push(object2);
22022
+ compiles.set(context.ref, compile);
22023
+ }
22024
+ }
22025
+ for (const { context, targets } of compiles.values()) {
22026
+ if (Date.now() > input.until) break;
22027
+ const { reader, files, request } = await this.open(input.version, source, context, signal);
22028
+ const { pages, requiredFiles } = await this.analyzer.references(
22029
+ request,
22030
+ targets.map((object2) => ({
22031
+ targetPath: object2.anchor.path,
22032
+ symbolStart: object2.symbolStart,
22033
+ offset: 0,
22034
+ maxResults: input.maxResults
22035
+ })),
22036
+ signal,
22037
+ input.until
22038
+ );
22039
+ if (requiredFiles.length)
22040
+ throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
22041
+ if (pages.length > targets.length)
22042
+ throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
22043
+ for (const [at, page] of pages.entries()) {
22044
+ const read = found.get(targets[at]?.id ?? "");
22045
+ read.waiting--;
22046
+ if (!page || page.nextOffset !== void 0) read.complete = false;
22047
+ for (const reference of page?.references ?? []) {
22048
+ const location2 = canonicalJson(reference.anchor);
22049
+ if (!anchored(reference, files)) throw invalidProtocol();
22050
+ if (read.locations.has(location2)) continue;
22051
+ read.locations.add(location2);
22052
+ const owner = this.owner(input.version, reference.anchor);
22053
+ read.uses.push({ ...reference, ...owner ? { owner } : {} });
22054
+ }
22055
+ }
22056
+ await reader.assertStable();
22057
+ if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
22058
+ }
22059
+ return new Map(
22060
+ [...found].map(([ref, { uses, waiting, complete }]) => [
22061
+ ref,
22062
+ { uses, complete: complete && !waiting }
22063
+ ])
22064
+ );
22065
+ }
22066
+ async query(input, signal) {
22067
+ const source = this.readable(input.version, input.source);
21731
22068
  if (!Number.isSafeInteger(input.maxResults) || input.maxResults < 1 || input.maxResults > 200)
21732
22069
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
21733
22070
  const prefixes = (input.allowedPathPrefixes ?? ["."]).map(
@@ -21740,11 +22077,7 @@ var ProjectMapReferenceQuery = class {
21740
22077
  const object2 = requireMapObject(this.store, input.version, input, prefixes);
21741
22078
  if (object2.symbolStart === void 0)
21742
22079
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
21743
- const availableContexts = this.store.database.prepare(`SELECT DISTINCT c.context_ref, c.context_json
21744
- FROM project_map_contexts c, json_each(c.context_json, '$.inputFiles') f
21745
- WHERE c.version_ref = ? AND f.value = ?
21746
- AND json_extract(c.context_json, '$.mode') != 'SYNTAX_ONLY'
21747
- ORDER BY c.context_ref`).all(input.version, object2.anchor.path).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
22080
+ const availableContexts = this.contexts(input.version, object2.anchor.path);
21748
22081
  if (!availableContexts.length)
21749
22082
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_CONTEXT_UNAVAILABLE", false);
21750
22083
  const contexts = availableContexts.filter(
@@ -21785,58 +22118,38 @@ ${scope}`, input.cursor, 2) : [];
21785
22118
  }
21786
22119
  const context = contexts[cursor.context];
21787
22120
  if (!context) throw new ProjectEvidenceError("PROJECT_CONTINUATION_INVALID", false);
21788
- const entries = context.inputFiles.map((file2) => {
21789
- const entry = this.store.getEntry(input.version, file2);
21790
- if (entry?.state !== "TEXT")
21791
- throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
21792
- return entry;
21793
- });
21794
- const reader = await ProjectMapSourceReader.open(source, signal, false);
21795
- const files = /* @__PURE__ */ Object.create(null);
21796
- const contents = await reader.readAll(entries);
21797
- for (const [index, entry] of entries.entries()) {
21798
- const value = contents[index];
21799
- if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
21800
- files[entry.path] = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
21801
- value.content
21802
- );
21803
- }
21804
- const page = await this.analyzer.references(
21805
- {
21806
- contextRef: context.ref,
21807
- configPath: context.configPath,
21808
- rootFiles: context.rootFiles,
21809
- files,
21810
- inventory: context.inputFiles,
21811
- syntaxOnly: false,
21812
- workspace: context.workspace
21813
- },
21814
- {
21815
- targetPath: object2.anchor.path,
21816
- symbolStart: object2.symbolStart,
21817
- offset: cursor.offset,
21818
- maxResults: input.maxResults,
21819
- ...query
21820
- },
22121
+ const { reader, files, request } = await this.open(input.version, source, context, signal);
22122
+ const {
22123
+ pages: [page],
22124
+ requiredFiles
22125
+ } = await this.analyzer.references(
22126
+ request,
22127
+ [
22128
+ {
22129
+ targetPath: object2.anchor.path,
22130
+ symbolStart: object2.symbolStart,
22131
+ offset: cursor.offset,
22132
+ maxResults: input.maxResults,
22133
+ ...query
22134
+ }
22135
+ ],
21821
22136
  signal
21822
22137
  );
21823
- if (page.requiredFiles.length)
22138
+ if (requiredFiles.length)
21824
22139
  throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
22140
+ if (page === void 0) throw invalidProtocol();
22141
+ if (page === null)
22142
+ throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
21825
22143
  if (page.nextOffset !== void 0 && (!page.references.length || page.nextOffset !== cursor.offset + page.references.length))
21826
- throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
22144
+ throw invalidProtocol();
21827
22145
  const references = [];
21828
22146
  const locations = /* @__PURE__ */ new Set();
21829
22147
  for (const reference of page.references) {
21830
- const text = files[reference.anchor.path];
21831
22148
  const location2 = canonicalJson(reference.anchor);
21832
- if (text === void 0 || reference.anchor.start < 0 || reference.anchor.end < reference.anchor.start || reference.anchor.end > text.length || !mapPathAllowed(reference.anchor.path, prefixes) || !mapQueryPathMatches(reference.anchor.path, query.path) || !query.kinds.includes(reference.kind) || locations.has(location2))
21833
- throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
22149
+ if (!anchored(reference, files) || !mapPathAllowed(reference.anchor.path, prefixes) || !mapQueryPathMatches(reference.anchor.path, query.path) || !query.kinds.includes(reference.kind) || locations.has(location2))
22150
+ throw invalidProtocol();
21834
22151
  locations.add(location2);
21835
- const row = this.store.database.prepare(`SELECT object_json FROM project_map_objects
21836
- WHERE version_ref = ? AND path = ?
21837
- AND json_extract(object_json, '$.anchor.start') <= ? AND json_extract(object_json, '$.anchor.end') >= ?
21838
- ORDER BY json_extract(object_json, '$.anchor.end') - json_extract(object_json, '$.anchor.start'), entity_ref LIMIT 1`).get(input.version, reference.anchor.path, reference.anchor.start, reference.anchor.end);
21839
- const owner = row ? MapObjectSchema.parse(JSON.parse(String(row.object_json))) : void 0;
22152
+ const owner = this.owner(input.version, reference.anchor);
21840
22153
  const item = { ...reference, contextRef: context.ref, ...owner ? { owner } : {} };
21841
22154
  references.push(item);
21842
22155
  }
@@ -21948,6 +22261,7 @@ var CodeIndex = class {
21948
22261
  const coverage = await this.analyzer.analyze(
21949
22262
  reader,
21950
22263
  result.entries,
22264
+ { directory: source.directory.canonicalPath, digest: result.installedDigest },
21951
22265
  controller.signal,
21952
22266
  (unit, record2) => this.store.appendMapStage(stage, unit, record2),
21953
22267
  parent && { ...parent, link: (paths) => linked.push(...paths) }
@@ -21959,6 +22273,7 @@ var CodeIndex = class {
21959
22273
  this.store.publish(
21960
22274
  result.version,
21961
22275
  result.entries,
22276
+ result.installedDigest,
21962
22277
  stage,
21963
22278
  coverage,
21964
22279
  parent && linked.length ? { version: parent.version, paths: new Set(linked) } : void 0
@@ -21995,8 +22310,8 @@ var CodeIndex = class {
21995
22310
  for (const entry of this.store.listEntries(candidate))
21996
22311
  if (entry.contentDigest) entries2.set(entry.path, entry.contentDigest);
21997
22312
  let changed = 0;
21998
- for (const [path16, digest] of digests) if (entries2.get(path16) !== digest) changed++;
21999
- for (const path16 of entries2.keys()) if (!digests.has(path16)) changed++;
22313
+ for (const [path17, digest] of digests) if (entries2.get(path17) !== digest) changed++;
22314
+ for (const path17 of entries2.keys()) if (!digests.has(path17)) changed++;
22000
22315
  if (!best || changed < best.changed) best = { version: candidate, entries: entries2, changed };
22001
22316
  }
22002
22317
  if (!best) return void 0;
@@ -22056,6 +22371,25 @@ var CodeIndex = class {
22056
22371
  (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).query(input, signal2)
22057
22372
  );
22058
22373
  }
22374
+ findUses(input, signal) {
22375
+ return this.read(
22376
+ signal,
22377
+ (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).uses(input, signal2)
22378
+ );
22379
+ }
22380
+ /** The configurations of the compiler contexts a version's files are in. */
22381
+ contextConfigurations(version2, paths) {
22382
+ return new ProjectMapReferenceQuery(this.store, this.analyzer).contextConfigurations(
22383
+ version2,
22384
+ paths
22385
+ );
22386
+ }
22387
+ findDiagnostics(input, signal) {
22388
+ return this.read(
22389
+ signal,
22390
+ (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).diagnostics(input, signal2)
22391
+ );
22392
+ }
22059
22393
  get busy() {
22060
22394
  return this.captures.size > 0 || this.rebuilds.size > 0 || this.mapBuilds.size > 0;
22061
22395
  }
@@ -22135,9 +22469,9 @@ var CodeIndex = class {
22135
22469
  };
22136
22470
 
22137
22471
  // src/project-map-changes.ts
22138
- import { readFileSync as readFileSync3 } from "node:fs";
22472
+ import { readFileSync as readFileSync4 } from "node:fs";
22139
22473
  import { readFile } from "node:fs/promises";
22140
- import path10 from "node:path";
22474
+ import path11 from "node:path";
22141
22475
 
22142
22476
  // src/project-map-clients.ts
22143
22477
  var CLIENT_FILES = [
@@ -22172,16 +22506,16 @@ var LITERAL = /(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu;
22172
22506
  var MOUNTING = /(?:\b(?:prefix|root_path|base_path|basePath|baseURL|baseUrl)\s*[=:]|\b(?:Group|Route|Mount|mount|use|include_router|PathPrefix|StripPrefix)\s*\()\s*$/u;
22173
22507
  var LIMIT = Object.freeze({ routes: 40, clients: 5 });
22174
22508
  var ROUTE = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
22175
- var segments = (path16) => path16.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
22509
+ var segments = (path17) => path17.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
22176
22510
  var routeSegments = (label) => segments(label.slice(label.indexOf("/")));
22177
22511
  function requestedPath(literal3, joined) {
22178
22512
  const match = /^(?:https?:\/\/[^/\s]+|(?:\$\{[^}]*\})+|@\{|redirect:|forward:)?(\/[^\s?#()"'`,;|]*)/u.exec(
22179
22513
  literal3
22180
22514
  ) ?? void 0;
22181
- const path16 = match?.[1];
22182
- if (!path16 || path16.startsWith("//") || path16.length < 3) return void 0;
22183
- const parts = segments(path16);
22184
- if (joined && path16.endsWith("/")) parts.push({ text: "*", param: true });
22515
+ const path17 = match?.[1];
22516
+ if (!path17 || path17.startsWith("//") || path17.length < 3) return void 0;
22517
+ const parts = segments(path17);
22518
+ if (joined && path17.endsWith("/")) parts.push({ text: "*", param: true });
22185
22519
  return parts;
22186
22520
  }
22187
22521
  var same = (route, requested) => route.param || !requested.param && route.text === requested.text;
@@ -22289,9 +22623,9 @@ var routeClientsLine = ({ route, removed, clients }) => `${JSON.stringify(route)
22289
22623
 
22290
22624
  // src/project-map-dependencies.ts
22291
22625
  var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22292
- function imports(graph, path16) {
22626
+ function imports(graph, path17) {
22293
22627
  const found = [];
22294
- for (const relation of graph.relationsFrom(graph.objectsAt(path16).map((object2) => object2.id)))
22628
+ for (const relation of graph.relationsFrom(graph.objectsAt(path17).map((object2) => object2.id)))
22295
22629
  if (IMPORT_KINDS2.has(relation.kind) && relation.to !== void 0)
22296
22630
  found.push({
22297
22631
  target: graph.object(relation.to).anchor.path,
@@ -22308,9 +22642,9 @@ function pathBetween(edges, from, to) {
22308
22642
  if (via.has(target)) continue;
22309
22643
  via.set(target, module);
22310
22644
  if (target === to) {
22311
- const path16 = [to];
22312
- for (let step = module; step !== from; step = via.get(step) ?? from) path16.unshift(step);
22313
- return [from, ...path16];
22645
+ const path17 = [to];
22646
+ for (let step = module; step !== from; step = via.get(step) ?? from) path17.unshift(step);
22647
+ return [from, ...path17];
22314
22648
  }
22315
22649
  next.push(target);
22316
22650
  }
@@ -22372,8 +22706,8 @@ function newModuleDependencies(store, cache, working, base, files) {
22372
22706
  }
22373
22707
 
22374
22708
  // src/project-map-names.ts
22375
- import { readFileSync as readFileSync2 } from "node:fs";
22376
- import path9 from "node:path";
22709
+ import { readFileSync as readFileSync3 } from "node:fs";
22710
+ import path10 from "node:path";
22377
22711
  var CONFIG_KEY = /^\s*(?:export\s+|-\s+)?["']?([A-Za-z_][\w.-]*)["']?\s*(?:=|:(?:\s|$))/u;
22378
22712
  var CODE_READS = [
22379
22713
  // process.env.NAME, import.meta.env.NAME
@@ -22449,7 +22783,7 @@ async function strandedNames(project, diff, files, configuration, git2, options)
22449
22783
  } else for (const name of codeReads(line, file2.path)) names2.add(name);
22450
22784
  let text;
22451
22785
  try {
22452
- text = readFileSync2(path9.join(project, file2.path), "utf8");
22786
+ text = readFileSync3(path10.join(project, file2.path), "utf8");
22453
22787
  } catch {
22454
22788
  continue;
22455
22789
  }
@@ -22523,6 +22857,7 @@ var MODULES = /* @__PURE__ */ new Set(["FILE", "PACKAGE", "CONFIG"]);
22523
22857
  var MEMBER_CONTAINERS2 = /* @__PURE__ */ new Set(["CLASS", "INTERFACE", "TYPE", "ENUM"]);
22524
22858
  var KINDS = /* @__PURE__ */ new Set(["FUNCTION", "METHOD", "CLASS", "VARIABLE"]);
22525
22859
  var MIN_LINES = 3;
22860
+ var SHORT_COPIES = 3;
22526
22861
  var ALIKE = 0.8;
22527
22862
  var SIBLINGS_ALIKE = 0.95;
22528
22863
  var KEYWORDS = new Set(
@@ -22530,9 +22865,9 @@ var KEYWORDS = new Set(
22530
22865
  );
22531
22866
  var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
22532
22867
  FROM project_map_objects WHERE version_ref = ? AND kind <> 'PROPERTY'`;
22533
- function rows(store, version2, path16) {
22534
- const statement = store.database.prepare(path16 === void 0 ? ROWS : `${ROWS} AND path = ?`);
22535
- return (path16 === void 0 ? statement.all(version2) : statement.all(version2, path16)).map((row) => {
22868
+ function rows(store, version2, path17) {
22869
+ const statement = store.database.prepare(path17 === void 0 ? ROWS : `${ROWS} AND path = ?`);
22870
+ return (path17 === void 0 ? statement.all(version2) : statement.all(version2, path17)).map((row) => {
22536
22871
  const { anchor } = JSON.parse(String(row.object));
22537
22872
  return {
22538
22873
  id: String(row.id),
@@ -22572,11 +22907,12 @@ function lineWords(line) {
22572
22907
  return (line.replace(/([A-Z])([A-Z][a-z])/g, "$1 $2").replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().match(/[a-z][a-z0-9]+/g) ?? []).filter((word) => !KEYWORDS.has(word));
22573
22908
  }
22574
22909
  var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
22910
+ var copyText = (code) => code.replace(/^export\s+(?:default\s+)?/u, "").replace(/\s+/gu, " ").trim();
22575
22911
  async function similarCode(store, working, base, files, read) {
22576
- const code = (path16) => mapCodePath(path16) !== void 0 && !mapTestPath(path16);
22912
+ const code = (path17) => mapCodePath(path17) !== void 0 && !mapTestPath(path17);
22577
22913
  const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
22578
22914
  if (!changed.length) return [];
22579
- const names = (version2, path16) => new Set(declarations(rows(store, version2, path16)).map((item) => item.qualifiedName));
22915
+ const names = (version2, path17) => new Set(declarations(rows(store, version2, path17)).map((item) => item.qualifiedName));
22580
22916
  const movedOut = /* @__PURE__ */ new Set();
22581
22917
  if (base !== void 0)
22582
22918
  for (const file2 of files) {
@@ -22584,13 +22920,18 @@ async function similarCode(store, working, base, files, read) {
22584
22920
  const now = file2.status === "DELETED" ? /* @__PURE__ */ new Set() : names(working, file2.path);
22585
22921
  for (const name of names(base, file2.basePath)) if (!now.has(name)) movedOut.add(name);
22586
22922
  }
22587
- const eligible = (item) => KINDS.has(item.kind) && item.endLine - item.startLine + 1 >= MIN_LINES;
22923
+ const long = (item) => item.endLine - item.startLine + 1 >= MIN_LINES;
22588
22924
  const added = /* @__PURE__ */ new Set();
22925
+ const shortNames = /* @__PURE__ */ new Set();
22926
+ let longAdded = false;
22589
22927
  for (const file2 of changed) {
22590
22928
  const had = base !== void 0 && file2.basePath && file2.status !== "ADDED" ? names(base, file2.basePath) : void 0;
22591
22929
  for (const item of declarations(rows(store, working, file2.path)))
22592
- if (eligible(item) && within2(file2.lines, item) && !had?.has(item.qualifiedName) && !movedOut.has(item.qualifiedName))
22930
+ if (KINDS.has(item.kind) && within2(file2.lines, item) && !had?.has(item.qualifiedName) && !movedOut.has(item.qualifiedName)) {
22593
22931
  added.add(item.id);
22932
+ if (long(item)) longAdded = true;
22933
+ else shortNames.add(item.qualifiedName);
22934
+ }
22594
22935
  }
22595
22936
  if (!added.size) return [];
22596
22937
  const byPath = /* @__PURE__ */ new Map();
@@ -22601,14 +22942,22 @@ async function similarCode(store, working, base, files, read) {
22601
22942
  byPath.set(row.path, inFile);
22602
22943
  }
22603
22944
  const all = [];
22945
+ const shortCopies = /* @__PURE__ */ new Map();
22604
22946
  await Promise.all(
22605
- [...byPath].map(async ([path16, inFile]) => {
22606
- const found2 = declarations(inFile).filter(eligible);
22947
+ [...byPath].map(async ([path17, inFile]) => {
22948
+ const found2 = declarations(inFile).filter(
22949
+ (item) => KINDS.has(item.kind) && (long(item) ? longAdded : shortNames.has(item.qualifiedName))
22950
+ );
22607
22951
  if (!found2.length) return;
22608
- const text = await read(path16);
22952
+ const text = await read(path17);
22609
22953
  if (text === void 0) return;
22610
22954
  const lines = text.split("\n").map(lineWords);
22611
22955
  for (const declaration of found2) {
22956
+ if (!long(declaration)) {
22957
+ const key = `${declaration.qualifiedName}\0${copyText(text.slice(declaration.start, declaration.end))}`;
22958
+ shortCopies.set(key, [...shortCopies.get(key) ?? [], declaration]);
22959
+ continue;
22960
+ }
22612
22961
  const words = /* @__PURE__ */ new Map();
22613
22962
  for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
22614
22963
  for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
@@ -22646,7 +22995,22 @@ async function similarCode(store, working, base, files, read) {
22646
22995
  kind: row.kind,
22647
22996
  anchor: { startLine: row.startLine, endLine: row.endLine }
22648
22997
  });
22998
+ const linkedTo = (declaration) => {
22999
+ const scope = graph.scope(declaration.id).refs;
23000
+ return /* @__PURE__ */ new Set([
23001
+ ...graph.relationsFrom(scope).flatMap((relation) => relation.to ? [graph.owner(relation.to)] : []),
23002
+ ...graph.relationsTo(scope).map((relation) => graph.owner(relation.from))
23003
+ ]);
23004
+ };
22649
23005
  const found = [];
23006
+ const add = (declaration, best, others, score) => found.push({
23007
+ path: declaration.path,
23008
+ name: declaration.qualifiedName,
23009
+ label: label(declaration),
23010
+ like: { path: best.path, name: best.qualifiedName, label: label(best) },
23011
+ others,
23012
+ score
23013
+ });
22650
23014
  for (const item of all) {
22651
23015
  const declaration = item.declaration;
22652
23016
  if (!added.has(declaration.id)) continue;
@@ -22662,32 +23026,65 @@ async function similarCode(store, working, base, files, read) {
22662
23026
  return score >= (siblings ? SIBLINGS_ALIKE : ALIKE);
22663
23027
  }).sort(([, left], [, right]) => right - left);
22664
23028
  if (!alike.length) continue;
22665
- const scope = graph.scope(declaration.id).refs;
22666
- const linked = /* @__PURE__ */ new Set([
22667
- ...graph.relationsFrom(scope).flatMap((relation) => relation.to ? [graph.owner(relation.to)] : []),
22668
- ...graph.relationsTo(scope).map((relation) => graph.owner(relation.from))
22669
- ]);
23029
+ const linked = linkedTo(declaration);
22670
23030
  const unlinked = alike.filter(([other]) => !linked.has(other.declaration.id));
22671
23031
  const best = unlinked[0];
22672
- if (!best) continue;
22673
- found.push({
22674
- path: declaration.path,
22675
- name: declaration.qualifiedName,
22676
- label: label(declaration),
22677
- like: {
22678
- path: best[0].declaration.path,
22679
- name: best[0].declaration.qualifiedName,
22680
- label: label(best[0].declaration)
22681
- },
22682
- others: unlinked.length - 1,
22683
- score: best[1]
22684
- });
23032
+ if (best) add(declaration, best[0].declaration, unlinked.length - 1, best[1]);
23033
+ }
23034
+ for (const copies of shortCopies.values()) {
23035
+ const existing = copies.filter((copy) => !added.has(copy.id)).sort((left, right) => left.path < right.path ? -1 : 1);
23036
+ if (!existing.length || existing.length > SHORT_COPIES) continue;
23037
+ for (const declaration of copies) {
23038
+ if (!added.has(declaration.id)) continue;
23039
+ const linked = linkedTo(declaration);
23040
+ const unlinked = existing.filter((copy) => !linked.has(copy.id));
23041
+ const best = unlinked[0];
23042
+ if (best) add(declaration, best, unlinked.length - 1, 1);
23043
+ }
22685
23044
  }
22686
23045
  return found.sort(
22687
23046
  (left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0) || right.score - left.score
22688
23047
  ).map(({ score: _score, ...similar }) => similar);
22689
23048
  }
22690
23049
 
23050
+ // src/project-map-shapes.ts
23051
+ var KINDS2 = /* @__PURE__ */ new Set(["PROPERTY", "TYPE", "INTERFACE", "ENUM"]);
23052
+ var READ_MS = 2e4;
23053
+ var mapIsShape = (object2) => KINDS2.has(object2.kind) && object2.execution !== "CLOSURE";
23054
+ var mapShapeDeadline = () => Date.now() + READ_MS;
23055
+ var MapShapeUses = class {
23056
+ constructor(graph, reader, until) {
23057
+ this.graph = graph;
23058
+ this.reader = reader;
23059
+ this.until = until;
23060
+ }
23061
+ graph;
23062
+ reader;
23063
+ until;
23064
+ /** Each field or type read, with each of its uses in the declarations outside it. */
23065
+ uses = /* @__PURE__ */ new Map();
23066
+ /** Those whose uses could not all be read, or that the deadline left out. */
23067
+ unread = /* @__PURE__ */ new Set();
23068
+ async read(refs) {
23069
+ const wanted = [...new Set(refs)].filter(
23070
+ (ref) => mapIsShape(this.graph.object(ref)) && !this.uses.has(ref) && !this.unread.has(ref)
23071
+ );
23072
+ if (!wanted.length) return;
23073
+ const found = Date.now() > this.until ? /* @__PURE__ */ new Map() : await this.reader(wanted, this.until);
23074
+ for (const ref of wanted) {
23075
+ const read = found.get(ref);
23076
+ if (!read?.complete) this.unread.add(ref);
23077
+ if (!read) continue;
23078
+ const outside = [];
23079
+ for (const use of read.uses) {
23080
+ const owner = this.graph.owner(use.owner);
23081
+ if (owner !== ref) outside.push({ ...use, owner });
23082
+ }
23083
+ this.uses.set(ref, outside);
23084
+ }
23085
+ }
23086
+ };
23087
+
22691
23088
  // src/project-map-changes.ts
22692
23089
  var git = new GitRunner();
22693
23090
  var gitOptions = (cwd, signal) => ({
@@ -22739,9 +23136,9 @@ async function readMapChanges(project, base, signal) {
22739
23136
  ...file2,
22740
23137
  baseText: (await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
22741
23138
  };
22742
- const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path16) => path16 && !inExcludedDirectory(path16));
22743
- for (const path16 of untracked)
22744
- files.push({ path: path16, status: "ADDED", lines: [EVERYTHING], baseLines: [], binary: false });
23139
+ const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path17) => path17 && !inExcludedDirectory(path17));
23140
+ for (const path17 of untracked)
23141
+ files.push({ path: path17, status: "ADDED", lines: [EVERYTHING], baseLines: [], binary: false });
22745
23142
  const stranded = await strandedNames(
22746
23143
  project,
22747
23144
  diff,
@@ -22819,8 +23216,14 @@ var NON_CODE = [
22819
23216
  [/(?:^|\/)\.env[^/]*$|\.(?:ya?ml|toml|ini|properties|conf|cfg)$/iu, "configuration"],
22820
23217
  [/\.(?:html?|jinja2?|j2|hbs|ejs|tmpl|tpl|gohtml|vue|svelte|wxml)$/iu, "template"]
22821
23218
  ];
22822
- var nonCodeKind = (path16) => NON_CODE.find(([pattern]) => pattern.test(path16))?.[1];
22823
- var LIMITS = Object.freeze({ depth: 8, declarations: 800, changed: 200, chain: 3, byName: 40 });
23219
+ var nonCodeKind = (path17) => NON_CODE.find(([pattern]) => pattern.test(path17))?.[1];
23220
+ var LIMITS = Object.freeze({
23221
+ depth: 8,
23222
+ declarations: 800,
23223
+ changed: 200,
23224
+ chain: 3,
23225
+ byName: 40
23226
+ });
22824
23227
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22825
23228
  var NAMING_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES", "EXTENDS", "IMPLEMENTS"]);
22826
23229
  var USED_BY = {
@@ -22828,16 +23231,25 @@ var USED_BY = {
22828
23231
  IMPLEMENTS: "implemented",
22829
23232
  OVERRIDES: "overridden"
22830
23233
  };
23234
+ var runsTarget = (relation) => CALLER_KINDS.has(relation.kind) && !relation.event;
22831
23235
  var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22832
23236
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
23237
+ var callerFrom = (ref, relation, certain) => ({
23238
+ ref,
23239
+ anchor: relation.anchor,
23240
+ ...relation.argument ? { argument: relation.argument } : {},
23241
+ certain
23242
+ });
22833
23243
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
22834
23244
  var Tracer = class {
22835
- constructor(graph, memberCalls) {
23245
+ constructor(graph, memberCalls, shapes) {
22836
23246
  this.graph = graph;
22837
23247
  this.memberCalls = memberCalls;
23248
+ this.shapes = shapes;
22838
23249
  }
22839
23250
  graph;
22840
23251
  memberCalls;
23252
+ shapes;
22841
23253
  reached = /* @__PURE__ */ new Map();
22842
23254
  entries = /* @__PURE__ */ new Map();
22843
23255
  tests = /* @__PURE__ */ new Map();
@@ -22846,6 +23258,7 @@ var Tracer = class {
22846
23258
  unclear = [];
22847
23259
  truncated = false;
22848
23260
  callerCount = /* @__PURE__ */ new Map();
23261
+ owners = /* @__PURE__ */ new Set();
22849
23262
  known = /* @__PURE__ */ new Map();
22850
23263
  // Declarations a decorator maps to a route: entry points already, never "top of a chain".
22851
23264
  routes = /* @__PURE__ */ new Set();
@@ -22853,24 +23266,50 @@ var Tracer = class {
22853
23266
  handlers = /* @__PURE__ */ new Map();
22854
23267
  /** Test support files that call the changed code; the tests beside and below them may use it. */
22855
23268
  support = /* @__PURE__ */ new Set();
22856
- name = (ref) => this.graph.qualifiedName(ref);
23269
+ // The trace walks the declarations relations name, closures and locals among them; a reader sees
23270
+ // the addressable declaration around each.
23271
+ name = (ref) => this.graph.qualifiedName(this.graph.owner(ref));
22857
23272
  // A module is named by its path alone.
22858
23273
  where = (ref) => {
22859
- const object2 = this.graph.object(ref);
23274
+ const object2 = this.graph.object(this.graph.owner(ref));
22860
23275
  return mapIsModule(object2) ? object2.anchor.path : `${object2.anchor.path}: ${this.name(ref)}`;
22861
23276
  };
22862
- /** Follows callers up from the given declarations, recording entry points and tests. */
22863
- trace(starts) {
23277
+ /**
23278
+ * Follows callers up from the given declarations, recording entry points and tests. The code of
23279
+ * one in own may flow into its members: the map keeps no reads of its locals, so they may be
23280
+ * affected, unlike what calls it.
23281
+ */
23282
+ async trace(starts, own = []) {
22864
23283
  let frontier = [];
22865
23284
  for (const ref of starts)
22866
23285
  if (!this.reached.has(ref)) {
22867
- const start = { ref, depth: 0, certain: true };
23286
+ const start = { ref, depth: 0, certain: true, shaped: true };
22868
23287
  this.reached.set(ref, start);
23288
+ this.owners.add(this.graph.owner(ref));
22869
23289
  frontier.push(start);
22870
23290
  }
22871
- for (const start of frontier) this.byName(start.ref);
22872
- while (frontier.length) {
23291
+ for (const start of frontier)
23292
+ for (const ref of /* @__PURE__ */ new Set([start.ref, this.graph.owner(start.ref)])) this.byName(ref);
23293
+ const uncertain = [];
23294
+ for (const ref of own) {
23295
+ const current = this.reached.get(ref);
23296
+ if (current)
23297
+ for (const member of this.members(ref))
23298
+ uncertain.push({
23299
+ current,
23300
+ caller: { ref: member, anchor: this.graph.object(member).anchor, certain: false }
23301
+ });
23302
+ }
23303
+ while (frontier.length || uncertain.length) {
23304
+ if (!frontier.length)
23305
+ frontier = uncertain.splice(0).flatMap(({ current, caller }) => this.step(current, caller, false));
22873
23306
  const next = [];
23307
+ await this.shapes.read(
23308
+ frontier.filter(({ ref, shaped }) => {
23309
+ const object2 = this.graph.object(ref);
23310
+ return this.graph.isAddressable(object2) && !testCode(object2.anchor.path) && (shaped || object2.kind === "PROPERTY");
23311
+ }).map(({ ref }) => ref)
23312
+ );
22874
23313
  for (const current of frontier) {
22875
23314
  const object2 = this.graph.object(current.ref);
22876
23315
  if (testCode(object2.anchor.path)) continue;
@@ -22878,10 +23317,10 @@ var Tracer = class {
22878
23317
  const callers = this.callers(current.ref);
22879
23318
  this.callerCount.set(current.ref, callers.length);
22880
23319
  for (const caller of callers) {
22881
- const site = `${caller.relation.anchor.path}:${caller.relation.anchor.startLine}`;
23320
+ const site = `${caller.anchor.path}:${caller.anchor.startLine}`;
22882
23321
  const certain = current.certain && caller.certain;
22883
- if (caller.relation.argument && ROUTE2.test(caller.relation.argument))
22884
- this.entry(caller.relation.argument, true, current, site, certain);
23322
+ if (caller.argument && ROUTE2.test(caller.argument))
23323
+ this.entry(caller.argument, true, current, site, certain);
22885
23324
  const callerObject = this.graph.object(caller.ref);
22886
23325
  if (testCode(callerObject.anchor.path)) {
22887
23326
  if (!mapRunnableTest(callerObject.anchor.path))
@@ -22889,7 +23328,7 @@ var Tracer = class {
22889
23328
  this.test(
22890
23329
  callerObject.anchor.path,
22891
23330
  this.name(caller.ref),
22892
- `calls ${this.name(current.ref)}`,
23331
+ `${caller.uses ? "uses" : "calls"} ${this.name(current.ref)}`,
22893
23332
  // Tests closer to the change come first; all of them rank before other relations.
22894
23333
  current.depth / 10
22895
23334
  );
@@ -22897,14 +23336,8 @@ var Tracer = class {
22897
23336
  this.area(current.ref, callerObject.anchor.path, this.name(caller.ref));
22898
23337
  continue;
22899
23338
  }
22900
- if (this.reached.has(caller.ref)) continue;
22901
- if (current.depth + 1 > LIMITS.depth || this.reached.size >= LIMITS.declarations) {
22902
- this.truncated = true;
22903
- continue;
22904
- }
22905
- const reached = { ref: caller.ref, depth: current.depth + 1, certain, via: current.ref };
22906
- this.reached.set(caller.ref, reached);
22907
- next.push(reached);
23339
+ if (certain) next.push(...this.step(current, caller, true));
23340
+ else uncertain.push({ current, caller });
22908
23341
  }
22909
23342
  }
22910
23343
  frontier = next;
@@ -22920,28 +23353,115 @@ var Tracer = class {
22920
23353
  this.test(
22921
23354
  call.path,
22922
23355
  this.name(this.graph.owner(call.from)),
22923
- `may call ${this.name(reached.ref)} through a receiver of unknown type`,
23356
+ `may call ${this.graph.qualifiedName(reached.ref)} through a receiver of unknown type`,
22924
23357
  3.5
22925
23358
  );
22926
23359
  }
22927
23360
  for (const reached of this.reached.values()) {
22928
- if (this.callerCount.get(reached.ref) !== 0) continue;
23361
+ if (this.callerCount.get(reached.ref) !== 0 || this.shapes.unread.has(reached.ref)) continue;
22929
23362
  const object2 = this.graph.object(reached.ref);
22930
23363
  if (testCode(object2.anchor.path) || this.routes.has(reached.ref)) continue;
22931
23364
  if (reached.depth === 0 && !mapMiniprogramTemplate(object2.anchor.path)) {
22932
23365
  const uses = this.usesWithoutCalls(reached.ref);
22933
23366
  this.unclear.push(
22934
- uses.length ? `${this.where(reached.ref)} has no callers in the map, and is used without a call: ${uses.join("; ")}` : `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
23367
+ uses.length ? `${this.where(reached.ref)} has no callers in the map, and is used without a call: ${uses.join("; ")}` : mapIsShape(object2) ? `${this.where(reached.ref)} has no callers in the map, and a search for references found no use: it may be read through reflection, serialization or a value of unknown type, or be unused` : `${this.where(reached.ref)} has no callers in the map: it may be wired by a framework, called dynamically, or unused`
22935
23368
  );
22936
- } else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
23369
+ } else if (!mapIsShape(object2) || !reached.used && object2.kind === "PROPERTY")
23370
+ this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
23371
+ }
23372
+ }
23373
+ step(current, caller, certain) {
23374
+ const known = this.reached.get(caller.ref);
23375
+ if (known) {
23376
+ if (!caller.uses) known.used = false;
23377
+ if (!caller.uses || !current.shaped || known.shaped) return [];
23378
+ known.shaped = true;
23379
+ this.known.delete(caller.ref);
23380
+ return [known];
23381
+ }
23382
+ const depth = this.climb(current.ref, caller.ref, current.depth, this.owners);
23383
+ if (depth === void 0) {
23384
+ this.truncated = true;
23385
+ return [];
23386
+ }
23387
+ const reached = {
23388
+ ref: caller.ref,
23389
+ depth,
23390
+ certain,
23391
+ via: current.ref,
23392
+ ...caller.uses ? { used: true, ...current.shaped ? { shaped: true } : {} } : {}
23393
+ };
23394
+ this.reached.set(caller.ref, reached);
23395
+ return [reached];
23396
+ }
23397
+ // The depth of a step from one declaration to another, unless it passes the trace's limits. The
23398
+ // limits count what a reader sees: moving between the locals of one declaration climbs nothing.
23399
+ climb(from, to, depth, owners) {
23400
+ const owner = this.graph.owner(to);
23401
+ const next = depth + (owner === this.graph.owner(from) ? 0 : 1);
23402
+ if (next > LIMITS.depth || !owners.has(owner) && owners.size >= LIMITS.declarations)
23403
+ return void 0;
23404
+ owners.add(owner);
23405
+ return next;
23406
+ }
23407
+ // Whether a relation starts in the declaration, not in an addressable declaration inside it.
23408
+ within(from, ref) {
23409
+ for (let at = from; at !== void 0; at = this.graph.parent(at)) {
23410
+ if (at === ref) return true;
23411
+ if (this.graph.isAddressable(this.graph.object(at))) return false;
23412
+ }
23413
+ return false;
23414
+ }
23415
+ /**
23416
+ * The locals of a declaration that code outside it calls, as the methods of the object a factory
23417
+ * returns. Fields and types are read by name, not called, so they have none.
23418
+ */
23419
+ members(ref) {
23420
+ const object2 = this.graph.object(ref);
23421
+ if (mapIsModule(object2) || mapIsShape(object2)) return [];
23422
+ return this.graph.scope(ref).refs.slice(1).filter(
23423
+ (local) => this.callers(local).some((caller) => this.graph.owner(caller.ref) !== ref)
23424
+ );
23425
+ }
23426
+ /**
23427
+ * Where a change on the lines of a declaration is followed from: the innermost local around each
23428
+ * line that runs apart from it, as a function does or as what others call does, and the declaration
23429
+ * itself for lines in none. Fields and types change as a whole.
23430
+ */
23431
+ startsAt(ref, lines) {
23432
+ const object2 = this.graph.object(ref);
23433
+ if (mapIsModule(object2) || mapIsShape(object2)) return { refs: [ref], own: [] };
23434
+ const locals = this.graph.scope(ref).refs.slice(1).map((local) => this.graph.object(local)).filter((local) => local.execution || this.callers(local.id).some((caller) => !caller.holds));
23435
+ const refs = /* @__PURE__ */ new Set();
23436
+ let own = false;
23437
+ const at = (from, to) => {
23438
+ const around = locals.filter(
23439
+ (local) => local.anchor.startLine <= to && from <= local.anchor.endLine
23440
+ );
23441
+ for (const local of around)
23442
+ if (!around.some(
23443
+ (other) => other !== local && local.anchor.start <= other.anchor.start && other.anchor.end <= local.anchor.end
23444
+ ))
23445
+ refs.add(local.id);
23446
+ if (!around.length) own = true;
23447
+ };
23448
+ for (const [from, to] of lines) {
23449
+ if (from > to) {
23450
+ if (object2.anchor.startLine <= to && from <= object2.anchor.endLine) at(from, to);
23451
+ continue;
23452
+ }
23453
+ const last = Math.min(to, object2.anchor.endLine);
23454
+ for (let line = Math.max(from, object2.anchor.startLine); line <= last; line++) at(line, line);
22937
23455
  }
23456
+ if (own) refs.add(ref);
23457
+ return { refs: [...refs], own: own ? [ref] : [] };
22938
23458
  }
22939
23459
  /**
22940
23460
  * The uses outside tests the map sees of a declaration besides calls: a class others extend or
22941
23461
  * implement, a member that overrides another or that others override, and a decorator that may
22942
23462
  * wire it to be run (a route, a task, a registry). A decorator of the language's own library
22943
- * (dataclass, staticmethod) only shapes the declaration. Reading a value is a reference, so a
22944
- * caller; writing one is not a use, as a value nothing reads is unused.
23463
+ * (dataclass, staticmethod) only shapes the declaration. Reading a value of module state is a
23464
+ * reference, so a caller; writing one is not a use, as a value nothing reads is unused.
22945
23465
  */
22946
23466
  usesWithoutCalls(ref) {
22947
23467
  const uses = [];
@@ -22970,10 +23490,11 @@ var Tracer = class {
22970
23490
  reach(refs, files, handlers) {
22971
23491
  const how = /* @__PURE__ */ new Map();
22972
23492
  const below = /* @__PURE__ */ new Map();
22973
- const seen = new Set(refs);
23493
+ const depths = new Map(refs.map((ref) => [ref, 0]));
23494
+ const owners = new Set(refs.map((ref) => this.graph.owner(ref)));
22974
23495
  let truncated = false;
22975
- let frontier = [...seen];
22976
- for (let depth = 0; frontier.length; depth++) {
23496
+ let frontier = [...depths.keys()];
23497
+ while (frontier.length) {
22977
23498
  const next = [];
22978
23499
  for (const current of frontier) {
22979
23500
  if (handlers.has(current)) how.set(current, "route");
@@ -22985,12 +23506,13 @@ var Tracer = class {
22985
23506
  const callees = below.get(caller.ref);
22986
23507
  if (callees) callees.push(current);
22987
23508
  else below.set(caller.ref, [current]);
22988
- if (seen.has(caller.ref)) continue;
22989
- if (depth + 1 > LIMITS.depth || seen.size >= LIMITS.declarations) {
23509
+ if (depths.has(caller.ref)) continue;
23510
+ const depth = this.climb(current, caller.ref, depths.get(current) ?? 0, owners);
23511
+ if (depth === void 0) {
22990
23512
  truncated = true;
22991
23513
  continue;
22992
23514
  }
22993
- seen.add(caller.ref);
23515
+ depths.set(caller.ref, depth);
22994
23516
  next.push(caller.ref);
22995
23517
  }
22996
23518
  }
@@ -23012,43 +23534,47 @@ var Tracer = class {
23012
23534
  if (known) return known;
23013
23535
  const callers = [];
23014
23536
  for (const relation of this.graph.relationsTo([ref]))
23015
- if (CALLER_KINDS.has(relation.kind)) {
23016
- const owner = this.graph.owner(relation.from);
23017
- if (owner !== ref) callers.push({ ref: owner, relation, certain: true });
23018
- }
23537
+ if (runsTarget(relation) && !this.within(relation.from, ref))
23538
+ callers.push(callerFrom(relation.from, relation, true));
23539
+ for (const use of this.shapes.uses.get(ref) ?? [])
23540
+ callers.push({ ref: use.owner, anchor: use.anchor, certain: false, uses: true });
23019
23541
  const object2 = this.graph.object(ref);
23020
23542
  const parent = this.graph.parent(ref);
23021
23543
  const constructs = object2.execution === "CONSTRUCTOR" || object2.name === "__init__" || object2.name === "constructor";
23022
23544
  if (parent && this.graph.object(parent).kind === "CLASS") {
23023
- const implicit = constructs || /^__\w+__$/u.test(object2.name) || object2.kind === "PROPERTY" || this.graph.relationsFrom([ref]).some(
23545
+ const implicit = constructs || /^__\w+__$/u.test(object2.name) || this.graph.relationsFrom([ref]).some(
23024
23546
  (relation) => relation.kind === "DECORATED_BY" && /property$/u.test(relation.target)
23025
23547
  );
23026
23548
  if (implicit) {
23027
23549
  for (const relation of this.graph.relationsTo([parent]))
23028
- if (CALLER_KINDS.has(relation.kind)) {
23029
- const owner = this.graph.owner(relation.from);
23030
- if (owner !== ref && owner !== parent)
23031
- callers.push({
23032
- ref: owner,
23033
- relation,
23034
- certain: constructs && relation.kind === "CALLS"
23035
- });
23036
- }
23550
+ if (runsTarget(relation) && !this.within(relation.from, ref) && !this.within(relation.from, parent))
23551
+ callers.push(
23552
+ callerFrom(relation.from, relation, constructs && relation.kind === "CALLS")
23553
+ );
23037
23554
  }
23038
23555
  }
23556
+ const local = !this.graph.isAddressable(object2);
23039
23557
  if (!constructs) {
23040
23558
  for (const override of this.graph.relationsFrom([ref]))
23041
23559
  if (override.kind === "OVERRIDES" && override.to !== void 0) {
23042
23560
  const contract = override.to;
23043
23561
  const relations = this.graph.relationsTo([contract]);
23044
- const only = relations.filter((relation) => relation.kind === "OVERRIDES").length === 1;
23562
+ const only = relations.filter(
23563
+ (relation) => relation.kind === "OVERRIDES" && !(local && testCode(relation.anchor.path))
23564
+ ).length === 1;
23565
+ if (local && !only) continue;
23045
23566
  for (const relation of relations)
23046
- if (CALLER_KINDS.has(relation.kind)) {
23047
- const owner = this.graph.owner(relation.from);
23048
- if (owner !== ref) callers.push({ ref: owner, relation, certain: only });
23049
- }
23567
+ if (runsTarget(relation) && !this.within(relation.from, ref))
23568
+ callers.push(callerFrom(relation.from, relation, only));
23050
23569
  }
23051
23570
  }
23571
+ if (parent && local && callers.every((caller) => testCode(this.graph.object(caller.ref).anchor.path)))
23572
+ callers.push({
23573
+ ref: parent,
23574
+ anchor: object2.anchor,
23575
+ certain: callers.length === 0,
23576
+ holds: true
23577
+ });
23052
23578
  this.known.set(ref, callers);
23053
23579
  return callers;
23054
23580
  }
@@ -23075,15 +23601,18 @@ var Tracer = class {
23075
23601
  const calls = this.memberCalls.get(`${language}\0${object2.name}`) ?? [];
23076
23602
  if (calls.length)
23077
23603
  this.unclear.push(
23078
- `${calls.length} calls of a member named ${object2.name} on receivers of unknown type may reach ${this.name(ref)}; a text search finds them`
23604
+ `${calls.length} calls of a member named ${object2.name} on receivers of unknown type may reach ${this.graph.qualifiedName(ref)}; a text search finds them`
23079
23605
  );
23080
23606
  }
23081
23607
  entry(label, route, at, site, certain, top = false) {
23082
23608
  if (route) this.handlers.set(label, (this.handlers.get(label) ?? /* @__PURE__ */ new Set()).add(at.ref));
23083
23609
  const chain = [];
23084
- let step = !top ? at : at.via ? this.reached.get(at.via) : void 0;
23610
+ let shown = top ? this.graph.owner(at.ref) : void 0;
23611
+ let step = at;
23085
23612
  for (; step && chain.length < LIMITS.chain; ) {
23086
- chain.push(this.name(step.ref));
23613
+ const owner = this.graph.owner(step.ref);
23614
+ if (owner !== shown) chain.push(this.name(owner));
23615
+ shown = owner;
23087
23616
  step = step.via ? this.reached.get(step.via) : void 0;
23088
23617
  }
23089
23618
  const known = this.entries.get(label);
@@ -23100,35 +23629,35 @@ var Tracer = class {
23100
23629
  this.areas.set(area, known);
23101
23630
  }
23102
23631
  /** A related test file; the closest relation (lowest rank) explains it. */
23103
- test(path16, name, why, rank2) {
23104
- if (!mapRunnableTest(path16)) return;
23105
- const known = this.tests.get(path16) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
23632
+ test(path17, name, why, rank2) {
23633
+ if (!mapRunnableTest(path17)) return;
23634
+ const known = this.tests.get(path17) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
23106
23635
  if (rank2 < known.rank) Object.assign(known, { why, rank: rank2 });
23107
23636
  if (name && !name.startsWith("<")) known.names.add(name);
23108
- this.tests.set(path16, known);
23637
+ this.tests.set(path17, known);
23109
23638
  }
23110
23639
  };
23111
23640
  var mapRunnableTest = (file2) => /_test\.(?:go|py)$|(?:^|\/)test_[^/]*\.py$|\.(?:test|spec)\.[cm]?[jt]sx?$|(?:Test|Tests|IT)\.(?:java|kt)$/u.test(
23112
23641
  file2
23113
23642
  );
23114
23643
  var renamedTemplate = (file2) => file2.status === "RENAMED" && file2.basePath !== void 0 && mapMiniprogramTemplate(file2.basePath);
23115
- function mapChangeImpact(store, working, base, changes, project, tests) {
23644
+ async function mapChangeImpact(store, working, base, changes, shapes, until, project, tests) {
23116
23645
  const graph = new MapViewGraph(store, working);
23117
23646
  const cache = new MapViewCache();
23118
23647
  const memberCalls = cache.memberCalls(store, working);
23119
- const tracer = new Tracer(graph, memberCalls);
23648
+ const tracer = new Tracer(graph, memberCalls, new MapShapeUses(graph, shapes.working, until));
23120
23649
  const changed = [];
23121
23650
  const unclear = [];
23122
23651
  const removed = [];
23123
- const declarations2 = (g, path16) => g.objectsAt(path16).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
23124
- const units = (g, path16) => mapMiniprogramTemplate(path16) ? g.objectsAt(path16).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : declarations2(g, path16);
23652
+ const declarations2 = (g, path17) => g.objectsAt(path17).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
23653
+ const units = (g, path17) => mapMiniprogramTemplate(path17) ? g.objectsAt(path17).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : declarations2(g, path17);
23125
23654
  let changedCount = 0;
23126
23655
  const starts = [];
23127
23656
  const importers = /* @__PURE__ */ new Map();
23128
23657
  let mapped;
23129
23658
  const mappedPaths = () => mapped ??= store.database.prepare("SELECT DISTINCT path FROM project_map_objects WHERE version_ref = ?").all(working).map((row) => String(row.path));
23130
- const topLevelChanged = (path16) => {
23131
- const note = `top-level code of ${path16} changed (imports, constants or registrations)`;
23659
+ const topLevelChanged = (path17) => {
23660
+ const note = `top-level code of ${path17} changed (imports, constants or registrations)`;
23132
23661
  if (!unclear.includes(note)) unclear.push(note);
23133
23662
  };
23134
23663
  for (const file2 of changes.files) {
@@ -23167,7 +23696,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23167
23696
  changed.push(
23168
23697
  `${file2.path}${template ? " (template)" : `: ${graph.qualifiedName(ref)} ${mapDeclarationLabel(object2)}`}${file2.status === "ADDED" ? " (new file)" : ""}`
23169
23698
  );
23170
- starts.push(ref);
23699
+ starts.push(tracer.startsAt(ref, file2.lines));
23171
23700
  }
23172
23701
  for (const relation of graph.relationsFrom(objects2.map((object2) => object2.id)))
23173
23702
  if (relation.argument && ROUTE2.test(relation.argument) && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine))
@@ -23179,8 +23708,18 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23179
23708
  sameDirectoryTests(mappedPaths(), file2.path, tracer);
23180
23709
  mirroredTests(mappedPaths(), file2.path, tracer);
23181
23710
  }
23182
- tracer.trace(starts);
23183
- const untested = tests && untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests);
23711
+ await tracer.trace(
23712
+ starts.flatMap((start) => start.refs),
23713
+ starts.flatMap((start) => start.own)
23714
+ );
23715
+ const unread = [...tracer.shapes.unread];
23716
+ if (unread.length)
23717
+ unclear.push(
23718
+ `who uses ${unread.length} fields or types the change reaches was not read, so what they affect is not known (${unread.slice(0, LIST.names).map((ref) => graph.qualifiedName(ref)).join(
23719
+ ", "
23720
+ )}${unread.length > LIST.names ? ", \u2026" : ""}); project_find_references lists their uses`
23721
+ );
23722
+ const untested = tests && await untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests);
23184
23723
  if (project) routeTests(project, store, working, [...tracer.entries.values()], tracer);
23185
23724
  supportTests(store, working, tracer);
23186
23725
  const rewrittenTests = [];
@@ -23202,7 +23741,11 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23202
23741
  const names = existingTestsChanged(before, graph, file2, project);
23203
23742
  if (names.length) rewrittenTests.push({ path: file2.path, names });
23204
23743
  }
23205
- const beforeTracer = new Tracer(before, cache.memberCalls(store, base));
23744
+ const beforeTracer = new Tracer(
23745
+ before,
23746
+ cache.memberCalls(store, base),
23747
+ new MapShapeUses(before, shapes.base, until)
23748
+ );
23206
23749
  const changedIn = new Map(
23207
23750
  changes.files.flatMap((file2) => file2.basePath ? [[file2.basePath, file2]] : [])
23208
23751
  );
@@ -23221,6 +23764,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23221
23764
  );
23222
23765
  };
23223
23766
  const gone = [];
23767
+ const goneShapes = [];
23224
23768
  for (const file2 of changes.files) {
23225
23769
  if (!file2.basePath || file2.binary || testCode(file2.basePath)) continue;
23226
23770
  const renamed = renamedTemplate(file2);
@@ -23252,12 +23796,40 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23252
23796
  mapIsModule(user) ? `${user.anchor.path}${mapMiniprogramTemplate(user.anchor.path) ? " (template)" : ": top-level code"}` : `${user.anchor.path}: ${before.qualifiedName(owner)}`
23253
23797
  );
23254
23798
  }
23799
+ goneShapes.push({
23800
+ shapes: mapIsShape(object2) ? [object2.id] : before.objectsAt(file2.basePath).filter((member) => inside(member.id) && mapIsShape(member)).map((member) => member.id),
23801
+ inside,
23802
+ usedBy
23803
+ });
23255
23804
  removed.push({
23256
23805
  declaration: mapIsModule(object2) ? `${file2.basePath} (template)` : `${file2.basePath}: ${before.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`,
23257
- usedBy: [...usedBy].sort()
23806
+ usedBy
23258
23807
  });
23259
23808
  }
23260
23809
  }
23810
+ await beforeTracer.shapes.read(goneShapes.flatMap((item) => item.shapes));
23811
+ const nowDeclared = new Set(
23812
+ changes.files.flatMap(
23813
+ (file2) => file2.status === "DELETED" ? [] : graph.objectsAt(file2.path).map((object2) => same2(graph, object2.id))
23814
+ )
23815
+ );
23816
+ for (const { shapes: inRemoved, inside, usedBy } of goneShapes)
23817
+ for (const shape of inRemoved) {
23818
+ if (nowDeclared.has(same2(before, shape))) continue;
23819
+ if (beforeTracer.shapes.unread.has(shape))
23820
+ unclear.push(
23821
+ `${before.object(shape).anchor.path}: ${before.qualifiedName(shape)} was removed, and who used it was not read; search the code for its name`
23822
+ );
23823
+ for (const { owner, anchor } of beforeTracer.shapes.uses.get(shape) ?? []) {
23824
+ const file2 = changedIn.get(anchor.path);
23825
+ if (inside(owner) || file2 && (file2.status === "DELETED" || overlaps(file2.baseLines, anchor.startLine, anchor.endLine)))
23826
+ continue;
23827
+ const user = before.object(owner);
23828
+ usedBy.add(
23829
+ mapIsModule(user) ? `${user.anchor.path}: top-level code` : `${user.anchor.path}: ${before.qualifiedName(owner)}`
23830
+ );
23831
+ }
23832
+ }
23261
23833
  const removedAt = (ref) => {
23262
23834
  for (let at = ref; at !== void 0; at = before.parent(at))
23263
23835
  if (gone.includes(at)) return true;
@@ -23265,13 +23837,13 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23265
23837
  };
23266
23838
  const lost = /* @__PURE__ */ new Map();
23267
23839
  const changedAt = new Map(changes.files.map((file2) => [file2.path, file2]));
23268
- for (const path16 of mappedPaths().filter(mapMiniprogramTemplate)) {
23269
- const template = graph.objectsAt(path16).find((object2) => mapIsModule(object2));
23840
+ for (const path17 of mappedPaths().filter(mapMiniprogramTemplate)) {
23841
+ const template = graph.objectsAt(path17).find((object2) => mapIsModule(object2));
23270
23842
  if (!template) continue;
23271
23843
  const broken = graph.relationsFrom(graph.scope(template.id).refs).filter((relation) => relation.to === void 0 && NAMING_KINDS.has(relation.kind));
23272
23844
  if (!broken.length) continue;
23273
- const file2 = changedAt.get(path16);
23274
- const basePath = file2 ? file2.basePath : path16;
23845
+ const file2 = changedAt.get(path17);
23846
+ const basePath = file2 ? file2.basePath : path17;
23275
23847
  const was = basePath === void 0 ? void 0 : before.objectsAt(basePath).find(mapIsModule);
23276
23848
  const links = was ? before.relationsFrom(before.scope(was.id).refs) : [];
23277
23849
  for (const relation of broken) {
@@ -23280,7 +23852,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23280
23852
  );
23281
23853
  if (earlier.some((link) => link.to === void 0)) continue;
23282
23854
  const event = miniprogramEventOf(relation.target);
23283
- const at = `${path16}:${relation.anchor.startLine}`;
23855
+ const at = `${path17}:${relation.anchor.startLine}`;
23284
23856
  if (file2 && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine)) {
23285
23857
  unclear.push(
23286
23858
  event ? `${at} binds the ${event.event} event of <${event.tag}>, which it does not emit` : relation.kind === "REFERENCES" ? `${at} puts <${relation.target}>, which its registration does not find` : `${at} binds ${relation.target}, which its page or component does not register`
@@ -23292,12 +23864,11 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23292
23864
  const object2 = before.object(reached);
23293
23865
  const name = mapIsModule(object2) ? `${object2.anchor.path} (template)${event ? `: ${event.event} event` : ""}` : `${object2.anchor.path}: ${before.qualifiedName(reached)} ${mapDeclarationLabel(object2)}`;
23294
23866
  const users = lost.get(name) ?? /* @__PURE__ */ new Set();
23295
- users.add(`${path16} (template)`);
23867
+ users.add(`${path17} (template)`);
23296
23868
  lost.set(name, users);
23297
23869
  }
23298
23870
  }
23299
- for (const [declaration, users] of lost)
23300
- removed.push({ declaration, usedBy: [...users].sort() });
23871
+ for (const [declaration, users] of lost) removed.push({ declaration, usedBy: users });
23301
23872
  for (const file2 of changes.files) {
23302
23873
  if (!file2.basePath || file2.status === "DELETED" || testCode(file2.basePath)) continue;
23303
23874
  const module = before.objectsAt(file2.basePath).find(mapIsModule);
@@ -23307,21 +23878,21 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23307
23878
  topLevelChanged(file2.path);
23308
23879
  }
23309
23880
  if (gone.length) {
23310
- beforeTracer.trace(gone);
23881
+ await beforeTracer.trace(gone, gone);
23311
23882
  for (const entry of beforeTracer.entries.values())
23312
23883
  if (!tracer.entries.has(entry.label)) tracer.entries.set(entry.label, entry);
23313
- for (const [path16, test] of beforeTracer.tests) {
23314
- const known = tracer.tests.get(path16);
23884
+ for (const [path17, test] of beforeTracer.tests) {
23885
+ const known = tracer.tests.get(path17);
23315
23886
  if (known) for (const name of test.names) known.names.add(name);
23316
- else tracer.tests.set(path16, test);
23887
+ else tracer.tests.set(path17, test);
23317
23888
  }
23318
23889
  for (const [area, known] of beforeTracer.areas) {
23319
23890
  const now = tracer.areas.get(area);
23320
23891
  if (!now) tracer.areas.set(area, known);
23321
23892
  else {
23322
23893
  for (const name of known.through) now.through.add(name);
23323
- for (const [path16, names] of known.tests)
23324
- now.tests.set(path16, /* @__PURE__ */ new Set([...now.tests.get(path16) ?? [], ...names]));
23894
+ for (const [path17, names] of known.tests)
23895
+ now.tests.set(path17, /* @__PURE__ */ new Set([...now.tests.get(path17) ?? [], ...names]));
23325
23896
  }
23326
23897
  }
23327
23898
  unclear.push(...beforeTracer.unclear.filter((line) => !line.includes("has no callers")));
@@ -23343,32 +23914,50 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23343
23914
  called.add(before.owner(relation.to));
23344
23915
  }
23345
23916
  const outsideTests = (callers, g) => callers.filter((caller) => !testCode(g.object(caller.ref).anchor.path));
23917
+ const candidates = [];
23346
23918
  for (const ref of called) {
23347
23919
  const object2 = before.object(ref);
23348
23920
  if (mapIsModule(object2) || testCode(object2.anchor.path) || gone.includes(ref)) continue;
23349
- const path16 = moved.has(object2.anchor.path) ? moved.get(object2.anchor.path) : object2.anchor.path;
23350
- if (path16 === void 0) continue;
23921
+ const path17 = moved.has(object2.anchor.path) ? moved.get(object2.anchor.path) : object2.anchor.path;
23922
+ if (path17 === void 0) continue;
23351
23923
  const name = before.qualifiedName(ref);
23352
- const now = declarations2(graph, path16).find(
23924
+ const now = declarations2(graph, path17).find(
23353
23925
  (candidate) => candidate.kind === object2.kind && graph.qualifiedName(candidate.id) === name
23354
23926
  );
23355
- if (!now || outsideTests(tracer.callers(now.id), graph).length || tracer.usesWithoutCalls(now.id).length)
23356
- continue;
23927
+ if (!now) continue;
23928
+ const calls = tracer.callers(now.id).filter((caller) => !caller.uses);
23929
+ if (outsideTests(calls, graph).length || tracer.usesWithoutCalls(now.id).length) continue;
23357
23930
  if (!outsideTests(beforeTracer.callers(ref), before).length) continue;
23358
- const tested = tracer.callers(now.id).length > 0;
23359
- uncalled.push(
23360
- `${path16}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
23361
- );
23931
+ candidates.push({ path: path17, name, now, tested: calls.length > 0 });
23932
+ }
23933
+ await tracer.shapes.read(candidates.map(({ now }) => now.id));
23934
+ const unknown2 = [];
23935
+ for (const { path: path17, name, now, tested } of candidates) {
23936
+ if (tracer.shapes.unread.has(now.id)) unknown2.push(name);
23937
+ else if (!tracer.shapes.uses.get(now.id)?.some(({ owner, write }) => !write && !testCode(graph.object(owner).anchor.path))) {
23938
+ uncalled.push(
23939
+ `${path17}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
23940
+ );
23941
+ }
23362
23942
  }
23363
23943
  uncalled.sort();
23944
+ if (unknown2.length)
23945
+ unclear.push(
23946
+ `${unknown2.length} fields lost callers the diff removed, and whether others use them was not read (${unknown2.sort().slice(0, LIST.names).join(
23947
+ ", "
23948
+ )}${unknown2.length > LIST.names ? ", \u2026" : ""}); project_find_references lists their uses`
23949
+ );
23364
23950
  }
23365
23951
  return {
23366
23952
  changed,
23367
- removed,
23953
+ removed: removed.map(({ declaration, usedBy }) => ({
23954
+ declaration,
23955
+ usedBy: [...usedBy].sort()
23956
+ })),
23368
23957
  rewrittenTests,
23369
23958
  entries: [...tracer.entries.values()].sort(entryOrder),
23370
- tests: [...tracer.tests].map(([path16, test]) => ({
23371
- path: path16,
23959
+ tests: [...tracer.tests].map(([path17, test]) => ({
23960
+ path: path17,
23372
23961
  names: [...test.names].sort(),
23373
23962
  why: test.why,
23374
23963
  rank: test.rank
@@ -23378,7 +23967,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23378
23967
  areas: [...tracer.areas].map(([area, known]) => ({
23379
23968
  area,
23380
23969
  through: [...known.through].sort(),
23381
- tests: [...known.tests].map(([path16, names]) => ({ path: path16, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
23970
+ tests: [...known.tests].map(([path17, names]) => ({ path: path17, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
23382
23971
  })).sort((left, right) => right.tests.length - left.tests.length),
23383
23972
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
23384
23973
  removedRoutes,
@@ -23389,7 +23978,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23389
23978
  };
23390
23979
  }
23391
23980
  var entryOrder = (left, right) => Number(right.certain) - Number(left.certain) || Number(right.route) - Number(left.route) || (left.label < right.label ? -1 : left.label > right.label ? 1 : 0);
23392
- function untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests) {
23981
+ async function untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests) {
23393
23982
  const given = new Set(tests);
23394
23983
  const routes = /* @__PURE__ */ new Set();
23395
23984
  const handlers = /* @__PURE__ */ new Set();
@@ -23397,7 +23986,7 @@ function untestedChanges(project, graph, tracer, memberCalls, starts, changed, t
23397
23986
  for (const test of given) {
23398
23987
  let text;
23399
23988
  try {
23400
- text = readFileSync3(path10.join(project, test), "utf8");
23989
+ text = readFileSync4(path11.join(project, test), "utf8");
23401
23990
  } catch {
23402
23991
  continue;
23403
23992
  }
@@ -23408,16 +23997,24 @@ function untestedChanges(project, graph, tracer, memberCalls, starts, changed, t
23408
23997
  for (const ref of refs) handlers.add(ref);
23409
23998
  }
23410
23999
  }
23411
- const { how, truncated } = tracer.reach(starts, given, handlers);
24000
+ const { how, truncated } = tracer.reach(
24001
+ starts.flatMap((start) => start.refs),
24002
+ given,
24003
+ handlers
24004
+ );
23412
24005
  const unreached = [];
23413
24006
  const throughRoutes = [];
23414
- for (const [at, ref] of starts.entries()) {
23415
- const found = how.get(ref);
23416
- if (found === "route") throughRoutes.push(changed[at] ?? "");
23417
- else if (!found) unreached.push(at);
23418
- }
23419
- const above = new Tracer(graph, memberCalls);
23420
- above.trace(unreached.map((at) => starts[at] ?? ""));
24007
+ for (const [at, start] of starts.entries()) {
24008
+ const found = start.refs.map((ref) => how.get(ref));
24009
+ if (found.includes("call")) continue;
24010
+ if (found.includes("route")) throughRoutes.push(changed[at] ?? "");
24011
+ else unreached.push(at);
24012
+ }
24013
+ const above = new Tracer(graph, memberCalls, tracer.shapes);
24014
+ await above.trace(
24015
+ unreached.flatMap((at) => starts[at]?.refs ?? []),
24016
+ unreached.flatMap((at) => starts[at]?.own ?? [])
24017
+ );
23421
24018
  return {
23422
24019
  changed: unreached.map((at) => changed[at] ?? ""),
23423
24020
  entries: [...above.entries.values()].sort(entryOrder),
@@ -23433,7 +24030,7 @@ function existingTestsChanged(before, after, file2, project) {
23433
24030
  let workingLines = [];
23434
24031
  if (file2.status !== "DELETED" && project)
23435
24032
  try {
23436
- workingLines = readFileSync3(path10.join(project, file2.path), "utf8").split("\n");
24033
+ workingLines = readFileSync4(path11.join(project, file2.path), "utf8").split("\n");
23437
24034
  } catch {
23438
24035
  }
23439
24036
  const key = (graph, object2) => `${object2.kind}\0${graph.qualifiedName(object2.id)}`;
@@ -23472,10 +24069,10 @@ function importerTests(graph, objects2, tracer, importers) {
23472
24069
  }
23473
24070
  const next = [];
23474
24071
  for (const imported of modules)
23475
- for (const { path: path16, module } of importers.get(imported) ?? [])
23476
- if (testCode(path16))
24072
+ for (const { path: path17, module } of importers.get(imported) ?? [])
24073
+ if (testCode(path17))
23477
24074
  tracer.test(
23478
- path16,
24075
+ path17,
23479
24076
  void 0,
23480
24077
  hop ? "imports a changed file indirectly" : "imports a changed file",
23481
24078
  hop ? 4 : 2
@@ -23523,7 +24120,7 @@ function routeTests(project, store, version2, entries, tracer) {
23523
24120
  if (!mapRunnableTest(candidate)) continue;
23524
24121
  let text;
23525
24122
  try {
23526
- text = readFileSync3(path10.join(project, candidate), "utf8");
24123
+ text = readFileSync4(path11.join(project, candidate), "utf8");
23527
24124
  } catch {
23528
24125
  continue;
23529
24126
  }
@@ -23541,9 +24138,9 @@ function routeTests(project, store, version2, entries, tracer) {
23541
24138
  }
23542
24139
  }
23543
24140
  }
23544
- function sameDirectoryTests(paths, path16, tracer) {
23545
- const slash = path16.lastIndexOf("/");
23546
- const directory = slash < 0 ? "" : path16.slice(0, slash + 1);
24141
+ function sameDirectoryTests(paths, path17, tracer) {
24142
+ const slash = path17.lastIndexOf("/");
24143
+ const directory = slash < 0 ? "" : path17.slice(0, slash + 1);
23547
24144
  for (const candidate of paths) {
23548
24145
  if (!candidate.startsWith(directory)) continue;
23549
24146
  if (candidate.slice(directory.length).includes("/") || !mapTestPath(candidate)) continue;
@@ -23574,9 +24171,9 @@ var LIST = Object.freeze({
23574
24171
  similar: 10,
23575
24172
  similarNames: 3
23576
24173
  });
23577
- function routesIn(graph, path16) {
24174
+ function routesIn(graph, path17) {
23578
24175
  const routes = /* @__PURE__ */ new Set();
23579
- for (const relation of graph.relationsFrom(graph.objectsAt(path16).map((object2) => object2.id))) {
24176
+ for (const relation of graph.relationsFrom(graph.objectsAt(path17).map((object2) => object2.id))) {
23580
24177
  const route = relation.kind === "DECORATED_BY" ? relation.route ?? relation.argument : relation.argument;
23581
24178
  if (route && ROUTE2.test(route)) routes.add(route);
23582
24179
  }
@@ -23594,7 +24191,37 @@ async function checkMapChanges(input, signal) {
23594
24191
  const base = changes.files.some(
23595
24192
  (file2) => file2.basePath !== void 0 && (file2.baseLines.length || file2.baseText !== void 0 || renamedTemplate(file2))
23596
24193
  ) ? await input.baseVersion(changes.commit, signal) : void 0;
23597
- const impact = mapChangeImpact(index.store, working, base, changes, project, input.tests);
24194
+ const usesIn = (version2, source) => async (refs, until2) => {
24195
+ const found = await index.findUses(
24196
+ { version: version2, source, refs, until: until2, maxResults: MAP_REFERENCES_MAX },
24197
+ signal
24198
+ );
24199
+ return new Map(
24200
+ [...found].map(([ref, { uses, complete }]) => [
24201
+ ref,
24202
+ {
24203
+ complete,
24204
+ uses: uses.flatMap(
24205
+ ({ kind, owner, anchor }) => owner && kind !== "IMPORT_EXPORT" ? [{ owner: owner.id, anchor, write: kind === "WRITE" }] : []
24206
+ )
24207
+ }
24208
+ ])
24209
+ );
24210
+ };
24211
+ const until = mapShapeDeadline();
24212
+ const impact = await mapChangeImpact(
24213
+ index.store,
24214
+ working,
24215
+ base,
24216
+ changes,
24217
+ {
24218
+ working: usesIn(working, input.source),
24219
+ base: usesIn(base ?? working, { ...input.source, kind: "COMMIT", commit: changes.commit })
24220
+ },
24221
+ until,
24222
+ project,
24223
+ input.tests
24224
+ );
23598
24225
  return {
23599
24226
  text: mapChangesText(
23600
24227
  changes,
@@ -23605,8 +24232,9 @@ async function checkMapChanges(input, signal) {
23605
24232
  working,
23606
24233
  base,
23607
24234
  changes.files,
23608
- (file2) => readFile(path10.join(project, file2), "utf8").catch(() => void 0)
23609
- )
24235
+ (file2) => readFile(path11.join(project, file2), "utf8").catch(() => void 0)
24236
+ ),
24237
+ changes.files.length ? await compileBreaks(input, changes, base, until, signal) : void 0
23610
24238
  )
23611
24239
  };
23612
24240
  }
@@ -23626,7 +24254,81 @@ async function mapRouteClients(project, store, working, impact, signal) {
23626
24254
  if (!routes.length) return [];
23627
24255
  return routeClients(routes, registrations, git, gitOptions(project, signal));
23628
24256
  }
23629
- function mapChangesText(changes, impact, clients = [], similar = []) {
24257
+ async function compileBreaks(input, changes, base, until, signal) {
24258
+ const { index, working } = input;
24259
+ const present = changes.files.filter((file2) => file2.status !== "DELETED").map((file2) => file2.path);
24260
+ const gone = changes.files.flatMap((file2) => file2.basePath ? [file2.basePath] : []);
24261
+ const after = await index.findDiagnostics(
24262
+ {
24263
+ version: working,
24264
+ source: input.source,
24265
+ configurations: [
24266
+ .../* @__PURE__ */ new Set([
24267
+ ...index.contextConfigurations(working, present),
24268
+ ...base ? index.contextConfigurations(base, gone) : []
24269
+ ])
24270
+ ],
24271
+ until
24272
+ },
24273
+ signal
24274
+ );
24275
+ const missing = new Set(after.contexts.flatMap((context) => context.missing));
24276
+ const views = new MapViewCache();
24277
+ const { notInstalled } = views.coverageNotes(index.store, working);
24278
+ if (notInstalled.length) {
24279
+ for (const { source, target, specifier } of views.imports(index.store, working))
24280
+ if (target === null && present.includes(source)) {
24281
+ const name = mapPackageOf(specifier);
24282
+ if (name && notInstalled.includes(name)) missing.add(name);
24283
+ }
24284
+ }
24285
+ const changedIn = new Map(changes.files.map((file2) => [file2.path, file2]));
24286
+ const onUnchanged = after.contexts.flatMap(({ configPath, errors: errors2 }) => {
24287
+ const unchanged = errors2.filter((item) => {
24288
+ const file2 = changedIn.get(item.path);
24289
+ return !file2 || !overlaps(file2.lines, item.line, item.line);
24290
+ });
24291
+ return unchanged.length ? [{ configPath, unchanged }] : [];
24292
+ });
24293
+ const before = onUnchanged.length && Date.now() <= until ? await index.findDiagnostics(
24294
+ {
24295
+ version: base ?? await input.baseVersion(changes.commit, signal),
24296
+ source: { ...input.source, kind: "COMMIT", commit: changes.commit },
24297
+ configurations: onUnchanged.map(({ configPath }) => configPath),
24298
+ until
24299
+ },
24300
+ signal
24301
+ ) : { contexts: [], unchecked: [] };
24302
+ const inBase = new Map(
24303
+ changes.files.flatMap((file2) => file2.basePath ? [[file2.basePath, file2]] : [])
24304
+ );
24305
+ const named = (path17, item) => `${path17}\0${item.code}\0${item.span}\0${item.text}`;
24306
+ const compiled = new Map(before.contexts.map((context) => [context.configPath, context.errors]));
24307
+ const unchecked = new Set(after.unchecked);
24308
+ const errors = /* @__PURE__ */ new Set();
24309
+ for (const { configPath, unchanged } of onUnchanged) {
24310
+ const had = compiled.get(configPath);
24311
+ if (!had) {
24312
+ unchecked.add(configPath);
24313
+ continue;
24314
+ }
24315
+ const known = /* @__PURE__ */ new Map();
24316
+ for (const item of had) {
24317
+ const file2 = inBase.get(item.path);
24318
+ if (file2 && overlaps(file2.baseLines, item.line, item.line)) continue;
24319
+ const name = named(file2?.path ?? item.path, item);
24320
+ known.set(name, (known.get(name) ?? 0) + 1);
24321
+ }
24322
+ for (const item of unchanged) {
24323
+ const name = named(item.path, item);
24324
+ const left = known.get(name) ?? 0;
24325
+ if (left) known.set(name, left - 1);
24326
+ else errors.add(`${item.path}:${item.line} TS${item.code} ${item.text.split("\n")[0]}`);
24327
+ }
24328
+ }
24329
+ return { errors: [...errors], missing: [...missing].sort(), unchecked: [...unchecked].sort() };
24330
+ }
24331
+ function mapChangesText(changes, impact, clients = [], similar = [], compile = { errors: [], missing: [], unchecked: [] }) {
23630
24332
  const files = changes.files.length;
23631
24333
  const direct = impact.tests.filter((test) => test.rank < 4);
23632
24334
  const indirect = impact.tests.filter((test) => test.rank >= 4);
@@ -23650,10 +24352,23 @@ Nothing changed against ${changes.base}.`;
23650
24352
  LIST.changed
23651
24353
  );
23652
24354
  list(
23653
- "REMOVED OR RENAMED (no code the diff left unchanged uses them)",
24355
+ "REMOVED OR RENAMED (no reference found on a line the diff left unchanged)",
23654
24356
  impact.removed.filter(({ usedBy }) => !usedBy.length).map(({ declaration }) => declaration),
23655
24357
  LIST.changed
23656
24358
  );
24359
+ list(
24360
+ "NEW COMPILE ERRORS ON LINES THE DIFF LEFT UNCHANGED (the compiler reports these now and did not before: the diff broke this code)",
24361
+ compile.errors,
24362
+ LIST.changed
24363
+ );
24364
+ if (compile.missing.length)
24365
+ lines.push(
24366
+ `PACKAGES NOT FOUND (${compile.missing.slice(0, LIST.names).join(", ")}${compile.missing.length > LIST.names ? `, +${compile.missing.length - LIST.names} more` : ""}): are dependencies installed in this directory? Values typed by them have no type to follow, so calls through them (framework page methods among them), their uses and compile errors are not seen, and this report can miss what the change reaches.`
24367
+ );
24368
+ if (compile.unchecked.length)
24369
+ lines.push(
24370
+ `NOT CHECKED FOR NEW COMPILE ERRORS (${compile.unchecked.slice(0, LIST.names).join(", ")}${compile.unchecked.length > LIST.names ? `, +${compile.unchecked.length - LIST.names} more` : ""}): the check ran out of time before compiling them on both sides, or the base has no such configuration, so errors the diff caused there are not listed.`
24371
+ );
23657
24372
  list(
23658
24373
  "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls or otherwise uses them now)",
23659
24374
  impact.uncalled,
@@ -23755,7 +24470,7 @@ Nothing changed against ${changes.base}.`;
23755
24470
  LIST.entries
23756
24471
  );
23757
24472
  list(
23758
- "POSSIBLY AFFECTED (through a call on an interface or base member, which may dispatch elsewhere)",
24473
+ "POSSIBLY AFFECTED (through a call on an interface or base member, which may dispatch elsewhere, or through code that uses a changed field or type, which may not depend on what changed)",
23759
24474
  impact.entries.filter((e) => !e.certain).map(entry),
23760
24475
  LIST.entries
23761
24476
  );
@@ -23868,7 +24583,7 @@ CREATE INDEX layermap_commit_version ON layermap_commit_versions(version_ref);
23868
24583
  `;
23869
24584
  var schemaVersion = (database) => Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23870
24585
  function openMapDatabase(file2) {
23871
- mkdirSync(path11.dirname(file2), { recursive: true, mode: 448 });
24586
+ mkdirSync(path12.dirname(file2), { recursive: true, mode: 448 });
23872
24587
  const database = new DatabaseSync(file2);
23873
24588
  try {
23874
24589
  database.exec(BUSY_TIMEOUT);
@@ -23905,10 +24620,10 @@ function openMapDatabase(file2) {
23905
24620
  throw error51;
23906
24621
  }
23907
24622
  }
23908
- var mapDatabasePath = (cacheDirectory2, canonicalProject) => path11.join(
24623
+ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path12.join(
23909
24624
  cacheDirectory2,
23910
24625
  "projects",
23911
- createHash4("sha256").update(canonicalProject).digest("hex").slice(0, 24),
24626
+ createHash5("sha256").update(canonicalProject).digest("hex").slice(0, 24),
23912
24627
  "map.sqlite"
23913
24628
  );
23914
24629
  var LayerMap = class _LayerMap {
@@ -23941,7 +24656,7 @@ var LayerMap = class _LayerMap {
23941
24656
  if (!stat3.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
23942
24657
  const source = {
23943
24658
  kind: "WORKTREE",
23944
- projectRef: `layermap:${createHash4("sha256").update(project).digest("hex").slice(0, 24)}`,
24659
+ projectRef: `layermap:${createHash5("sha256").update(project).digest("hex").slice(0, 24)}`,
23945
24660
  directory: { canonicalPath: project, device: String(stat3.dev), inode: String(stat3.ino) }
23946
24661
  };
23947
24662
  const file2 = mapDatabasePath(options.cacheDirectory, project);
@@ -23983,12 +24698,22 @@ var LayerMap = class _LayerMap {
23983
24698
  */
23984
24699
  versionAt(commit, signal, hold) {
23985
24700
  return this.serialized(async () => {
24701
+ const root = this.source.directory.canonicalPath;
24702
+ const tree = await new GitRunner().run(
24703
+ ["ls-tree", "-r", "-z", "--name-only", "--full-tree", commit],
24704
+ { cwd: root, signal, timeoutMs: 6e4, maxOutputBytes: null }
24705
+ );
23986
24706
  const key = digestValue({
23987
24707
  projectRef: this.source.projectRef,
23988
24708
  commit,
23989
24709
  scope: DEFAULT_INITIAL_EVIDENCE_SCOPE,
23990
24710
  analyzer: this.analyzer,
23991
- policy: SOURCE_POLICY
24711
+ policy: SOURCE_POLICY,
24712
+ // A commit's map holds what its types resolve to now, so the packages count too.
24713
+ installed: mapInstalledDigest(
24714
+ root,
24715
+ tree.stdout.toString("utf8").split("\0").filter(Boolean)
24716
+ )
23992
24717
  });
23993
24718
  const known = this.store.database.prepare("SELECT version_ref FROM layermap_commit_versions WHERE capture_key = ?").get(key)?.version_ref;
23994
24719
  const version2 = typeof known === "string" && hold(known) ? known : (await this.prepare({ ...this.source, kind: "COMMIT", commit }, signal, hold)).version;
@@ -24167,6 +24892,7 @@ var LayerMap = class _LayerMap {
24167
24892
  {
24168
24893
  index: this.index,
24169
24894
  project: this.project,
24895
+ source: this.source,
24170
24896
  working: await this.current(signal, hold),
24171
24897
  base: input.base ?? "HEAD",
24172
24898
  baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal, hold),
@@ -24197,25 +24923,25 @@ var LayerMap = class _LayerMap {
24197
24923
 
24198
24924
  // src/agent/environment.ts
24199
24925
  var packageRoot = (() => {
24200
- for (let directory = path12.dirname(fileURLToPath(import.meta.url)); ; ) {
24201
- const manifest = path12.join(directory, "package.json");
24202
- if (existsSync5(manifest) && JSON.parse(readFileSync4(manifest, "utf8")).name === "layermap")
24926
+ for (let directory = path13.dirname(fileURLToPath(import.meta.url)); ; ) {
24927
+ const manifest = path13.join(directory, "package.json");
24928
+ if (existsSync6(manifest) && JSON.parse(readFileSync5(manifest, "utf8")).name === "layermap")
24203
24929
  return directory;
24204
- if (path12.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
24205
- directory = path12.dirname(directory);
24930
+ if (path13.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
24931
+ directory = path13.dirname(directory);
24206
24932
  }
24207
24933
  })();
24208
- var packageVersion = async () => JSON.parse(await readFile2(path12.join(packageRoot, "package.json"), "utf8")).version;
24934
+ var packageVersion = async () => JSON.parse(await readFile2(path13.join(packageRoot, "package.json"), "utf8")).version;
24209
24935
  var cacheDirectory = (env = process.env) => {
24210
- if (env.LAYERMAP_CACHE) return path12.resolve(env.LAYERMAP_CACHE);
24211
- if (process.platform === "darwin") return path12.join(homedir(), "Library", "Caches", "layermap");
24936
+ if (env.LAYERMAP_CACHE) return path13.resolve(env.LAYERMAP_CACHE);
24937
+ if (process.platform === "darwin") return path13.join(homedir(), "Library", "Caches", "layermap");
24212
24938
  if (process.platform === "win32")
24213
- return path12.join(
24214
- env.LOCALAPPDATA || path12.join(homedir(), "AppData", "Local"),
24939
+ return path13.join(
24940
+ env.LOCALAPPDATA || path13.join(homedir(), "AppData", "Local"),
24215
24941
  "layermap",
24216
24942
  "Cache"
24217
24943
  );
24218
- return path12.join(env.XDG_CACHE_HOME || path12.join(homedir(), ".cache"), "layermap");
24944
+ return path13.join(env.XDG_CACHE_HOME || path13.join(homedir(), ".cache"), "layermap");
24219
24945
  };
24220
24946
  var projectDirectory = (directory) => new Promise(
24221
24947
  (resolve) => execFile(
@@ -24223,7 +24949,7 @@ var projectDirectory = (directory) => new Promise(
24223
24949
  ["rev-parse", "--show-toplevel"],
24224
24950
  { cwd: directory, timeout: 1e4 },
24225
24951
  (error51, stdout) => resolve(
24226
- error51 ? { directory: path12.resolve(directory), git: false } : { directory: stdout.trim(), git: true }
24952
+ error51 ? { directory: path13.resolve(directory), git: false } : { directory: stdout.trim(), git: true }
24227
24953
  )
24228
24954
  )
24229
24955
  );
@@ -24233,7 +24959,7 @@ var relativeTo = (directory, value) => Object.fromEntries(
24233
24959
  Object.fromEntries(
24234
24960
  Object.entries(resources).map(([key, field]) => [
24235
24961
  key,
24236
- key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path12.relative(directory, field) : field
24962
+ key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path13.relative(directory, field) : field
24237
24963
  ])
24238
24964
  )
24239
24965
  ])
@@ -24244,7 +24970,7 @@ var resolvePlaceholder = (field) => {
24244
24970
  createRequire(import.meta.url).resolve("typescript/package.json")
24245
24971
  );
24246
24972
  const native = `@typescript/typescript-${process.platform}-${process.arch}/package.json`;
24247
- return path12.join(path12.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
24973
+ return path13.join(path13.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
24248
24974
  }
24249
24975
  const resolved = field.replaceAll("{platform}", process.platform).replaceAll("{arch}", process.arch);
24250
24976
  return field.includes("{platform}") ? executableName(resolved) : resolved;
@@ -24256,24 +24982,24 @@ var absoluteIn = (directory, value) => Object.fromEntries(
24256
24982
  Object.entries(resources).map(([key, field]) => {
24257
24983
  if (!key.endsWith("Path") || typeof field !== "string") return [key, field];
24258
24984
  const resolved = resolvePlaceholder(field);
24259
- return [key, path12.isAbsolute(resolved) ? resolved : path12.join(directory, resolved)];
24985
+ return [key, path13.isAbsolute(resolved) ? resolved : path13.join(directory, resolved)];
24260
24986
  })
24261
24987
  )
24262
24988
  ])
24263
24989
  );
24264
24990
  var readAnalyzers = async (directory) => {
24265
- const file2 = path12.join(directory, "analyzers.json");
24266
- if (!existsSync5(file2)) return void 0;
24991
+ const file2 = path13.join(directory, "analyzers.json");
24992
+ if (!existsSync6(file2)) return void 0;
24267
24993
  const analyzers = absoluteIn(directory, JSON.parse(await readFile2(file2, "utf8")));
24268
24994
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
24269
24995
  };
24270
24996
  var sourceDigest = async () => {
24271
- const hash2 = createHash5("sha256").update(await readFile2(path12.join(packageRoot, "package.json")));
24997
+ const hash2 = createHash6("sha256").update(await readFile2(path13.join(packageRoot, "package.json")));
24272
24998
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
24273
- const directory = path12.join(packageRoot, part);
24274
- if (!existsSync5(directory)) continue;
24999
+ const directory = path13.join(packageRoot, part);
25000
+ if (!existsSync6(directory)) continue;
24275
25001
  for (const entry of (await readdir(directory, { recursive: true })).sort()) {
24276
- const file2 = path12.join(directory, entry);
25002
+ const file2 = path13.join(directory, entry);
24277
25003
  const info = await stat(file2);
24278
25004
  if (info.isFile()) hash2.update(`${part}/${entry}\0${info.size}\0${info.mtimeMs}\0`);
24279
25005
  }
@@ -24281,11 +25007,11 @@ var sourceDigest = async () => {
24281
25007
  return hash2.digest("hex").slice(0, 16);
24282
25008
  };
24283
25009
  async function resolveAnalyzers(cache, log2, env = process.env) {
24284
- for (const directory2 of [env.LAYERMAP_ANALYZERS, path12.join(packageRoot, "analyzers")]) {
24285
- const analyzers = directory2 && await readAnalyzers(path12.resolve(directory2));
25010
+ for (const directory2 of [env.LAYERMAP_ANALYZERS, path13.join(packageRoot, "analyzers")]) {
25011
+ const analyzers = directory2 && await readAnalyzers(path13.resolve(directory2));
24286
25012
  if (analyzers) return analyzers;
24287
25013
  }
24288
- const directory = path12.join(cache, "analyzers", await sourceDigest());
25014
+ const directory = path13.join(cache, "analyzers", await sourceDigest());
24289
25015
  const built = await readAnalyzers(directory);
24290
25016
  if (built) return built;
24291
25017
  log2("Building the language analyzers (once per LayerMap version)...");
@@ -24301,73 +25027,73 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
24301
25027
  python: parser.pythonResources,
24302
25028
  java: parser.javaResources
24303
25029
  });
24304
- await writeFile(path12.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
25030
+ await writeFile(path13.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
24305
25031
  `);
24306
25032
  await rename(staging, directory).catch(() => rm(staging, { recursive: true, force: true }));
24307
25033
  return await readAnalyzers(directory);
24308
25034
  }
24309
25035
  var DAY = 24 * 60 * 60 * 1e3;
24310
25036
  async function pruneCache(cache, project, now = Date.now(), installed = packageRoot, env = process.env) {
24311
- const used = path12.join(path12.dirname(mapDatabasePath(cache, project)), "last-used");
24312
- await mkdir(path12.dirname(used), { recursive: true, mode: 448 });
25037
+ const used = path13.join(path13.dirname(mapDatabasePath(cache, project)), "last-used");
25038
+ await mkdir(path13.dirname(used), { recursive: true, mode: 448 });
24313
25039
  await writeFile(used, "");
24314
25040
  await utimes(used, now / 1e3, now / 1e3);
24315
- const projects = path12.join(cache, "projects");
25041
+ const projects = path13.join(cache, "projects");
24316
25042
  for (const name of await readdir(projects).catch(() => [])) {
24317
- const directory = path12.join(projects, name);
24318
- const marker = path12.join(directory, "last-used");
24319
- const last = (await stat(existsSync5(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
25043
+ const directory = path13.join(projects, name);
25044
+ const marker = path13.join(directory, "last-used");
25045
+ const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
24320
25046
  if (last !== void 0 && now - last > 30 * DAY)
24321
25047
  await rm(directory, { recursive: true, force: true });
24322
25048
  }
24323
- const builds = path12.join(cache, "analyzers");
25049
+ const builds = path13.join(cache, "analyzers");
24324
25050
  const current = await sourceDigest();
24325
25051
  for (const name of await readdir(builds).catch(() => [])) {
24326
25052
  if (name === current) continue;
24327
- const built = (await stat(path12.join(builds, name)).catch(() => void 0))?.mtimeMs;
25053
+ const built = (await stat(path13.join(builds, name)).catch(() => void 0))?.mtimeMs;
24328
25054
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
24329
- await rm(path12.join(builds, name), { recursive: true, force: true });
25055
+ await rm(path13.join(builds, name), { recursive: true, force: true });
24330
25056
  }
24331
- const own = path12.dirname(path12.dirname(installed));
24332
- const versions = path12.join(cache, "versions");
24333
- const launched = path12.dirname(own) === versions;
25057
+ const own = path13.dirname(path13.dirname(installed));
25058
+ const versions = path13.join(cache, "versions");
25059
+ const launched = path13.dirname(own) === versions;
24334
25060
  if (launched) await pruneVersions(versions, own, now);
24335
- const npx = launched ? path12.join(
24336
- env.npm_config_cache || (process.platform === "win32" ? path12.join(env.LOCALAPPDATA || path12.join(homedir(), "AppData", "Local"), "npm-cache") : path12.join(homedir(), ".npm")),
25061
+ const npx = launched ? path13.join(
25062
+ env.npm_config_cache || (process.platform === "win32" ? path13.join(env.LOCALAPPDATA || path13.join(homedir(), "AppData", "Local"), "npm-cache") : path13.join(homedir(), ".npm")),
24337
25063
  "_npx"
24338
- ) : path12.dirname(own);
24339
- if (path12.basename(path12.dirname(installed)) === "node_modules" && path12.basename(npx) === "_npx")
25064
+ ) : path13.dirname(own);
25065
+ if (path13.basename(path13.dirname(installed)) === "node_modules" && path13.basename(npx) === "_npx")
24340
25066
  await pruneNpxInstalls(npx, installed, now);
24341
25067
  }
24342
25068
  async function pruneVersions(versions, own, now) {
24343
- const used = path12.join(own, "last-used");
25069
+ const used = path13.join(own, "last-used");
24344
25070
  await writeFile(used, "");
24345
25071
  await utimes(used, now / 1e3, now / 1e3);
24346
25072
  for (const name of await readdir(versions).catch(() => [])) {
24347
- const directory = path12.join(versions, name);
24348
- const marker = path12.join(directory, "last-used");
24349
- const last = (await stat(existsSync5(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
25073
+ const directory = path13.join(versions, name);
25074
+ const marker = path13.join(directory, "last-used");
25075
+ const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
24350
25076
  if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
24351
25077
  await rm(directory, { recursive: true, force: true });
24352
25078
  }
24353
25079
  }
24354
25080
  async function pruneNpxInstalls(npx, installed, now) {
24355
- const own = path12.dirname(path12.dirname(installed));
25081
+ const own = path13.dirname(path13.dirname(installed));
24356
25082
  const manifest = async (file2) => JSON.parse(await readFile2(file2, "utf8").catch(() => "{}"));
24357
25083
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
24358
- const current = parts((await manifest(path12.join(installed, "package.json"))).version);
25084
+ const current = parts((await manifest(path13.join(installed, "package.json"))).version);
24359
25085
  const older = (version2) => {
24360
25086
  for (let index = 0; index < 3; index++)
24361
25087
  if (version2[index] !== current[index]) return (version2[index] ?? 0) < (current[index] ?? 0);
24362
25088
  return false;
24363
25089
  };
24364
25090
  for (const name of await readdir(npx).catch(() => [])) {
24365
- const directory = path12.join(npx, name);
25091
+ const directory = path13.join(npx, name);
24366
25092
  if (directory === own) continue;
24367
- const requested = (await manifest(path12.join(directory, "package.json"))).dependencies ?? {};
25093
+ const requested = (await manifest(path13.join(directory, "package.json"))).dependencies ?? {};
24368
25094
  if (Object.keys(requested).join() !== "layermap") continue;
24369
25095
  const version2 = parts(
24370
- (await manifest(path12.join(directory, "node_modules", "layermap", "package.json"))).version
25096
+ (await manifest(path13.join(directory, "node_modules", "layermap", "package.json"))).version
24371
25097
  );
24372
25098
  if (version2.length !== 3 || version2.some(Number.isNaN) || !older(version2)) continue;
24373
25099
  const at = (await stat(directory).catch(() => void 0))?.mtimeMs;
@@ -24386,9 +25112,9 @@ var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task nee
24386
25112
  var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
24387
25113
 
24388
25114
  // src/agent/projects.ts
24389
- import { existsSync as existsSync6 } from "node:fs";
25115
+ import { existsSync as existsSync7 } from "node:fs";
24390
25116
  import { readdir as readdir2, realpath as realpath3, stat as stat2 } from "node:fs/promises";
24391
- import path13 from "node:path";
25117
+ import path14 from "node:path";
24392
25118
 
24393
25119
  // src/tools.ts
24394
25120
  var AGENT_MAP_TOOL_HOST = Object.freeze({
@@ -24412,7 +25138,7 @@ var MAP_TOOL_NAMES = Object.freeze({
24412
25138
  references: "project_find_references",
24413
25139
  check: "project_check_changes"
24414
25140
  });
24415
- var mapDirectoryPath = (path16) => path16.length > 1 && path16.endsWith("/") && !path16.endsWith("//") ? path16.slice(0, -1) : path16;
25141
+ var mapDirectoryPath = (path17) => path17.length > 1 && path17.endsWith("/") && !path17.endsWith("//") ? path17.slice(0, -1) : path17;
24416
25142
  var ProjectMapSearchInputSchema = external_exports.object({
24417
25143
  path: external_exports.string().default("."),
24418
25144
  query: external_exports.string().min(1).max(256),
@@ -24445,7 +25171,7 @@ var ProjectMapCheckInputSchema = external_exports.object({
24445
25171
  "A file or directory in the repository to check, when the session works in more than one; the check covers that repository's whole working tree."
24446
25172
  ),
24447
25173
  tests: external_exports.array(external_exports.string().min(1).max(1e3)).max(200).optional().describe(
24448
- "Test files that should cover the change, such as the ones you wrote for it, as paths are given to the other tools: the report then adds NOT REACHED BY THE GIVEN TESTS, the changed declarations none of them calls or requests through a route, with the entry points above them."
25174
+ "Test files that should cover the change, such as the ones you wrote for it, as paths are given to the other tools: the report then adds NOT REACHED BY THE GIVEN TESTS, the changed declarations none of them calls or requests through a route, or uses when it is a field or type, with the entry points above them."
24449
25175
  )
24450
25176
  }).strip();
24451
25177
  var locatorSchema = MapObjectLocatorSchema.describe(
@@ -24472,35 +25198,35 @@ var mapToolDescriptions = (host) => {
24472
25198
  return Object.freeze({
24473
25199
  search: `${lead("search")}Find declarations and files whose names, paths or source documentation match query terms. ANY (default) matches any term, ALL requires every term, LITERAL matches the exact text. Results are ranked by relevance and grouped by file with the declaration name, kind, 1-based line range and matched fields (${MAP_KINDS_LEGEND}). Zoom into a result with project_explore_map({path,name}) or ${host.readResult}. This is not a full-text search and does not prove absence; ${host.textSearch}. Continue with offset and unchanged conditions.`,
24474
25200
  explore: `${lead("explore")}Read the static project map, zooming from the whole project to one declaration. path "." or a directory lists modules, module imports, external packages and its files: with exported declarations when the listing is small, as file names and line counts by directory when larger, and as modules only when very large. Start here to see what exists before searching or reading. A file path lists its declarations and members, imports, importers and top-level statements. A file path with name (or Container.member), optionally narrowed by its start line, or with a line alone, shows that declaration's calls, callers (including uses as a value), writes, heritage, decorators and members, aggregated per related declaration with @line sites; closures and locals are folded into their named container. depth also expands the related declarations hop by hop: up to 8 in one direction, which traces callers up to entry points (INCOMING) or callees down (OUTGOING), and up to 3 for BOTH. To find what a change affects, select the declaration with direction INCOMING and a depth up to 8, continue from any NOT EXPANDED declarations the view names, then confirm the entry points in source. Test files and standard-library call targets are hidden and counted by default; includeTests and includeUnresolved show them. Views use ${MAP_KINDS_LEGEND}. In a declaration view, ${MAP_DECLARATION_LEGEND} ${host.readSource} The map is static: trace stops, possible callers by name, framework wiring and unresolved targets need source reading, and a missing relationship does not prove absence. When a page reports more entries, continue with offset and otherwise unchanged arguments.`,
24475
- check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed, and that nothing extends, implements, overrides or wires with a decorator; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it; given tests, NOT REACHED BY THE GIVEN TESTS, the changed declarations none of them calls or requests through a route, with the entry points above them. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
25201
+ check: `${lead("check")}Compares the working tree with a commit (HEAD by default, so uncommitted and untracked changes), finds the declarations the diff changed, removed or renamed, and follows their callers, and the code using a field or type, up to 8 levels. It reports, conclusion first: AFFECTED ENTRY POINTS reached through resolved calls, each route with its HTTP methods and full path and the chain to the change; POSSIBLY AFFECTED ones reached only through a call on an interface or base member, or through code that uses a changed field or type; REQUESTED BY, the code and templates outside the tests that request the path of a route whose handler the change reaches or a route it removed, found by text; EXISTING TESTS CHANGED, the tests that existed before the diff and whose code it changed or removed; SHARED BY, when tests reach the changed code through more than one area (package or module), so a change meant for one feature may change others; NAMES STILL USED ELSEWHERE, environment variables and configuration keys the diff removed from a file that other files still read or set, found by text; NEW MODULE DEPENDENCIES, imports between the modules of the project overview that the base did not have, and those that make two modules depend on each other, for you to judge against the project's layers; NEW COMPILE ERRORS, what the compiler reports on lines the diff left unchanged and did not report before, in code a tsconfig covers; PACKAGES NOT FOUND, packages the changed code needs that are not installed in this directory, whose types the trace then lacks; EXISTING CODE LIKE THE NEW CODE, declarations the diff adds whose code reads almost the same as code the project already has; LEFT WITHOUT CALLERS, declarations whose last callers outside the tests the diff removed or changed, and that nothing extends, implements, overrides or wires with a decorator; CHECK BY HAND for what a static map cannot follow (changed configuration, templates, migrations or dependency files, changed route registrations, declarations with no callers, calls by name on receivers of unknown type); and RELATED TESTS, the existing test files that call the changed code, import a changed file or sit beside it; given tests, NOT REACHED BY THE GIVEN TESTS, the changed declarations none of them calls or requests through a route, or uses when it is a field or type, with the entry points above them. It does not run or write tests: run the related ones if the change needs verifying; a failing or rewritten test of a feature the request is not about means the change leaked, so restore the test and narrow the change; a new dependency that runs against the layers or closes a cycle means moving what both modules need down rather than importing upward; new code like existing code means using the existing code, or removing the old if the new replaces it; code left without callers means deleting it, with the tests that only test it, when the change replaced it; call it once when the edits are done; and confirm the entry points in source, since an empty list does not prove a change safe.`,
24476
25202
  references: `${lead("references")}Compute usages of a mapped declaration from current source, including aliases, re-exports and non-call references. Select it with symbol {path,name,line?} as printed by project_explore_map or project_search_map (line is its start line when names repeat), or with an entityRef or locator {path,start,kind}. Broader and more expensive than the cached callers in project_explore_map; file or unsupported declarations may lack a reference target. path and kinds filter usage locations before paging. ${host.grantRules}objects contains compact declarations; targetRef and reference ownerRef identify them. ${host.readReference} A file that several compiler contexts read (such as packages of one workspace) lists its references once per context, each with that context's configPath. Continue with nextCursor and unchanged conditions, including after an empty partial page. Filtered exhaustion and missing results do not prove absence.`
24477
25203
  });
24478
25204
  };
24479
25205
 
24480
25206
  // src/agent/projects.ts
24481
25207
  var escapes = (relative) => {
24482
- const normal = path13.normalize(relative);
24483
- return normal === ".." || normal.startsWith(`..${path13.sep}`);
25208
+ const normal = path14.normalize(relative);
25209
+ return normal === ".." || normal.startsWith(`..${path14.sep}`);
24484
25210
  };
24485
25211
  async function locate(start, given) {
24486
- if (start.git && !path13.isAbsolute(given) && !escapes(given))
25212
+ if (start.git && !path14.isAbsolute(given) && !escapes(given))
24487
25213
  return { project: start.directory, path: given };
24488
- const absolute = path13.resolve(start.directory, given);
25214
+ const absolute = path14.resolve(start.directory, given);
24489
25215
  let directory = absolute;
24490
25216
  while (!(await stat2(directory).catch(() => void 0))?.isDirectory()) {
24491
- if (path13.dirname(directory) === directory) return void 0;
24492
- directory = path13.dirname(directory);
25217
+ if (path14.dirname(directory) === directory) return void 0;
25218
+ directory = path14.dirname(directory);
24493
25219
  }
24494
- const real = path13.join(await realpath3(directory), path13.relative(directory, absolute));
25220
+ const real = path14.join(await realpath3(directory), path14.relative(directory, absolute));
24495
25221
  const { directory: project, git: git2 } = await projectDirectory(directory);
24496
25222
  if (!git2) return void 0;
24497
- const relative = path13.relative(project, real);
25223
+ const relative = path14.relative(project, real);
24498
25224
  if (escapes(relative)) return void 0;
24499
- return { project, path: relative ? relative.split(path13.sep).join("/") : "." };
25225
+ return { project, path: relative ? relative.split(path14.sep).join("/") : "." };
24500
25226
  }
24501
25227
  async function repositoriesIn(directory) {
24502
25228
  const entries = await readdir2(directory, { withFileTypes: true }).catch(() => []);
24503
- return entries.filter((entry) => entry.isDirectory() && existsSync6(path13.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
25229
+ return entries.filter((entry) => entry.isDirectory() && existsSync7(path14.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
24504
25230
  }
24505
25231
  async function routeMapCall(start, { name, args }) {
24506
25232
  const holder = ["symbol", "locator"].find(
@@ -24512,7 +25238,7 @@ async function routeMapCall(start, { name, args }) {
24512
25238
  if (!located) {
24513
25239
  const repositories = start.git ? [] : await repositoriesIn(start.directory);
24514
25240
  const such = repositories.length ? `, such as ${repositories.join(", ")}` : "";
24515
- return named === "." ? `LAYERMAP_NOT_A_GIT_REPOSITORY: This session started in ${start.directory}, which is not in a Git repository. Name a file or directory in one, relative to that folder or absolute${such}.` : `LAYERMAP_NOT_A_GIT_REPOSITORY: ${path13.resolve(start.directory, named)} is not in a Git repository; LayerMap maps Git repositories${start.git ? "" : `. Name a file or directory in one, relative to ${start.directory} or absolute${such}`}.`;
25241
+ return named === "." ? `LAYERMAP_NOT_A_GIT_REPOSITORY: This session started in ${start.directory}, which is not in a Git repository. Name a file or directory in one, relative to that folder or absolute${such}.` : `LAYERMAP_NOT_A_GIT_REPOSITORY: ${path14.resolve(start.directory, named)} is not in a Git repository; LayerMap maps Git repositories${start.git ? "" : `. Name a file or directory in one, relative to ${start.directory} or absolute${such}`}.`;
24516
25242
  }
24517
25243
  if (!holder) {
24518
25244
  const routed2 = value === void 0 ? args : { ...args, path: located.path };
@@ -24828,10 +25554,10 @@ ${text}` : text
24828
25554
 
24829
25555
  // src/agent/setup.ts
24830
25556
  import { execFile as execFile2 } from "node:child_process";
24831
- import { existsSync as existsSync7 } from "node:fs";
25557
+ import { existsSync as existsSync8 } from "node:fs";
24832
25558
  import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24833
25559
  import { homedir as homedir2 } from "node:os";
24834
- import path14 from "node:path";
25560
+ import path15 from "node:path";
24835
25561
  var SERVER = "layermap";
24836
25562
  var SETUP_RULE = `mcp__${SERVER}`;
24837
25563
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
@@ -24839,11 +25565,11 @@ var BEGIN = "<!-- layermap:begin -->";
24839
25565
  var END = "<!-- layermap:end -->";
24840
25566
  var launcherScript = (template, version2) => `// Generated from scripts/launcher.mjs.
24841
25567
  ${template.replace("__VERSION__", JSON.stringify(version2))}`;
24842
- var PUBLISHED_LAUNCHER = path14.join(packageRoot, "dist", "launcher.mjs");
24843
- var launcherFile = (env = process.env) => path14.join(cacheDirectory(env), "server.mjs");
24844
- var mcpLaunchCommand = (env = process.env, published = existsSync7(PUBLISHED_LAUNCHER)) => {
25568
+ var PUBLISHED_LAUNCHER = path15.join(packageRoot, "dist", "launcher.mjs");
25569
+ var launcherFile = (env = process.env) => path15.join(cacheDirectory(env), "server.mjs");
25570
+ var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAUNCHER)) => {
24845
25571
  if (published) return ["node", launcherFile(env)];
24846
- const script = path14.resolve(process.argv[1] ?? "");
25572
+ const script = path15.resolve(process.argv[1] ?? "");
24847
25573
  const execArgv = [];
24848
25574
  for (let index = 0; index < process.execArgv.length; index++) {
24849
25575
  const argument = process.execArgv[index];
@@ -24870,7 +25596,7 @@ var run = (command, args, env) => new Promise((resolve) => {
24870
25596
  );
24871
25597
  });
24872
25598
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
24873
- const settings = existsSync7(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
25599
+ const settings = existsSync8(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
24874
25600
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
24875
25601
  throw new Error(`${file2} is not a settings object.`);
24876
25602
  settings.permissions ??= {};
@@ -24879,11 +25605,12 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
24879
25605
  throw new Error(`${file2} has permissions.allow that is not a list.`);
24880
25606
  if (settings.permissions.allow.includes(rule)) return false;
24881
25607
  settings.permissions.allow.push(rule);
24882
- await mkdir2(path14.dirname(file2), { recursive: true });
25608
+ await mkdir2(path15.dirname(file2), { recursive: true });
24883
25609
  await writeFile2(file2, `${JSON.stringify(settings, null, 2)}
24884
25610
  `);
24885
25611
  return true;
24886
25612
  }
25613
+ var CODEX_TOOL_TIMEOUT_SEC = 300;
24887
25614
  async function configureCodexServer(file2) {
24888
25615
  const lines = (await readFile3(file2, "utf8")).split("\n");
24889
25616
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
@@ -24893,7 +25620,7 @@ async function configureCodexServer(file2) {
24893
25620
  const wanted = {
24894
25621
  default_tools_approval_mode: '"approve"',
24895
25622
  startup_timeout_sec: "120",
24896
- tool_timeout_sec: "120"
25623
+ tool_timeout_sec: String(CODEX_TOOL_TIMEOUT_SEC)
24897
25624
  };
24898
25625
  const present = new Set(
24899
25626
  lines.slice(header2 + 1, end).map((line) => line.split("=")[0]?.trim() ?? "")
@@ -24908,17 +25635,17 @@ async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
24908
25635
  const block = `${BEGIN}
24909
25636
  ${note}
24910
25637
  ${END}`;
24911
- const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
25638
+ const text = existsSync8(file2) ? await readFile3(file2, "utf8") : "";
24912
25639
  const start = text.indexOf(BEGIN);
24913
25640
  const end = text.indexOf(END);
24914
25641
  const next = start >= 0 && end > start ? `${text.slice(0, start)}${block}${text.slice(end + END.length)}` : `${text}${text && !text.endsWith("\n") ? "\n" : ""}${text ? "\n" : ""}${block}
24915
25642
  `;
24916
25643
  if (next === text) return;
24917
- await mkdir2(path14.dirname(file2), { recursive: true });
25644
+ await mkdir2(path15.dirname(file2), { recursive: true });
24918
25645
  await writeFile2(file2, next);
24919
25646
  }
24920
25647
  async function removeInstructionNote(file2) {
24921
- if (!existsSync7(file2)) return;
25648
+ if (!existsSync8(file2)) return;
24922
25649
  const text = await readFile3(file2, "utf8");
24923
25650
  const start = text.indexOf(BEGIN);
24924
25651
  const end = text.indexOf(END);
@@ -24929,7 +25656,7 @@ async function removeInstructionNote(file2) {
24929
25656
  else await writeFile2(file2, rest);
24930
25657
  }
24931
25658
  async function disallowInClaudeSettings(file2) {
24932
- if (!existsSync7(file2)) return;
25659
+ if (!existsSync8(file2)) return;
24933
25660
  const settings = JSON.parse(await readFile3(file2, "utf8"));
24934
25661
  const allow = settings?.permissions?.allow;
24935
25662
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
@@ -24942,11 +25669,11 @@ async function disallowInClaudeSettings(file2) {
24942
25669
  }
24943
25670
  var YAML_BEGIN = "# layermap:begin";
24944
25671
  var YAML_END = "# layermap:end";
24945
- var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path14.delimiter).find((directory) => path14.isAbsolute(directory) && existsSync7(path14.join(directory, "node"))) ?? path14.dirname(process.execPath);
25672
+ var nodeDirectory = (env = process.env) => (env.PATH ?? "").split(path15.delimiter).find((directory) => path15.isAbsolute(directory) && existsSync8(path15.join(directory, "node"))) ?? path15.dirname(process.execPath);
24946
25673
  var dshPatchBlock = (command, env) => {
24947
25674
  const node = nodeDirectory(env);
24948
- const [program = "", ...args] = command[0] === "node" ? [path14.join(node, "node"), ...command.slice(1)] : command;
24949
- const searchPath2 = `${JSON.stringify(`${node}${path14.delimiter}`)} + process.env.PATH`;
25675
+ const [program = "", ...args] = command[0] === "node" ? [path15.join(node, "node"), ...command.slice(1)] : command;
25676
+ const searchPath2 = `${JSON.stringify(`${node}${path15.delimiter}`)} + process.env.PATH`;
24950
25677
  return [
24951
25678
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
24952
25679
  "- insert:",
@@ -24965,7 +25692,7 @@ var dshPatchBlock = (command, env) => {
24965
25692
  ].join("\n");
24966
25693
  };
24967
25694
  async function writeDshPatch(file2, block) {
24968
- const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
25695
+ const text = existsSync8(file2) ? await readFile3(file2, "utf8") : "";
24969
25696
  const start = text.indexOf(YAML_BEGIN);
24970
25697
  const end = text.indexOf(YAML_END);
24971
25698
  let next;
@@ -24981,11 +25708,11 @@ async function writeDshPatch(file2, block) {
24981
25708
  `;
24982
25709
  }
24983
25710
  if (next === text) return;
24984
- await mkdir2(path14.dirname(file2), { recursive: true });
25711
+ await mkdir2(path15.dirname(file2), { recursive: true });
24985
25712
  await writeFile2(file2, next);
24986
25713
  }
24987
25714
  async function removeDshPatch(file2) {
24988
- if (!existsSync7(file2)) return;
25715
+ if (!existsSync8(file2)) return;
24989
25716
  const text = await readFile3(file2, "utf8");
24990
25717
  const start = text.indexOf(YAML_BEGIN);
24991
25718
  const end = text.indexOf(YAML_END);
@@ -24999,31 +25726,31 @@ async function removeDshPatch(file2) {
24999
25726
  var agentFiles = (options) => {
25000
25727
  const env = options.env ?? process.env;
25001
25728
  if (options.agent === "dsh") {
25002
- const home = env.DSH_HOME || path14.join(homedir2(), ".dsh");
25729
+ const home = env.DSH_HOME || path15.join(homedir2(), ".dsh");
25003
25730
  return {
25004
- settings: path14.join(home, "cordis.patch.yml"),
25005
- instructions: path14.join(home, "AGENTS.md")
25731
+ settings: path15.join(home, "cordis.patch.yml"),
25732
+ instructions: path15.join(home, "AGENTS.md")
25006
25733
  };
25007
25734
  }
25008
25735
  if (options.agent === "codex") {
25009
- const home = env.CODEX_HOME ?? path14.join(homedir2(), ".codex");
25010
- return { settings: path14.join(home, "config.toml"), instructions: path14.join(home, "AGENTS.md") };
25736
+ const home = env.CODEX_HOME ?? path15.join(homedir2(), ".codex");
25737
+ return { settings: path15.join(home, "config.toml"), instructions: path15.join(home, "AGENTS.md") };
25011
25738
  }
25012
25739
  if (options.scope === "user") {
25013
- const home = env.CLAUDE_CONFIG_DIR ?? path14.join(homedir2(), ".claude");
25740
+ const home = env.CLAUDE_CONFIG_DIR ?? path15.join(homedir2(), ".claude");
25014
25741
  return {
25015
- settings: path14.join(home, "settings.json"),
25016
- instructions: path14.join(home, "CLAUDE.md")
25742
+ settings: path15.join(home, "settings.json"),
25743
+ instructions: path15.join(home, "CLAUDE.md")
25017
25744
  };
25018
25745
  }
25019
25746
  const local = options.scope === "local";
25020
25747
  return {
25021
- settings: path14.join(
25748
+ settings: path15.join(
25022
25749
  options.project,
25023
25750
  ".claude",
25024
25751
  local ? "settings.local.json" : "settings.json"
25025
25752
  ),
25026
- instructions: path14.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
25753
+ instructions: path15.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
25027
25754
  };
25028
25755
  };
25029
25756
  async function setupAgent(options) {
@@ -25035,7 +25762,7 @@ async function setupAgent(options) {
25035
25762
  );
25036
25763
  return false;
25037
25764
  }
25038
- const published = existsSync7(PUBLISHED_LAUNCHER);
25765
+ const published = existsSync8(PUBLISHED_LAUNCHER);
25039
25766
  const command = mcpLaunchCommand(env, published);
25040
25767
  const quoted = command.map((part) => /^[\w./:@=-]+$/u.test(part) ? part : JSON.stringify(part));
25041
25768
  const { settings, instructions } = agentFiles(options);
@@ -25043,7 +25770,7 @@ async function setupAgent(options) {
25043
25770
  const writeLauncher = async () => {
25044
25771
  if (!published) return;
25045
25772
  const file2 = launcherFile(env);
25046
- await mkdir2(path14.dirname(file2), { recursive: true, mode: 448 });
25773
+ await mkdir2(path15.dirname(file2), { recursive: true, mode: 448 });
25047
25774
  await writeFile2(
25048
25775
  `${file2}.${process.pid}`,
25049
25776
  launcherScript(await readFile3(PUBLISHED_LAUNCHER, "utf8"), options.version)
@@ -25074,7 +25801,7 @@ async function setupAgent(options) {
25074
25801
  } else {
25075
25802
  log2(`codex mcp add ${SERVER} -- ${quoted.join(" ")}`);
25076
25803
  log2(
25077
- `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = 120 in ${settings}`
25804
+ `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC} in ${settings}`
25078
25805
  );
25079
25806
  }
25080
25807
  if (note) log2(`add a note naming the map tools to ${instructions}`);
@@ -25161,10 +25888,10 @@ var log = (line) => process.stderr.write(`${line}
25161
25888
  async function checkedTests(project, tests) {
25162
25889
  const here = await realpath4(process.cwd());
25163
25890
  return tests.map((test) => {
25164
- const relative = path15.relative(project, path15.resolve(here, test));
25165
- if (!relative || relative === ".." || relative.startsWith(`..${path15.sep}`) || path15.isAbsolute(relative))
25891
+ const relative = path16.relative(project, path16.resolve(here, test));
25892
+ if (!relative || relative === ".." || relative.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative))
25166
25893
  throw new Error(`${test} is not in ${project}.`);
25167
- return relative.split(path15.sep).join("/");
25894
+ return relative.split(path16.sep).join("/");
25168
25895
  });
25169
25896
  }
25170
25897
  var usage = (code) => {