layermap 0.1.33 → 0.1.34

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,13 @@ 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}/`);
16665
16775
  var mapQueryPathSql = (column) => `(? = '.' OR ${column} = ? OR substr(${column}, 1, length(?) + 1) = ? || '/')`;
16666
16776
 
16667
16777
  // src/project-map-search-focus.ts
@@ -16759,7 +16869,7 @@ var declarationKinds = /* @__PURE__ */ new Set([
16759
16869
  "METHOD",
16760
16870
  "TYPE"
16761
16871
  ]);
16762
- var fileStem = (path16) => path16.slice(path16.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16872
+ var fileStem = (path17) => path17.slice(path17.lastIndexOf("/") + 1).replace(/\.(?:[cm]?[jt]sx?|vue|svelte|go|pyi?)$/iu, "");
16763
16873
  var compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
16764
16874
  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
16875
  function mapSearchQuery(input) {
@@ -16786,10 +16896,10 @@ function mapSearchQuery(input) {
16786
16896
  }
16787
16897
  function rank(object2, documentation, relationCount, query, focus) {
16788
16898
  const name = object2.name.toLowerCase();
16789
- const path16 = object2.anchor.path.toLowerCase();
16899
+ const path17 = object2.anchor.path.toLowerCase();
16790
16900
  const values = {
16791
16901
  NAME: [name],
16792
- PATH: [path16],
16902
+ PATH: [path17],
16793
16903
  DOCUMENTATION: documentation.map((text) => text.toLowerCase())
16794
16904
  };
16795
16905
  const matched = query.terms.map((term) => ({
@@ -16814,12 +16924,12 @@ function rank(object2, documentation, relationCount, query, focus) {
16814
16924
  score += 7e3;
16815
16925
  signals.push("SYMBOL_CONTAINS");
16816
16926
  } else if (matchedFields.includes("NAME")) signals.push("SYMBOL_CONTAINS");
16817
- if (object2.kind === "FILE" && fileStem(path16) === normalizedQuery) {
16927
+ if (object2.kind === "FILE" && fileStem(path17) === normalizedQuery) {
16818
16928
  score += 11e3;
16819
16929
  signals.push("EXACT_FILE_STEM");
16820
16930
  }
16821
16931
  if (matchedFields.includes("PATH")) {
16822
- score += path16.includes(normalizedQuery) ? 2500 : 0;
16932
+ score += path17.includes(normalizedQuery) ? 2500 : 0;
16823
16933
  signals.push("PATH_CONTAINS");
16824
16934
  }
16825
16935
  if (matchedFields.includes("DOCUMENTATION")) {
@@ -16834,8 +16944,8 @@ function rank(object2, documentation, relationCount, query, focus) {
16834
16944
  score += kindWeight[object2.kind] + Math.min(1200, relationCount * 20) + (focus?.score ?? 0);
16835
16945
  if (declarationKinds.has(object2.kind)) signals.push("DECLARATION");
16836
16946
  if (relationCount > 0) signals.push("GRAPH_CONNECTED");
16837
- const isTest = mapTestPath(path16);
16838
- const isGenerated = generatedPath.test(path16);
16947
+ const isTest = mapTestPath(path17);
16948
+ const isGenerated = generatedPath.test(path17);
16839
16949
  const hasTestIntent = query.terms.some((term) => testQuery.test(term));
16840
16950
  score += isTest ? hasTestIntent ? 1e3 : -5e3 : 300;
16841
16951
  score += isGenerated ? -3e3 : 300;
@@ -17134,7 +17244,7 @@ function mapPageFrontier(frontier, rows2) {
17134
17244
  }
17135
17245
 
17136
17246
  // src/project-map-language-go.ts
17137
- import { existsSync as existsSync3 } from "node:fs";
17247
+ import { existsSync as existsSync4 } from "node:fs";
17138
17248
 
17139
17249
  // src/project-map-analysis-validation.ts
17140
17250
  function validateMapAnalysis(analysis, input) {
@@ -17297,7 +17407,11 @@ var MapFactsSchema = external_exports.object({
17297
17407
  state: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
17298
17408
  }).strict();
17299
17409
  var MapReferenceFactsSchema = external_exports.object({
17300
- references: external_exports.array(external_exports.object({ ...span, kind: MapReferenceKindSchema }).strict())
17410
+ pages: external_exports.array(
17411
+ external_exports.object({
17412
+ references: external_exports.array(external_exports.object({ ...span, kind: MapReferenceKindSchema }).strict())
17413
+ }).strict().nullable()
17414
+ )
17301
17415
  }).strict();
17302
17416
  var invalid = () => {
17303
17417
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
@@ -17319,13 +17433,13 @@ function utf16Offsets(text) {
17319
17433
  }
17320
17434
  function offsetConverter(files, offsets) {
17321
17435
  const converters = /* @__PURE__ */ new Map();
17322
- return (path16, offset) => {
17323
- let convert = converters.get(path16);
17436
+ return (path17, offset) => {
17437
+ let convert = converters.get(path17);
17324
17438
  if (!convert) {
17325
- const text = files[path16];
17439
+ const text = files[path17];
17326
17440
  if (text === void 0) return invalid();
17327
17441
  convert = offsets === "UTF16" ? (value) => value <= text.length ? value : invalid() : utf16Offsets(text);
17328
- converters.set(path16, convert);
17442
+ converters.set(path17, convert);
17329
17443
  }
17330
17444
  return convert(offset);
17331
17445
  };
@@ -17356,7 +17470,7 @@ function mapFactsAnalysis(facts, input, context) {
17356
17470
  const collect = new MapOutputCollector(output);
17357
17471
  const positions = new MapSourcePositions(input.files);
17358
17472
  const offset = offsetConverter(input.files, context.offsets);
17359
- const anchor = (path16, start, end) => positions.span(path16, offset(path16, start), offset(path16, end));
17473
+ const anchor = (path17, start, end) => positions.span(path17, offset(path17, start), offset(path17, end));
17360
17474
  const located = /* @__PURE__ */ new Map();
17361
17475
  const canonical = /* @__PURE__ */ new Map();
17362
17476
  const bySpan = /* @__PURE__ */ new Map();
@@ -17491,11 +17605,21 @@ function mapFactsAnalysis(facts, input, context) {
17491
17605
  }
17492
17606
  return output;
17493
17607
  }
17494
- function mapReferencesPage(facts, files, reference, offsets) {
17608
+ function mapReferencePages(facts, files, requests, offsets) {
17609
+ if (facts.pages.length !== requests.length) invalid();
17495
17610
  const positions = new MapSourcePositions(files);
17496
17611
  const offset = offsetConverter(files, offsets);
17612
+ return {
17613
+ pages: facts.pages.map((found, at) => {
17614
+ const request = requests[at];
17615
+ return found && referencePage(found, positions, offset, request);
17616
+ }),
17617
+ requiredFiles: []
17618
+ };
17619
+ }
17620
+ function referencePage(found, positions, offset, reference) {
17497
17621
  const references = /* @__PURE__ */ new Map();
17498
- for (const fact of facts.references) {
17622
+ for (const fact of found.references) {
17499
17623
  if (!mapQueryPathMatches(fact.path, reference.path ?? ".")) continue;
17500
17624
  if (reference.kinds && !reference.kinds.includes(fact.kind)) continue;
17501
17625
  const anchor = positions.span(
@@ -17514,15 +17638,14 @@ function mapReferencesPage(facts, files, reference, offsets) {
17514
17638
  const next = reference.offset + selected.length;
17515
17639
  return {
17516
17640
  references: selected,
17517
- ...next < ordered.length ? { nextOffset: next } : {},
17518
- requiredFiles: []
17641
+ ...next < ordered.length ? { nextOffset: next } : {}
17519
17642
  };
17520
17643
  }
17521
17644
 
17522
17645
  // src/project-map-process.ts
17523
17646
  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";
17647
+ import { existsSync as existsSync3, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
17648
+ import path8 from "node:path";
17526
17649
 
17527
17650
  // src/project-map-failure.ts
17528
17651
  var PhaseSchema = external_exports.enum([
@@ -17648,24 +17771,24 @@ var ProjectMapStopUnconfirmedError = class extends ProjectEvidenceError {
17648
17771
  }
17649
17772
  };
17650
17773
  var installedMapParserResources = () => {
17651
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17774
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17652
17775
  return {
17653
- workerPath: path7.join(directory, "project-map-worker.mjs"),
17654
- compilerPath: path7.join(directory, "project-map-native/tsc")
17776
+ workerPath: path8.join(directory, "project-map-worker.mjs"),
17777
+ compilerPath: path8.join(directory, "project-map-native/tsc")
17655
17778
  };
17656
17779
  };
17657
17780
  var installedPythonMapResources = () => {
17658
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17781
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17659
17782
  return {
17660
- workerPath: path7.join(directory, "project-map-python-worker.mjs"),
17661
- compilerPath: path7.join(directory, "project-map-python/typeshed")
17783
+ workerPath: path8.join(directory, "project-map-python-worker.mjs"),
17784
+ compilerPath: path8.join(directory, "project-map-python/typeshed")
17662
17785
  };
17663
17786
  };
17664
17787
  function discoverJavaRuntime(env = process.env) {
17665
17788
  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))));
17789
+ for (const directory of (env.PATH ?? env.Path ?? "").split(path8.delimiter)) {
17790
+ const java = path8.join(directory, executableName("java"));
17791
+ if (directory && existsSync3(java)) homes.push(path8.dirname(path8.dirname(realpathSync2(java))));
17669
17792
  }
17670
17793
  homes.push(
17671
17794
  ...["/opt/homebrew/opt", "/usr/local/opt"].flatMap(
@@ -17673,7 +17796,7 @@ function discoverJavaRuntime(env = process.env) {
17673
17796
  (formula) => `${prefix}/${formula}/libexec/openjdk.jdk/Contents/Home`
17674
17797
  )
17675
17798
  ),
17676
- ...env.HOME ? [path7.join(env.HOME, ".sdkman/candidates/java/current")] : []
17799
+ ...env.HOME ? [path8.join(env.HOME, ".sdkman/candidates/java/current")] : []
17677
17800
  );
17678
17801
  if (process.platform === "darwin")
17679
17802
  try {
@@ -17688,12 +17811,12 @@ function discoverJavaRuntime(env = process.env) {
17688
17811
  }
17689
17812
  for (const home of homes) {
17690
17813
  if (!home) continue;
17691
- const runtimePath = path7.join(home, "bin", executableName("java"));
17692
- if (!existsSync2(runtimePath) || !existsSync2(path7.join(home, "bin", executableName("javac"))))
17814
+ const runtimePath = path8.join(home, "bin", executableName("java"));
17815
+ if (!existsSync3(runtimePath) || !existsSync3(path8.join(home, "bin", executableName("javac"))))
17693
17816
  continue;
17694
17817
  let release = "";
17695
17818
  try {
17696
- release = readFileSync(path7.join(home, "release"), "utf8");
17819
+ release = readFileSync2(path8.join(home, "release"), "utf8");
17697
17820
  } catch {
17698
17821
  continue;
17699
17822
  }
@@ -17704,26 +17827,26 @@ function discoverJavaRuntime(env = process.env) {
17704
17827
  return void 0;
17705
17828
  }
17706
17829
  var installedJavaMapResources = () => {
17707
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17708
- const compilerPath = path7.join(directory, "project-map-java/java-map.jar");
17830
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17831
+ const compilerPath = path8.join(directory, "project-map-java/java-map.jar");
17709
17832
  return {
17710
- workerPath: path7.join(directory, "project-map-java-worker.mjs"),
17833
+ workerPath: path8.join(directory, "project-map-java-worker.mjs"),
17711
17834
  compilerPath,
17712
17835
  // A build without a JDK leaves no analyzer to run, whatever runtime this machine has.
17713
- ...existsSync2(compilerPath) ? discoverJavaRuntime() : {}
17836
+ ...existsSync3(compilerPath) ? discoverJavaRuntime() : {}
17714
17837
  };
17715
17838
  };
17716
17839
  var installedGoMapResources = () => {
17717
- const directory = path7.dirname(path7.resolve(process.argv[1] ?? "."));
17840
+ const directory = path8.dirname(path8.resolve(process.argv[1] ?? "."));
17718
17841
  return {
17719
- workerPath: path7.join(directory, "project-map-go-worker.mjs"),
17720
- compilerPath: path7.join(directory, "project-map-go/go-map")
17842
+ workerPath: path8.join(directory, "project-map-go-worker.mjs"),
17843
+ compilerPath: path8.join(directory, "project-map-go/go-map")
17721
17844
  };
17722
17845
  };
17723
17846
  function runMapOperation(resources, input, schema, signal, observeTiming) {
17724
17847
  if (signal.aborted)
17725
17848
  return Promise.reject(new ProjectEvidenceError("PROJECT_READ_CANCELLED", true));
17726
- if (!path7.isAbsolute(resources.workerPath) || !path7.isAbsolute(resources.compilerPath)) {
17849
+ if (!path8.isAbsolute(resources.workerPath) || !path8.isAbsolute(resources.compilerPath)) {
17727
17850
  return Promise.reject(
17728
17851
  new ProjectEvidenceError("PROJECT_MAP_PARSER_CONFIGURATION_INVALID", false)
17729
17852
  );
@@ -17923,8 +18046,8 @@ var goModule = /(?:^|\/)go\.mod$/u;
17923
18046
  var codeHosts = /* @__PURE__ */ new Set(["github.com", "gitlab.com", "bitbucket.org"]);
17924
18047
  var GO_MAP_LANGUAGE = Object.freeze({
17925
18048
  id: "go-1.24-map-v9",
17926
- claims: (path16) => path16.endsWith(".go"),
17927
- reads: (path16) => goModule.test(path16),
18049
+ claims: (path17) => path17.endsWith(".go"),
18050
+ reads: (path17) => goModule.test(path17),
17928
18051
  // A module path, or the standard library, whose first path element has no dot.
17929
18052
  importName: (specifier) => {
17930
18053
  const parts = specifier.split("/");
@@ -17933,7 +18056,7 @@ var GO_MAP_LANGUAGE = Object.freeze({
17933
18056
  return parts.slice(0, size).join("/");
17934
18057
  },
17935
18058
  // Go imports a package: the directory of the file.
17936
- importTarget: (path16) => `${path16.slice(0, path16.lastIndexOf("/") + 1) || "./"}`,
18059
+ importTarget: (path17) => `${path17.slice(0, path17.lastIndexOf("/") + 1) || "./"}`,
17937
18060
  create: () => new GoMapAnalyzer()
17938
18061
  });
17939
18062
  var GO_GAPS = [
@@ -17979,12 +18102,12 @@ var GoMapAnalyzer = class {
17979
18102
  }
17980
18103
  }
17981
18104
  async analyze(session, signal) {
17982
- const modules = session.readable.map((entry) => entry.path).filter((path16) => goModule.test(path16)).sort();
17983
- const moduleOf = (path16) => {
18105
+ const modules = session.readable.map((entry) => entry.path).filter((path17) => goModule.test(path17)).sort();
18106
+ const moduleOf = (path17) => {
17984
18107
  let best;
17985
18108
  for (const modFile of modules) {
17986
18109
  const directory = modFile.slice(0, modFile.lastIndexOf("/") + 1);
17987
- if (path16.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
18110
+ if (path17.startsWith(directory) && (!best || directory.length > best.lastIndexOf("/") + 1))
17988
18111
  best = modFile;
17989
18112
  }
17990
18113
  return best;
@@ -18000,11 +18123,11 @@ var GoMapAnalyzer = class {
18000
18123
  for (const modFile of [...groups.keys()].sort()) {
18001
18124
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18002
18125
  const files = /* @__PURE__ */ Object.create(null);
18003
- for (const path16 of [...groups.get(modFile) ?? [], ...modFile ? [modFile] : []]) {
18004
- const text = session.texts[path16];
18126
+ for (const path17 of [...groups.get(modFile) ?? [], ...modFile ? [modFile] : []]) {
18127
+ const text = session.texts[path17];
18005
18128
  if (text === void 0)
18006
18129
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18007
- files[path16] = text;
18130
+ files[path17] = text;
18008
18131
  }
18009
18132
  const input = {
18010
18133
  contextRef: digestValue({
@@ -18016,7 +18139,7 @@ var GoMapAnalyzer = class {
18016
18139
  inventory: Object.keys(files).sort(),
18017
18140
  syntaxOnly: false
18018
18141
  };
18019
- const built = existsSync3(this.resources.compilerPath);
18142
+ const built = existsSync4(this.resources.compilerPath);
18020
18143
  const reused = session.reuse(input.contextRef, { modFile, built }, Object.keys(files));
18021
18144
  if (reused) {
18022
18145
  session.accept(reused);
@@ -18034,34 +18157,33 @@ var GoMapAnalyzer = class {
18034
18157
  session.accept(analysis);
18035
18158
  }
18036
18159
  }
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);
18160
+ async references(input, references, signal, observe) {
18161
+ if (!existsSync4(this.resources.compilerPath))
18162
+ return { pages: references.map(() => null), requiredFiles: [] };
18041
18163
  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;
18164
+ for (const [path17, value] of Object.entries(input.files))
18165
+ if (this.claims(path17) || goModule.test(path17)) files[path17] = value;
18044
18166
  const facts = await this.operation(
18045
18167
  {
18046
18168
  ...input,
18047
18169
  files,
18048
18170
  operation: "REFERENCES",
18049
18171
  modFile: input.configPath ?? "",
18050
- target: {
18051
- path: reference.targetPath,
18052
- offset: mapFactsOffset(text, reference.symbolStart, "UTF8_BYTES")
18053
- }
18172
+ targets: references.map(({ targetPath, symbolStart }) => ({
18173
+ path: targetPath,
18174
+ offset: mapFactsOffset(input.files[targetPath] ?? "", symbolStart, "UTF8_BYTES")
18175
+ }))
18054
18176
  },
18055
18177
  MapReferenceFactsSchema,
18056
18178
  signal,
18057
18179
  observe
18058
18180
  );
18059
- return mapReferencesPage(facts, files, reference, "UTF8_BYTES");
18181
+ return mapReferencePages(facts, files, references, "UTF8_BYTES");
18060
18182
  }
18061
18183
  };
18062
18184
 
18063
18185
  // src/project-map-language-java.ts
18064
- import { existsSync as existsSync4 } from "node:fs";
18186
+ import { existsSync as existsSync5 } from "node:fs";
18065
18187
  var BUILD_FILES = [
18066
18188
  "settings.gradle.kts",
18067
18189
  "settings.gradle",
@@ -18070,14 +18192,14 @@ var BUILD_FILES = [
18070
18192
  "pom.xml"
18071
18193
  ];
18072
18194
  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);
18195
+ var directoryOf = (path17) => path17.slice(0, path17.lastIndexOf("/") + 1);
18196
+ var nameOf = (path17) => path17.slice(path17.lastIndexOf("/") + 1);
18075
18197
  var DEFAULT_RELEASE = 21;
18076
18198
  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
18199
  var JAVA_MAP_LANGUAGE = Object.freeze({
18078
18200
  id: "javac-lombok-1.18.48-map-v8",
18079
- claims: (path16) => path16.endsWith(".java"),
18080
- reads: (path16) => buildFile.test(path16),
18201
+ claims: (path17) => path17.endsWith(".java"),
18202
+ reads: (path17) => buildFile.test(path17),
18081
18203
  // A package of the Java platform, or a library named by its first two package segments.
18082
18204
  importName: (specifier) => platformPackage.test(specifier) ? "Java standard library" : specifier.split(".").slice(0, 2).join("."),
18083
18205
  create: () => new JavaMapAnalyzer()
@@ -18140,7 +18262,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18140
18262
  // The runtime found at startup may be gone since (an upgraded JDK replaces its directory).
18141
18263
  refreshRuntime() {
18142
18264
  const { runtimePath } = this.resources;
18143
- if (runtimePath && !existsSync4(runtimePath)) {
18265
+ if (runtimePath && !existsSync5(runtimePath)) {
18144
18266
  const { runtimePath: _gone, runtimeVersion: _version, ...rest } = this.resources;
18145
18267
  this.resources = { ...rest, ...discoverJavaRuntime() };
18146
18268
  }
@@ -18167,12 +18289,12 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18167
18289
  // The worker's request for a context: the Java sources, the release and which are tests.
18168
18290
  request(input, buildTexts) {
18169
18291
  const files = /* @__PURE__ */ Object.create(null);
18170
- for (const [path16, text] of Object.entries(input.files))
18171
- if (this.claims(path16)) files[path16] = text;
18292
+ for (const [path17, text] of Object.entries(input.files))
18293
+ if (this.claims(path17)) files[path17] = text;
18172
18294
  return {
18173
18295
  files,
18174
18296
  release: javaRelease(buildTexts, this.resources.runtimeVersion),
18175
- tests: Object.keys(files).filter((path16) => mapTestPath(path16))
18297
+ tests: Object.keys(files).filter((path17) => mapTestPath(path17))
18176
18298
  };
18177
18299
  }
18178
18300
  // The build files of a context's root directory, which declare its Java version.
@@ -18184,35 +18306,35 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18184
18306
  }
18185
18307
  async analyze(session, signal) {
18186
18308
  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));
18309
+ const builds = session.readable.map((entry) => entry.path).filter((path17) => buildFile.test(path17));
18310
+ for (const path17 of builds) session.configuration(path17);
18311
+ const rank2 = (path17) => BUILD_FILES.indexOf(nameOf(path17));
18190
18312
  const roots = /* @__PURE__ */ new Map();
18191
18313
  const modules = /* @__PURE__ */ new Map();
18192
- for (const path16 of builds) {
18193
- const directory = directoryOf(path16);
18314
+ for (const path17 of builds) {
18315
+ const directory = directoryOf(path17);
18194
18316
  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)) {
18317
+ if (current === void 0 || rank2(path17) < rank2(current)) modules.set(directory, path17);
18318
+ const text = session.texts[path17] ?? "";
18319
+ if (/settings\.gradle(?:\.kts)?$/u.test(path17) || path17.endsWith("pom.xml") && /<modules>/u.test(text)) {
18198
18320
  const root = roots.get(directory);
18199
- if (root === void 0 || rank2(path16) < rank2(root)) roots.set(directory, path16);
18321
+ if (root === void 0 || rank2(path17) < rank2(root)) roots.set(directory, path17);
18200
18322
  }
18201
18323
  }
18202
- const configOf = (path16) => {
18324
+ const configOf = (path17) => {
18203
18325
  let outer;
18204
18326
  for (const directory of roots.keys())
18205
- if (path16.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18327
+ if (path17.startsWith(directory) && (outer === void 0 || directory.length < outer.length))
18206
18328
  outer = directory;
18207
18329
  if (outer !== void 0) return roots.get(outer);
18208
18330
  let nearest;
18209
18331
  for (const directory of modules.keys())
18210
- if (path16.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18332
+ if (path17.startsWith(directory) && (nearest === void 0 || directory.length > nearest.length))
18211
18333
  nearest = directory;
18212
18334
  return nearest === void 0 ? "" : modules.get(nearest);
18213
18335
  };
18214
- const output = (path16) => [...modules.keys()].some(
18215
- (directory) => path16.startsWith(`${directory}build/`) || path16.startsWith(`${directory}target/`)
18336
+ const output = (path17) => [...modules.keys()].some(
18337
+ (directory) => path17.startsWith(`${directory}build/`) || path17.startsWith(`${directory}target/`)
18216
18338
  );
18217
18339
  const groups = /* @__PURE__ */ new Map();
18218
18340
  for (const entry of session.readable) {
@@ -18227,13 +18349,13 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18227
18349
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18228
18350
  const files = /* @__PURE__ */ Object.create(null);
18229
18351
  const rootBuilds = configPath ? BUILD_FILES.map((name) => `${directoryOf(configPath)}${name}`).filter(
18230
- (path16) => builds.includes(path16)
18352
+ (path17) => builds.includes(path17)
18231
18353
  ) : [];
18232
- for (const path16 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18233
- const text = session.texts[path16];
18354
+ for (const path17 of [...groups.get(configPath) ?? [], ...rootBuilds]) {
18355
+ const text = session.texts[path17];
18234
18356
  if (text === void 0)
18235
18357
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18236
- files[path16] = text;
18358
+ files[path17] = text;
18237
18359
  }
18238
18360
  const input = {
18239
18361
  contextRef: digestValue({
@@ -18258,7 +18380,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18258
18380
  release: request.release,
18259
18381
  tests: request.tests,
18260
18382
  runtime,
18261
- built: existsSync4(this.resources.compilerPath),
18383
+ built: existsSync5(this.resources.compilerPath),
18262
18384
  lombokConfig
18263
18385
  },
18264
18386
  Object.keys(files)
@@ -18276,7 +18398,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18276
18398
  const prior = JavaStateSchema.safeParse(previous?.state).data;
18277
18399
  const incremental = previous && prior?.basis === basis ? {
18278
18400
  changed: Object.keys(request.files).filter(
18279
- (path16) => digests.get(path16) !== previous.digests.get(path16)
18401
+ (path17) => digests.get(path17) !== previous.digests.get(path17)
18280
18402
  ),
18281
18403
  state: prior.java
18282
18404
  } : void 0;
@@ -18293,7 +18415,7 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18293
18415
  this.resources.runtimeVersion,
18294
18416
  [
18295
18417
  ...this.resources.runtimePath ? [] : [
18296
- existsSync4(this.resources.compilerPath) ? "JAVA_RUNTIME_UNAVAILABLE" : "JAVA_ANALYZER_NOT_BUILT"
18418
+ existsSync5(this.resources.compilerPath) ? "JAVA_RUNTIME_UNAVAILABLE" : "JAVA_ANALYZER_NOT_BUILT"
18297
18419
  ],
18298
18420
  ...lombokConfig ? ["LOMBOK_CONFIG_NOT_APPLIED"] : []
18299
18421
  ]
@@ -18305,34 +18427,37 @@ var JavaMapAnalyzer = class _JavaMapAnalyzer {
18305
18427
  continue;
18306
18428
  }
18307
18429
  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)))
18430
+ if (!incremental || facts.focus.some((path17) => !Object.hasOwn(request.files, path17)) || incremental.changed.some((path17) => !focus.has(path17)))
18309
18431
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18310
18432
  analysis.objects = analysis.objects.filter((object2) => focus.has(object2.anchor.path));
18311
18433
  analysis.relations = analysis.relations.filter((relation) => focus.has(relation.anchor.path));
18312
18434
  analysis.notes = analysis.notes.filter((note) => focus.has(note.anchor.path));
18313
18435
  session.accept(analysis, {
18314
18436
  state,
18315
- linked: analysis.parsedFiles.filter((path16) => !focus.has(path16))
18437
+ linked: analysis.parsedFiles.filter((path17) => !focus.has(path17))
18316
18438
  });
18317
18439
  }
18318
18440
  }
18319
- async references(input, reference, signal, observe) {
18441
+ async references(input, references, signal, observe) {
18320
18442
  this.refreshRuntime();
18321
- if (input.files[reference.targetPath] === void 0 || !this.resources.runtimePath)
18322
- throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
18443
+ if (!this.resources.runtimePath)
18444
+ return { pages: references.map(() => null), requiredFiles: [] };
18323
18445
  const request = this.request(input, _JavaMapAnalyzer.buildTexts(input.files, input.configPath));
18324
18446
  const facts = await this.operation(
18325
18447
  {
18326
18448
  ...input,
18327
18449
  ...request,
18328
18450
  operation: "REFERENCES",
18329
- target: { path: reference.targetPath, offset: reference.symbolStart }
18451
+ targets: references.map(({ targetPath, symbolStart }) => ({
18452
+ path: targetPath,
18453
+ offset: symbolStart
18454
+ }))
18330
18455
  },
18331
18456
  MapReferenceFactsSchema,
18332
18457
  signal,
18333
18458
  observe
18334
18459
  );
18335
- return mapReferencesPage(facts, request.files, reference, "UTF16");
18460
+ return mapReferencePages(facts, request.files, references, "UTF16");
18336
18461
  }
18337
18462
  };
18338
18463
 
@@ -18624,12 +18749,12 @@ var PYTHON_STANDARD_LIBRARY = /* @__PURE__ */ new Set([
18624
18749
  // src/project-map-language-python.ts
18625
18750
  var CONFIGURATION = ["pyrightconfig.json", "pyproject.toml", "setup.cfg"];
18626
18751
  var pythonConfig = /(?:^|\/)(?:pyrightconfig\.json|pyproject\.toml|setup\.cfg)$/u;
18627
- var directoryOf2 = (path16) => path16.slice(0, path16.lastIndexOf("/") + 1);
18752
+ var directoryOf2 = (path17) => path17.slice(0, path17.lastIndexOf("/") + 1);
18628
18753
  var DEFAULT_PYTHON = { major: 3, minor: 13 };
18629
18754
  var PYTHON_MAP_LANGUAGE = Object.freeze({
18630
18755
  id: "pyright-1.1.414-map-v13",
18631
- claims: (path16) => /\.pyi?$/u.test(path16),
18632
- reads: (path16) => pythonConfig.test(path16),
18756
+ claims: (path17) => /\.pyi?$/u.test(path17),
18757
+ reads: (path17) => pythonConfig.test(path17),
18633
18758
  // An absolute import names the standard library or a distribution's top-level package.
18634
18759
  importName: (specifier) => {
18635
18760
  const top = specifier.split(".", 1)[0] ?? specifier;
@@ -18681,21 +18806,21 @@ var PythonMapAnalyzer = class {
18681
18806
  return {
18682
18807
  root: input.configPath ? directoryOf2(input.configPath).replace(/\/$/u, "") : "",
18683
18808
  pythonVersion: pythonVersion(input.files, input.configPath),
18684
- tests: Object.keys(input.files).filter((path16) => this.claims(path16) && mapTestPath(path16))
18809
+ tests: Object.keys(input.files).filter((path17) => this.claims(path17) && mapTestPath(path17))
18685
18810
  };
18686
18811
  }
18687
18812
  async analyze(session, signal) {
18688
18813
  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);
18814
+ for (const path17 of session.readable.map((entry) => entry.path).filter((path18) => pythonConfig.test(path18))) {
18815
+ const directory = directoryOf2(path17);
18691
18816
  const current = roots.get(directory);
18692
18817
  const rank2 = (file2) => CONFIGURATION.indexOf(file2.slice(directory.length));
18693
- if (current === void 0 || rank2(path16) < rank2(current)) roots.set(directory, path16);
18818
+ if (current === void 0 || rank2(path17) < rank2(current)) roots.set(directory, path17);
18694
18819
  }
18695
- const rootOf = (path16) => {
18820
+ const rootOf = (path17) => {
18696
18821
  let best;
18697
18822
  for (const directory of roots.keys())
18698
- if (path16.startsWith(directory) && (best === void 0 || directory.length > best.length))
18823
+ if (path17.startsWith(directory) && (best === void 0 || directory.length > best.length))
18699
18824
  best = directory;
18700
18825
  return best === void 0 ? "" : roots.get(best);
18701
18826
  };
@@ -18710,11 +18835,11 @@ var PythonMapAnalyzer = class {
18710
18835
  for (const configPath of [...groups.keys()].sort()) {
18711
18836
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
18712
18837
  const files = /* @__PURE__ */ Object.create(null);
18713
- for (const path16 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
18714
- const text = session.texts[path16];
18838
+ for (const path17 of [...groups.get(configPath) ?? [], ...configPath ? [configPath] : []]) {
18839
+ const text = session.texts[path17];
18715
18840
  if (text === void 0)
18716
18841
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18717
- files[path16] = text;
18842
+ files[path17] = text;
18718
18843
  }
18719
18844
  const input = {
18720
18845
  contextRef: digestValue({
@@ -18758,30 +18883,31 @@ var PythonMapAnalyzer = class {
18758
18883
  session.accept(analysis);
18759
18884
  }
18760
18885
  }
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);
18886
+ async references(input, references, signal, observe) {
18764
18887
  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;
18888
+ for (const [path17, value] of Object.entries(input.files))
18889
+ if (this.claims(path17) || pythonConfig.test(path17)) files[path17] = value;
18767
18890
  const facts = await this.operation(
18768
18891
  {
18769
18892
  ...input,
18770
18893
  files,
18771
18894
  ...this.request({ ...input, files }),
18772
18895
  operation: "REFERENCES",
18773
- target: { path: reference.targetPath, offset: reference.symbolStart }
18896
+ targets: references.map(({ targetPath, symbolStart }) => ({
18897
+ path: targetPath,
18898
+ offset: symbolStart
18899
+ }))
18774
18900
  },
18775
18901
  MapReferenceFactsSchema,
18776
18902
  signal,
18777
18903
  observe
18778
18904
  );
18779
- return mapReferencesPage(facts, files, reference, "UTF16");
18905
+ return mapReferencePages(facts, files, references, "UTF16");
18780
18906
  }
18781
18907
  };
18782
18908
 
18783
18909
  // src/project-map-miniprogram.ts
18784
- import path8 from "node:path";
18910
+ import path9 from "node:path";
18785
18911
  import {
18786
18912
  isCallExpression,
18787
18913
  isExpressionStatement,
@@ -18799,9 +18925,9 @@ var miniprogramTemplateOf = (script, inventory) => /\.[cm]?[jt]sx?$/u.test(scrip
18799
18925
  function miniprogramConfiguration(template, inventory) {
18800
18926
  const own = template.replace(/\.wxml$/u, ".json");
18801
18927
  const configuration = inventory.has(own) ? { own } : {};
18802
- for (let directory = path8.posix.dirname(template); ; directory = path8.posix.dirname(directory)) {
18928
+ for (let directory = path9.posix.dirname(template); ; directory = path9.posix.dirname(directory)) {
18803
18929
  const root = directory === "." ? "" : directory;
18804
- const app = path8.posix.join(root, "app.json");
18930
+ const app = path9.posix.join(root, "app.json");
18805
18931
  if (inventory.has(app)) return { ...configuration, app, root };
18806
18932
  if (!root) return configuration;
18807
18933
  }
@@ -18813,9 +18939,9 @@ var miniprogramEventOf = (target) => {
18813
18939
 
18814
18940
  // src/project-map-language-typescript.ts
18815
18941
  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",
18942
+ id: "typescript-7.0.2-map-v24",
18943
+ claims: (path17) => /\.[cm]?[jt]sx?$/u.test(path17),
18944
+ reads: (path17) => path17.endsWith(".json") || path17.endsWith(".wxml") || path17 === "pnpm-workspace.yaml",
18819
18945
  create: () => new TypeScriptMapAnalyzer()
18820
18946
  });
18821
18947
  var CONFIGURATIONS_KEPT = 4;
@@ -18827,8 +18953,8 @@ var TypeScriptMapAnalyzer = class {
18827
18953
  id = TYPESCRIPT_MAP_LANGUAGE.id;
18828
18954
  claims = TYPESCRIPT_MAP_LANGUAGE.claims;
18829
18955
  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.
18956
+ // Discovery reads the texts of the files the language reads and what is installed, nothing else,
18957
+ // so a result stands while they are the same, as they are when only other languages' files changed.
18832
18958
  configurations = /* @__PURE__ */ new Map();
18833
18959
  async operation(input, schema, signal, observe) {
18834
18960
  const start = performance.now();
@@ -18850,16 +18976,24 @@ var TypeScriptMapAnalyzer = class {
18850
18976
  observe?.({ ...event, phase: "FINISHED", elapsedMs: performance.now() - start });
18851
18977
  }
18852
18978
  }
18853
- references(input, reference, signal, observe) {
18979
+ references(input, references, signal, observe, until) {
18854
18980
  return this.operation(
18855
- { ...input, operation: "REFERENCES", reference },
18856
- MapReferencePageSchema,
18981
+ { ...input, operation: "REFERENCES", references, ...until === void 0 ? {} : { until } },
18982
+ MapReferenceBatchSchema,
18983
+ signal,
18984
+ observe
18985
+ );
18986
+ }
18987
+ diagnostics(input, signal, observe) {
18988
+ return this.operation(
18989
+ { ...input, operation: "DIAGNOSTICS" },
18990
+ MapDiagnosticsSchema,
18857
18991
  signal,
18858
18992
  observe
18859
18993
  );
18860
18994
  }
18861
18995
  async analyze(session, signal) {
18862
- const { entries, texts: unitTexts, observe } = session;
18996
+ const { entries, texts: unitTexts, observe, installed } = session;
18863
18997
  const byPath = new Map(session.readable.map((entry) => [entry.path, entry]));
18864
18998
  const inventory = [...byPath.keys()];
18865
18999
  const inventorySet = new Set(inventory);
@@ -18907,9 +19041,14 @@ var TypeScriptMapAnalyzer = class {
18907
19041
  configPath: configPath ?? null,
18908
19042
  rootFiles: rootFiles ?? null,
18909
19043
  inventory,
18910
- workspace: workspace ?? null
19044
+ workspace: workspace ?? null,
19045
+ installed: installed.digest
18911
19046
  },
18912
- Object.keys(texts)
19047
+ [
19048
+ ...workspace?.configurationFiles ?? [],
19049
+ ...configPath ? [configPath] : [],
19050
+ ...rootFiles ?? inventory
19051
+ ]
18913
19052
  );
18914
19053
  if (reused) {
18915
19054
  accept(reused);
@@ -18924,7 +19063,8 @@ var TypeScriptMapAnalyzer = class {
18924
19063
  files: texts,
18925
19064
  inventory,
18926
19065
  syntaxOnly: false,
18927
- ...workspace ? { workspace } : {}
19066
+ ...workspace ? { workspace } : {},
19067
+ dependencies: installed.directory
18928
19068
  };
18929
19069
  const analysis = await this.operation(
18930
19070
  { ...input, operation: "BUILD" },
@@ -18937,9 +19077,9 @@ var TypeScriptMapAnalyzer = class {
18937
19077
  accept(analysis);
18938
19078
  return;
18939
19079
  }
18940
- const required2 = analysis.requiredFiles.map((path16) => {
18941
- const entry = byPath.get(path16);
18942
- if (!entry || Object.hasOwn(texts, path16))
19080
+ const required2 = analysis.requiredFiles.map((path17) => {
19081
+ const entry = byPath.get(path17);
19082
+ if (!entry || Object.hasOwn(texts, path17))
18943
19083
  throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
18944
19084
  return entry;
18945
19085
  });
@@ -18948,7 +19088,8 @@ var TypeScriptMapAnalyzer = class {
18948
19088
  }
18949
19089
  };
18950
19090
  const configurationKey = digestValue({
18951
- files: session.readable.map((entry) => [entry.path, entry.contentDigest ?? null])
19091
+ files: session.readable.map((entry) => [entry.path, entry.contentDigest ?? null]),
19092
+ installed: installed.digest
18952
19093
  });
18953
19094
  const discovered = this.configurations.get(configurationKey) ?? await this.operation(
18954
19095
  {
@@ -18956,7 +19097,8 @@ var TypeScriptMapAnalyzer = class {
18956
19097
  contextRef: digestValue({ entries, purpose: "CONFIGURE" }),
18957
19098
  files: unitTexts,
18958
19099
  inventory,
18959
- syntaxOnly: false
19100
+ syntaxOnly: false,
19101
+ dependencies: installed.directory
18960
19102
  },
18961
19103
  MapConfigurationResultSchema,
18962
19104
  signal,
@@ -18997,16 +19139,16 @@ var MAP_LANGUAGES = Object.freeze([
18997
19139
  ]);
18998
19140
  var mapAnalyzerSuite = (languages) => languages.map((language) => language.id).sort().join("+");
18999
19141
  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;
19142
+ var mapCodePath = (path17) => MAP_LANGUAGES.some((language) => language.claims(path17));
19143
+ var languageOf = (path17) => MAP_LANGUAGES.find((language) => language.claims(path17));
19144
+ var mapLanguageOf = (path17) => languageOf(path17)?.id;
19003
19145
  var npmPackage = (specifier) => {
19004
19146
  if (specifier.startsWith("node:")) return "node:*";
19005
19147
  const parts = specifier.split("/");
19006
19148
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0] ?? specifier;
19007
19149
  };
19008
19150
  var mapExternalImport = (sourcePath, specifier) => languageOf(sourcePath)?.importName?.(specifier) ?? npmPackage(specifier);
19009
- var mapImportTarget = (path16) => languageOf(path16)?.importTarget?.(path16) ?? path16;
19151
+ var mapImportTarget = (path17) => languageOf(path17)?.importTarget?.(path17) ?? path17;
19010
19152
 
19011
19153
  // src/project-map-view.ts
19012
19154
  var MAP_VIEW_FORMAT = "PROJECT_MAP_VIEW_V1";
@@ -19019,6 +19161,7 @@ var MAP_VIEW_LIMITS = Object.freeze({
19019
19161
  members: 40,
19020
19162
  externalPackages: 20,
19021
19163
  unresolvedTargets: 12,
19164
+ notInstalled: 8,
19022
19165
  // Call targets are written text; a long call chain keeps its receiver and its last members.
19023
19166
  targetText: 120,
19024
19167
  // Calls naming a method on an unknown receiver are listed up to this many, else counted.
@@ -19045,10 +19188,10 @@ var notFound = () => {
19045
19188
  };
19046
19189
  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
19190
  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);
19191
+ var within = (path17, directory) => directory === "." || path17.startsWith(`${directory}/`);
19192
+ var parentDirectory = (path17) => {
19193
+ const slash = path17.lastIndexOf("/");
19194
+ return slash < 0 ? "." : path17.slice(0, slash);
19052
19195
  };
19053
19196
  var compareText2 = (left, right) => left < right ? -1 : left > right ? 1 : 0;
19054
19197
  var byCount = ([leftName, left], [rightName, right]) => right - left || compareText2(leftName, rightName);
@@ -19122,7 +19265,7 @@ function pageBlocks(view, head, whole, offset, budget) {
19122
19265
  if (offset === blocks.length) return materialize(0);
19123
19266
  return mapQueryPage(blocks.length - offset, materialize, (page) => page, budget);
19124
19267
  }
19125
- var inModule = (path16, module) => module.direct ? parentDirectory(path16) === module.directory : within(path16, module.directory);
19268
+ var inModule = (path17, module) => module.direct ? parentDirectory(path17) === module.directory : within(path17, module.directory);
19126
19269
  var moduleLabel = (module) => module.direct ? `${module.directory === "." ? "" : `${module.directory}/`}* (files directly here)` : `${module.directory}/`;
19127
19270
  function childModules(module, files) {
19128
19271
  if (module.direct) return [];
@@ -19177,9 +19320,9 @@ function mapProjectModules(entries) {
19177
19320
  (entry) => entry.state === "TEXT" && mapCodePath(entry.path) && !mapTestPath(entry.path)
19178
19321
  ).map((entry) => entry.path)
19179
19322
  );
19180
- return (path16) => {
19181
- if (mapTestPath(path16)) return void 0;
19182
- const module = modules.find((candidate) => inModule(path16, candidate));
19323
+ return (path17) => {
19324
+ if (mapTestPath(path17)) return void 0;
19325
+ const module = modules.find((candidate) => inModule(path17, candidate));
19183
19326
  return module && moduleLabel(module);
19184
19327
  };
19185
19328
  }
@@ -19291,12 +19434,12 @@ function loadMemberCalls(store, version2) {
19291
19434
  FROM project_map_relations
19292
19435
  WHERE version_ref = ? AND to_ref IS NULL AND json_extract(relation_json, '$.kind') = 'CALLS'
19293
19436
  AND json_extract(relation_json, '$.unresolvedReason') IN ('SYMBOL_NOT_RESOLVED', 'SYNTAX_ONLY')`).all(version2)) {
19294
- const path16 = String(row.path);
19437
+ const path17 = String(row.path);
19295
19438
  const target = String(row.target);
19296
19439
  const name = MEMBER_NAME.exec(target)?.[1];
19297
- const language = mapLanguageOf(path16);
19440
+ const language = mapLanguageOf(path17);
19298
19441
  if (!name || !language) continue;
19299
- const call = { from: String(row.from_ref), path: path16, line: Number(row.line), target };
19442
+ const call = { from: String(row.from_ref), path: path17, line: Number(row.line), target };
19300
19443
  const key = memberKey(language, name);
19301
19444
  const known = calls.get(key);
19302
19445
  if (known) known.push(call);
@@ -19332,6 +19475,7 @@ var MAP_LIMITS = {
19332
19475
  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
19476
  LOMBOK_CONFIG_NOT_APPLIED: "lombok.config settings are not applied, so names Lombok generates may differ from the build's",
19334
19477
  NO_JAVA_BUILD: "Java files outside a Gradle or Maven build are analyzed together as one program",
19478
+ 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
19479
  NO_ADMITTED_TSCONFIG: "TypeScript and JavaScript files outside a tsconfig use inferred settings",
19336
19480
  NO_PYTHON_CONFIGURATION: "Python files outside a project configuration use inferred settings"
19337
19481
  };
@@ -19340,7 +19484,12 @@ function loadCoverageNotes(store, version2) {
19340
19484
  const gaps = row ? JSON.parse(String(row.coverage_json)).gaps : [];
19341
19485
  const files = /* @__PURE__ */ new Map();
19342
19486
  const limits = /* @__PURE__ */ new Set();
19487
+ const notInstalled = /* @__PURE__ */ new Set();
19343
19488
  for (const gap of gaps) {
19489
+ if (gap.code === MAP_DEPENDENCY_NOT_INSTALLED && gap.package) {
19490
+ notInstalled.add(gap.package);
19491
+ continue;
19492
+ }
19344
19493
  if (gap.path === void 0) {
19345
19494
  const limit = MAP_LIMITS[gap.code];
19346
19495
  if (limit) limits.add(limit);
@@ -19351,13 +19500,18 @@ function loadCoverageNotes(store, version2) {
19351
19500
  if (!codes.includes(gap.code)) codes.push(gap.code);
19352
19501
  files.set(gap.path, codes);
19353
19502
  }
19354
- for (const [path16, codes] of files)
19503
+ for (const [path17, codes] of files)
19355
19504
  if (codes.length > 1 && codes.includes("NOT_IN_PARSED_CONTEXT"))
19356
19505
  files.set(
19357
- path16,
19506
+ path17,
19358
19507
  codes.filter((code) => code !== "NOT_IN_PARSED_CONTEXT")
19359
19508
  );
19360
- return { files, limits: [...limits] };
19509
+ const missing = [...notInstalled].sort();
19510
+ if (missing.length)
19511
+ limits.add(
19512
+ `${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`
19513
+ );
19514
+ return { files, limits: [...limits], notInstalled: missing };
19361
19515
  }
19362
19516
  var MapViewCache = class {
19363
19517
  facts = new VersionCache(loadDirectoryFacts);
@@ -19394,9 +19548,9 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19394
19548
  const visiblePaths = new Set(visible.map((entry) => entry.path));
19395
19549
  const code = visible.filter((entry) => entry.state === "TEXT" && mapCodePath(entry.path)).map((entry) => entry.path);
19396
19550
  const modules = mapModules(directory, code);
19397
- const moduleOf = (path16) => modules.find((module) => inModule(path16, module));
19398
- const outside = (path16) => {
19399
- const parts = path16.split("/");
19551
+ const moduleOf = (path17) => modules.find((module) => inModule(path17, module));
19552
+ const outside = (path17) => {
19553
+ const parts = path17.split("/");
19400
19554
  return `${parts.slice(0, Math.min(2, parts.length - 1)).join("/") || "."}/ (outside)`;
19401
19555
  };
19402
19556
  const moduleImports = /* @__PURE__ */ new Map();
@@ -19421,8 +19575,8 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19421
19575
  const blocks = [];
19422
19576
  if (modules.length > 1) {
19423
19577
  const sizes = /* @__PURE__ */ new Map();
19424
- for (const path16 of code) {
19425
- const module = moduleOf(path16);
19578
+ for (const path17 of code) {
19579
+ const module = moduleOf(path17);
19426
19580
  if (module) increment(sizes, moduleLabel(module));
19427
19581
  }
19428
19582
  blocks.push(
@@ -19451,18 +19605,18 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19451
19605
  )}${packages.length > shown.length ? `, +${packages.length - shown.length} more` : ""}`
19452
19606
  );
19453
19607
  }
19454
- const lineCount = (path16) => {
19455
- const file2 = facts.files.get(path16);
19456
- const gaps = coverage.files.get(path16) ?? [];
19608
+ const lineCount = (path17) => {
19609
+ const file2 = facts.files.get(path17);
19610
+ const gaps = coverage.files.get(path17) ?? [];
19457
19611
  if (file2?.parsed === false) return `[not parsed${gaps.length ? `: ${gaps.join("; ")}` : ""}]`;
19458
19612
  return `${file2 ? `${file2.lines}L` : "?L"}${gaps.length ? ` [${gaps.join("; ")}]` : ""}`;
19459
19613
  };
19460
19614
  const codeDirectories = /* @__PURE__ */ new Set();
19461
- for (const path16 of code)
19462
- for (let parent = parentDirectory(path16); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19615
+ for (const path17 of code)
19616
+ for (let parent = parentDirectory(path17); parent !== "." && !codeDirectories.has(parent); parent = parentDirectory(parent))
19463
19617
  codeDirectories.add(parent);
19464
- const groupOf = (path16) => {
19465
- let group = parentDirectory(path16);
19618
+ const groupOf = (path17) => {
19619
+ let group = parentDirectory(path17);
19466
19620
  for (let parent = group; parent !== "." && parent !== directory && !codeDirectories.has(parent); parent = parentDirectory(parent))
19467
19621
  group = parent;
19468
19622
  return group;
@@ -19494,11 +19648,11 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19494
19648
  ]);
19495
19649
  }
19496
19650
  const detailed = [
19497
- ...code.map((path16) => {
19498
- const declarations2 = (facts.exported.get(path16) ?? []).map(({ text: text2 }) => text2);
19651
+ ...code.map((path17) => {
19652
+ const declarations2 = (facts.exported.get(path17) ?? []).map(({ text: text2 }) => text2);
19499
19653
  return [
19500
- path16,
19501
- `${path16} ${lineCount(path16)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19654
+ path17,
19655
+ `${path17} ${lineCount(path17)}${declarations2.length ? `: ${declarations2.join(", ")}` : ""}`
19502
19656
  ];
19503
19657
  }),
19504
19658
  ...listedOther.map((entry) => [
@@ -19509,7 +19663,7 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19509
19663
  ];
19510
19664
  const directories = /* @__PURE__ */ new Map();
19511
19665
  for (const entry of [
19512
- ...code.map((path16) => ({ path: path16, item: lineCount(path16) })),
19666
+ ...code.map((path17) => ({ path: path17, item: lineCount(path17) })),
19513
19667
  ...listedOther.map((entry2) => ({
19514
19668
  path: entry2.path,
19515
19669
  item: entry2.state === "TEXT" ? "" : `(${entry2.state})`
@@ -19537,10 +19691,10 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19537
19691
  );
19538
19692
  const text = visible.filter((entry) => entry.state === "TEXT").length;
19539
19693
  const resolution = /* @__PURE__ */ new Map();
19540
- for (const path16 of code) {
19541
- const counts = facts.calls.get(path16);
19694
+ for (const path17 of code) {
19695
+ const counts = facts.calls.get(path17);
19542
19696
  if (!counts) continue;
19543
- const language = facts.files.get(path16)?.language ?? "unknown";
19697
+ const language = facts.files.get(path17)?.language ?? "unknown";
19544
19698
  const total = resolution.get(language) ?? { resolved: 0, unresolved: 0, external: 0 };
19545
19699
  total.resolved += counts.resolved;
19546
19700
  total.unresolved += counts.unresolved;
@@ -19556,7 +19710,7 @@ function directoryView(facts, coverage, entries, input, directory, prefixes) {
19556
19710
  `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
19711
  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
19712
  ...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.`
19713
+ `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
19714
  ] : [],
19561
19715
  ...directory === "." && coverage.limits.length ? [`Map limits: ${coverage.limits.join("; ")}.`] : []
19562
19716
  ];
@@ -19599,8 +19753,8 @@ var DeclarationGroups = class {
19599
19753
  prefixes;
19600
19754
  showTests;
19601
19755
  memberCalls;
19602
- visible(path16) {
19603
- return mapPathAllowed(path16, this.prefixes) && (this.showTests || !mapTestPath(path16));
19756
+ visible(path17) {
19757
+ return mapPathAllowed(path17, this.prefixes) && (this.showTests || !mapTestPath(path17));
19604
19758
  }
19605
19759
  entry(object2, imported = false) {
19606
19760
  if (mapMiniprogramTemplate(object2.anchor.path)) return "(template)";
@@ -19645,11 +19799,11 @@ var DeclarationGroups = class {
19645
19799
  value.lines.push(line);
19646
19800
  aggregates.set(key, value);
19647
19801
  };
19648
- const dispatch = (arrow, label, ref2, path16, line) => {
19802
+ const dispatch = (arrow, label, ref2, path17, line) => {
19649
19803
  const other = graph.object(graph.owner(ref2));
19650
19804
  if (owned.has(other.id)) return;
19651
- if (!this.visible(path16)) {
19652
- if (mapPathAllowed(path16, this.prefixes)) omittedTests++;
19805
+ if (!this.visible(path17)) {
19806
+ if (mapPathAllowed(path17, this.prefixes)) omittedTests++;
19653
19807
  return;
19654
19808
  }
19655
19809
  add(arrow, label, other, line);
@@ -19713,7 +19867,7 @@ var DeclarationGroups = class {
19713
19867
  else
19714
19868
  add(
19715
19869
  "\u2192",
19716
- shows(relation) ? "shows" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
19870
+ relation.event ? `calls via ${relation.event} event` : shows(relation) ? "shows" : OUTGOING[relation.kind] ?? relation.kind.toLowerCase(),
19717
19871
  other,
19718
19872
  relation.anchor.startLine,
19719
19873
  relation.argument
@@ -19738,7 +19892,7 @@ var DeclarationGroups = class {
19738
19892
  if (mapPathAllowed(relation.anchor.path, this.prefixes)) omittedTests++;
19739
19893
  continue;
19740
19894
  }
19741
- const label = relation.kind === "CALLS" && focus.kind === "CLASS" ? "instantiated by" : shows(relation) ? "shown by" : INCOMING[relation.kind] ?? relation.kind.toLowerCase();
19895
+ 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
19896
  add(
19743
19897
  "\u2190",
19744
19898
  label,
@@ -19806,7 +19960,7 @@ var DeclarationGroups = class {
19806
19960
  else files2.set(call.path, [item]);
19807
19961
  }
19808
19962
  lines.push(
19809
- ` \u2190 possible callers by name: ${[...files2].map(([path16, items]) => `${path16}: ${items.join(", ")}`).join("; ")}${inTests}`
19963
+ ` \u2190 possible callers by name: ${[...files2].map(([path17, items]) => `${path17}: ${items.join(", ")}`).join("; ")}${inTests}`
19810
19964
  );
19811
19965
  } else if (possibleInTests)
19812
19966
  lines.push(` \u2190 possible callers by name: ${possibleInTests} in test files (includeTests)`);
@@ -19842,14 +19996,14 @@ var DeclarationGroups = class {
19842
19996
  return { lines, neighbors: [...new Set(neighbors)] };
19843
19997
  }
19844
19998
  };
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) ?? [];
19999
+ function fileView(store, coverage, graph, input, path17, prefixes) {
20000
+ const entry = store.getEntry(input.version, path17);
20001
+ if (!entry || !mapPathAllowed(path17, prefixes)) return notFound();
20002
+ const showTests = input.includeTests === true || mapTestPath(path17);
20003
+ 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;
20004
+ const gaps = coverage.files.get(path17) ?? [];
19851
20005
  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`}`
20006
+ `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
20007
  ];
19854
20008
  if (!module || entry.state !== "TEXT")
19855
20009
  return pageBlocks("FILE", head, [], input.offset ?? 0, input.outputBudget);
@@ -19869,7 +20023,7 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19869
20023
  tags.set(relation.from, list);
19870
20024
  }
19871
20025
  const describe3 = (object2) => [
19872
- `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path16 ? "" : ` (${object2.anchor.path})`}`,
20026
+ `${object2.name} ${mapDeclarationLabel(object2)}${object2.anchor.path === path17 ? "" : ` (${object2.anchor.path})`}`,
19873
20027
  ...tags.get(object2.id) ?? []
19874
20028
  ].join(" ");
19875
20029
  const declarations2 = [];
@@ -19884,11 +20038,11 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19884
20038
  );
19885
20039
  }
19886
20040
  const elsewhere = /* @__PURE__ */ new Map();
19887
- for (const object2 of graph.objectsAt(path16)) {
20041
+ for (const object2 of graph.objectsAt(path17)) {
19888
20042
  const parent = mapIsModule(object2) ? void 0 : graph.parent(object2.id);
19889
20043
  if (parent === void 0 || !graph.isAddressable(object2)) continue;
19890
20044
  const container = graph.object(parent);
19891
- if (mapIsModule(container) || container.anchor.path === path16) continue;
20045
+ if (mapIsModule(container) || container.anchor.path === path17) continue;
19892
20046
  const into = elsewhere.get(parent);
19893
20047
  if (into) into.push(object2);
19894
20048
  else elsewhere.set(parent, [object2]);
@@ -19902,7 +20056,7 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19902
20056
  if (declarations2.length) blocks.push(["DECLARATIONS (* exported)", ...declarations2].join("\n"));
19903
20057
  const imports2 = /* @__PURE__ */ new Set();
19904
20058
  const external = /* @__PURE__ */ new Set();
19905
- const fileObjects = graph.objectsAt(path16).map((object2) => object2.id);
20059
+ const fileObjects = graph.objectsAt(path17).map((object2) => object2.id);
19906
20060
  for (const relation of graph.relationsFrom(fileObjects)) {
19907
20061
  if (!IMPORT_KINDS.has(relation.kind)) continue;
19908
20062
  if (relation.to === void 0) external.add(relation.target);
@@ -19913,8 +20067,8 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19913
20067
  }
19914
20068
  const importers = /* @__PURE__ */ new Set();
19915
20069
  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);
20070
+ const imported = mapImportTarget(path17);
20071
+ 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
20072
  for (const relation of graph.relationsTo(packageModules)) {
19919
20073
  if (!IMPORT_KINDS.has(relation.kind)) continue;
19920
20074
  const source = relation.anchor.path;
@@ -19942,16 +20096,16 @@ function fileView(store, coverage, graph, input, path16, prefixes) {
19942
20096
  if (scope.length) blocks.push(["MODULE SCOPE (top-level statements)", ...scope].join("\n"));
19943
20097
  return pageBlocks("FILE", head, blocks, input.offset ?? 0, input.outputBudget);
19944
20098
  }
19945
- function declarationView(graph, input, path16, prefixes, memberCalls) {
20099
+ function declarationView(graph, input, path17, prefixes, memberCalls) {
19946
20100
  const requested = input.depth ?? 1;
19947
20101
  if (!Number.isSafeInteger(requested) || requested < 1 || requested > MAP_VIEW_LIMITS.directedDepth)
19948
20102
  return invalid2();
19949
20103
  const both = (input.direction ?? "BOTH") === "BOTH";
19950
20104
  const depth = both ? Math.min(requested, MAP_VIEW_LIMITS.bothDepth) : requested;
19951
20105
  const { name, line } = input;
19952
- const selected = mapSelectDeclarations(graph, path16, name, line);
20106
+ const selected = mapSelectDeclarations(graph, path17, name, line);
19953
20107
  if (!selected.length) return notFound();
19954
- const showTests = input.includeTests === true || mapTestPath(path16);
20108
+ const showTests = input.includeTests === true || mapTestPath(path17);
19955
20109
  const groups = new DeclarationGroups(graph, input, prefixes, showTests, memberCalls);
19956
20110
  const blocks = [];
19957
20111
  const seen = /* @__PURE__ */ new Set();
@@ -19999,7 +20153,7 @@ function declarationView(graph, input, path16, prefixes, memberCalls) {
19999
20153
  );
20000
20154
  }
20001
20155
  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"}`,
20156
+ `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
20157
  ...truncated ? [`Expansion stopped at ${MAP_VIEW_LIMITS.declarations} declarations.`] : [],
20004
20158
  ...(input.direction ?? "BOTH") === "OUTGOING" ? [] : [callerCoverage(input.textSearch ?? DEFAULT_TEXT_SEARCH)]
20005
20159
  ];
@@ -20126,10 +20280,10 @@ var ProjectMapQuery = class {
20126
20280
  view(input, signal) {
20127
20281
  this.requireReadableMap(input.version, signal);
20128
20282
  const { offset, prefixes } = admission(input);
20129
- const path16 = normalizeProjectEvidencePath(input.path, true) || ".";
20283
+ const path17 = normalizeProjectEvidencePath(input.path, true) || ".";
20130
20284
  const view = mapView(
20131
20285
  this.store,
20132
- { ...input, path: path16, offset, allowedPathPrefixes: prefixes },
20286
+ { ...input, path: path17, offset, allowedPathPrefixes: prefixes },
20133
20287
  this.views
20134
20288
  );
20135
20289
  if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
@@ -20329,13 +20483,13 @@ var ProjectMapSourceReader = class _ProjectMapSourceReader {
20329
20483
  */
20330
20484
  async readAll(expected) {
20331
20485
  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))
20486
+ const paths = expected.map(({ path: path17 }) => {
20487
+ assertProjectEvidencePathNotSensitive(path17);
20488
+ if (isProjectEvidenceTraversalExcluded(path17))
20335
20489
  throw new ProjectEvidenceError("PROJECT_FILE_NOT_ALLOWED", false);
20336
- return path16;
20490
+ return path17;
20337
20491
  });
20338
- const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path16) => this.session.captureFile(path16));
20492
+ const results = this.commit ? await this.commit.readAll(paths) : await concurrently(paths, (path17) => this.session.captureFile(path17));
20339
20493
  for (const [index, { entry }] of results.entries()) {
20340
20494
  const wanted = expected[index];
20341
20495
  if (entry.state !== wanted?.state || entry.contentDigest !== wanted.contentDigest || entry.byteLength !== wanted.byteLength)
@@ -20696,7 +20850,7 @@ ${scopeDigest}`;
20696
20850
  throw new ProjectEvidenceError("PROJECT_READ_RANGE_NOT_AVAILABLE", false);
20697
20851
  const entry = this.store.getEntry(input.version, relativePath);
20698
20852
  if (!entry) throw new ProjectEvidenceError("PROJECT_PATH_NOT_READABLE", false);
20699
- const contentDigest = this.requireTextContentDigest(entry);
20853
+ const contentDigest2 = this.requireTextContentDigest(entry);
20700
20854
  const session = new ProjectMapReadSession(this.store, input.version, input.source, signal);
20701
20855
  const content = await session.read(entry);
20702
20856
  await session.assertStable();
@@ -20714,7 +20868,7 @@ ${scopeDigest}`;
20714
20868
  endLine: startLine + Math.max(0, selected.length - 1)
20715
20869
  }),
20716
20870
  text: selected.join("\n"),
20717
- contentDigest,
20871
+ contentDigest: contentDigest2,
20718
20872
  sourceHasMore: endLine < Math.min(declaration?.endLine ?? lines.length, lines.length),
20719
20873
  ...object2 ? {
20720
20874
  symbol: Object.freeze({
@@ -20795,7 +20949,7 @@ ${scopeDigest}`;
20795
20949
  };
20796
20950
 
20797
20951
  // src/code-index-store.ts
20798
- import { createHash as createHash3, randomBytes, randomUUID } from "node:crypto";
20952
+ import { createHash as createHash4, randomBytes, randomUUID } from "node:crypto";
20799
20953
  var CODE_INDEX_SCHEMA = `
20800
20954
  CREATE TABLE project_code_meta (meta_key TEXT PRIMARY KEY, meta_value TEXT NOT NULL);
20801
20955
  CREATE TABLE project_code_versions (
@@ -21043,12 +21197,13 @@ var CodeIndexStore = class {
21043
21197
  discardMapStage(buildRef) {
21044
21198
  this.database.prepare("DELETE FROM project_map_staging WHERE build_ref = ?").run(buildRef);
21045
21199
  }
21046
- publish(version2, entries, buildRef, coverage, linked) {
21200
+ publish(version2, entries, installedDigest, buildRef, coverage, linked) {
21047
21201
  if (version2.version !== digestValue({
21048
21202
  projectRef: version2.projectRef,
21049
21203
  pathPrefixes: version2.pathPrefixes,
21050
21204
  entries,
21051
- analyzer: version2.analyzer
21205
+ analyzer: version2.analyzer,
21206
+ installed: installedDigest
21052
21207
  }) || 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
21208
  return corrupt2();
21054
21209
  this.database.exec("BEGIN IMMEDIATE");
@@ -21057,7 +21212,7 @@ var CodeIndexStore = class {
21057
21212
  const staged = this.stageUnits(buildRef, paths, linked);
21058
21213
  const reused = linked ? this.database.prepare(`SELECT path, unit_ref FROM project_map_version_units
21059
21214
  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)))
21215
+ if (reused.length !== (linked?.paths.size ?? 0) || reused.some(({ path: path17 }) => !paths.has(path17)) || staged.some(({ path: path17 }) => linked?.paths.has(path17)))
21061
21216
  throw new MapReplayConflict();
21062
21217
  const units = [...staged, ...reused].sort(
21063
21218
  (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0
@@ -21108,7 +21263,7 @@ var CodeIndexStore = class {
21108
21263
  const member = this.database.prepare(
21109
21264
  "INSERT INTO project_map_version_units VALUES (?, ?, ?)"
21110
21265
  );
21111
- for (const { path: path16, unit } of reused) member.run(version2.version, path16, unit);
21266
+ for (const { path: path17, unit } of reused) member.run(version2.version, path17, unit);
21112
21267
  this.database.prepare("INSERT INTO project_map_coverage VALUES (?, ?)").run(version2.version, canonicalJson(coverage));
21113
21268
  }
21114
21269
  this.database.exec(`DELETE FROM project_map_publish_objects;
@@ -21163,7 +21318,7 @@ var CodeIndexStore = class {
21163
21318
  corrupt2();
21164
21319
  }
21165
21320
  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));
21321
+ 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
21322
  if (database.prepare(`SELECT 1 FROM project_map_objects gone
21168
21323
  WHERE gone.version_ref = ? AND gone.path IN (SELECT value FROM json_each(?))
21169
21324
  AND gone.entity_ref NOT IN (SELECT entity_ref FROM project_map_publish_objects)
@@ -21185,17 +21340,17 @@ var CodeIndexStore = class {
21185
21340
  const units = [];
21186
21341
  for (const row of database.prepare(`SELECT path FROM project_map_publish_objects
21187
21342
  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");
21343
+ const path17 = String(row.path);
21344
+ const hash2 = createHash4("sha256").update(path17).update("\0");
21190
21345
  for (const [mark, statement] of [
21191
21346
  ["object", objects2],
21192
21347
  ["relation", relations],
21193
21348
  ["note", pathNotes]
21194
21349
  ])
21195
- for (const fact of statement.all(path16))
21350
+ for (const fact of statement.all(path17))
21196
21351
  for (const value of Object.values(fact))
21197
21352
  hash2.update(mark).update("\0").update(String(value)).update("\0");
21198
- units.push({ path: path16, unit: hash2.digest("hex") });
21353
+ units.push({ path: path17, unit: hash2.digest("hex") });
21199
21354
  }
21200
21355
  return units;
21201
21356
  }
@@ -21213,13 +21368,13 @@ var CodeIndexStore = class {
21213
21368
  "INSERT INTO project_map_unit_notes SELECT ?, * FROM project_map_publish_notes WHERE path = ?"
21214
21369
  );
21215
21370
  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);
21371
+ for (const { path: path17, unit } of units) {
21372
+ if (insertUnit.run(unit, path17).changes) {
21373
+ unitObjects.run(unit, path17);
21374
+ unitRelations.run(unit, path17);
21375
+ unitNotes.run(unit, path17);
21221
21376
  }
21222
- member.run(version2, path16, unit);
21377
+ member.run(version2, path17, unit);
21223
21378
  }
21224
21379
  }
21225
21380
  /**
@@ -21472,27 +21627,30 @@ var contextFiles = (context) => [
21472
21627
  ...context.configurationFiles,
21473
21628
  ...context.workspace?.configurationFiles ?? []
21474
21629
  ];
21475
- function replayableContexts(parent, digests) {
21630
+ var codeFiles = (context, parsedFiles, claims) => [...context.inputFiles.filter(claims), ...parsedFiles];
21631
+ function replayableContexts(parent, digests, claims) {
21632
+ const factFiles = /* @__PURE__ */ new Map();
21476
21633
  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();
21634
+ const analyzed = /* @__PURE__ */ new Set();
21635
+ for (const [ref, { context }] of parent.contexts) {
21636
+ const { analysis, paths } = parent.shell(ref);
21637
+ const files = /* @__PURE__ */ new Set([...codeFiles(context, analysis.parsedFiles, claims), ...paths ?? []]);
21638
+ factFiles.set(ref, files);
21639
+ for (const path17 of files) {
21640
+ const refs = sharing.get(path17) ?? /* @__PURE__ */ new Set();
21480
21641
  refs.add(ref);
21481
- sharing.set(path16, refs);
21642
+ sharing.set(path17, refs);
21482
21643
  }
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))
21644
+ if (!paths || !contextFiles(context).every(
21645
+ (path17) => digests.get(path17) !== void 0 && digests.get(path17) === parent.entries.get(path17)
21493
21646
  ))
21494
- replayable.add(ref);
21495
- return { replayable, sharing };
21647
+ analyzed.add(ref);
21648
+ }
21649
+ for (const ref of analyzed)
21650
+ for (const path17 of factFiles.get(ref) ?? [])
21651
+ for (const other of sharing.get(path17) ?? []) analyzed.add(other);
21652
+ const replayable = new Set([...parent.contexts.keys()].filter((ref) => !analyzed.has(ref)));
21653
+ return { replayable, sharing, factFiles };
21496
21654
  }
21497
21655
  var invalidParent = () => {
21498
21656
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
@@ -21522,16 +21680,20 @@ var ProjectMapAnalyzer = class {
21522
21680
  languages;
21523
21681
  observe;
21524
21682
  id;
21525
- claims(path16) {
21526
- return this.languages.some((language) => language.claims(path16));
21683
+ claims(path17) {
21684
+ return this.languages.some((language) => language.claims(path17));
21527
21685
  }
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);
21686
+ // A context holds one language's code, so its requests are that language's.
21687
+ async references(input, references, signal, until) {
21688
+ const [first] = references;
21689
+ const language = first && this.languages.find((item) => item.claims(first.targetPath));
21690
+ return language?.references ? language.references(input, references, signal, this.observe, until) : { pages: references.map(() => null), requiredFiles: [] };
21691
+ }
21692
+ // A context's compiler diagnostics, undefined for a language without a compiler to ask.
21693
+ diagnostics(input, path17, signal) {
21694
+ return this.languages.find((language) => language.claims(path17))?.diagnostics?.(input, signal, this.observe);
21533
21695
  }
21534
- async analyze(reader, entries, signal, consume, parent) {
21696
+ async analyze(reader, entries, installed, signal, consume, parent) {
21535
21697
  const result = {
21536
21698
  gaps: [{ code: "MAP_COVERS_ADMITTED_SCOPE_AND_POLICY_ONLY" }],
21537
21699
  parsedFiles: []
@@ -21553,7 +21715,12 @@ var ProjectMapAnalyzer = class {
21553
21715
  const digests = /* @__PURE__ */ new Map();
21554
21716
  for (const entry of entries)
21555
21717
  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() };
21718
+ const claims = (path17) => this.claims(path17);
21719
+ const { replayable, sharing, factFiles } = parent ? replayableContexts(parent, digests, claims) : {
21720
+ replayable: /* @__PURE__ */ new Set(),
21721
+ sharing: /* @__PURE__ */ new Map(),
21722
+ factFiles: /* @__PURE__ */ new Map()
21723
+ };
21557
21724
  const requests = /* @__PURE__ */ new Map();
21558
21725
  const states = /* @__PURE__ */ new Map();
21559
21726
  const replayed = /* @__PURE__ */ new Map();
@@ -21563,13 +21730,13 @@ var ProjectMapAnalyzer = class {
21563
21730
  const reuse = (contextRef2, request, files2) => {
21564
21731
  const digest = digestValue({
21565
21732
  request,
21566
- files: files2.map((path16) => [path16, digests.get(path16) ?? null])
21733
+ files: files2.map((path17) => [path17, digests.get(path17) ?? null])
21567
21734
  });
21568
21735
  requests.set(contextRef2, digest);
21569
21736
  if (!parent || !replayable.has(contextRef2)) return void 0;
21570
21737
  if (parent.contexts.get(contextRef2)?.requestDigest !== digest) return void 0;
21571
21738
  const { analysis, state, paths } = parent.shell(contextRef2);
21572
- if (!paths) return void 0;
21739
+ if (!paths) return invalidParent();
21573
21740
  if (state !== void 0) states.set(contextRef2, state);
21574
21741
  replayed.set(contextRef2, paths);
21575
21742
  this.observe?.({
@@ -21602,7 +21769,7 @@ var ProjectMapAnalyzer = class {
21602
21769
  const ref = analysis.contexts[0]?.ref ?? "";
21603
21770
  if (options?.linked?.length) {
21604
21771
  if (!parent || analysis.contexts.length !== 1) return invalidParent();
21605
- for (const path16 of options.linked) linked.add(path16);
21772
+ for (const path17 of options.linked) linked.add(path17);
21606
21773
  this.observe?.({
21607
21774
  operation: "LINK",
21608
21775
  phase: "FINISHED",
@@ -21629,11 +21796,11 @@ var ProjectMapAnalyzer = class {
21629
21796
  });
21630
21797
  for (const file2 of analysis.parsedFiles) parsed.add(file2);
21631
21798
  const staged = factPaths(analysis);
21632
- for (const path16 of staged) stagedPaths.add(path16);
21799
+ for (const path17 of staged) stagedPaths.add(path17);
21633
21800
  for (const context of analysis.contexts) {
21634
21801
  for (const file2 of context.configurationFiles) configurationInputs.add(file2);
21635
21802
  if (!replayed.has(context.ref))
21636
- for (const file2 of options?.linked?.length ? staged : contextFiles(context))
21803
+ for (const file2 of options?.linked?.length ? staged : codeFiles(context, analysis.parsedFiles, claims))
21637
21804
  analyzedFiles.add(file2);
21638
21805
  }
21639
21806
  for (const gap of analysis.gaps) result.gaps.push(gap);
@@ -21652,13 +21819,14 @@ var ProjectMapAnalyzer = class {
21652
21819
  await language.analyze(
21653
21820
  {
21654
21821
  entries,
21822
+ installed,
21655
21823
  readable: own,
21656
21824
  texts,
21657
21825
  read,
21658
21826
  accept,
21659
21827
  reuse,
21660
21828
  previous,
21661
- configuration: (path16) => configurationInputs.add(path16),
21829
+ configuration: (path17) => configurationInputs.add(path17),
21662
21830
  observe: this.observe
21663
21831
  },
21664
21832
  signal
@@ -21695,12 +21863,12 @@ var ProjectMapAnalyzer = class {
21695
21863
  if (files.objects.length) accept(files);
21696
21864
  if (parent && (replayed.size || linked.size)) {
21697
21865
  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)))
21866
+ for (const path17 of factFiles.get(ref) ?? invalidParent())
21867
+ if (analyzedFiles.has(path17) || [...sharing.get(path17) ?? []].some((other) => !replayed.has(other)))
21700
21868
  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();
21869
+ for (const paths of replayed.values()) for (const path17 of paths) linked.add(path17);
21870
+ for (const path17 of linked)
21871
+ if (analyzedFiles.has(path17) || stagedPaths.has(path17)) throw new MapReplayConflict();
21704
21872
  parent.link([...linked]);
21705
21873
  }
21706
21874
  result.parsedFiles = [...parsed].sort();
@@ -21709,6 +21877,11 @@ var ProjectMapAnalyzer = class {
21709
21877
  };
21710
21878
 
21711
21879
  // src/project-map-reference-query.ts
21880
+ var invalidProtocol = () => new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
21881
+ var anchored = ({ anchor }, files) => {
21882
+ const text = files[anchor.path];
21883
+ return text !== void 0 && anchor.start >= 0 && anchor.end >= anchor.start && anchor.end <= text.length;
21884
+ };
21712
21885
  var ProjectMapReferenceQuery = class {
21713
21886
  constructor(store, analyzer) {
21714
21887
  this.store = store;
@@ -21716,18 +21889,186 @@ var ProjectMapReferenceQuery = class {
21716
21889
  }
21717
21890
  store;
21718
21891
  analyzer;
21719
- async query(input, signal) {
21892
+ // The source to read a complete map version from, once that version is this source's to read.
21893
+ readable(version2, input) {
21720
21894
  const source = Object.freeze({
21721
- ...input.source,
21722
- directory: Object.freeze({ ...input.source.directory })
21895
+ ...input,
21896
+ directory: Object.freeze({ ...input.directory })
21723
21897
  });
21724
- const version2 = this.store.requireVersion(input.version);
21725
- if (version2.analyzer !== this.analyzer.id)
21898
+ const stored = this.store.requireVersion(version2);
21899
+ if (stored.analyzer !== this.analyzer.id)
21726
21900
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
21727
- if (version2.projectRef !== source.projectRef)
21901
+ if (stored.projectRef !== source.projectRef)
21728
21902
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_ACCESS_REVOKED", false);
21729
- if (!this.store.getIndexProgress(input.version).complete)
21903
+ if (!this.store.getIndexProgress(version2).complete)
21730
21904
  throw new ProjectEvidenceError("PROJECT_EVIDENCE_INDEX_UNAVAILABLE", true);
21905
+ return source;
21906
+ }
21907
+ // The compiler contexts a file is in.
21908
+ contexts(version2, path17) {
21909
+ return this.store.database.prepare(`SELECT DISTINCT c.context_ref, c.context_json
21910
+ FROM project_map_contexts c, json_each(c.context_json, '$.inputFiles') f
21911
+ WHERE c.version_ref = ? AND f.value = ?
21912
+ AND json_extract(c.context_json, '$.mode') != 'SYNTAX_ONLY'
21913
+ ORDER BY c.context_ref`).all(version2, path17).map((value) => MapContextSchema.parse(JSON.parse(String(value.context_json))));
21914
+ }
21915
+ // A context's sources, and the request for its compile.
21916
+ async open(version2, source, context, signal) {
21917
+ const entries = context.inputFiles.map((file2) => {
21918
+ const entry = this.store.getEntry(version2, file2);
21919
+ if (entry?.state !== "TEXT")
21920
+ throw new ProjectEvidenceError("PROJECT_EVIDENCE_STORE_CORRUPT", false);
21921
+ return entry;
21922
+ });
21923
+ const reader = await ProjectMapSourceReader.open(source, signal, false);
21924
+ const files = /* @__PURE__ */ Object.create(null);
21925
+ const contents = await reader.readAll(entries);
21926
+ for (const [index, entry] of entries.entries()) {
21927
+ const value = contents[index];
21928
+ if (!value?.content) throw new ProjectEvidenceError("PROJECT_MAP_SOURCE_CHANGED", true);
21929
+ files[entry.path] = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
21930
+ value.content
21931
+ );
21932
+ }
21933
+ return {
21934
+ reader,
21935
+ files,
21936
+ request: {
21937
+ contextRef: context.ref,
21938
+ configPath: context.configPath,
21939
+ rootFiles: context.rootFiles,
21940
+ files,
21941
+ inventory: context.inputFiles,
21942
+ syntaxOnly: false,
21943
+ workspace: context.workspace,
21944
+ dependencies: source.directory.canonicalPath
21945
+ }
21946
+ };
21947
+ }
21948
+ /** The configurations of the contexts a version's files are in. */
21949
+ contextConfigurations(version2, paths) {
21950
+ return paths.flatMap(
21951
+ (path17) => this.contexts(version2, path17).flatMap((context) => context.configPath ?? [])
21952
+ );
21953
+ }
21954
+ /**
21955
+ * What the compiler says is wrong in each context of the given configurations, for as long as
21956
+ * the deadline leaves; a context started is compiled to the end, so what each holds is whole. A
21957
+ * context without a configuration was given options of ours, so its errors say nothing of how
21958
+ * the project compiles. Contexts of a language without a compiler to ask are not counted.
21959
+ */
21960
+ async diagnostics(input, signal) {
21961
+ const source = this.readable(input.version, input.source);
21962
+ const contexts = /* @__PURE__ */ new Map();
21963
+ for (const row of this.store.database.prepare(`SELECT DISTINCT context_ref, context_json FROM project_map_contexts
21964
+ WHERE version_ref = ? AND json_extract(context_json, '$.mode') != 'SYNTAX_ONLY'
21965
+ ORDER BY context_ref`).all(input.version)) {
21966
+ const context = MapContextSchema.parse(JSON.parse(String(row.context_json)));
21967
+ if (context.configPath && input.configurations.includes(context.configPath))
21968
+ contexts.set(context.configPath, context);
21969
+ }
21970
+ const compiled = [];
21971
+ const unchecked = [];
21972
+ for (const [configPath, context] of contexts) {
21973
+ if (Date.now() > input.until) {
21974
+ unchecked.push(configPath);
21975
+ continue;
21976
+ }
21977
+ const [path17] = context.rootFiles ?? context.inputFiles;
21978
+ const { reader, request } = await this.open(input.version, source, context, signal);
21979
+ const result = path17 === void 0 ? void 0 : await this.analyzer.diagnostics(request, path17, signal);
21980
+ await reader.assertStable();
21981
+ if (!result) continue;
21982
+ if (result.requiredFiles.length)
21983
+ throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
21984
+ const found = new Map(
21985
+ result.diagnostics.map((item) => [
21986
+ `${item.path}:${item.line}:${item.code}:${item.text}`,
21987
+ item
21988
+ ])
21989
+ );
21990
+ compiled.push({ configPath, errors: [...found.values()], missing: result.missing });
21991
+ }
21992
+ return { contexts: compiled, unchecked };
21993
+ }
21994
+ // The innermost object around a location.
21995
+ owner(version2, anchor) {
21996
+ const row = this.store.database.prepare(`SELECT object_json FROM project_map_objects
21997
+ WHERE version_ref = ? AND path = ?
21998
+ AND json_extract(object_json, '$.anchor.start') <= ? AND json_extract(object_json, '$.anchor.end') >= ?
21999
+ 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);
22000
+ return row ? MapObjectSchema.parse(JSON.parse(String(row.object_json))) : void 0;
22001
+ }
22002
+ /**
22003
+ * The uses of many declarations of one version, each context they are in compiled once, for as
22004
+ * long as the deadline leaves. A declaration not read to the end says so, with what was found.
22005
+ */
22006
+ async uses(input, signal) {
22007
+ const source = this.readable(input.version, input.source);
22008
+ const found = /* @__PURE__ */ new Map();
22009
+ const contextsOf = /* @__PURE__ */ new Map();
22010
+ const compiles = /* @__PURE__ */ new Map();
22011
+ for (const ref of input.refs) {
22012
+ const object2 = requireMapObject(this.store, input.version, { entityRef: ref }, ["."]);
22013
+ const path17 = object2.anchor.path;
22014
+ const contexts = contextsOf.get(path17) ?? this.contexts(input.version, path17);
22015
+ contextsOf.set(path17, contexts);
22016
+ const readable = object2.symbolStart === void 0 ? [] : contexts;
22017
+ found.set(ref, {
22018
+ uses: [],
22019
+ locations: /* @__PURE__ */ new Set(),
22020
+ waiting: readable.length,
22021
+ complete: readable.length > 0
22022
+ });
22023
+ for (const context of readable) {
22024
+ const compile = compiles.get(context.ref) ?? { context, targets: [] };
22025
+ compile.targets.push(object2);
22026
+ compiles.set(context.ref, compile);
22027
+ }
22028
+ }
22029
+ for (const { context, targets } of compiles.values()) {
22030
+ if (Date.now() > input.until) break;
22031
+ const { reader, files, request } = await this.open(input.version, source, context, signal);
22032
+ const { pages, requiredFiles } = await this.analyzer.references(
22033
+ request,
22034
+ targets.map((object2) => ({
22035
+ targetPath: object2.anchor.path,
22036
+ symbolStart: object2.symbolStart,
22037
+ offset: 0,
22038
+ maxResults: input.maxResults
22039
+ })),
22040
+ signal,
22041
+ input.until
22042
+ );
22043
+ if (requiredFiles.length)
22044
+ throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
22045
+ if (pages.length > targets.length)
22046
+ throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
22047
+ for (const [at, page] of pages.entries()) {
22048
+ const read = found.get(targets[at]?.id ?? "");
22049
+ read.waiting--;
22050
+ if (!page || page.nextOffset !== void 0) read.complete = false;
22051
+ for (const reference of page?.references ?? []) {
22052
+ const location2 = canonicalJson(reference.anchor);
22053
+ if (!anchored(reference, files)) throw invalidProtocol();
22054
+ if (read.locations.has(location2)) continue;
22055
+ read.locations.add(location2);
22056
+ const owner = this.owner(input.version, reference.anchor);
22057
+ read.uses.push({ ...reference, ...owner ? { owner } : {} });
22058
+ }
22059
+ }
22060
+ await reader.assertStable();
22061
+ if (signal.aborted) throw new ProjectEvidenceError("PROJECT_READ_CANCELLED", true);
22062
+ }
22063
+ return new Map(
22064
+ [...found].map(([ref, { uses, waiting, complete }]) => [
22065
+ ref,
22066
+ { uses, complete: complete && !waiting }
22067
+ ])
22068
+ );
22069
+ }
22070
+ async query(input, signal) {
22071
+ const source = this.readable(input.version, input.source);
21731
22072
  if (!Number.isSafeInteger(input.maxResults) || input.maxResults < 1 || input.maxResults > 200)
21732
22073
  throw new ProjectEvidenceError("PROJECT_READ_INPUT_INVALID", false);
21733
22074
  const prefixes = (input.allowedPathPrefixes ?? ["."]).map(
@@ -21740,11 +22081,7 @@ var ProjectMapReferenceQuery = class {
21740
22081
  const object2 = requireMapObject(this.store, input.version, input, prefixes);
21741
22082
  if (object2.symbolStart === void 0)
21742
22083
  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))));
22084
+ const availableContexts = this.contexts(input.version, object2.anchor.path);
21748
22085
  if (!availableContexts.length)
21749
22086
  throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_CONTEXT_UNAVAILABLE", false);
21750
22087
  const contexts = availableContexts.filter(
@@ -21785,58 +22122,38 @@ ${scope}`, input.cursor, 2) : [];
21785
22122
  }
21786
22123
  const context = contexts[cursor.context];
21787
22124
  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
- },
22125
+ const { reader, files, request } = await this.open(input.version, source, context, signal);
22126
+ const {
22127
+ pages: [page],
22128
+ requiredFiles
22129
+ } = await this.analyzer.references(
22130
+ request,
22131
+ [
22132
+ {
22133
+ targetPath: object2.anchor.path,
22134
+ symbolStart: object2.symbolStart,
22135
+ offset: cursor.offset,
22136
+ maxResults: input.maxResults,
22137
+ ...query
22138
+ }
22139
+ ],
21821
22140
  signal
21822
22141
  );
21823
- if (page.requiredFiles.length)
22142
+ if (requiredFiles.length)
21824
22143
  throw new ProjectEvidenceError("PROJECT_MAP_CONTEXT_INCOMPLETE", false);
22144
+ if (page === void 0) throw invalidProtocol();
22145
+ if (page === null)
22146
+ throw new ProjectEvidenceError("PROJECT_MAP_REFERENCE_TARGET_UNAVAILABLE", false);
21825
22147
  if (page.nextOffset !== void 0 && (!page.references.length || page.nextOffset !== cursor.offset + page.references.length))
21826
- throw new ProjectEvidenceError("PROJECT_MAP_PROTOCOL_INVALID", false);
22148
+ throw invalidProtocol();
21827
22149
  const references = [];
21828
22150
  const locations = /* @__PURE__ */ new Set();
21829
22151
  for (const reference of page.references) {
21830
- const text = files[reference.anchor.path];
21831
22152
  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);
22153
+ if (!anchored(reference, files) || !mapPathAllowed(reference.anchor.path, prefixes) || !mapQueryPathMatches(reference.anchor.path, query.path) || !query.kinds.includes(reference.kind) || locations.has(location2))
22154
+ throw invalidProtocol();
21834
22155
  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;
22156
+ const owner = this.owner(input.version, reference.anchor);
21840
22157
  const item = { ...reference, contextRef: context.ref, ...owner ? { owner } : {} };
21841
22158
  references.push(item);
21842
22159
  }
@@ -21948,6 +22265,7 @@ var CodeIndex = class {
21948
22265
  const coverage = await this.analyzer.analyze(
21949
22266
  reader,
21950
22267
  result.entries,
22268
+ { directory: source.directory.canonicalPath, digest: result.installedDigest },
21951
22269
  controller.signal,
21952
22270
  (unit, record2) => this.store.appendMapStage(stage, unit, record2),
21953
22271
  parent && { ...parent, link: (paths) => linked.push(...paths) }
@@ -21959,6 +22277,7 @@ var CodeIndex = class {
21959
22277
  this.store.publish(
21960
22278
  result.version,
21961
22279
  result.entries,
22280
+ result.installedDigest,
21962
22281
  stage,
21963
22282
  coverage,
21964
22283
  parent && linked.length ? { version: parent.version, paths: new Set(linked) } : void 0
@@ -21995,8 +22314,8 @@ var CodeIndex = class {
21995
22314
  for (const entry of this.store.listEntries(candidate))
21996
22315
  if (entry.contentDigest) entries2.set(entry.path, entry.contentDigest);
21997
22316
  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++;
22317
+ for (const [path17, digest] of digests) if (entries2.get(path17) !== digest) changed++;
22318
+ for (const path17 of entries2.keys()) if (!digests.has(path17)) changed++;
22000
22319
  if (!best || changed < best.changed) best = { version: candidate, entries: entries2, changed };
22001
22320
  }
22002
22321
  if (!best) return void 0;
@@ -22056,6 +22375,25 @@ var CodeIndex = class {
22056
22375
  (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).query(input, signal2)
22057
22376
  );
22058
22377
  }
22378
+ findUses(input, signal) {
22379
+ return this.read(
22380
+ signal,
22381
+ (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).uses(input, signal2)
22382
+ );
22383
+ }
22384
+ /** The configurations of the compiler contexts a version's files are in. */
22385
+ contextConfigurations(version2, paths) {
22386
+ return new ProjectMapReferenceQuery(this.store, this.analyzer).contextConfigurations(
22387
+ version2,
22388
+ paths
22389
+ );
22390
+ }
22391
+ findDiagnostics(input, signal) {
22392
+ return this.read(
22393
+ signal,
22394
+ (signal2) => new ProjectMapReferenceQuery(this.store, this.analyzer).diagnostics(input, signal2)
22395
+ );
22396
+ }
22059
22397
  get busy() {
22060
22398
  return this.captures.size > 0 || this.rebuilds.size > 0 || this.mapBuilds.size > 0;
22061
22399
  }
@@ -22135,9 +22473,9 @@ var CodeIndex = class {
22135
22473
  };
22136
22474
 
22137
22475
  // src/project-map-changes.ts
22138
- import { readFileSync as readFileSync3 } from "node:fs";
22476
+ import { readFileSync as readFileSync4 } from "node:fs";
22139
22477
  import { readFile } from "node:fs/promises";
22140
- import path10 from "node:path";
22478
+ import path11 from "node:path";
22141
22479
 
22142
22480
  // src/project-map-clients.ts
22143
22481
  var CLIENT_FILES = [
@@ -22172,16 +22510,16 @@ var LITERAL = /(["'`])((?:\\.|(?!\1)[^\\])*)\1/gu;
22172
22510
  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
22511
  var LIMIT = Object.freeze({ routes: 40, clients: 5 });
22174
22512
  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) }));
22513
+ var segments = (path17) => path17.split("/").filter(Boolean).map((text) => ({ text, param: PARAM.test(text) || /[{}$<>%]/u.test(text) }));
22176
22514
  var routeSegments = (label) => segments(label.slice(label.indexOf("/")));
22177
22515
  function requestedPath(literal3, joined) {
22178
22516
  const match = /^(?:https?:\/\/[^/\s]+|(?:\$\{[^}]*\})+|@\{|redirect:|forward:)?(\/[^\s?#()"'`,;|]*)/u.exec(
22179
22517
  literal3
22180
22518
  ) ?? 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 });
22519
+ const path17 = match?.[1];
22520
+ if (!path17 || path17.startsWith("//") || path17.length < 3) return void 0;
22521
+ const parts = segments(path17);
22522
+ if (joined && path17.endsWith("/")) parts.push({ text: "*", param: true });
22185
22523
  return parts;
22186
22524
  }
22187
22525
  var same = (route, requested) => route.param || !requested.param && route.text === requested.text;
@@ -22289,9 +22627,9 @@ var routeClientsLine = ({ route, removed, clients }) => `${JSON.stringify(route)
22289
22627
 
22290
22628
  // src/project-map-dependencies.ts
22291
22629
  var IMPORT_KINDS2 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22292
- function imports(graph, path16) {
22630
+ function imports(graph, path17) {
22293
22631
  const found = [];
22294
- for (const relation of graph.relationsFrom(graph.objectsAt(path16).map((object2) => object2.id)))
22632
+ for (const relation of graph.relationsFrom(graph.objectsAt(path17).map((object2) => object2.id)))
22295
22633
  if (IMPORT_KINDS2.has(relation.kind) && relation.to !== void 0)
22296
22634
  found.push({
22297
22635
  target: graph.object(relation.to).anchor.path,
@@ -22308,9 +22646,9 @@ function pathBetween(edges, from, to) {
22308
22646
  if (via.has(target)) continue;
22309
22647
  via.set(target, module);
22310
22648
  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];
22649
+ const path17 = [to];
22650
+ for (let step = module; step !== from; step = via.get(step) ?? from) path17.unshift(step);
22651
+ return [from, ...path17];
22314
22652
  }
22315
22653
  next.push(target);
22316
22654
  }
@@ -22372,8 +22710,8 @@ function newModuleDependencies(store, cache, working, base, files) {
22372
22710
  }
22373
22711
 
22374
22712
  // src/project-map-names.ts
22375
- import { readFileSync as readFileSync2 } from "node:fs";
22376
- import path9 from "node:path";
22713
+ import { readFileSync as readFileSync3 } from "node:fs";
22714
+ import path10 from "node:path";
22377
22715
  var CONFIG_KEY = /^\s*(?:export\s+|-\s+)?["']?([A-Za-z_][\w.-]*)["']?\s*(?:=|:(?:\s|$))/u;
22378
22716
  var CODE_READS = [
22379
22717
  // process.env.NAME, import.meta.env.NAME
@@ -22449,7 +22787,7 @@ async function strandedNames(project, diff, files, configuration, git2, options)
22449
22787
  } else for (const name of codeReads(line, file2.path)) names2.add(name);
22450
22788
  let text;
22451
22789
  try {
22452
- text = readFileSync2(path9.join(project, file2.path), "utf8");
22790
+ text = readFileSync3(path10.join(project, file2.path), "utf8");
22453
22791
  } catch {
22454
22792
  continue;
22455
22793
  }
@@ -22523,6 +22861,7 @@ var MODULES = /* @__PURE__ */ new Set(["FILE", "PACKAGE", "CONFIG"]);
22523
22861
  var MEMBER_CONTAINERS2 = /* @__PURE__ */ new Set(["CLASS", "INTERFACE", "TYPE", "ENUM"]);
22524
22862
  var KINDS = /* @__PURE__ */ new Set(["FUNCTION", "METHOD", "CLASS", "VARIABLE"]);
22525
22863
  var MIN_LINES = 3;
22864
+ var SHORT_COPIES = 3;
22526
22865
  var ALIKE = 0.8;
22527
22866
  var SIBLINGS_ALIKE = 0.95;
22528
22867
  var KEYWORDS = new Set(
@@ -22530,9 +22869,9 @@ var KEYWORDS = new Set(
22530
22869
  );
22531
22870
  var ROWS = `SELECT entity_ref AS id, path, name, kind, object_json AS object
22532
22871
  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) => {
22872
+ function rows(store, version2, path17) {
22873
+ const statement = store.database.prepare(path17 === void 0 ? ROWS : `${ROWS} AND path = ?`);
22874
+ return (path17 === void 0 ? statement.all(version2) : statement.all(version2, path17)).map((row) => {
22536
22875
  const { anchor } = JSON.parse(String(row.object));
22537
22876
  return {
22538
22877
  id: String(row.id),
@@ -22572,11 +22911,12 @@ function lineWords(line) {
22572
22911
  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
22912
  }
22574
22913
  var within2 = (lines, declaration) => lines.some(([from, to]) => from <= declaration.startLine && declaration.endLine <= to);
22914
+ var copyText = (code) => code.replace(/^export\s+(?:default\s+)?/u, "").replace(/\s+/gu, " ").trim();
22575
22915
  async function similarCode(store, working, base, files, read) {
22576
- const code = (path16) => mapCodePath(path16) !== void 0 && !mapTestPath(path16);
22916
+ const code = (path17) => mapCodePath(path17) !== void 0 && !mapTestPath(path17);
22577
22917
  const changed = files.filter((file2) => file2.status !== "DELETED" && code(file2.path));
22578
22918
  if (!changed.length) return [];
22579
- const names = (version2, path16) => new Set(declarations(rows(store, version2, path16)).map((item) => item.qualifiedName));
22919
+ const names = (version2, path17) => new Set(declarations(rows(store, version2, path17)).map((item) => item.qualifiedName));
22580
22920
  const movedOut = /* @__PURE__ */ new Set();
22581
22921
  if (base !== void 0)
22582
22922
  for (const file2 of files) {
@@ -22584,13 +22924,18 @@ async function similarCode(store, working, base, files, read) {
22584
22924
  const now = file2.status === "DELETED" ? /* @__PURE__ */ new Set() : names(working, file2.path);
22585
22925
  for (const name of names(base, file2.basePath)) if (!now.has(name)) movedOut.add(name);
22586
22926
  }
22587
- const eligible = (item) => KINDS.has(item.kind) && item.endLine - item.startLine + 1 >= MIN_LINES;
22927
+ const long = (item) => item.endLine - item.startLine + 1 >= MIN_LINES;
22588
22928
  const added = /* @__PURE__ */ new Set();
22929
+ const shortNames = /* @__PURE__ */ new Set();
22930
+ let longAdded = false;
22589
22931
  for (const file2 of changed) {
22590
22932
  const had = base !== void 0 && file2.basePath && file2.status !== "ADDED" ? names(base, file2.basePath) : void 0;
22591
22933
  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))
22934
+ if (KINDS.has(item.kind) && within2(file2.lines, item) && !had?.has(item.qualifiedName) && !movedOut.has(item.qualifiedName)) {
22593
22935
  added.add(item.id);
22936
+ if (long(item)) longAdded = true;
22937
+ else shortNames.add(item.qualifiedName);
22938
+ }
22594
22939
  }
22595
22940
  if (!added.size) return [];
22596
22941
  const byPath = /* @__PURE__ */ new Map();
@@ -22601,14 +22946,22 @@ async function similarCode(store, working, base, files, read) {
22601
22946
  byPath.set(row.path, inFile);
22602
22947
  }
22603
22948
  const all = [];
22949
+ const shortCopies = /* @__PURE__ */ new Map();
22604
22950
  await Promise.all(
22605
- [...byPath].map(async ([path16, inFile]) => {
22606
- const found2 = declarations(inFile).filter(eligible);
22951
+ [...byPath].map(async ([path17, inFile]) => {
22952
+ const found2 = declarations(inFile).filter(
22953
+ (item) => KINDS.has(item.kind) && (long(item) ? longAdded : shortNames.has(item.qualifiedName))
22954
+ );
22607
22955
  if (!found2.length) return;
22608
- const text = await read(path16);
22956
+ const text = await read(path17);
22609
22957
  if (text === void 0) return;
22610
22958
  const lines = text.split("\n").map(lineWords);
22611
22959
  for (const declaration of found2) {
22960
+ if (!long(declaration)) {
22961
+ const key = `${declaration.qualifiedName}\0${copyText(text.slice(declaration.start, declaration.end))}`;
22962
+ shortCopies.set(key, [...shortCopies.get(key) ?? [], declaration]);
22963
+ continue;
22964
+ }
22612
22965
  const words = /* @__PURE__ */ new Map();
22613
22966
  for (const line of lines.slice(declaration.startLine - 1, declaration.endLine))
22614
22967
  for (const word of line) words.set(word, (words.get(word) ?? 0) + 1);
@@ -22646,7 +22999,22 @@ async function similarCode(store, working, base, files, read) {
22646
22999
  kind: row.kind,
22647
23000
  anchor: { startLine: row.startLine, endLine: row.endLine }
22648
23001
  });
23002
+ const linkedTo = (declaration) => {
23003
+ const scope = graph.scope(declaration.id).refs;
23004
+ return /* @__PURE__ */ new Set([
23005
+ ...graph.relationsFrom(scope).flatMap((relation) => relation.to ? [graph.owner(relation.to)] : []),
23006
+ ...graph.relationsTo(scope).map((relation) => graph.owner(relation.from))
23007
+ ]);
23008
+ };
22649
23009
  const found = [];
23010
+ const add = (declaration, best, others, score) => found.push({
23011
+ path: declaration.path,
23012
+ name: declaration.qualifiedName,
23013
+ label: label(declaration),
23014
+ like: { path: best.path, name: best.qualifiedName, label: label(best) },
23015
+ others,
23016
+ score
23017
+ });
22650
23018
  for (const item of all) {
22651
23019
  const declaration = item.declaration;
22652
23020
  if (!added.has(declaration.id)) continue;
@@ -22662,32 +23030,65 @@ async function similarCode(store, working, base, files, read) {
22662
23030
  return score >= (siblings ? SIBLINGS_ALIKE : ALIKE);
22663
23031
  }).sort(([, left], [, right]) => right - left);
22664
23032
  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
- ]);
23033
+ const linked = linkedTo(declaration);
22670
23034
  const unlinked = alike.filter(([other]) => !linked.has(other.declaration.id));
22671
23035
  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
- });
23036
+ if (best) add(declaration, best[0].declaration, unlinked.length - 1, best[1]);
23037
+ }
23038
+ for (const copies of shortCopies.values()) {
23039
+ const existing = copies.filter((copy) => !added.has(copy.id)).sort((left, right) => left.path < right.path ? -1 : 1);
23040
+ if (!existing.length || existing.length > SHORT_COPIES) continue;
23041
+ for (const declaration of copies) {
23042
+ if (!added.has(declaration.id)) continue;
23043
+ const linked = linkedTo(declaration);
23044
+ const unlinked = existing.filter((copy) => !linked.has(copy.id));
23045
+ const best = unlinked[0];
23046
+ if (best) add(declaration, best, unlinked.length - 1, 1);
23047
+ }
22685
23048
  }
22686
23049
  return found.sort(
22687
23050
  (left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0) || right.score - left.score
22688
23051
  ).map(({ score: _score, ...similar }) => similar);
22689
23052
  }
22690
23053
 
23054
+ // src/project-map-shapes.ts
23055
+ var KINDS2 = /* @__PURE__ */ new Set(["PROPERTY", "TYPE", "INTERFACE", "ENUM"]);
23056
+ var READ_MS = 2e4;
23057
+ var mapIsShape = (object2) => KINDS2.has(object2.kind) && object2.execution !== "CLOSURE";
23058
+ var mapShapeDeadline = () => Date.now() + READ_MS;
23059
+ var MapShapeUses = class {
23060
+ constructor(graph, reader, until) {
23061
+ this.graph = graph;
23062
+ this.reader = reader;
23063
+ this.until = until;
23064
+ }
23065
+ graph;
23066
+ reader;
23067
+ until;
23068
+ /** Each field or type read, with each of its uses in the declarations outside it. */
23069
+ uses = /* @__PURE__ */ new Map();
23070
+ /** Those whose uses could not all be read, or that the deadline left out. */
23071
+ unread = /* @__PURE__ */ new Set();
23072
+ async read(refs) {
23073
+ const wanted = [...new Set(refs)].filter(
23074
+ (ref) => mapIsShape(this.graph.object(ref)) && !this.uses.has(ref) && !this.unread.has(ref)
23075
+ );
23076
+ if (!wanted.length) return;
23077
+ const found = Date.now() > this.until ? /* @__PURE__ */ new Map() : await this.reader(wanted, this.until);
23078
+ for (const ref of wanted) {
23079
+ const read = found.get(ref);
23080
+ if (!read?.complete) this.unread.add(ref);
23081
+ if (!read) continue;
23082
+ const outside = [];
23083
+ for (const use of read.uses) {
23084
+ const owner = this.graph.owner(use.owner);
23085
+ if (owner !== ref) outside.push({ ...use, owner });
23086
+ }
23087
+ this.uses.set(ref, outside);
23088
+ }
23089
+ }
23090
+ };
23091
+
22691
23092
  // src/project-map-changes.ts
22692
23093
  var git = new GitRunner();
22693
23094
  var gitOptions = (cwd, signal) => ({
@@ -22739,9 +23140,9 @@ async function readMapChanges(project, base, signal) {
22739
23140
  ...file2,
22740
23141
  baseText: (await git.run(["show", `${commit}:${file2.basePath}`], gitOptions(project, signal))).stdout.toString("utf8")
22741
23142
  };
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 });
23143
+ const untracked = (await git.run(["ls-files", "--others", "--exclude-standard", "-z"], gitOptions(project, signal))).stdout.toString("utf8").split("\0").filter((path17) => path17 && !inExcludedDirectory(path17));
23144
+ for (const path17 of untracked)
23145
+ files.push({ path: path17, status: "ADDED", lines: [EVERYTHING], baseLines: [], binary: false });
22745
23146
  const stranded = await strandedNames(
22746
23147
  project,
22747
23148
  diff,
@@ -22819,8 +23220,14 @@ var NON_CODE = [
22819
23220
  [/(?:^|\/)\.env[^/]*$|\.(?:ya?ml|toml|ini|properties|conf|cfg)$/iu, "configuration"],
22820
23221
  [/\.(?:html?|jinja2?|j2|hbs|ejs|tmpl|tpl|gohtml|vue|svelte|wxml)$/iu, "template"]
22821
23222
  ];
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 });
23223
+ var nonCodeKind = (path17) => NON_CODE.find(([pattern]) => pattern.test(path17))?.[1];
23224
+ var LIMITS = Object.freeze({
23225
+ depth: 8,
23226
+ declarations: 800,
23227
+ changed: 200,
23228
+ chain: 3,
23229
+ byName: 40
23230
+ });
22824
23231
  var CALLER_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES"]);
22825
23232
  var NAMING_KINDS = /* @__PURE__ */ new Set(["CALLS", "REFERENCES", "EXTENDS", "IMPLEMENTS"]);
22826
23233
  var USED_BY = {
@@ -22828,16 +23235,25 @@ var USED_BY = {
22828
23235
  IMPLEMENTS: "implemented",
22829
23236
  OVERRIDES: "overridden"
22830
23237
  };
23238
+ var runsTarget = (relation) => CALLER_KINDS.has(relation.kind) && !relation.event;
22831
23239
  var IMPORT_KINDS3 = /* @__PURE__ */ new Set(["IMPORTS", "TEST_IMPORTS"]);
22832
23240
  var ROUTE2 = /^(?:[A-Z]+(?:\|[A-Z]+)* +)?\/\S*$/u;
23241
+ var callerFrom = (ref, relation, certain) => ({
23242
+ ref,
23243
+ anchor: relation.anchor,
23244
+ ...relation.argument ? { argument: relation.argument } : {},
23245
+ certain
23246
+ });
22833
23247
  var areaOf = (file2) => /\.(?:go|java|kt)$/u.test(file2) ? file2.slice(0, file2.lastIndexOf("/") + 1) || "./" : file2;
22834
23248
  var Tracer = class {
22835
- constructor(graph, memberCalls) {
23249
+ constructor(graph, memberCalls, shapes) {
22836
23250
  this.graph = graph;
22837
23251
  this.memberCalls = memberCalls;
23252
+ this.shapes = shapes;
22838
23253
  }
22839
23254
  graph;
22840
23255
  memberCalls;
23256
+ shapes;
22841
23257
  reached = /* @__PURE__ */ new Map();
22842
23258
  entries = /* @__PURE__ */ new Map();
22843
23259
  tests = /* @__PURE__ */ new Map();
@@ -22846,6 +23262,7 @@ var Tracer = class {
22846
23262
  unclear = [];
22847
23263
  truncated = false;
22848
23264
  callerCount = /* @__PURE__ */ new Map();
23265
+ owners = /* @__PURE__ */ new Set();
22849
23266
  known = /* @__PURE__ */ new Map();
22850
23267
  // Declarations a decorator maps to a route: entry points already, never "top of a chain".
22851
23268
  routes = /* @__PURE__ */ new Set();
@@ -22853,24 +23270,50 @@ var Tracer = class {
22853
23270
  handlers = /* @__PURE__ */ new Map();
22854
23271
  /** Test support files that call the changed code; the tests beside and below them may use it. */
22855
23272
  support = /* @__PURE__ */ new Set();
22856
- name = (ref) => this.graph.qualifiedName(ref);
23273
+ // The trace walks the declarations relations name, closures and locals among them; a reader sees
23274
+ // the addressable declaration around each.
23275
+ name = (ref) => this.graph.qualifiedName(this.graph.owner(ref));
22857
23276
  // A module is named by its path alone.
22858
23277
  where = (ref) => {
22859
- const object2 = this.graph.object(ref);
23278
+ const object2 = this.graph.object(this.graph.owner(ref));
22860
23279
  return mapIsModule(object2) ? object2.anchor.path : `${object2.anchor.path}: ${this.name(ref)}`;
22861
23280
  };
22862
- /** Follows callers up from the given declarations, recording entry points and tests. */
22863
- trace(starts) {
23281
+ /**
23282
+ * Follows callers up from the given declarations, recording entry points and tests. The code of
23283
+ * one in own may flow into its members: the map keeps no reads of its locals, so they may be
23284
+ * affected, unlike what calls it.
23285
+ */
23286
+ async trace(starts, own = []) {
22864
23287
  let frontier = [];
22865
23288
  for (const ref of starts)
22866
23289
  if (!this.reached.has(ref)) {
22867
- const start = { ref, depth: 0, certain: true };
23290
+ const start = { ref, depth: 0, certain: true, shaped: true };
22868
23291
  this.reached.set(ref, start);
23292
+ this.owners.add(this.graph.owner(ref));
22869
23293
  frontier.push(start);
22870
23294
  }
22871
- for (const start of frontier) this.byName(start.ref);
22872
- while (frontier.length) {
23295
+ for (const start of frontier)
23296
+ for (const ref of /* @__PURE__ */ new Set([start.ref, this.graph.owner(start.ref)])) this.byName(ref);
23297
+ const uncertain = [];
23298
+ for (const ref of own) {
23299
+ const current = this.reached.get(ref);
23300
+ if (current)
23301
+ for (const member of this.members(ref))
23302
+ uncertain.push({
23303
+ current,
23304
+ caller: { ref: member, anchor: this.graph.object(member).anchor, certain: false }
23305
+ });
23306
+ }
23307
+ while (frontier.length || uncertain.length) {
23308
+ if (!frontier.length)
23309
+ frontier = uncertain.splice(0).flatMap(({ current, caller }) => this.step(current, caller, false));
22873
23310
  const next = [];
23311
+ await this.shapes.read(
23312
+ frontier.filter(({ ref, shaped }) => {
23313
+ const object2 = this.graph.object(ref);
23314
+ return this.graph.isAddressable(object2) && !testCode(object2.anchor.path) && (shaped || object2.kind === "PROPERTY");
23315
+ }).map(({ ref }) => ref)
23316
+ );
22874
23317
  for (const current of frontier) {
22875
23318
  const object2 = this.graph.object(current.ref);
22876
23319
  if (testCode(object2.anchor.path)) continue;
@@ -22878,10 +23321,10 @@ var Tracer = class {
22878
23321
  const callers = this.callers(current.ref);
22879
23322
  this.callerCount.set(current.ref, callers.length);
22880
23323
  for (const caller of callers) {
22881
- const site = `${caller.relation.anchor.path}:${caller.relation.anchor.startLine}`;
23324
+ const site = `${caller.anchor.path}:${caller.anchor.startLine}`;
22882
23325
  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);
23326
+ if (caller.argument && ROUTE2.test(caller.argument))
23327
+ this.entry(caller.argument, true, current, site, certain);
22885
23328
  const callerObject = this.graph.object(caller.ref);
22886
23329
  if (testCode(callerObject.anchor.path)) {
22887
23330
  if (!mapRunnableTest(callerObject.anchor.path))
@@ -22889,7 +23332,7 @@ var Tracer = class {
22889
23332
  this.test(
22890
23333
  callerObject.anchor.path,
22891
23334
  this.name(caller.ref),
22892
- `calls ${this.name(current.ref)}`,
23335
+ `${caller.uses ? "uses" : "calls"} ${this.name(current.ref)}`,
22893
23336
  // Tests closer to the change come first; all of them rank before other relations.
22894
23337
  current.depth / 10
22895
23338
  );
@@ -22897,14 +23340,8 @@ var Tracer = class {
22897
23340
  this.area(current.ref, callerObject.anchor.path, this.name(caller.ref));
22898
23341
  continue;
22899
23342
  }
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);
23343
+ if (certain) next.push(...this.step(current, caller, true));
23344
+ else uncertain.push({ current, caller });
22908
23345
  }
22909
23346
  }
22910
23347
  frontier = next;
@@ -22920,28 +23357,115 @@ var Tracer = class {
22920
23357
  this.test(
22921
23358
  call.path,
22922
23359
  this.name(this.graph.owner(call.from)),
22923
- `may call ${this.name(reached.ref)} through a receiver of unknown type`,
23360
+ `may call ${this.graph.qualifiedName(reached.ref)} through a receiver of unknown type`,
22924
23361
  3.5
22925
23362
  );
22926
23363
  }
22927
23364
  for (const reached of this.reached.values()) {
22928
- if (this.callerCount.get(reached.ref) !== 0) continue;
23365
+ if (this.callerCount.get(reached.ref) !== 0 || this.shapes.unread.has(reached.ref)) continue;
22929
23366
  const object2 = this.graph.object(reached.ref);
22930
23367
  if (testCode(object2.anchor.path) || this.routes.has(reached.ref)) continue;
22931
23368
  if (reached.depth === 0 && !mapMiniprogramTemplate(object2.anchor.path)) {
22932
23369
  const uses = this.usesWithoutCalls(reached.ref);
22933
23370
  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`
23371
+ 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
23372
  );
22936
- } else this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
23373
+ } else if (!mapIsShape(object2) || !reached.used && object2.kind === "PROPERTY")
23374
+ this.entry(this.where(reached.ref), false, reached, void 0, reached.certain, true);
23375
+ }
23376
+ }
23377
+ step(current, caller, certain) {
23378
+ const known = this.reached.get(caller.ref);
23379
+ if (known) {
23380
+ if (!caller.uses) known.used = false;
23381
+ if (!caller.uses || !current.shaped || known.shaped) return [];
23382
+ known.shaped = true;
23383
+ this.known.delete(caller.ref);
23384
+ return [known];
23385
+ }
23386
+ const depth = this.climb(current.ref, caller.ref, current.depth, this.owners);
23387
+ if (depth === void 0) {
23388
+ this.truncated = true;
23389
+ return [];
23390
+ }
23391
+ const reached = {
23392
+ ref: caller.ref,
23393
+ depth,
23394
+ certain,
23395
+ via: current.ref,
23396
+ ...caller.uses ? { used: true, ...current.shaped ? { shaped: true } : {} } : {}
23397
+ };
23398
+ this.reached.set(caller.ref, reached);
23399
+ return [reached];
23400
+ }
23401
+ // The depth of a step from one declaration to another, unless it passes the trace's limits. The
23402
+ // limits count what a reader sees: moving between the locals of one declaration climbs nothing.
23403
+ climb(from, to, depth, owners) {
23404
+ const owner = this.graph.owner(to);
23405
+ const next = depth + (owner === this.graph.owner(from) ? 0 : 1);
23406
+ if (next > LIMITS.depth || !owners.has(owner) && owners.size >= LIMITS.declarations)
23407
+ return void 0;
23408
+ owners.add(owner);
23409
+ return next;
23410
+ }
23411
+ // Whether a relation starts in the declaration, not in an addressable declaration inside it.
23412
+ within(from, ref) {
23413
+ for (let at = from; at !== void 0; at = this.graph.parent(at)) {
23414
+ if (at === ref) return true;
23415
+ if (this.graph.isAddressable(this.graph.object(at))) return false;
22937
23416
  }
23417
+ return false;
23418
+ }
23419
+ /**
23420
+ * The locals of a declaration that code outside it calls, as the methods of the object a factory
23421
+ * returns. Fields and types are read by name, not called, so they have none.
23422
+ */
23423
+ members(ref) {
23424
+ const object2 = this.graph.object(ref);
23425
+ if (mapIsModule(object2) || mapIsShape(object2)) return [];
23426
+ return this.graph.scope(ref).refs.slice(1).filter(
23427
+ (local) => this.callers(local).some((caller) => this.graph.owner(caller.ref) !== ref)
23428
+ );
23429
+ }
23430
+ /**
23431
+ * Where a change on the lines of a declaration is followed from: the innermost local around each
23432
+ * line that runs apart from it, as a function does or as what others call does, and the declaration
23433
+ * itself for lines in none. Fields and types change as a whole.
23434
+ */
23435
+ startsAt(ref, lines) {
23436
+ const object2 = this.graph.object(ref);
23437
+ if (mapIsModule(object2) || mapIsShape(object2)) return { refs: [ref], own: [] };
23438
+ 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));
23439
+ const refs = /* @__PURE__ */ new Set();
23440
+ let own = false;
23441
+ const at = (from, to) => {
23442
+ const around = locals.filter(
23443
+ (local) => local.anchor.startLine <= to && from <= local.anchor.endLine
23444
+ );
23445
+ for (const local of around)
23446
+ if (!around.some(
23447
+ (other) => other !== local && local.anchor.start <= other.anchor.start && other.anchor.end <= local.anchor.end
23448
+ ))
23449
+ refs.add(local.id);
23450
+ if (!around.length) own = true;
23451
+ };
23452
+ for (const [from, to] of lines) {
23453
+ if (from > to) {
23454
+ if (object2.anchor.startLine <= to && from <= object2.anchor.endLine) at(from, to);
23455
+ continue;
23456
+ }
23457
+ const last = Math.min(to, object2.anchor.endLine);
23458
+ for (let line = Math.max(from, object2.anchor.startLine); line <= last; line++) at(line, line);
23459
+ }
23460
+ if (own) refs.add(ref);
23461
+ return { refs: [...refs], own: own ? [ref] : [] };
22938
23462
  }
22939
23463
  /**
22940
23464
  * The uses outside tests the map sees of a declaration besides calls: a class others extend or
22941
23465
  * implement, a member that overrides another or that others override, and a decorator that may
22942
23466
  * 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.
23467
+ * (dataclass, staticmethod) only shapes the declaration. Reading a value of module state is a
23468
+ * reference, so a caller; writing one is not a use, as a value nothing reads is unused.
22945
23469
  */
22946
23470
  usesWithoutCalls(ref) {
22947
23471
  const uses = [];
@@ -22970,10 +23494,11 @@ var Tracer = class {
22970
23494
  reach(refs, files, handlers) {
22971
23495
  const how = /* @__PURE__ */ new Map();
22972
23496
  const below = /* @__PURE__ */ new Map();
22973
- const seen = new Set(refs);
23497
+ const depths = new Map(refs.map((ref) => [ref, 0]));
23498
+ const owners = new Set(refs.map((ref) => this.graph.owner(ref)));
22974
23499
  let truncated = false;
22975
- let frontier = [...seen];
22976
- for (let depth = 0; frontier.length; depth++) {
23500
+ let frontier = [...depths.keys()];
23501
+ while (frontier.length) {
22977
23502
  const next = [];
22978
23503
  for (const current of frontier) {
22979
23504
  if (handlers.has(current)) how.set(current, "route");
@@ -22985,12 +23510,13 @@ var Tracer = class {
22985
23510
  const callees = below.get(caller.ref);
22986
23511
  if (callees) callees.push(current);
22987
23512
  else below.set(caller.ref, [current]);
22988
- if (seen.has(caller.ref)) continue;
22989
- if (depth + 1 > LIMITS.depth || seen.size >= LIMITS.declarations) {
23513
+ if (depths.has(caller.ref)) continue;
23514
+ const depth = this.climb(current, caller.ref, depths.get(current) ?? 0, owners);
23515
+ if (depth === void 0) {
22990
23516
  truncated = true;
22991
23517
  continue;
22992
23518
  }
22993
- seen.add(caller.ref);
23519
+ depths.set(caller.ref, depth);
22994
23520
  next.push(caller.ref);
22995
23521
  }
22996
23522
  }
@@ -23012,43 +23538,47 @@ var Tracer = class {
23012
23538
  if (known) return known;
23013
23539
  const callers = [];
23014
23540
  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
- }
23541
+ if (runsTarget(relation) && !this.within(relation.from, ref))
23542
+ callers.push(callerFrom(relation.from, relation, true));
23543
+ for (const use of this.shapes.uses.get(ref) ?? [])
23544
+ callers.push({ ref: use.owner, anchor: use.anchor, certain: false, uses: true });
23019
23545
  const object2 = this.graph.object(ref);
23020
23546
  const parent = this.graph.parent(ref);
23021
23547
  const constructs = object2.execution === "CONSTRUCTOR" || object2.name === "__init__" || object2.name === "constructor";
23022
23548
  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(
23549
+ const implicit = constructs || /^__\w+__$/u.test(object2.name) || this.graph.relationsFrom([ref]).some(
23024
23550
  (relation) => relation.kind === "DECORATED_BY" && /property$/u.test(relation.target)
23025
23551
  );
23026
23552
  if (implicit) {
23027
23553
  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
- }
23554
+ if (runsTarget(relation) && !this.within(relation.from, ref) && !this.within(relation.from, parent))
23555
+ callers.push(
23556
+ callerFrom(relation.from, relation, constructs && relation.kind === "CALLS")
23557
+ );
23037
23558
  }
23038
23559
  }
23560
+ const local = !this.graph.isAddressable(object2);
23039
23561
  if (!constructs) {
23040
23562
  for (const override of this.graph.relationsFrom([ref]))
23041
23563
  if (override.kind === "OVERRIDES" && override.to !== void 0) {
23042
23564
  const contract = override.to;
23043
23565
  const relations = this.graph.relationsTo([contract]);
23044
- const only = relations.filter((relation) => relation.kind === "OVERRIDES").length === 1;
23566
+ const only = relations.filter(
23567
+ (relation) => relation.kind === "OVERRIDES" && !(local && testCode(relation.anchor.path))
23568
+ ).length === 1;
23569
+ if (local && !only) continue;
23045
23570
  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
- }
23571
+ if (runsTarget(relation) && !this.within(relation.from, ref))
23572
+ callers.push(callerFrom(relation.from, relation, only));
23050
23573
  }
23051
23574
  }
23575
+ if (parent && local && callers.every((caller) => testCode(this.graph.object(caller.ref).anchor.path)))
23576
+ callers.push({
23577
+ ref: parent,
23578
+ anchor: object2.anchor,
23579
+ certain: callers.length === 0,
23580
+ holds: true
23581
+ });
23052
23582
  this.known.set(ref, callers);
23053
23583
  return callers;
23054
23584
  }
@@ -23075,15 +23605,18 @@ var Tracer = class {
23075
23605
  const calls = this.memberCalls.get(`${language}\0${object2.name}`) ?? [];
23076
23606
  if (calls.length)
23077
23607
  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`
23608
+ `${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
23609
  );
23080
23610
  }
23081
23611
  entry(label, route, at, site, certain, top = false) {
23082
23612
  if (route) this.handlers.set(label, (this.handlers.get(label) ?? /* @__PURE__ */ new Set()).add(at.ref));
23083
23613
  const chain = [];
23084
- let step = !top ? at : at.via ? this.reached.get(at.via) : void 0;
23614
+ let shown = top ? this.graph.owner(at.ref) : void 0;
23615
+ let step = at;
23085
23616
  for (; step && chain.length < LIMITS.chain; ) {
23086
- chain.push(this.name(step.ref));
23617
+ const owner = this.graph.owner(step.ref);
23618
+ if (owner !== shown) chain.push(this.name(owner));
23619
+ shown = owner;
23087
23620
  step = step.via ? this.reached.get(step.via) : void 0;
23088
23621
  }
23089
23622
  const known = this.entries.get(label);
@@ -23100,35 +23633,35 @@ var Tracer = class {
23100
23633
  this.areas.set(area, known);
23101
23634
  }
23102
23635
  /** 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 };
23636
+ test(path17, name, why, rank2) {
23637
+ if (!mapRunnableTest(path17)) return;
23638
+ const known = this.tests.get(path17) ?? { names: /* @__PURE__ */ new Set(), why, rank: rank2 };
23106
23639
  if (rank2 < known.rank) Object.assign(known, { why, rank: rank2 });
23107
23640
  if (name && !name.startsWith("<")) known.names.add(name);
23108
- this.tests.set(path16, known);
23641
+ this.tests.set(path17, known);
23109
23642
  }
23110
23643
  };
23111
23644
  var mapRunnableTest = (file2) => /_test\.(?:go|py)$|(?:^|\/)test_[^/]*\.py$|\.(?:test|spec)\.[cm]?[jt]sx?$|(?:Test|Tests|IT)\.(?:java|kt)$/u.test(
23112
23645
  file2
23113
23646
  );
23114
23647
  var renamedTemplate = (file2) => file2.status === "RENAMED" && file2.basePath !== void 0 && mapMiniprogramTemplate(file2.basePath);
23115
- function mapChangeImpact(store, working, base, changes, project, tests) {
23648
+ async function mapChangeImpact(store, working, base, changes, shapes, until, project, tests) {
23116
23649
  const graph = new MapViewGraph(store, working);
23117
23650
  const cache = new MapViewCache();
23118
23651
  const memberCalls = cache.memberCalls(store, working);
23119
- const tracer = new Tracer(graph, memberCalls);
23652
+ const tracer = new Tracer(graph, memberCalls, new MapShapeUses(graph, shapes.working, until));
23120
23653
  const changed = [];
23121
23654
  const unclear = [];
23122
23655
  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);
23656
+ const declarations2 = (g, path17) => g.objectsAt(path17).filter((object2) => !mapIsModule(object2) && g.isAddressable(object2));
23657
+ const units = (g, path17) => mapMiniprogramTemplate(path17) ? g.objectsAt(path17).filter((object2) => mapIsModule(object2) && object2.parsing === "PARSED") : declarations2(g, path17);
23125
23658
  let changedCount = 0;
23126
23659
  const starts = [];
23127
23660
  const importers = /* @__PURE__ */ new Map();
23128
23661
  let mapped;
23129
23662
  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)`;
23663
+ const topLevelChanged = (path17) => {
23664
+ const note = `top-level code of ${path17} changed (imports, constants or registrations)`;
23132
23665
  if (!unclear.includes(note)) unclear.push(note);
23133
23666
  };
23134
23667
  for (const file2 of changes.files) {
@@ -23167,7 +23700,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23167
23700
  changed.push(
23168
23701
  `${file2.path}${template ? " (template)" : `: ${graph.qualifiedName(ref)} ${mapDeclarationLabel(object2)}`}${file2.status === "ADDED" ? " (new file)" : ""}`
23169
23702
  );
23170
- starts.push(ref);
23703
+ starts.push(tracer.startsAt(ref, file2.lines));
23171
23704
  }
23172
23705
  for (const relation of graph.relationsFrom(objects2.map((object2) => object2.id)))
23173
23706
  if (relation.argument && ROUTE2.test(relation.argument) && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine))
@@ -23179,8 +23712,18 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23179
23712
  sameDirectoryTests(mappedPaths(), file2.path, tracer);
23180
23713
  mirroredTests(mappedPaths(), file2.path, tracer);
23181
23714
  }
23182
- tracer.trace(starts);
23183
- const untested = tests && untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests);
23715
+ await tracer.trace(
23716
+ starts.flatMap((start) => start.refs),
23717
+ starts.flatMap((start) => start.own)
23718
+ );
23719
+ const unread = [...tracer.shapes.unread];
23720
+ if (unread.length)
23721
+ unclear.push(
23722
+ `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(
23723
+ ", "
23724
+ )}${unread.length > LIST.names ? ", \u2026" : ""}); project_find_references lists their uses`
23725
+ );
23726
+ const untested = tests && await untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests);
23184
23727
  if (project) routeTests(project, store, working, [...tracer.entries.values()], tracer);
23185
23728
  supportTests(store, working, tracer);
23186
23729
  const rewrittenTests = [];
@@ -23202,7 +23745,11 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23202
23745
  const names = existingTestsChanged(before, graph, file2, project);
23203
23746
  if (names.length) rewrittenTests.push({ path: file2.path, names });
23204
23747
  }
23205
- const beforeTracer = new Tracer(before, cache.memberCalls(store, base));
23748
+ const beforeTracer = new Tracer(
23749
+ before,
23750
+ cache.memberCalls(store, base),
23751
+ new MapShapeUses(before, shapes.base, until)
23752
+ );
23206
23753
  const changedIn = new Map(
23207
23754
  changes.files.flatMap((file2) => file2.basePath ? [[file2.basePath, file2]] : [])
23208
23755
  );
@@ -23221,6 +23768,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23221
23768
  );
23222
23769
  };
23223
23770
  const gone = [];
23771
+ const goneShapes = [];
23224
23772
  for (const file2 of changes.files) {
23225
23773
  if (!file2.basePath || file2.binary || testCode(file2.basePath)) continue;
23226
23774
  const renamed = renamedTemplate(file2);
@@ -23252,12 +23800,40 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23252
23800
  mapIsModule(user) ? `${user.anchor.path}${mapMiniprogramTemplate(user.anchor.path) ? " (template)" : ": top-level code"}` : `${user.anchor.path}: ${before.qualifiedName(owner)}`
23253
23801
  );
23254
23802
  }
23803
+ goneShapes.push({
23804
+ shapes: mapIsShape(object2) ? [object2.id] : before.objectsAt(file2.basePath).filter((member) => inside(member.id) && mapIsShape(member)).map((member) => member.id),
23805
+ inside,
23806
+ usedBy
23807
+ });
23255
23808
  removed.push({
23256
23809
  declaration: mapIsModule(object2) ? `${file2.basePath} (template)` : `${file2.basePath}: ${before.qualifiedName(object2.id)} ${mapDeclarationLabel(object2)}`,
23257
- usedBy: [...usedBy].sort()
23810
+ usedBy
23258
23811
  });
23259
23812
  }
23260
23813
  }
23814
+ await beforeTracer.shapes.read(goneShapes.flatMap((item) => item.shapes));
23815
+ const nowDeclared = new Set(
23816
+ changes.files.flatMap(
23817
+ (file2) => file2.status === "DELETED" ? [] : graph.objectsAt(file2.path).map((object2) => same2(graph, object2.id))
23818
+ )
23819
+ );
23820
+ for (const { shapes: inRemoved, inside, usedBy } of goneShapes)
23821
+ for (const shape of inRemoved) {
23822
+ if (nowDeclared.has(same2(before, shape))) continue;
23823
+ if (beforeTracer.shapes.unread.has(shape))
23824
+ unclear.push(
23825
+ `${before.object(shape).anchor.path}: ${before.qualifiedName(shape)} was removed, and who used it was not read; search the code for its name`
23826
+ );
23827
+ for (const { owner, anchor } of beforeTracer.shapes.uses.get(shape) ?? []) {
23828
+ const file2 = changedIn.get(anchor.path);
23829
+ if (inside(owner) || file2 && (file2.status === "DELETED" || overlaps(file2.baseLines, anchor.startLine, anchor.endLine)))
23830
+ continue;
23831
+ const user = before.object(owner);
23832
+ usedBy.add(
23833
+ mapIsModule(user) ? `${user.anchor.path}: top-level code` : `${user.anchor.path}: ${before.qualifiedName(owner)}`
23834
+ );
23835
+ }
23836
+ }
23261
23837
  const removedAt = (ref) => {
23262
23838
  for (let at = ref; at !== void 0; at = before.parent(at))
23263
23839
  if (gone.includes(at)) return true;
@@ -23265,13 +23841,13 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23265
23841
  };
23266
23842
  const lost = /* @__PURE__ */ new Map();
23267
23843
  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));
23844
+ for (const path17 of mappedPaths().filter(mapMiniprogramTemplate)) {
23845
+ const template = graph.objectsAt(path17).find((object2) => mapIsModule(object2));
23270
23846
  if (!template) continue;
23271
23847
  const broken = graph.relationsFrom(graph.scope(template.id).refs).filter((relation) => relation.to === void 0 && NAMING_KINDS.has(relation.kind));
23272
23848
  if (!broken.length) continue;
23273
- const file2 = changedAt.get(path16);
23274
- const basePath = file2 ? file2.basePath : path16;
23849
+ const file2 = changedAt.get(path17);
23850
+ const basePath = file2 ? file2.basePath : path17;
23275
23851
  const was = basePath === void 0 ? void 0 : before.objectsAt(basePath).find(mapIsModule);
23276
23852
  const links = was ? before.relationsFrom(before.scope(was.id).refs) : [];
23277
23853
  for (const relation of broken) {
@@ -23280,7 +23856,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23280
23856
  );
23281
23857
  if (earlier.some((link) => link.to === void 0)) continue;
23282
23858
  const event = miniprogramEventOf(relation.target);
23283
- const at = `${path16}:${relation.anchor.startLine}`;
23859
+ const at = `${path17}:${relation.anchor.startLine}`;
23284
23860
  if (file2 && overlaps(file2.lines, relation.anchor.startLine, relation.anchor.endLine)) {
23285
23861
  unclear.push(
23286
23862
  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 +23868,11 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23292
23868
  const object2 = before.object(reached);
23293
23869
  const name = mapIsModule(object2) ? `${object2.anchor.path} (template)${event ? `: ${event.event} event` : ""}` : `${object2.anchor.path}: ${before.qualifiedName(reached)} ${mapDeclarationLabel(object2)}`;
23294
23870
  const users = lost.get(name) ?? /* @__PURE__ */ new Set();
23295
- users.add(`${path16} (template)`);
23871
+ users.add(`${path17} (template)`);
23296
23872
  lost.set(name, users);
23297
23873
  }
23298
23874
  }
23299
- for (const [declaration, users] of lost)
23300
- removed.push({ declaration, usedBy: [...users].sort() });
23875
+ for (const [declaration, users] of lost) removed.push({ declaration, usedBy: users });
23301
23876
  for (const file2 of changes.files) {
23302
23877
  if (!file2.basePath || file2.status === "DELETED" || testCode(file2.basePath)) continue;
23303
23878
  const module = before.objectsAt(file2.basePath).find(mapIsModule);
@@ -23307,21 +23882,21 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23307
23882
  topLevelChanged(file2.path);
23308
23883
  }
23309
23884
  if (gone.length) {
23310
- beforeTracer.trace(gone);
23885
+ await beforeTracer.trace(gone, gone);
23311
23886
  for (const entry of beforeTracer.entries.values())
23312
23887
  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);
23888
+ for (const [path17, test] of beforeTracer.tests) {
23889
+ const known = tracer.tests.get(path17);
23315
23890
  if (known) for (const name of test.names) known.names.add(name);
23316
- else tracer.tests.set(path16, test);
23891
+ else tracer.tests.set(path17, test);
23317
23892
  }
23318
23893
  for (const [area, known] of beforeTracer.areas) {
23319
23894
  const now = tracer.areas.get(area);
23320
23895
  if (!now) tracer.areas.set(area, known);
23321
23896
  else {
23322
23897
  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]));
23898
+ for (const [path17, names] of known.tests)
23899
+ now.tests.set(path17, /* @__PURE__ */ new Set([...now.tests.get(path17) ?? [], ...names]));
23325
23900
  }
23326
23901
  }
23327
23902
  unclear.push(...beforeTracer.unclear.filter((line) => !line.includes("has no callers")));
@@ -23343,32 +23918,50 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23343
23918
  called.add(before.owner(relation.to));
23344
23919
  }
23345
23920
  const outsideTests = (callers, g) => callers.filter((caller) => !testCode(g.object(caller.ref).anchor.path));
23921
+ const candidates = [];
23346
23922
  for (const ref of called) {
23347
23923
  const object2 = before.object(ref);
23348
23924
  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;
23925
+ const path17 = moved.has(object2.anchor.path) ? moved.get(object2.anchor.path) : object2.anchor.path;
23926
+ if (path17 === void 0) continue;
23351
23927
  const name = before.qualifiedName(ref);
23352
- const now = declarations2(graph, path16).find(
23928
+ const now = declarations2(graph, path17).find(
23353
23929
  (candidate) => candidate.kind === object2.kind && graph.qualifiedName(candidate.id) === name
23354
23930
  );
23355
- if (!now || outsideTests(tracer.callers(now.id), graph).length || tracer.usesWithoutCalls(now.id).length)
23356
- continue;
23931
+ if (!now) continue;
23932
+ const calls = tracer.callers(now.id).filter((caller) => !caller.uses);
23933
+ if (outsideTests(calls, graph).length || tracer.usesWithoutCalls(now.id).length) continue;
23357
23934
  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
- );
23935
+ candidates.push({ path: path17, name, now, tested: calls.length > 0 });
23936
+ }
23937
+ await tracer.shapes.read(candidates.map(({ now }) => now.id));
23938
+ const unknown2 = [];
23939
+ for (const { path: path17, name, now, tested } of candidates) {
23940
+ if (tracer.shapes.unread.has(now.id)) unknown2.push(name);
23941
+ else if (!tracer.shapes.uses.get(now.id)?.some(({ owner, write }) => !write && !testCode(graph.object(owner).anchor.path))) {
23942
+ uncalled.push(
23943
+ `${path17}: ${name} ${mapDeclarationLabel(now)}${tested ? " (only tests call it now)" : ""}`
23944
+ );
23945
+ }
23362
23946
  }
23363
23947
  uncalled.sort();
23948
+ if (unknown2.length)
23949
+ unclear.push(
23950
+ `${unknown2.length} fields lost callers the diff removed, and whether others use them was not read (${unknown2.sort().slice(0, LIST.names).join(
23951
+ ", "
23952
+ )}${unknown2.length > LIST.names ? ", \u2026" : ""}); project_find_references lists their uses`
23953
+ );
23364
23954
  }
23365
23955
  return {
23366
23956
  changed,
23367
- removed,
23957
+ removed: removed.map(({ declaration, usedBy }) => ({
23958
+ declaration,
23959
+ usedBy: [...usedBy].sort()
23960
+ })),
23368
23961
  rewrittenTests,
23369
23962
  entries: [...tracer.entries.values()].sort(entryOrder),
23370
- tests: [...tracer.tests].map(([path16, test]) => ({
23371
- path: path16,
23963
+ tests: [...tracer.tests].map(([path17, test]) => ({
23964
+ path: path17,
23372
23965
  names: [...test.names].sort(),
23373
23966
  why: test.why,
23374
23967
  rank: test.rank
@@ -23378,7 +23971,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23378
23971
  areas: [...tracer.areas].map(([area, known]) => ({
23379
23972
  area,
23380
23973
  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)
23974
+ tests: [...known.tests].map(([path17, names]) => ({ path: path17, names: [...names].sort() })).sort((left, right) => right.names.length - left.names.length)
23382
23975
  })).sort((left, right) => right.tests.length - left.tests.length),
23383
23976
  unclear: [.../* @__PURE__ */ new Set([...unclear, ...tracer.unclear])],
23384
23977
  removedRoutes,
@@ -23389,7 +23982,7 @@ function mapChangeImpact(store, working, base, changes, project, tests) {
23389
23982
  };
23390
23983
  }
23391
23984
  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) {
23985
+ async function untestedChanges(project, graph, tracer, memberCalls, starts, changed, tests) {
23393
23986
  const given = new Set(tests);
23394
23987
  const routes = /* @__PURE__ */ new Set();
23395
23988
  const handlers = /* @__PURE__ */ new Set();
@@ -23397,7 +23990,7 @@ function untestedChanges(project, graph, tracer, memberCalls, starts, changed, t
23397
23990
  for (const test of given) {
23398
23991
  let text;
23399
23992
  try {
23400
- text = readFileSync3(path10.join(project, test), "utf8");
23993
+ text = readFileSync4(path11.join(project, test), "utf8");
23401
23994
  } catch {
23402
23995
  continue;
23403
23996
  }
@@ -23408,16 +24001,24 @@ function untestedChanges(project, graph, tracer, memberCalls, starts, changed, t
23408
24001
  for (const ref of refs) handlers.add(ref);
23409
24002
  }
23410
24003
  }
23411
- const { how, truncated } = tracer.reach(starts, given, handlers);
24004
+ const { how, truncated } = tracer.reach(
24005
+ starts.flatMap((start) => start.refs),
24006
+ given,
24007
+ handlers
24008
+ );
23412
24009
  const unreached = [];
23413
24010
  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] ?? ""));
24011
+ for (const [at, start] of starts.entries()) {
24012
+ const found = start.refs.map((ref) => how.get(ref));
24013
+ if (found.includes("call")) continue;
24014
+ if (found.includes("route")) throughRoutes.push(changed[at] ?? "");
24015
+ else unreached.push(at);
24016
+ }
24017
+ const above = new Tracer(graph, memberCalls, tracer.shapes);
24018
+ await above.trace(
24019
+ unreached.flatMap((at) => starts[at]?.refs ?? []),
24020
+ unreached.flatMap((at) => starts[at]?.own ?? [])
24021
+ );
23421
24022
  return {
23422
24023
  changed: unreached.map((at) => changed[at] ?? ""),
23423
24024
  entries: [...above.entries.values()].sort(entryOrder),
@@ -23433,7 +24034,7 @@ function existingTestsChanged(before, after, file2, project) {
23433
24034
  let workingLines = [];
23434
24035
  if (file2.status !== "DELETED" && project)
23435
24036
  try {
23436
- workingLines = readFileSync3(path10.join(project, file2.path), "utf8").split("\n");
24037
+ workingLines = readFileSync4(path11.join(project, file2.path), "utf8").split("\n");
23437
24038
  } catch {
23438
24039
  }
23439
24040
  const key = (graph, object2) => `${object2.kind}\0${graph.qualifiedName(object2.id)}`;
@@ -23472,10 +24073,10 @@ function importerTests(graph, objects2, tracer, importers) {
23472
24073
  }
23473
24074
  const next = [];
23474
24075
  for (const imported of modules)
23475
- for (const { path: path16, module } of importers.get(imported) ?? [])
23476
- if (testCode(path16))
24076
+ for (const { path: path17, module } of importers.get(imported) ?? [])
24077
+ if (testCode(path17))
23477
24078
  tracer.test(
23478
- path16,
24079
+ path17,
23479
24080
  void 0,
23480
24081
  hop ? "imports a changed file indirectly" : "imports a changed file",
23481
24082
  hop ? 4 : 2
@@ -23523,7 +24124,7 @@ function routeTests(project, store, version2, entries, tracer) {
23523
24124
  if (!mapRunnableTest(candidate)) continue;
23524
24125
  let text;
23525
24126
  try {
23526
- text = readFileSync3(path10.join(project, candidate), "utf8");
24127
+ text = readFileSync4(path11.join(project, candidate), "utf8");
23527
24128
  } catch {
23528
24129
  continue;
23529
24130
  }
@@ -23541,9 +24142,9 @@ function routeTests(project, store, version2, entries, tracer) {
23541
24142
  }
23542
24143
  }
23543
24144
  }
23544
- function sameDirectoryTests(paths, path16, tracer) {
23545
- const slash = path16.lastIndexOf("/");
23546
- const directory = slash < 0 ? "" : path16.slice(0, slash + 1);
24145
+ function sameDirectoryTests(paths, path17, tracer) {
24146
+ const slash = path17.lastIndexOf("/");
24147
+ const directory = slash < 0 ? "" : path17.slice(0, slash + 1);
23547
24148
  for (const candidate of paths) {
23548
24149
  if (!candidate.startsWith(directory)) continue;
23549
24150
  if (candidate.slice(directory.length).includes("/") || !mapTestPath(candidate)) continue;
@@ -23574,9 +24175,9 @@ var LIST = Object.freeze({
23574
24175
  similar: 10,
23575
24176
  similarNames: 3
23576
24177
  });
23577
- function routesIn(graph, path16) {
24178
+ function routesIn(graph, path17) {
23578
24179
  const routes = /* @__PURE__ */ new Set();
23579
- for (const relation of graph.relationsFrom(graph.objectsAt(path16).map((object2) => object2.id))) {
24180
+ for (const relation of graph.relationsFrom(graph.objectsAt(path17).map((object2) => object2.id))) {
23580
24181
  const route = relation.kind === "DECORATED_BY" ? relation.route ?? relation.argument : relation.argument;
23581
24182
  if (route && ROUTE2.test(route)) routes.add(route);
23582
24183
  }
@@ -23594,7 +24195,37 @@ async function checkMapChanges(input, signal) {
23594
24195
  const base = changes.files.some(
23595
24196
  (file2) => file2.basePath !== void 0 && (file2.baseLines.length || file2.baseText !== void 0 || renamedTemplate(file2))
23596
24197
  ) ? await input.baseVersion(changes.commit, signal) : void 0;
23597
- const impact = mapChangeImpact(index.store, working, base, changes, project, input.tests);
24198
+ const usesIn = (version2, source) => async (refs, until2) => {
24199
+ const found = await index.findUses(
24200
+ { version: version2, source, refs, until: until2, maxResults: MAP_REFERENCES_MAX },
24201
+ signal
24202
+ );
24203
+ return new Map(
24204
+ [...found].map(([ref, { uses, complete }]) => [
24205
+ ref,
24206
+ {
24207
+ complete,
24208
+ uses: uses.flatMap(
24209
+ ({ kind, owner, anchor }) => owner && kind !== "IMPORT_EXPORT" ? [{ owner: owner.id, anchor, write: kind === "WRITE" }] : []
24210
+ )
24211
+ }
24212
+ ])
24213
+ );
24214
+ };
24215
+ const until = mapShapeDeadline();
24216
+ const impact = await mapChangeImpact(
24217
+ index.store,
24218
+ working,
24219
+ base,
24220
+ changes,
24221
+ {
24222
+ working: usesIn(working, input.source),
24223
+ base: usesIn(base ?? working, { ...input.source, kind: "COMMIT", commit: changes.commit })
24224
+ },
24225
+ until,
24226
+ project,
24227
+ input.tests
24228
+ );
23598
24229
  return {
23599
24230
  text: mapChangesText(
23600
24231
  changes,
@@ -23605,8 +24236,9 @@ async function checkMapChanges(input, signal) {
23605
24236
  working,
23606
24237
  base,
23607
24238
  changes.files,
23608
- (file2) => readFile(path10.join(project, file2), "utf8").catch(() => void 0)
23609
- )
24239
+ (file2) => readFile(path11.join(project, file2), "utf8").catch(() => void 0)
24240
+ ),
24241
+ changes.files.length ? await compileBreaks(input, changes, base, until, signal) : void 0
23610
24242
  )
23611
24243
  };
23612
24244
  }
@@ -23626,7 +24258,81 @@ async function mapRouteClients(project, store, working, impact, signal) {
23626
24258
  if (!routes.length) return [];
23627
24259
  return routeClients(routes, registrations, git, gitOptions(project, signal));
23628
24260
  }
23629
- function mapChangesText(changes, impact, clients = [], similar = []) {
24261
+ async function compileBreaks(input, changes, base, until, signal) {
24262
+ const { index, working } = input;
24263
+ const present = changes.files.filter((file2) => file2.status !== "DELETED").map((file2) => file2.path);
24264
+ const gone = changes.files.flatMap((file2) => file2.basePath ? [file2.basePath] : []);
24265
+ const after = await index.findDiagnostics(
24266
+ {
24267
+ version: working,
24268
+ source: input.source,
24269
+ configurations: [
24270
+ .../* @__PURE__ */ new Set([
24271
+ ...index.contextConfigurations(working, present),
24272
+ ...base ? index.contextConfigurations(base, gone) : []
24273
+ ])
24274
+ ],
24275
+ until
24276
+ },
24277
+ signal
24278
+ );
24279
+ const missing = new Set(after.contexts.flatMap((context) => context.missing));
24280
+ const views = new MapViewCache();
24281
+ const { notInstalled } = views.coverageNotes(index.store, working);
24282
+ if (notInstalled.length) {
24283
+ for (const { source, target, specifier } of views.imports(index.store, working))
24284
+ if (target === null && present.includes(source)) {
24285
+ const name = mapPackageOf(specifier);
24286
+ if (name && notInstalled.includes(name)) missing.add(name);
24287
+ }
24288
+ }
24289
+ const changedIn = new Map(changes.files.map((file2) => [file2.path, file2]));
24290
+ const onUnchanged = after.contexts.flatMap(({ configPath, errors: errors2 }) => {
24291
+ const unchanged = errors2.filter((item) => {
24292
+ const file2 = changedIn.get(item.path);
24293
+ return !file2 || !overlaps(file2.lines, item.line, item.line);
24294
+ });
24295
+ return unchanged.length ? [{ configPath, unchanged }] : [];
24296
+ });
24297
+ const before = onUnchanged.length && Date.now() <= until ? await index.findDiagnostics(
24298
+ {
24299
+ version: base ?? await input.baseVersion(changes.commit, signal),
24300
+ source: { ...input.source, kind: "COMMIT", commit: changes.commit },
24301
+ configurations: onUnchanged.map(({ configPath }) => configPath),
24302
+ until
24303
+ },
24304
+ signal
24305
+ ) : { contexts: [], unchecked: [] };
24306
+ const inBase = new Map(
24307
+ changes.files.flatMap((file2) => file2.basePath ? [[file2.basePath, file2]] : [])
24308
+ );
24309
+ const named = (path17, item) => `${path17}\0${item.code}\0${item.span}\0${item.text}`;
24310
+ const compiled = new Map(before.contexts.map((context) => [context.configPath, context.errors]));
24311
+ const unchecked = new Set(after.unchecked);
24312
+ const errors = /* @__PURE__ */ new Set();
24313
+ for (const { configPath, unchanged } of onUnchanged) {
24314
+ const had = compiled.get(configPath);
24315
+ if (!had) {
24316
+ unchecked.add(configPath);
24317
+ continue;
24318
+ }
24319
+ const known = /* @__PURE__ */ new Map();
24320
+ for (const item of had) {
24321
+ const file2 = inBase.get(item.path);
24322
+ if (file2 && overlaps(file2.baseLines, item.line, item.line)) continue;
24323
+ const name = named(file2?.path ?? item.path, item);
24324
+ known.set(name, (known.get(name) ?? 0) + 1);
24325
+ }
24326
+ for (const item of unchanged) {
24327
+ const name = named(item.path, item);
24328
+ const left = known.get(name) ?? 0;
24329
+ if (left) known.set(name, left - 1);
24330
+ else errors.add(`${item.path}:${item.line} TS${item.code} ${item.text.split("\n")[0]}`);
24331
+ }
24332
+ }
24333
+ return { errors: [...errors], missing: [...missing].sort(), unchecked: [...unchecked].sort() };
24334
+ }
24335
+ function mapChangesText(changes, impact, clients = [], similar = [], compile = { errors: [], missing: [], unchecked: [] }) {
23630
24336
  const files = changes.files.length;
23631
24337
  const direct = impact.tests.filter((test) => test.rank < 4);
23632
24338
  const indirect = impact.tests.filter((test) => test.rank >= 4);
@@ -23650,10 +24356,23 @@ Nothing changed against ${changes.base}.`;
23650
24356
  LIST.changed
23651
24357
  );
23652
24358
  list(
23653
- "REMOVED OR RENAMED (no code the diff left unchanged uses them)",
24359
+ "REMOVED OR RENAMED (no reference found on a line the diff left unchanged)",
23654
24360
  impact.removed.filter(({ usedBy }) => !usedBy.length).map(({ declaration }) => declaration),
23655
24361
  LIST.changed
23656
24362
  );
24363
+ list(
24364
+ "NEW COMPILE ERRORS ON LINES THE DIFF LEFT UNCHANGED (the compiler reports these now and did not before: the diff broke this code)",
24365
+ compile.errors,
24366
+ LIST.changed
24367
+ );
24368
+ if (compile.missing.length)
24369
+ lines.push(
24370
+ `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.`
24371
+ );
24372
+ if (compile.unchecked.length)
24373
+ lines.push(
24374
+ `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.`
24375
+ );
23657
24376
  list(
23658
24377
  "LEFT WITHOUT CALLERS (the diff removed or changed their last callers; nothing outside tests calls or otherwise uses them now)",
23659
24378
  impact.uncalled,
@@ -23755,7 +24474,7 @@ Nothing changed against ${changes.base}.`;
23755
24474
  LIST.entries
23756
24475
  );
23757
24476
  list(
23758
- "POSSIBLY AFFECTED (through a call on an interface or base member, which may dispatch elsewhere)",
24477
+ "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
24478
  impact.entries.filter((e) => !e.certain).map(entry),
23760
24479
  LIST.entries
23761
24480
  );
@@ -23868,7 +24587,7 @@ CREATE INDEX layermap_commit_version ON layermap_commit_versions(version_ref);
23868
24587
  `;
23869
24588
  var schemaVersion = (database) => Number(database.prepare("PRAGMA user_version").get()?.user_version ?? 0);
23870
24589
  function openMapDatabase(file2) {
23871
- mkdirSync(path11.dirname(file2), { recursive: true, mode: 448 });
24590
+ mkdirSync(path12.dirname(file2), { recursive: true, mode: 448 });
23872
24591
  const database = new DatabaseSync(file2);
23873
24592
  try {
23874
24593
  database.exec(BUSY_TIMEOUT);
@@ -23905,10 +24624,10 @@ function openMapDatabase(file2) {
23905
24624
  throw error51;
23906
24625
  }
23907
24626
  }
23908
- var mapDatabasePath = (cacheDirectory2, canonicalProject) => path11.join(
24627
+ var mapDatabasePath = (cacheDirectory2, canonicalProject) => path12.join(
23909
24628
  cacheDirectory2,
23910
24629
  "projects",
23911
- createHash4("sha256").update(canonicalProject).digest("hex").slice(0, 24),
24630
+ createHash5("sha256").update(canonicalProject).digest("hex").slice(0, 24),
23912
24631
  "map.sqlite"
23913
24632
  );
23914
24633
  var LayerMap = class _LayerMap {
@@ -23941,7 +24660,7 @@ var LayerMap = class _LayerMap {
23941
24660
  if (!stat3.isDirectory()) throw new ProjectEvidenceError("PROJECT_PATH_INVALID", false);
23942
24661
  const source = {
23943
24662
  kind: "WORKTREE",
23944
- projectRef: `layermap:${createHash4("sha256").update(project).digest("hex").slice(0, 24)}`,
24663
+ projectRef: `layermap:${createHash5("sha256").update(project).digest("hex").slice(0, 24)}`,
23945
24664
  directory: { canonicalPath: project, device: String(stat3.dev), inode: String(stat3.ino) }
23946
24665
  };
23947
24666
  const file2 = mapDatabasePath(options.cacheDirectory, project);
@@ -23983,12 +24702,22 @@ var LayerMap = class _LayerMap {
23983
24702
  */
23984
24703
  versionAt(commit, signal, hold) {
23985
24704
  return this.serialized(async () => {
24705
+ const root = this.source.directory.canonicalPath;
24706
+ const tree = await new GitRunner().run(
24707
+ ["ls-tree", "-r", "-z", "--name-only", "--full-tree", commit],
24708
+ { cwd: root, signal, timeoutMs: 6e4, maxOutputBytes: null }
24709
+ );
23986
24710
  const key = digestValue({
23987
24711
  projectRef: this.source.projectRef,
23988
24712
  commit,
23989
24713
  scope: DEFAULT_INITIAL_EVIDENCE_SCOPE,
23990
24714
  analyzer: this.analyzer,
23991
- policy: SOURCE_POLICY
24715
+ policy: SOURCE_POLICY,
24716
+ // A commit's map holds what its types resolve to now, so the packages count too.
24717
+ installed: mapInstalledDigest(
24718
+ root,
24719
+ tree.stdout.toString("utf8").split("\0").filter(Boolean)
24720
+ )
23992
24721
  });
23993
24722
  const known = this.store.database.prepare("SELECT version_ref FROM layermap_commit_versions WHERE capture_key = ?").get(key)?.version_ref;
23994
24723
  const version2 = typeof known === "string" && hold(known) ? known : (await this.prepare({ ...this.source, kind: "COMMIT", commit }, signal, hold)).version;
@@ -24167,6 +24896,7 @@ var LayerMap = class _LayerMap {
24167
24896
  {
24168
24897
  index: this.index,
24169
24898
  project: this.project,
24899
+ source: this.source,
24170
24900
  working: await this.current(signal, hold),
24171
24901
  base: input.base ?? "HEAD",
24172
24902
  baseVersion: (commit, baseSignal) => this.versionAt(commit, baseSignal, hold),
@@ -24197,25 +24927,25 @@ var LayerMap = class _LayerMap {
24197
24927
 
24198
24928
  // src/agent/environment.ts
24199
24929
  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")
24930
+ for (let directory = path13.dirname(fileURLToPath(import.meta.url)); ; ) {
24931
+ const manifest = path13.join(directory, "package.json");
24932
+ if (existsSync6(manifest) && JSON.parse(readFileSync5(manifest, "utf8")).name === "layermap")
24203
24933
  return directory;
24204
- if (path12.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
24205
- directory = path12.dirname(directory);
24934
+ if (path13.dirname(directory) === directory) throw new Error("LayerMap cannot find its package.");
24935
+ directory = path13.dirname(directory);
24206
24936
  }
24207
24937
  })();
24208
- var packageVersion = async () => JSON.parse(await readFile2(path12.join(packageRoot, "package.json"), "utf8")).version;
24938
+ var packageVersion = async () => JSON.parse(await readFile2(path13.join(packageRoot, "package.json"), "utf8")).version;
24209
24939
  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");
24940
+ if (env.LAYERMAP_CACHE) return path13.resolve(env.LAYERMAP_CACHE);
24941
+ if (process.platform === "darwin") return path13.join(homedir(), "Library", "Caches", "layermap");
24212
24942
  if (process.platform === "win32")
24213
- return path12.join(
24214
- env.LOCALAPPDATA || path12.join(homedir(), "AppData", "Local"),
24943
+ return path13.join(
24944
+ env.LOCALAPPDATA || path13.join(homedir(), "AppData", "Local"),
24215
24945
  "layermap",
24216
24946
  "Cache"
24217
24947
  );
24218
- return path12.join(env.XDG_CACHE_HOME || path12.join(homedir(), ".cache"), "layermap");
24948
+ return path13.join(env.XDG_CACHE_HOME || path13.join(homedir(), ".cache"), "layermap");
24219
24949
  };
24220
24950
  var projectDirectory = (directory) => new Promise(
24221
24951
  (resolve) => execFile(
@@ -24223,7 +24953,7 @@ var projectDirectory = (directory) => new Promise(
24223
24953
  ["rev-parse", "--show-toplevel"],
24224
24954
  { cwd: directory, timeout: 1e4 },
24225
24955
  (error51, stdout) => resolve(
24226
- error51 ? { directory: path12.resolve(directory), git: false } : { directory: stdout.trim(), git: true }
24956
+ error51 ? { directory: path13.resolve(directory), git: false } : { directory: stdout.trim(), git: true }
24227
24957
  )
24228
24958
  )
24229
24959
  );
@@ -24233,7 +24963,7 @@ var relativeTo = (directory, value) => Object.fromEntries(
24233
24963
  Object.fromEntries(
24234
24964
  Object.entries(resources).map(([key, field]) => [
24235
24965
  key,
24236
- key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path12.relative(directory, field) : field
24966
+ key.endsWith("Path") && typeof field === "string" && field.startsWith(directory) ? path13.relative(directory, field) : field
24237
24967
  ])
24238
24968
  )
24239
24969
  ])
@@ -24244,7 +24974,7 @@ var resolvePlaceholder = (field) => {
24244
24974
  createRequire(import.meta.url).resolve("typescript/package.json")
24245
24975
  );
24246
24976
  const native = `@typescript/typescript-${process.platform}-${process.arch}/package.json`;
24247
- return path12.join(path12.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
24977
+ return path13.join(path13.dirname(compiler.resolve(native)), "lib", executableName("tsc"));
24248
24978
  }
24249
24979
  const resolved = field.replaceAll("{platform}", process.platform).replaceAll("{arch}", process.arch);
24250
24980
  return field.includes("{platform}") ? executableName(resolved) : resolved;
@@ -24256,24 +24986,24 @@ var absoluteIn = (directory, value) => Object.fromEntries(
24256
24986
  Object.entries(resources).map(([key, field]) => {
24257
24987
  if (!key.endsWith("Path") || typeof field !== "string") return [key, field];
24258
24988
  const resolved = resolvePlaceholder(field);
24259
- return [key, path12.isAbsolute(resolved) ? resolved : path12.join(directory, resolved)];
24989
+ return [key, path13.isAbsolute(resolved) ? resolved : path13.join(directory, resolved)];
24260
24990
  })
24261
24991
  )
24262
24992
  ])
24263
24993
  );
24264
24994
  var readAnalyzers = async (directory) => {
24265
- const file2 = path12.join(directory, "analyzers.json");
24266
- if (!existsSync5(file2)) return void 0;
24995
+ const file2 = path13.join(directory, "analyzers.json");
24996
+ if (!existsSync6(file2)) return void 0;
24267
24997
  const analyzers = absoluteIn(directory, JSON.parse(await readFile2(file2, "utf8")));
24268
24998
  return analyzers.java.runtimePath ? analyzers : { ...analyzers, java: { ...analyzers.java, ...discoverJavaRuntime() } };
24269
24999
  };
24270
25000
  var sourceDigest = async () => {
24271
- const hash2 = createHash5("sha256").update(await readFile2(path12.join(packageRoot, "package.json")));
25001
+ const hash2 = createHash6("sha256").update(await readFile2(path13.join(packageRoot, "package.json")));
24272
25002
  for (const part of ["src", "go-map", "java-map", "scripts"]) {
24273
- const directory = path12.join(packageRoot, part);
24274
- if (!existsSync5(directory)) continue;
25003
+ const directory = path13.join(packageRoot, part);
25004
+ if (!existsSync6(directory)) continue;
24275
25005
  for (const entry of (await readdir(directory, { recursive: true })).sort()) {
24276
- const file2 = path12.join(directory, entry);
25006
+ const file2 = path13.join(directory, entry);
24277
25007
  const info = await stat(file2);
24278
25008
  if (info.isFile()) hash2.update(`${part}/${entry}\0${info.size}\0${info.mtimeMs}\0`);
24279
25009
  }
@@ -24281,11 +25011,11 @@ var sourceDigest = async () => {
24281
25011
  return hash2.digest("hex").slice(0, 16);
24282
25012
  };
24283
25013
  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));
25014
+ for (const directory2 of [env.LAYERMAP_ANALYZERS, path13.join(packageRoot, "analyzers")]) {
25015
+ const analyzers = directory2 && await readAnalyzers(path13.resolve(directory2));
24286
25016
  if (analyzers) return analyzers;
24287
25017
  }
24288
- const directory = path12.join(cache, "analyzers", await sourceDigest());
25018
+ const directory = path13.join(cache, "analyzers", await sourceDigest());
24289
25019
  const built = await readAnalyzers(directory);
24290
25020
  if (built) return built;
24291
25021
  log2("Building the language analyzers (once per LayerMap version)...");
@@ -24301,73 +25031,73 @@ async function resolveAnalyzers(cache, log2, env = process.env) {
24301
25031
  python: parser.pythonResources,
24302
25032
  java: parser.javaResources
24303
25033
  });
24304
- await writeFile(path12.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
25034
+ await writeFile(path13.join(staging, "analyzers.json"), `${JSON.stringify(stored, null, 2)}
24305
25035
  `);
24306
25036
  await rename(staging, directory).catch(() => rm(staging, { recursive: true, force: true }));
24307
25037
  return await readAnalyzers(directory);
24308
25038
  }
24309
25039
  var DAY = 24 * 60 * 60 * 1e3;
24310
25040
  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 });
25041
+ const used = path13.join(path13.dirname(mapDatabasePath(cache, project)), "last-used");
25042
+ await mkdir(path13.dirname(used), { recursive: true, mode: 448 });
24313
25043
  await writeFile(used, "");
24314
25044
  await utimes(used, now / 1e3, now / 1e3);
24315
- const projects = path12.join(cache, "projects");
25045
+ const projects = path13.join(cache, "projects");
24316
25046
  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;
25047
+ const directory = path13.join(projects, name);
25048
+ const marker = path13.join(directory, "last-used");
25049
+ const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
24320
25050
  if (last !== void 0 && now - last > 30 * DAY)
24321
25051
  await rm(directory, { recursive: true, force: true });
24322
25052
  }
24323
- const builds = path12.join(cache, "analyzers");
25053
+ const builds = path13.join(cache, "analyzers");
24324
25054
  const current = await sourceDigest();
24325
25055
  for (const name of await readdir(builds).catch(() => [])) {
24326
25056
  if (name === current) continue;
24327
- const built = (await stat(path12.join(builds, name)).catch(() => void 0))?.mtimeMs;
25057
+ const built = (await stat(path13.join(builds, name)).catch(() => void 0))?.mtimeMs;
24328
25058
  if (built !== void 0 && now - built > (name.includes(".") ? DAY / 24 : DAY))
24329
- await rm(path12.join(builds, name), { recursive: true, force: true });
25059
+ await rm(path13.join(builds, name), { recursive: true, force: true });
24330
25060
  }
24331
- const own = path12.dirname(path12.dirname(installed));
24332
- const versions = path12.join(cache, "versions");
24333
- const launched = path12.dirname(own) === versions;
25061
+ const own = path13.dirname(path13.dirname(installed));
25062
+ const versions = path13.join(cache, "versions");
25063
+ const launched = path13.dirname(own) === versions;
24334
25064
  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")),
25065
+ const npx = launched ? path13.join(
25066
+ env.npm_config_cache || (process.platform === "win32" ? path13.join(env.LOCALAPPDATA || path13.join(homedir(), "AppData", "Local"), "npm-cache") : path13.join(homedir(), ".npm")),
24337
25067
  "_npx"
24338
- ) : path12.dirname(own);
24339
- if (path12.basename(path12.dirname(installed)) === "node_modules" && path12.basename(npx) === "_npx")
25068
+ ) : path13.dirname(own);
25069
+ if (path13.basename(path13.dirname(installed)) === "node_modules" && path13.basename(npx) === "_npx")
24340
25070
  await pruneNpxInstalls(npx, installed, now);
24341
25071
  }
24342
25072
  async function pruneVersions(versions, own, now) {
24343
- const used = path12.join(own, "last-used");
25073
+ const used = path13.join(own, "last-used");
24344
25074
  await writeFile(used, "");
24345
25075
  await utimes(used, now / 1e3, now / 1e3);
24346
25076
  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;
25077
+ const directory = path13.join(versions, name);
25078
+ const marker = path13.join(directory, "last-used");
25079
+ const last = (await stat(existsSync6(marker) ? marker : directory).catch(() => void 0))?.mtimeMs;
24350
25080
  if (last !== void 0 && now - last > (name.startsWith(".") ? DAY / 24 : 7 * DAY))
24351
25081
  await rm(directory, { recursive: true, force: true });
24352
25082
  }
24353
25083
  }
24354
25084
  async function pruneNpxInstalls(npx, installed, now) {
24355
- const own = path12.dirname(path12.dirname(installed));
25085
+ const own = path13.dirname(path13.dirname(installed));
24356
25086
  const manifest = async (file2) => JSON.parse(await readFile2(file2, "utf8").catch(() => "{}"));
24357
25087
  const parts = (version2) => version2?.split(".").map(Number) ?? [];
24358
- const current = parts((await manifest(path12.join(installed, "package.json"))).version);
25088
+ const current = parts((await manifest(path13.join(installed, "package.json"))).version);
24359
25089
  const older = (version2) => {
24360
25090
  for (let index = 0; index < 3; index++)
24361
25091
  if (version2[index] !== current[index]) return (version2[index] ?? 0) < (current[index] ?? 0);
24362
25092
  return false;
24363
25093
  };
24364
25094
  for (const name of await readdir(npx).catch(() => [])) {
24365
- const directory = path12.join(npx, name);
25095
+ const directory = path13.join(npx, name);
24366
25096
  if (directory === own) continue;
24367
- const requested = (await manifest(path12.join(directory, "package.json"))).dependencies ?? {};
25097
+ const requested = (await manifest(path13.join(directory, "package.json"))).dependencies ?? {};
24368
25098
  if (Object.keys(requested).join() !== "layermap") continue;
24369
25099
  const version2 = parts(
24370
- (await manifest(path12.join(directory, "node_modules", "layermap", "package.json"))).version
25100
+ (await manifest(path13.join(directory, "node_modules", "layermap", "package.json"))).version
24371
25101
  );
24372
25102
  if (version2.length !== 3 || version2.some(Number.isNaN) || !older(version2)) continue;
24373
25103
  const at = (await stat(directory).catch(() => void 0))?.mtimeMs;
@@ -24386,9 +25116,9 @@ var AGENT_MAP_NOTE = "The layermap MCP server is available here. When a task nee
24386
25116
  var projectHeading = (project) => `Project ${project} (paths are relative to it)`;
24387
25117
 
24388
25118
  // src/agent/projects.ts
24389
- import { existsSync as existsSync6 } from "node:fs";
25119
+ import { existsSync as existsSync7 } from "node:fs";
24390
25120
  import { readdir as readdir2, realpath as realpath3, stat as stat2 } from "node:fs/promises";
24391
- import path13 from "node:path";
25121
+ import path14 from "node:path";
24392
25122
 
24393
25123
  // src/tools.ts
24394
25124
  var AGENT_MAP_TOOL_HOST = Object.freeze({
@@ -24412,7 +25142,7 @@ var MAP_TOOL_NAMES = Object.freeze({
24412
25142
  references: "project_find_references",
24413
25143
  check: "project_check_changes"
24414
25144
  });
24415
- var mapDirectoryPath = (path16) => path16.length > 1 && path16.endsWith("/") && !path16.endsWith("//") ? path16.slice(0, -1) : path16;
25145
+ var mapDirectoryPath = (path17) => path17.length > 1 && path17.endsWith("/") && !path17.endsWith("//") ? path17.slice(0, -1) : path17;
24416
25146
  var ProjectMapSearchInputSchema = external_exports.object({
24417
25147
  path: external_exports.string().default("."),
24418
25148
  query: external_exports.string().min(1).max(256),
@@ -24445,7 +25175,7 @@ var ProjectMapCheckInputSchema = external_exports.object({
24445
25175
  "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
25176
  ),
24447
25177
  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."
25178
+ "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
25179
  )
24450
25180
  }).strip();
24451
25181
  var locatorSchema = MapObjectLocatorSchema.describe(
@@ -24472,35 +25202,35 @@ var mapToolDescriptions = (host) => {
24472
25202
  return Object.freeze({
24473
25203
  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
25204
  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.`,
25205
+ 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
25206
  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
25207
  });
24478
25208
  };
24479
25209
 
24480
25210
  // src/agent/projects.ts
24481
25211
  var escapes = (relative) => {
24482
- const normal = path13.normalize(relative);
24483
- return normal === ".." || normal.startsWith(`..${path13.sep}`);
25212
+ const normal = path14.normalize(relative);
25213
+ return normal === ".." || normal.startsWith(`..${path14.sep}`);
24484
25214
  };
24485
25215
  async function locate(start, given) {
24486
- if (start.git && !path13.isAbsolute(given) && !escapes(given))
25216
+ if (start.git && !path14.isAbsolute(given) && !escapes(given))
24487
25217
  return { project: start.directory, path: given };
24488
- const absolute = path13.resolve(start.directory, given);
25218
+ const absolute = path14.resolve(start.directory, given);
24489
25219
  let directory = absolute;
24490
25220
  while (!(await stat2(directory).catch(() => void 0))?.isDirectory()) {
24491
- if (path13.dirname(directory) === directory) return void 0;
24492
- directory = path13.dirname(directory);
25221
+ if (path14.dirname(directory) === directory) return void 0;
25222
+ directory = path14.dirname(directory);
24493
25223
  }
24494
- const real = path13.join(await realpath3(directory), path13.relative(directory, absolute));
25224
+ const real = path14.join(await realpath3(directory), path14.relative(directory, absolute));
24495
25225
  const { directory: project, git: git2 } = await projectDirectory(directory);
24496
25226
  if (!git2) return void 0;
24497
- const relative = path13.relative(project, real);
25227
+ const relative = path14.relative(project, real);
24498
25228
  if (escapes(relative)) return void 0;
24499
- return { project, path: relative ? relative.split(path13.sep).join("/") : "." };
25229
+ return { project, path: relative ? relative.split(path14.sep).join("/") : "." };
24500
25230
  }
24501
25231
  async function repositoriesIn(directory) {
24502
25232
  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();
25233
+ return entries.filter((entry) => entry.isDirectory() && existsSync7(path14.join(directory, entry.name, ".git"))).map((entry) => `${entry.name}/`).sort();
24504
25234
  }
24505
25235
  async function routeMapCall(start, { name, args }) {
24506
25236
  const holder = ["symbol", "locator"].find(
@@ -24512,7 +25242,7 @@ async function routeMapCall(start, { name, args }) {
24512
25242
  if (!located) {
24513
25243
  const repositories = start.git ? [] : await repositoriesIn(start.directory);
24514
25244
  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}`}.`;
25245
+ 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
25246
  }
24517
25247
  if (!holder) {
24518
25248
  const routed2 = value === void 0 ? args : { ...args, path: located.path };
@@ -24828,10 +25558,10 @@ ${text}` : text
24828
25558
 
24829
25559
  // src/agent/setup.ts
24830
25560
  import { execFile as execFile2 } from "node:child_process";
24831
- import { existsSync as existsSync7 } from "node:fs";
25561
+ import { existsSync as existsSync8 } from "node:fs";
24832
25562
  import { mkdir as mkdir2, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
24833
25563
  import { homedir as homedir2 } from "node:os";
24834
- import path14 from "node:path";
25564
+ import path15 from "node:path";
24835
25565
  var SERVER = "layermap";
24836
25566
  var SETUP_RULE = `mcp__${SERVER}`;
24837
25567
  var PLUGIN_RULE = `mcp__plugin_${SERVER}_${SERVER}`;
@@ -24839,11 +25569,11 @@ var BEGIN = "<!-- layermap:begin -->";
24839
25569
  var END = "<!-- layermap:end -->";
24840
25570
  var launcherScript = (template, version2) => `// Generated from scripts/launcher.mjs.
24841
25571
  ${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)) => {
25572
+ var PUBLISHED_LAUNCHER = path15.join(packageRoot, "dist", "launcher.mjs");
25573
+ var launcherFile = (env = process.env) => path15.join(cacheDirectory(env), "server.mjs");
25574
+ var mcpLaunchCommand = (env = process.env, published = existsSync8(PUBLISHED_LAUNCHER)) => {
24845
25575
  if (published) return ["node", launcherFile(env)];
24846
- const script = path14.resolve(process.argv[1] ?? "");
25576
+ const script = path15.resolve(process.argv[1] ?? "");
24847
25577
  const execArgv = [];
24848
25578
  for (let index = 0; index < process.execArgv.length; index++) {
24849
25579
  const argument = process.execArgv[index];
@@ -24870,7 +25600,7 @@ var run = (command, args, env) => new Promise((resolve) => {
24870
25600
  );
24871
25601
  });
24872
25602
  async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
24873
- const settings = existsSync7(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
25603
+ const settings = existsSync8(file2) ? JSON.parse(await readFile3(file2, "utf8")) : {};
24874
25604
  if (typeof settings !== "object" || settings === null || Array.isArray(settings))
24875
25605
  throw new Error(`${file2} is not a settings object.`);
24876
25606
  settings.permissions ??= {};
@@ -24879,11 +25609,12 @@ async function allowInClaudeSettings(file2, rule = SETUP_RULE) {
24879
25609
  throw new Error(`${file2} has permissions.allow that is not a list.`);
24880
25610
  if (settings.permissions.allow.includes(rule)) return false;
24881
25611
  settings.permissions.allow.push(rule);
24882
- await mkdir2(path14.dirname(file2), { recursive: true });
25612
+ await mkdir2(path15.dirname(file2), { recursive: true });
24883
25613
  await writeFile2(file2, `${JSON.stringify(settings, null, 2)}
24884
25614
  `);
24885
25615
  return true;
24886
25616
  }
25617
+ var CODEX_TOOL_TIMEOUT_SEC = 300;
24887
25618
  async function configureCodexServer(file2) {
24888
25619
  const lines = (await readFile3(file2, "utf8")).split("\n");
24889
25620
  const header2 = lines.findIndex((line) => line.trim() === `[mcp_servers.${SERVER}]`);
@@ -24893,7 +25624,7 @@ async function configureCodexServer(file2) {
24893
25624
  const wanted = {
24894
25625
  default_tools_approval_mode: '"approve"',
24895
25626
  startup_timeout_sec: "120",
24896
- tool_timeout_sec: "120"
25627
+ tool_timeout_sec: String(CODEX_TOOL_TIMEOUT_SEC)
24897
25628
  };
24898
25629
  const present = new Set(
24899
25630
  lines.slice(header2 + 1, end).map((line) => line.split("=")[0]?.trim() ?? "")
@@ -24908,17 +25639,17 @@ async function writeInstructionNote(file2, note = AGENT_MAP_NOTE) {
24908
25639
  const block = `${BEGIN}
24909
25640
  ${note}
24910
25641
  ${END}`;
24911
- const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
25642
+ const text = existsSync8(file2) ? await readFile3(file2, "utf8") : "";
24912
25643
  const start = text.indexOf(BEGIN);
24913
25644
  const end = text.indexOf(END);
24914
25645
  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
25646
  `;
24916
25647
  if (next === text) return;
24917
- await mkdir2(path14.dirname(file2), { recursive: true });
25648
+ await mkdir2(path15.dirname(file2), { recursive: true });
24918
25649
  await writeFile2(file2, next);
24919
25650
  }
24920
25651
  async function removeInstructionNote(file2) {
24921
- if (!existsSync7(file2)) return;
25652
+ if (!existsSync8(file2)) return;
24922
25653
  const text = await readFile3(file2, "utf8");
24923
25654
  const start = text.indexOf(BEGIN);
24924
25655
  const end = text.indexOf(END);
@@ -24929,7 +25660,7 @@ async function removeInstructionNote(file2) {
24929
25660
  else await writeFile2(file2, rest);
24930
25661
  }
24931
25662
  async function disallowInClaudeSettings(file2) {
24932
- if (!existsSync7(file2)) return;
25663
+ if (!existsSync8(file2)) return;
24933
25664
  const settings = JSON.parse(await readFile3(file2, "utf8"));
24934
25665
  const allow = settings?.permissions?.allow;
24935
25666
  const ours = (rule) => rule === SETUP_RULE || rule === PLUGIN_RULE;
@@ -24942,11 +25673,11 @@ async function disallowInClaudeSettings(file2) {
24942
25673
  }
24943
25674
  var YAML_BEGIN = "# layermap:begin";
24944
25675
  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);
25676
+ 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
25677
  var dshPatchBlock = (command, env) => {
24947
25678
  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`;
25679
+ const [program = "", ...args] = command[0] === "node" ? [path15.join(node, "node"), ...command.slice(1)] : command;
25680
+ const searchPath2 = `${JSON.stringify(`${node}${path15.delimiter}`)} + process.env.PATH`;
24950
25681
  return [
24951
25682
  `${YAML_BEGIN} (written by \`layermap setup dsh\`; \`layermap remove dsh\` deletes it)`,
24952
25683
  "- insert:",
@@ -24965,7 +25696,7 @@ var dshPatchBlock = (command, env) => {
24965
25696
  ].join("\n");
24966
25697
  };
24967
25698
  async function writeDshPatch(file2, block) {
24968
- const text = existsSync7(file2) ? await readFile3(file2, "utf8") : "";
25699
+ const text = existsSync8(file2) ? await readFile3(file2, "utf8") : "";
24969
25700
  const start = text.indexOf(YAML_BEGIN);
24970
25701
  const end = text.indexOf(YAML_END);
24971
25702
  let next;
@@ -24981,11 +25712,11 @@ async function writeDshPatch(file2, block) {
24981
25712
  `;
24982
25713
  }
24983
25714
  if (next === text) return;
24984
- await mkdir2(path14.dirname(file2), { recursive: true });
25715
+ await mkdir2(path15.dirname(file2), { recursive: true });
24985
25716
  await writeFile2(file2, next);
24986
25717
  }
24987
25718
  async function removeDshPatch(file2) {
24988
- if (!existsSync7(file2)) return;
25719
+ if (!existsSync8(file2)) return;
24989
25720
  const text = await readFile3(file2, "utf8");
24990
25721
  const start = text.indexOf(YAML_BEGIN);
24991
25722
  const end = text.indexOf(YAML_END);
@@ -24999,31 +25730,31 @@ async function removeDshPatch(file2) {
24999
25730
  var agentFiles = (options) => {
25000
25731
  const env = options.env ?? process.env;
25001
25732
  if (options.agent === "dsh") {
25002
- const home = env.DSH_HOME || path14.join(homedir2(), ".dsh");
25733
+ const home = env.DSH_HOME || path15.join(homedir2(), ".dsh");
25003
25734
  return {
25004
- settings: path14.join(home, "cordis.patch.yml"),
25005
- instructions: path14.join(home, "AGENTS.md")
25735
+ settings: path15.join(home, "cordis.patch.yml"),
25736
+ instructions: path15.join(home, "AGENTS.md")
25006
25737
  };
25007
25738
  }
25008
25739
  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") };
25740
+ const home = env.CODEX_HOME ?? path15.join(homedir2(), ".codex");
25741
+ return { settings: path15.join(home, "config.toml"), instructions: path15.join(home, "AGENTS.md") };
25011
25742
  }
25012
25743
  if (options.scope === "user") {
25013
- const home = env.CLAUDE_CONFIG_DIR ?? path14.join(homedir2(), ".claude");
25744
+ const home = env.CLAUDE_CONFIG_DIR ?? path15.join(homedir2(), ".claude");
25014
25745
  return {
25015
- settings: path14.join(home, "settings.json"),
25016
- instructions: path14.join(home, "CLAUDE.md")
25746
+ settings: path15.join(home, "settings.json"),
25747
+ instructions: path15.join(home, "CLAUDE.md")
25017
25748
  };
25018
25749
  }
25019
25750
  const local = options.scope === "local";
25020
25751
  return {
25021
- settings: path14.join(
25752
+ settings: path15.join(
25022
25753
  options.project,
25023
25754
  ".claude",
25024
25755
  local ? "settings.local.json" : "settings.json"
25025
25756
  ),
25026
- instructions: path14.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
25757
+ instructions: path15.join(options.project, local ? "CLAUDE.local.md" : "CLAUDE.md")
25027
25758
  };
25028
25759
  };
25029
25760
  async function setupAgent(options) {
@@ -25035,7 +25766,7 @@ async function setupAgent(options) {
25035
25766
  );
25036
25767
  return false;
25037
25768
  }
25038
- const published = existsSync7(PUBLISHED_LAUNCHER);
25769
+ const published = existsSync8(PUBLISHED_LAUNCHER);
25039
25770
  const command = mcpLaunchCommand(env, published);
25040
25771
  const quoted = command.map((part) => /^[\w./:@=-]+$/u.test(part) ? part : JSON.stringify(part));
25041
25772
  const { settings, instructions } = agentFiles(options);
@@ -25043,7 +25774,7 @@ async function setupAgent(options) {
25043
25774
  const writeLauncher = async () => {
25044
25775
  if (!published) return;
25045
25776
  const file2 = launcherFile(env);
25046
- await mkdir2(path14.dirname(file2), { recursive: true, mode: 448 });
25777
+ await mkdir2(path15.dirname(file2), { recursive: true, mode: 448 });
25047
25778
  await writeFile2(
25048
25779
  `${file2}.${process.pid}`,
25049
25780
  launcherScript(await readFile3(PUBLISHED_LAUNCHER, "utf8"), options.version)
@@ -25074,7 +25805,7 @@ async function setupAgent(options) {
25074
25805
  } else {
25075
25806
  log2(`codex mcp add ${SERVER} -- ${quoted.join(" ")}`);
25076
25807
  log2(
25077
- `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = 120 in ${settings}`
25808
+ `set default_tools_approval_mode = "approve", startup_timeout_sec = 120 and tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC} in ${settings}`
25078
25809
  );
25079
25810
  }
25080
25811
  if (note) log2(`add a note naming the map tools to ${instructions}`);
@@ -25161,10 +25892,10 @@ var log = (line) => process.stderr.write(`${line}
25161
25892
  async function checkedTests(project, tests) {
25162
25893
  const here = await realpath4(process.cwd());
25163
25894
  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))
25895
+ const relative = path16.relative(project, path16.resolve(here, test));
25896
+ if (!relative || relative === ".." || relative.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative))
25166
25897
  throw new Error(`${test} is not in ${project}.`);
25167
- return relative.split(path15.sep).join("/");
25898
+ return relative.split(path16.sep).join("/");
25168
25899
  });
25169
25900
  }
25170
25901
  var usage = (code) => {