carrick 0.3.154 → 0.3.155

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.
Files changed (150) hide show
  1. package/bin/carrick.mjs +26 -4
  2. package/dist/cli.d.ts +6 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/contract.d.ts +10 -0
  6. package/dist/contract.js.map +1 -1
  7. package/dist/facts/diff.d.ts +27 -0
  8. package/dist/facts/diff.js +134 -0
  9. package/dist/facts/diff.js.map +1 -0
  10. package/dist/facts/enabled.d.ts +2 -0
  11. package/dist/facts/enabled.js +9 -0
  12. package/dist/facts/enabled.js.map +1 -0
  13. package/dist/facts/fetch.d.ts +48 -0
  14. package/dist/facts/fetch.js +235 -0
  15. package/dist/facts/fetch.js.map +1 -0
  16. package/dist/facts/files.d.ts +21 -0
  17. package/dist/facts/files.js +58 -0
  18. package/dist/facts/files.js.map +1 -0
  19. package/dist/facts/lines.d.ts +70 -0
  20. package/dist/facts/lines.js +335 -0
  21. package/dist/facts/lines.js.map +1 -0
  22. package/dist/facts/match.d.ts +91 -0
  23. package/dist/facts/match.js +1122 -0
  24. package/dist/facts/match.js.map +1 -0
  25. package/dist/facts/peers.d.ts +48 -0
  26. package/dist/facts/peers.js +143 -0
  27. package/dist/facts/peers.js.map +1 -0
  28. package/dist/facts/refresh-run.d.ts +2 -0
  29. package/dist/facts/refresh-run.js +18 -0
  30. package/dist/facts/refresh-run.js.map +1 -0
  31. package/dist/facts/rules/packages.d.ts +16 -0
  32. package/dist/facts/rules/packages.js +157 -0
  33. package/dist/facts/rules/packages.js.map +1 -0
  34. package/dist/facts/rules/same-name.d.ts +28 -0
  35. package/dist/facts/rules/same-name.js +131 -0
  36. package/dist/facts/rules/same-name.js.map +1 -0
  37. package/dist/facts/store.d.ts +119 -0
  38. package/dist/facts/store.js +341 -0
  39. package/dist/facts/store.js.map +1 -0
  40. package/dist/git-remote.d.ts +6 -0
  41. package/dist/git-remote.js +37 -0
  42. package/dist/git-remote.js.map +1 -0
  43. package/dist/hook/apply-patch.d.ts +23 -0
  44. package/dist/hook/apply-patch.js +92 -0
  45. package/dist/hook/apply-patch.js.map +1 -1
  46. package/dist/hook/bash-targets.d.ts +8 -0
  47. package/dist/hook/bash-targets.js +23 -11
  48. package/dist/hook/bash-targets.js.map +1 -1
  49. package/dist/hook/edit-flow.d.ts +29 -2
  50. package/dist/hook/edit-flow.js +80 -29
  51. package/dist/hook/edit-flow.js.map +1 -1
  52. package/dist/hook/late.d.ts +29 -0
  53. package/dist/hook/late.js +121 -26
  54. package/dist/hook/late.js.map +1 -1
  55. package/dist/hook/post-bash.js +45 -22
  56. package/dist/hook/post-bash.js.map +1 -1
  57. package/dist/hook/post-edit.d.ts +16 -1
  58. package/dist/hook/post-edit.js +177 -13
  59. package/dist/hook/post-edit.js.map +1 -1
  60. package/dist/hook/post-read.js +8 -12
  61. package/dist/hook/post-read.js.map +1 -1
  62. package/dist/hook/post-search.d.ts +2 -0
  63. package/dist/hook/post-search.js +25 -0
  64. package/dist/hook/post-search.js.map +1 -0
  65. package/dist/hook/probe.d.ts +18 -3
  66. package/dist/hook/probe.js +30 -6
  67. package/dist/hook/probe.js.map +1 -1
  68. package/dist/hook/rechecks.d.ts +66 -11
  69. package/dist/hook/rechecks.js +115 -29
  70. package/dist/hook/rechecks.js.map +1 -1
  71. package/dist/hook/refresh.d.ts +9 -0
  72. package/dist/hook/refresh.js +10 -0
  73. package/dist/hook/refresh.js.map +1 -1
  74. package/dist/hook/reuse.d.ts +16 -2
  75. package/dist/hook/reuse.js +49 -6
  76. package/dist/hook/reuse.js.map +1 -1
  77. package/dist/hook/session-key.d.ts +12 -0
  78. package/dist/hook/session-key.js +30 -0
  79. package/dist/hook/session-key.js.map +1 -0
  80. package/dist/hook/session-start.js +14 -7
  81. package/dist/hook/session-start.js.map +1 -1
  82. package/dist/hook/stop-wait.d.ts +2 -9
  83. package/dist/hook/stop-wait.js +96 -113
  84. package/dist/hook/stop-wait.js.map +1 -1
  85. package/dist/hook/stop.js +13 -8
  86. package/dist/hook/stop.js.map +1 -1
  87. package/dist/hook/subagent-stop.d.ts +2 -0
  88. package/dist/hook/subagent-stop.js +45 -0
  89. package/dist/hook/subagent-stop.js.map +1 -0
  90. package/dist/hook/timings.d.ts +72 -0
  91. package/dist/hook/timings.js +175 -0
  92. package/dist/hook/timings.js.map +1 -0
  93. package/dist/hook/user-prompt.js +17 -13
  94. package/dist/hook/user-prompt.js.map +1 -1
  95. package/dist/hook/worktree.d.ts +11 -0
  96. package/dist/hook/worktree.js +27 -1
  97. package/dist/hook/worktree.js.map +1 -1
  98. package/dist/init/repo-copies.d.ts +6 -0
  99. package/dist/init/repo-copies.js +7 -3
  100. package/dist/init/repo-copies.js.map +1 -1
  101. package/dist/init/repos.d.ts +2 -2
  102. package/dist/init/repos.js +1 -34
  103. package/dist/init/repos.js.map +1 -1
  104. package/dist/init/settings.js +25 -13
  105. package/dist/init/settings.js.map +1 -1
  106. package/dist/render.d.ts +8 -33
  107. package/dist/render.js +31 -122
  108. package/dist/render.js.map +1 -1
  109. package/package.json +6 -6
  110. package/plugin/.claude-plugin/plugin.json +1 -1
  111. package/plugin/hooks/hooks.json +44 -3
  112. package/sidecar/dist/src/capture/anchors.d.ts +12 -1
  113. package/sidecar/dist/src/capture/anchors.js +28 -47
  114. package/sidecar/dist/src/capture/api.d.ts +41 -1
  115. package/sidecar/dist/src/capture/augmentations.d.ts +2 -0
  116. package/sidecar/dist/src/capture/augmentations.js +1 -1
  117. package/sidecar/dist/src/capture/check-classify.d.ts +12 -1
  118. package/sidecar/dist/src/capture/check-classify.js +43 -0
  119. package/sidecar/dist/src/capture/check-deep.d.ts +44 -1
  120. package/sidecar/dist/src/capture/check-deep.js +161 -2
  121. package/sidecar/dist/src/capture/check.js +23 -2
  122. package/sidecar/dist/src/capture/checkout.d.ts +9 -3
  123. package/sidecar/dist/src/capture/checkout.js +12 -5
  124. package/sidecar/dist/src/capture/deep-walk.d.ts +25 -0
  125. package/sidecar/dist/src/capture/deep-walk.js +41 -0
  126. package/sidecar/dist/src/capture/deno-project.d.ts +22 -0
  127. package/sidecar/dist/src/capture/deno-project.js +48 -1
  128. package/sidecar/dist/src/capture/index.d.ts +2 -1
  129. package/sidecar/dist/src/capture/index.js +14 -4
  130. package/sidecar/dist/src/capture/machinery.d.ts +8 -53
  131. package/sidecar/dist/src/capture/machinery.js +10 -157
  132. package/sidecar/dist/src/capture/self-check.d.ts +7 -0
  133. package/sidecar/dist/src/capture/self-check.js +44 -1
  134. package/sidecar/dist/src/capture/site-node.d.ts +166 -0
  135. package/sidecar/dist/src/capture/site-node.js +570 -0
  136. package/sidecar/dist/src/capture/tool-env.d.ts +12 -0
  137. package/sidecar/dist/src/capture/tool-env.js +26 -0
  138. package/sidecar/dist/src/library-claims.js +211 -20
  139. package/sidecar/dist/src/node-index.d.ts +2 -0
  140. package/sidecar/dist/src/node-index.js +5 -1
  141. package/sidecar/dist/src/position-rows.d.ts +39 -4
  142. package/sidecar/dist/src/position-rows.js +233 -16
  143. package/sidecar/dist/src/project-loader.js +13 -5
  144. package/sidecar/dist/src/retype.d.ts +13 -0
  145. package/sidecar/dist/src/retype.js +126 -0
  146. package/sidecar/dist/src/type-inferrer.d.ts +33 -145
  147. package/sidecar/dist/src/type-inferrer.js +68 -524
  148. package/sidecar/dist/src/types.d.ts +55 -2
  149. package/sidecar/dist/src/validators.d.ts +800 -142
  150. package/sidecar/dist/src/validators.js +11 -1
@@ -24,8 +24,9 @@ import ts from 'typescript';
24
24
  import * as fs from 'node:fs';
25
25
  import * as path from 'node:path';
26
26
  import { sidecarCompilerOptions } from './compiler-options.js';
27
- import { findDisqualifyingTopTypes, provenanceOf } from './deep-walk.js';
27
+ import { findDisqualifyingTopTypes, findForeignDeclarationPositions, provenanceOf } from './deep-walk.js';
28
28
  import { UNWIDENED_LOCAL_NAME } from './check-probe.js';
29
+ import { isGlobalScopeFile } from './self-check.js';
29
30
  export function openProbeProgram(probesDir, plans) {
30
31
  if (plans.length === 0)
31
32
  return undefined;
@@ -86,6 +87,14 @@ export function probeDeepFindings(opened, plans) {
86
87
  * classifier already reports; there is nothing to add here).
87
88
  */
88
89
  function walkImportedAlias(file, localName, program, checker) {
90
+ const imported = importedAliasType(file, localName, checker);
91
+ if (!imported)
92
+ return undefined;
93
+ return findDisqualifyingTopTypes(imported.type, program, checker, imported.at).map((finding) => provenanceOf(finding));
94
+ }
95
+ /** The declared type of one of the probe's imported surface aliases, and the
96
+ * import name it is read at; `undefined` when it does not resolve. */
97
+ function importedAliasType(file, localName, checker) {
89
98
  for (const statement of file.statements) {
90
99
  if (!ts.isImportDeclaration(statement))
91
100
  continue;
@@ -102,8 +111,158 @@ function walkImportedAlias(file, localName, program, checker) {
102
111
  const type = checker.getDeclaredTypeOfSymbol(target);
103
112
  if (!type)
104
113
  return undefined;
105
- return findDisqualifyingTopTypes(type, program, checker, element.name).map((finding) => provenanceOf(finding));
114
+ return { type, at: element.name };
106
115
  }
107
116
  }
108
117
  return undefined;
109
118
  }
119
+ /**
120
+ * Which probed sides read a declaration that only another service declares
121
+ * (carrick#1047 J1-1).
122
+ *
123
+ * Each service compiles alone. The judge loads every probed stub into one
124
+ * program, so a global-scope file of one stub (a script, a `declare global`, a
125
+ * module augmentation) can merge into a name another stub's type reads, and
126
+ * that type is then one neither service compiles. A side can only read
127
+ * another stub's declaration through such a file: a stub that names a sibling
128
+ * by its package name does not resolve in this workspace (carrick#2970). So a
129
+ * side is walked only when the program holds a global-scope file of another
130
+ * stub, and otherwise costs nothing.
131
+ *
132
+ * A declaration in another stub's tree is not foreign when its text equals a
133
+ * declaration of the same symbol in the side's own tree: a typing file two
134
+ * services both carry says the same thing in each.
135
+ *
136
+ * Nor is one that merges into a built-in global, one TypeScript's default
137
+ * library declares (`interface Array<T>`, `Date`, `Promise`), unless it lies
138
+ * in the tree of the pair's other side. Both sides read the same built-in in
139
+ * the judge's program, so a third service's augmentation of it cannot move
140
+ * the verdict; the other side's can, as that side's own compile has it and
141
+ * this side's does not.
142
+ *
143
+ * Fails closed. A walk out of budget is `exhaustedAt`; a run with no program
144
+ * whose workspace holds another stub's global-scope file is `unwalked`.
145
+ */
146
+ export function pairForeignFindings(opened, plans, ws) {
147
+ const results = new Map();
148
+ const dirOfService = new Map(ws.stubs.map((s) => [s.serviceName, s.packageDir]));
149
+ const roots = [...new Set([ws.workspaceDir, fs.realpathSync(ws.workspaceDir)])].map((r) => path.join(r, 'packages').split(path.sep).join('/') + '/');
150
+ const stubDirs = new Set(ws.stubs.map((s) => s.packageDir));
151
+ /** The stub package dir a file lies in, outside its installed packages. */
152
+ const stubDirOf = (fileName) => {
153
+ const normal = fileName.split(path.sep).join('/');
154
+ for (const root of roots) {
155
+ if (!normal.startsWith(root))
156
+ continue;
157
+ const rest = normal.slice(root.length);
158
+ const dir = rest.slice(0, rest.indexOf('/'));
159
+ if (rest.includes('/node_modules/') || !stubDirs.has(dir))
160
+ return undefined;
161
+ return dir;
162
+ }
163
+ return undefined;
164
+ };
165
+ const globalDirs = opened
166
+ ? new Set(opened.program
167
+ .getSourceFiles()
168
+ .filter((sf) => stubDirOf(sf.fileName) !== undefined && isGlobalScopeFile(sf))
169
+ .map((sf) => stubDirOf(sf.fileName)))
170
+ : globalScopeDirsOnDisk(ws);
171
+ const reachable = (dir) => [...globalDirs].some((g) => g !== dir);
172
+ if (![...dirOfService.values()].some(reachable))
173
+ return results;
174
+ const sideOf = (plan, side) => plan.spec[side].service_name;
175
+ if (!opened) {
176
+ for (const plan of plans) {
177
+ const found = {};
178
+ for (const side of ['producer', 'consumer']) {
179
+ if (reachable(dirOfService.get(sideOf(plan, side))))
180
+ found[side] = 'unwalked';
181
+ }
182
+ if (Object.keys(found).length > 0)
183
+ results.set(plan.pairId, found);
184
+ }
185
+ return results;
186
+ }
187
+ const { program, checker, probesDir } = opened;
188
+ const normalText = (d) => d.getText().replace(/\s+/g, ' ');
189
+ /** Whether `d` is, or is written inside, an interface or class that merges
190
+ * into a symbol the default library declares: the augmentation itself, a
191
+ * member it adds, or a type literal written in that member. */
192
+ const mergesIntoDefaultLibrary = (d) => {
193
+ for (let n = d; n && !ts.isSourceFile(n); n = n.parent) {
194
+ if (!ts.isInterfaceDeclaration(n) && !ts.isClassDeclaration(n))
195
+ continue;
196
+ const merged = n.name ? checker.getSymbolAtLocation(n.name) : undefined;
197
+ return (merged?.declarations ?? []).some((x) => program.isSourceFileDefaultLibrary(x.getSourceFile()));
198
+ }
199
+ return false;
200
+ };
201
+ for (const plan of plans) {
202
+ const file = program.getSourceFile(path.join(probesDir, 'probes', plan.fileName));
203
+ if (!file)
204
+ continue;
205
+ const found = {};
206
+ for (const side of ['producer', 'consumer']) {
207
+ const own = dirOfService.get(sideOf(plan, side));
208
+ if (!reachable(own))
209
+ continue;
210
+ const other = dirOfService.get(sideOf(plan, side === 'producer' ? 'consumer' : 'producer'));
211
+ const foreignOf = (symbol) => {
212
+ const declarations = symbol.declarations ?? [];
213
+ const ownTexts = new Set(declarations.filter((d) => stubDirOf(d.getSourceFile().fileName) === own).map(normalText));
214
+ for (const d of declarations) {
215
+ const dir = stubDirOf(d.getSourceFile().fileName);
216
+ if (dir === undefined || dir === own || ownTexts.has(normalText(d)))
217
+ continue;
218
+ if (dir !== other && mergesIntoDefaultLibrary(d))
219
+ continue;
220
+ return ws.serviceOfPackageDir(dir) ?? dir;
221
+ }
222
+ return undefined;
223
+ };
224
+ // The sent side is read twice where the probe carries its unwidened
225
+ // reading (carrick#1538), and either reading may clear the pair.
226
+ const names = side === plan.direction.sent
227
+ ? plan.unwidenedFromLine === undefined
228
+ ? ['Sent']
229
+ : ['Sent', UNWIDENED_LOCAL_NAME]
230
+ : ['Expected'];
231
+ for (const name of names) {
232
+ const imported = importedAliasType(file, name, checker);
233
+ if (!imported)
234
+ continue;
235
+ const walk = findForeignDeclarationPositions(imported.type, program, checker, imported.at, foreignOf);
236
+ if (walk.hit) {
237
+ found[side] = walk.hit;
238
+ break;
239
+ }
240
+ if (walk.exhaustedAt !== undefined)
241
+ found[side] = { exhaustedAt: walk.exhaustedAt };
242
+ }
243
+ }
244
+ if (Object.keys(found).length > 0)
245
+ results.set(plan.pairId, found);
246
+ }
247
+ return results;
248
+ }
249
+ /** The stub dirs whose emitted tree holds a global-scope file, read from
250
+ * disk: the answer when no program could be built. */
251
+ function globalScopeDirsOnDisk(ws) {
252
+ const dirs = new Set();
253
+ for (const stub of ws.stubs) {
254
+ const typesDir = path.join(ws.workspaceDir, 'packages', stub.packageDir, 'types');
255
+ const files = fs.existsSync(typesDir)
256
+ ? fs.readdirSync(typesDir, { recursive: true }).filter((f) => /\.[cm]?ts$/.test(f))
257
+ : [];
258
+ for (const rel of files) {
259
+ const abs = path.join(typesDir, rel);
260
+ const source = ts.createSourceFile(abs, fs.readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest);
261
+ if (isGlobalScopeFile(source)) {
262
+ dirs.add(stub.packageDir);
263
+ break;
264
+ }
265
+ }
266
+ }
267
+ return dirs;
268
+ }
@@ -22,9 +22,10 @@ import ts from 'typescript';
22
22
  import { buildProbe, unwidenedAliasOf } from './check-probe.js';
23
23
  import { classifyPair, parseTscOutput, } from './check-classify.js';
24
24
  import { scrubPaths } from './check-scrub.js';
25
+ import { toolEnv } from './tool-env.js';
25
26
  import { assembleWorkspace, writeProbes, } from './check-workspace.js';
26
27
  import { buildPoisonIndexes } from './check-poison.js';
27
- import { openProbeProgram, probeDeepFindings } from './check-deep.js';
28
+ import { openProbeProgram, pairForeignFindings, probeDeepFindings } from './check-deep.js';
28
29
  import { onlyDeclaredOpenMembers } from './deep-walk.js';
29
30
  import { pairFieldReports } from './check-fields.js';
30
31
  import { pairDispatchUnions } from './check-union.js';
@@ -353,11 +354,13 @@ export async function runCheck(opts, onProgress) {
353
354
  errors: ['vendored pnpm not found'],
354
355
  };
355
356
  }
357
+ const t0 = Date.now();
356
358
  progress('assembling', 'assembling synthetic workspace');
357
359
  const ws = assembleWorkspace({
358
360
  stubs: opts.stubs,
359
361
  workspaceRoot: opts.workspaceRoot,
360
362
  });
363
+ const tAssembled = Date.now();
361
364
  const scrubCtx = {
362
365
  workspaceRoot: ws.workspaceDir,
363
366
  workspaceRealRoot: fs.realpathSync(ws.workspaceDir),
@@ -392,6 +395,7 @@ export async function runCheck(opts, onProgress) {
392
395
  }
393
396
  const { preGated, probing } = preGate(plans, aliasRecords);
394
397
  writeProbes(ws, probing);
398
+ const tProbed = Date.now();
395
399
  const errors = [];
396
400
  const degraded = [];
397
401
  // ---- Install (async, off the event loop) --------------------------------
@@ -400,7 +404,7 @@ export async function runCheck(opts, onProgress) {
400
404
  idleMs: opts.installIdleTimeoutMs ?? DEFAULT_INSTALL_IDLE_MS,
401
405
  totalMs: installTotalLimitMs(opts.installTimeoutMs),
402
406
  };
403
- const install = await runProcess(pnpmPath, ['install'], ws.workspaceDir, undefined, installLimits);
407
+ const install = await runProcess(pnpmPath, ['install'], ws.workspaceDir, toolEnv(), installLimits);
404
408
  if (install.code !== 0 || install.timedOut) {
405
409
  const failure = installFailure(install, installLimits);
406
410
  const installError = scrubPaths((install.stderr || install.stdout).trim().slice(0, 2000), scrubCtx);
@@ -432,10 +436,12 @@ export async function runCheck(opts, onProgress) {
432
436
  errors,
433
437
  };
434
438
  }
439
+ const tInstalled = Date.now();
435
440
  // ---- Judge (async, off the event loop) ----------------------------------
436
441
  progress('checking', `type-checking probes (judge: ${judge})`);
437
442
  const heap = childHeap(process.execArgv, process.env.NODE_OPTIONS, process.memoryUsage().rss / (1024 * 1024));
438
443
  const tsc = await runProcess(tscPath, ['--noEmit', '--pretty', 'false', '-p', path.join(ws.probesRel, 'tsconfig.json')], ws.workspaceDir, { ...process.env, NODE_OPTIONS: heap.nodeOptions });
444
+ const tTsc = Date.now();
439
445
  const diagnostics = parseTscOutput(tsc.stdout + '\n' + tsc.stderr);
440
446
  // Abnormal tsc termination: OOM/SIGKILL (exit code null), an internal
441
447
  // crash, or a fileless config error (e.g. TS18003, printed without a
@@ -520,6 +526,7 @@ export async function runCheck(opts, onProgress) {
520
526
  // carries a member-level any/unknown HERE — after install, where the capture
521
527
  // could not look (carrick#450). It sets `resolved` and nothing else; no
522
528
  // bucket depends on it.
529
+ const tAttributed = Date.now();
523
530
  const probeProgram = openProbeProgram(ws.probesDir, probing);
524
531
  const deepByPair = probeDeepFindings(probeProgram, probing);
525
532
  // The same program answers which FIELDS differ on a pair the judge called
@@ -529,6 +536,10 @@ export async function runCheck(opts, onProgress) {
529
536
  // And which pairs compared a union the expected side takes only in part,
530
537
  // the rest failing by nothing but the weak-type check (carrick#1995).
531
538
  const unionsByPair = pairDispatchUnions(probeProgram, probing);
539
+ // And which sides read a declaration only another service declares
540
+ // (carrick#1047 J1-1).
541
+ const foreignByPair = pairForeignFindings(probeProgram, probing, ws);
542
+ const tProbeProgram = Date.now();
532
543
  const verdicts = sortVerdicts([
533
544
  ...probing.map((plan) => classifyPair({
534
545
  plan,
@@ -539,10 +550,12 @@ export async function runCheck(opts, onProgress) {
539
550
  fieldReport: fieldsByPair.get(plan.pairId),
540
551
  dispatchUnion: unionsByPair.get(plan.pairId),
541
552
  rawTextSide: rawTextSideOf(plan, aliasRecords),
553
+ foreign: foreignByPair.get(plan.pairId),
542
554
  })),
543
555
  ...preGated,
544
556
  ...unresolved,
545
557
  ]);
558
+ const tClassified = Date.now();
546
559
  const workspaceDirOut = cleanup ? '' : ws.workspaceDir;
547
560
  if (cleanup)
548
561
  safeRm(ws);
@@ -556,6 +569,14 @@ export async function runCheck(opts, onProgress) {
556
569
  verdicts,
557
570
  degraded_services: dedupeDegraded(degraded),
558
571
  errors,
572
+ phase_ms: {
573
+ assemble: tAssembled - t0,
574
+ probes: tProbed - tAssembled,
575
+ install: tInstalled - tProbed,
576
+ tsc: tTsc - tInstalled,
577
+ probe_program: tProbeProgram - tAttributed,
578
+ classify: tClassified - tProbeProgram,
579
+ },
559
580
  };
560
581
  }
561
582
  /**
@@ -7,9 +7,12 @@
7
7
  * wrapper and every caller passes the compiler what it passed before. Set,
8
8
  * the compiler reads no file whose REAL path (links followed) is outside the
9
9
  * checkout, outside the sidecar's own install (its TypeScript library files),
10
- * and outside the directories the caller names as its own (a capture's stub).
11
- * A refused file reads as missing, so its types become `any`: the posture an
12
- * unprepared tree already has.
10
+ * and outside the directories the caller names as its own: a capture's stub,
11
+ * and the npm package directories the scan's own Deno graph resolved,
12
+ * beneath its npm cache (carrick#4076). A refused file reads as missing, so
13
+ * its types become `any`: the posture an unprepared tree already has. The
14
+ * Deno resolver and the Deno root-file list hand the compiler nothing the
15
+ * bound refuses, so a refused file never fails the whole service.
13
16
  */
14
17
  import ts from 'typescript';
15
18
  export declare const UNTRUSTED_TREE_ENV = "CARRICK_UNTRUSTED_TREE";
@@ -29,6 +32,9 @@ export interface ReadBound {
29
32
  /** `p` with every link resolved; a path that does not exist yet resolves
30
33
  * through its deepest existing ancestor. */
31
34
  export declare function realOf(p: string): string;
35
+ /** The sidecar's own install directory: outside any scanned checkout, so a
36
+ * command run there reads none of the tree's configuration. */
37
+ export declare function sidecarInstallDir(): string;
32
38
  /**
33
39
  * The bound for a scan of the service at `repoRoot`, or `undefined` when the
34
40
  * switch is off. `own` names directories the caller itself owns and reads
@@ -7,9 +7,12 @@
7
7
  * wrapper and every caller passes the compiler what it passed before. Set,
8
8
  * the compiler reads no file whose REAL path (links followed) is outside the
9
9
  * checkout, outside the sidecar's own install (its TypeScript library files),
10
- * and outside the directories the caller names as its own (a capture's stub).
11
- * A refused file reads as missing, so its types become `any`: the posture an
12
- * unprepared tree already has.
10
+ * and outside the directories the caller names as its own: a capture's stub,
11
+ * and the npm package directories the scan's own Deno graph resolved,
12
+ * beneath its npm cache (carrick#4076). A refused file reads as missing, so
13
+ * its types become `any`: the posture an unprepared tree already has. The
14
+ * Deno resolver and the Deno root-file list hand the compiler nothing the
15
+ * bound refuses, so a refused file never fails the whole service.
13
16
  */
14
17
  import * as fs from 'node:fs';
15
18
  import * as path from 'node:path';
@@ -71,13 +74,17 @@ export function realOf(p) {
71
74
  function within(real, root) {
72
75
  return real === root || real.startsWith(root.endsWith(path.sep) ? root : root + path.sep);
73
76
  }
77
+ /** The sidecar's own install directory: outside any scanned checkout, so a
78
+ * command run there reads none of the tree's configuration. */
79
+ export function sidecarInstallDir() {
80
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
81
+ }
74
82
  /** Where the sidecar's own files live: its install, and the TypeScript package
75
83
  * whose `lib.*.d.ts` every program reads (beside the sidecar in the npm
76
84
  * package, so not always beneath it). */
77
85
  function sidecarRoots() {
78
- const here = path.dirname(fileURLToPath(import.meta.url));
79
86
  const roots = [
80
- path.resolve(here, '..', '..', '..'),
87
+ sidecarInstallDir(),
81
88
  path.dirname(path.dirname(ts.getDefaultLibFilePath({}))),
82
89
  ];
83
90
  const configured = process.env.CARRICK_SIDECAR_DIR;
@@ -81,6 +81,31 @@ export declare function findUnresolvedPlaceholders(root: ts.Type, program: ts.Pr
81
81
  * each path.
82
82
  */
83
83
  export declare function findUncarriedPositions(root: ts.Type, program: ts.Program, checker: ts.TypeChecker, location: ts.Node, uncarried: (fileName: string) => boolean): string[];
84
+ /** What {@link findForeignDeclarationPositions} found on one type. */
85
+ export interface ForeignWalk {
86
+ /** The first position, in walk order, whose type or member another service
87
+ * declares, and that service. `path` is `''` at the root. */
88
+ hit?: {
89
+ service: string;
90
+ path: string;
91
+ };
92
+ /** Where the walk ran out of budget before it found one (`<root>` at the
93
+ * root): nothing is ruled out. */
94
+ exhaustedAt?: string;
95
+ }
96
+ /**
97
+ * The first position of `root` that reads a declaration another service
98
+ * declares (carrick#1047 J1-1): its type's symbols, or a member symbol of an
99
+ * object type there (a mapped type such as `Partial<T>` keeps the original
100
+ * member declarations). `foreignOf` names the other service for one symbol,
101
+ * or nothing.
102
+ *
103
+ * The same walk and budget as every other deep finding, plus the root, which
104
+ * the walk leaves to its callers: a type that is itself a merged interface is
105
+ * the commonest hit. Unlike `findUncarriedPositions`, a walk that runs out of
106
+ * budget before a hit says so, so the caller can fail closed.
107
+ */
108
+ export declare function findForeignDeclarationPositions(root: ts.Type, program: ts.Program, checker: ts.TypeChecker, location: ts.Node, foreignOf: (symbol: ts.Symbol) => string | undefined): ForeignWalk;
84
109
  /** TypeScript's unresolved-reference placeholder: `TypeFlags.Any` with the
85
110
  * internal `intrinsicName === 'error'` (stable since TS 1.x; see `anchors.ts`). */
86
111
  export declare function isErrorPlaceholder(t: ts.Type): boolean;
@@ -87,6 +87,47 @@ export function findUncarriedPositions(root, program, checker, location, uncarri
87
87
  .filter((finding) => finding.kind !== 'budget_exhausted')
88
88
  .map((finding) => finding.path);
89
89
  }
90
+ /**
91
+ * The first position of `root` that reads a declaration another service
92
+ * declares (carrick#1047 J1-1): its type's symbols, or a member symbol of an
93
+ * object type there (a mapped type such as `Partial<T>` keeps the original
94
+ * member declarations). `foreignOf` names the other service for one symbol,
95
+ * or nothing.
96
+ *
97
+ * The same walk and budget as every other deep finding, plus the root, which
98
+ * the walk leaves to its callers: a type that is itself a merged interface is
99
+ * the commonest hit. Unlike `findUncarriedPositions`, a walk that runs out of
100
+ * budget before a hit says so, so the caller can fail closed.
101
+ */
102
+ export function findForeignDeclarationPositions(root, program, checker, location, foreignOf) {
103
+ const declaredElsewhere = (t) => {
104
+ const members = t.flags & ts.TypeFlags.Object ? t.getProperties() : [];
105
+ for (const symbol of [t.aliasSymbol, t.getSymbol(), ...members]) {
106
+ const service = symbol && foreignOf(symbol);
107
+ if (service !== undefined)
108
+ return service;
109
+ }
110
+ return undefined;
111
+ };
112
+ const atRoot = declaredElsewhere(root);
113
+ if (atRoot !== undefined)
114
+ return { hit: { service: atRoot, path: '' } };
115
+ // The walk's head is its first flagged position, so the first service named
116
+ // here belongs to it.
117
+ let first;
118
+ const [head] = walkTopTypes(root, program, checker, location, (t) => {
119
+ const service = declaredElsewhere(t);
120
+ if (service === undefined)
121
+ return undefined;
122
+ first ??= service;
123
+ return 'unknown';
124
+ });
125
+ if (head === undefined)
126
+ return {};
127
+ if (head.kind === 'budget_exhausted' || first === undefined)
128
+ return { exhaustedAt: head.path };
129
+ return { hit: { service: first, path: head.path } };
130
+ }
90
131
  /** TypeScript's unresolved-reference placeholder: `TypeFlags.Any` with the
91
132
  * internal `intrinsicName === 'error'` (stable since TS 1.x; see `anchors.ts`). */
92
133
  export function isErrorPlaceholder(t) {
@@ -1,6 +1,7 @@
1
1
  /** Deno owns module resolution; both compiler frontends consume its graph. */
2
2
  import ts from 'typescript';
3
3
  import { WriteGuard } from './guarded-fs.js';
4
+ import { type ReadBound } from './checkout.js';
4
5
  export interface DenoConfig {
5
6
  configPath: string;
6
7
  workspaceRoot: string;
@@ -9,6 +10,15 @@ export interface DenoConfig {
9
10
  }
10
11
  /** Explicit TS configs keep their existing behaviour, including mixed repos. */
11
12
  export declare function findDenoConfig(repoRoot: string, explicit?: string): DenoConfig | undefined;
13
+ /**
14
+ * The npm package directories an untrusted scan may read (carrick#4076): the
15
+ * real path of each package's `localPath`, kept only when strictly beneath the
16
+ * real npm cache. No cache, no roots; a package that resolves anywhere else
17
+ * (the cache itself, a link out of it) is dropped.
18
+ */
19
+ export declare function npmReadRoots(packages: Record<string, {
20
+ localPath?: string;
21
+ }>, npmCache: string | undefined): string[];
12
22
  /** One request's immutable graph, shared by analysis, emit and relocation. */
13
23
  export declare class DenoProject {
14
24
  readonly config: DenoConfig;
@@ -25,9 +35,21 @@ export declare class DenoProject {
25
35
  private readonly redirects;
26
36
  private readonly npmPackages;
27
37
  private readonly externalNames;
38
+ /** Under CARRICK_UNTRUSTED_TREE, the npm package directories this graph
39
+ * resolved (`npmReadRoots`); empty otherwise. */
40
+ readonly readRoots: string[];
41
+ private bound;
28
42
  constructor(config: DenoConfig, repoRoot: string);
29
43
  private targetPath;
44
+ /** The read bound of whoever owns the compiler this graph resolves for (the
45
+ * loader's, or a capture's with its stub dirs), so `resolve` never hands it
46
+ * a file it would refuse (carrick#4076). */
47
+ bindReadBound(bound: ReadBound | undefined): void;
48
+ get readBound(): ReadBound | undefined;
49
+ /** A file the bound refuses resolves to nothing, so the import reads as
50
+ * missing (`any`) instead of failing the whole program. */
30
51
  resolve(spec: string, from: string, options: ts.CompilerOptions, host?: ts.ModuleResolutionHost): ts.ResolvedModule | undefined;
52
+ private resolveUnbounded;
31
53
  private npmOwner;
32
54
  /** Which registry package a resolved file belongs to (carrick#1260).
33
55
  *
@@ -8,6 +8,8 @@ import { execFileSync } from 'node:child_process';
8
8
  import { sidecarCompilerOptions } from './compiler-options.js';
9
9
  import { rewriteSpecifiers } from './specifiers.js';
10
10
  import { WriteGuard } from './guarded-fs.js';
11
+ import { toolEnv } from './tool-env.js';
12
+ import { realOf, sidecarInstallDir, untrustedTree } from './checkout.js';
11
13
  function readConfig(file) {
12
14
  const parsed = ts.parseConfigFileTextToJson(file, fs.readFileSync(file, 'utf8'));
13
15
  if (parsed.error)
@@ -77,7 +79,7 @@ function runDeno(args, cwd) {
77
79
  try {
78
80
  return execFileSync('deno', args, {
79
81
  cwd, encoding: 'utf8', timeout: 120_000, maxBuffer: 64 * 1024 * 1024,
80
- stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DENO_NO_UPDATE_CHECK: '1' },
82
+ stdio: ['ignore', 'pipe', 'pipe'], env: toolEnv({ DENO_NO_UPDATE_CHECK: '1' }),
81
83
  });
82
84
  }
83
85
  catch (err) {
@@ -85,6 +87,31 @@ function runDeno(args, cwd) {
85
87
  throw new Error(`Deno type preparation failed. Install Deno on PATH and prepare the project's dependencies without lifecycle scripts before scanning. ${detail.stderr || detail.message}`);
86
88
  }
87
89
  }
90
+ /**
91
+ * The npm package directories an untrusted scan may read (carrick#4076): the
92
+ * real path of each package's `localPath`, kept only when strictly beneath the
93
+ * real npm cache. No cache, no roots; a package that resolves anywhere else
94
+ * (the cache itself, a link out of it) is dropped.
95
+ */
96
+ export function npmReadRoots(packages, npmCache) {
97
+ if (!npmCache)
98
+ return [];
99
+ const cache = realOf(npmCache);
100
+ const prefix = cache.endsWith(path.sep) ? cache : cache + path.sep;
101
+ const roots = Object.values(packages).flatMap(pkg => pkg.localPath ? [realOf(pkg.localPath)] : []);
102
+ return [...new Set(roots.filter(root => root.startsWith(prefix) && root !== cache))];
103
+ }
104
+ /** The npm cache Deno itself uses, asked from the engine's install directory
105
+ * with no configuration, so nothing in the scanned tree can move it. */
106
+ function denoNpmCache() {
107
+ try {
108
+ const info = JSON.parse(runDeno(['info', '--json', '--no-config'], sidecarInstallDir()));
109
+ return typeof info.npmCache === 'string' && info.npmCache !== '' ? info.npmCache : undefined;
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
88
115
  /** One request's immutable graph, shared by analysis, emit and relocation. */
89
116
  export class DenoProject {
90
117
  config;
@@ -101,6 +128,10 @@ export class DenoProject {
101
128
  redirects;
102
129
  npmPackages;
103
130
  externalNames = new Map();
131
+ /** Under CARRICK_UNTRUSTED_TREE, the npm package directories this graph
132
+ * resolved (`npmReadRoots`); empty otherwise. */
133
+ readRoots;
134
+ bound;
104
135
  constructor(config, repoRoot) {
105
136
  this.config = config;
106
137
  this.repoRoot = repoRoot;
@@ -175,6 +206,7 @@ export class DenoProject {
175
206
  throw new Error(`Deno npm graph lacks localPath for ${id}. Use Deno 2.9.4 and run deno install --frozen --node-modules-dir=none before scanning.`);
176
207
  }
177
208
  }
209
+ this.readRoots = untrustedTree() ? npmReadRoots(this.npmPackages, denoNpmCache()) : [];
178
210
  for (const module of graph.modules) {
179
211
  this.modules.set(module.specifier, module);
180
212
  if (module.error)
@@ -248,7 +280,22 @@ export class DenoProject {
248
280
  }
249
281
  return this.localPaths.get(spec) ?? (spec.startsWith('file:') ? fileURLToPath(spec) : undefined);
250
282
  }
283
+ /** The read bound of whoever owns the compiler this graph resolves for (the
284
+ * loader's, or a capture's with its stub dirs), so `resolve` never hands it
285
+ * a file it would refuse (carrick#4076). */
286
+ bindReadBound(bound) {
287
+ this.bound = bound;
288
+ }
289
+ get readBound() {
290
+ return this.bound;
291
+ }
292
+ /** A file the bound refuses resolves to nothing, so the import reads as
293
+ * missing (`any`) instead of failing the whole program. */
251
294
  resolve(spec, from, options, host = ts.sys) {
295
+ const resolved = this.resolveUnbounded(spec, from, options, host);
296
+ return resolved && this.bound && !this.bound.allows(resolved.resolvedFileName) ? undefined : resolved;
297
+ }
298
+ resolveUnbounded(spec, from, options, host) {
252
299
  const edge = this.edges.get(path.resolve(from))?.get(spec);
253
300
  if (edge) {
254
301
  const target = this.targetPath(edge, from);
@@ -38,11 +38,12 @@ export { referenceRedirectOf, workspaceSourceRedirectOf } from './reference-redi
38
38
  export { findServiceTsconfig, GoverningConfigs } from './service-config.js';
39
39
  export { WriteGuard } from './guarded-fs.js';
40
40
  export { installedPackageDirectory } from './installed-package-directory.js';
41
- export { isDeclarationFileName, packageNameOf } from './specifiers.js';
41
+ export { isDeclarationFileName, isRelative, packageNameOf } from './specifiers.js';
42
42
  export type { InternalTypeChecker } from './node-builder.js';
43
43
  export { toPosix } from './installed-package.js';
44
44
  export { constituentsOf } from './result-label.js';
45
45
  export { moduleExport } from './anchors.js';
46
+ export { isFrameworkMachinery, nodeByLocatorText, normalizeLocatorText, symbolDeclaredOutside, typeIsOrContainsMachinery, type DeclaredOutside, } from './site-node.js';
46
47
  export { runCheck } from './check.js';
47
48
  export type { CheckProgress } from './check.js';
48
49
  export { jsonWireDeclarations } from './check-probe.js';
@@ -59,10 +59,13 @@ export { findServiceTsconfig, GoverningConfigs } from './service-config.js';
59
59
  // installed declaring file the way the capture's resolution walk does.
60
60
  export { WriteGuard } from './guarded-fs.js';
61
61
  export { installedPackageDirectory } from './installed-package-directory.js';
62
- export { isDeclarationFileName, packageNameOf } from './specifiers.js';
62
+ export { isDeclarationFileName, isRelative, packageNameOf } from './specifiers.js';
63
63
  export { toPosix } from './installed-package.js';
64
64
  export { constituentsOf } from './result-label.js';
65
65
  export { moduleExport } from './anchors.js';
66
+ // One node locator and one machinery test for the inferrer and the capture
67
+ // (carrick#3500).
68
+ export { isFrameworkMachinery, nodeByLocatorText, normalizeLocatorText, symbolDeclaredOutside, typeIsOrContainsMachinery, } from './site-node.js';
66
69
  // v2 check core ("tsc as the judge"). Same bundle, same seam: the sidecar
67
70
  // reaches it only through this door (index.js).
68
71
  export { runCheck } from './check.js';
@@ -220,12 +223,12 @@ export function captureStub(opts) {
220
223
  const stubDir = path.resolve(opts.outDir);
221
224
  const errors = [];
222
225
  // Under CARRICK_UNTRUSTED_TREE every compiler read below is held to the
223
- // checkout, the sidecar's own install and this stub; otherwise undefined
224
- // and nothing here changes (carrick#2230).
226
+ // checkout, the sidecar's own install, these stub dirs and a Deno graph's
227
+ // npm packages (`bound`, built once the Deno graph exists); otherwise
228
+ // undefined and nothing here changes (carrick#2230).
225
229
  // The backfilled stub (carrick#2041) is written beside the first.
226
230
  const backfillDir = plannedBackfill(opts) ? path.resolve(opts.backfillOutDir) : undefined;
227
231
  const stubDirs = backfillDir ? [stubDir, backfillDir] : [stubDir];
228
- const bound = untrustedReadBound(repoRoot, stubDirs);
229
232
  // The named config, else the one the init'd project reads too
230
233
  // (carrick#1776). A service with neither is typed under defaults below.
231
234
  const configPath = opts.tsconfigPath
@@ -264,6 +267,11 @@ export function captureStub(opts) {
264
267
  catch (err) {
265
268
  return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
266
269
  }
270
+ // The bound also admits the npm packages a Deno graph resolved, and the
271
+ // Deno resolver is held to this same bound, stub dirs included, so it never
272
+ // hands the compiler a file the bound refuses (carrick#4076).
273
+ const bound = untrustedReadBound(repoRoot, [...stubDirs, ...(deno?.readRoots ?? [])]);
274
+ deno?.bindReadBound(bound);
267
275
  if (deno) {
268
276
  parsed = deno.parsed;
269
277
  errors.push(...deno.diagnostics);
@@ -1073,6 +1081,7 @@ function demoteDanglingAliases(args) {
1073
1081
  failureReason: `declaration emit was skipped for module '${dangling}'; ` +
1074
1082
  'alias demoted to keep the partially emitted tree usable',
1075
1083
  namesUnemittedModule: true,
1084
+ unreadCause: 'site_unreadable',
1076
1085
  };
1077
1086
  });
1078
1087
  if (surfaceKey !== undefined && demoted.size > 0) {
@@ -1139,6 +1148,7 @@ function resolveAnchorsByOwner(opts, groups, emit, ctx) {
1139
1148
  serialization: 'structural_fallback',
1140
1149
  failureReason: `typed under ${owner.configPath}, the project that owns its file, whose options differ ` +
1141
1150
  `from ${emit.configPath}, which emits the surface; the module it names would be declared under the wrong options`,
1151
+ unreadCause: 'site_unreadable',
1142
1152
  };
1143
1153
  });
1144
1154
  if (owner !== emit) {