carrick 0.3.138 → 0.3.140

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 (33) hide show
  1. package/package.json +7 -6
  2. package/plugin/.claude-plugin/plugin.json +1 -1
  3. package/sidecar/dist/src/affected-set.d.ts +172 -0
  4. package/sidecar/dist/src/affected-set.js +936 -0
  5. package/sidecar/dist/src/capture/api.d.ts +34 -0
  6. package/sidecar/dist/src/capture/backfill.d.ts +37 -0
  7. package/sidecar/dist/src/capture/backfill.js +75 -0
  8. package/sidecar/dist/src/capture/index.js +419 -133
  9. package/sidecar/dist/src/capture/installed-package.js +36 -29
  10. package/sidecar/dist/src/capture/self-check.d.ts +14 -3
  11. package/sidecar/dist/src/capture/self-check.js +168 -30
  12. package/sidecar/dist/src/index.js +84 -14
  13. package/sidecar/dist/src/infer-cache.d.ts +0 -8
  14. package/sidecar/dist/src/infer-cache.js +0 -14
  15. package/sidecar/dist/src/library-claims.js +4 -3
  16. package/sidecar/dist/src/module-format.d.ts +13 -2
  17. package/sidecar/dist/src/module-format.js +31 -1
  18. package/sidecar/dist/src/origin.d.ts +10 -7
  19. package/sidecar/dist/src/origin.js +10 -7
  20. package/sidecar/dist/src/program-files.d.ts +34 -11
  21. package/sidecar/dist/src/program-files.js +52 -10
  22. package/sidecar/dist/src/project-loader.d.ts +7 -0
  23. package/sidecar/dist/src/project-loader.js +20 -0
  24. package/sidecar/dist/src/retype-deferred.d.ts +34 -0
  25. package/sidecar/dist/src/retype-deferred.js +326 -0
  26. package/sidecar/dist/src/retype-selector.d.ts +43 -0
  27. package/sidecar/dist/src/retype-selector.js +217 -0
  28. package/sidecar/dist/src/retype.d.ts +28 -3
  29. package/sidecar/dist/src/retype.js +106 -41
  30. package/sidecar/dist/src/type-inferrer.js +3 -2
  31. package/sidecar/dist/src/types.d.ts +113 -3
  32. package/sidecar/dist/src/validators.d.ts +413 -4
  33. package/sidecar/dist/src/validators.js +41 -1
@@ -38,6 +38,7 @@ import { rewriteEmittedSpecifiers } from './paths-rewrite.js';
38
38
  import { substituteMachinePathImports } from './machine-paths.js';
39
39
  import { installedPackageSpecifier, typesPackageOf, withInstalledPackages } from './installed-package.js';
40
40
  import { selfCheckStub } from './self-check.js';
41
+ import { backfillRerun, sharingHost } from './backfill.js';
41
42
  import { collectSpecifiers, isRelative, packageNameOf } from './specifiers.js';
42
43
  import { DenoProject, findDenoConfig } from './deno-project.js';
43
44
  import { emitsAlike, ProjectGraph } from './project-references.js';
@@ -148,7 +149,10 @@ export function captureStub(opts) {
148
149
  // Under CARRICK_UNTRUSTED_TREE every compiler read below is held to the
149
150
  // checkout, the sidecar's own install and this stub; otherwise undefined
150
151
  // and nothing here changes (carrick#2230).
151
- const bound = untrustedReadBound(repoRoot, [stubDir]);
152
+ // The backfilled stub (carrick#2041) is written beside the first.
153
+ const backfillDir = plannedBackfill(opts) ? path.resolve(opts.backfillOutDir) : undefined;
154
+ const stubDirs = backfillDir ? [stubDir, backfillDir] : [stubDir];
155
+ const bound = untrustedReadBound(repoRoot, stubDirs);
152
156
  // The named config, else the one the init'd project reads too
153
157
  // (carrick#1776). A service with neither is typed under defaults below.
154
158
  const configPath = opts.tsconfigPath
@@ -173,7 +177,7 @@ export function captureStub(opts) {
173
177
  let guard;
174
178
  try {
175
179
  const protect = opts.scanRoot === undefined ? [repoRoot] : [repoRoot, path.resolve(opts.scanRoot)];
176
- guard = WriteGuard.of({ dirs: [stubDir], protect });
180
+ guard = WriteGuard.of({ dirs: stubDirs, protect });
177
181
  }
178
182
  catch (err) {
179
183
  return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
@@ -278,7 +282,7 @@ export function captureStub(opts) {
278
282
  return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
279
283
  }
280
284
  // ---- Phase A: analysis program over placeholder entry + anchor sources ----
281
- let resolved;
285
+ let analysis;
282
286
  const progress = opts.onProgress ?? (() => { });
283
287
  // The files of a project that declare a module or global augmentation are
284
288
  // roots of both programs below: the one its anchors are read in and the one
@@ -300,8 +304,8 @@ export function captureStub(opts) {
300
304
  readsReferences: graphForRedirect?.hasReferences ?? false,
301
305
  };
302
306
  try {
303
- resolved = ownerGroups && emitProject
304
- ? resolveAnchorsByOwner(opts, ownerGroups, emitProject, analysisCtx, errors)
307
+ analysis = ownerGroups && emitProject
308
+ ? resolveAnchorsByOwner(opts, ownerGroups, emitProject, analysisCtx)
305
309
  : resolveAnchors(opts, parsed, analysisCtx, deno, emitProject);
306
310
  }
307
311
  catch (err) {
@@ -310,6 +314,175 @@ export function captureStub(opts) {
310
314
  // ---- Augmentation files of the project that emits the surface ----
311
315
  const augmentationSources = [...new Set([...augmentations(parsed), ...(deno?.globals ?? [])])];
312
316
  // ---- Phase B: declaration emit of the final entry ----
317
+ const scratch = WriteGuard.scratch('carrick-capture-v2-');
318
+ const staging = scratch.dir;
319
+ const emitOptions = sidecarCompilerOptions({
320
+ ...parsed.options,
321
+ // The load-bearing trio: emit declarations without checking, so
322
+ // type-error-laden and bare (no node_modules) checkouts still emit.
323
+ noCheck: true,
324
+ declaration: true,
325
+ emitDeclarationOnly: true,
326
+ noEmit: false,
327
+ declarationMap: false,
328
+ composite: false,
329
+ incremental: false,
330
+ outDir: staging,
331
+ rootDir: entryDir,
332
+ });
333
+ const emitCtx = {
334
+ entryPath,
335
+ entryDir,
336
+ surfaceDeclaration,
337
+ guard,
338
+ progress,
339
+ rootNames: [entryPath, ...augmentationSources],
340
+ options: emitOptions,
341
+ // A backfill's emit differs from the first only in the entry: every other
342
+ // file it reads is answered with the one the first emit parsed.
343
+ host: plannedBackfill(opts)
344
+ ? sharingHost(programHost(emitOptions, deno, bound) ?? ts.createCompilerHost(emitOptions), (file) => path.resolve(file) === entryPath)
345
+ : programHost(emitOptions, deno, bound),
346
+ staging,
347
+ };
348
+ let first;
349
+ const analysisErrors = analysis.errors;
350
+ let backfill;
351
+ try {
352
+ try {
353
+ first = emitSurface(analysis.resolved, emitCtx);
354
+ }
355
+ catch (err) {
356
+ return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
357
+ }
358
+ // ---- Literal backfill (carrick#2041): the demoted aliases the scanner
359
+ // holds a text for, re-anchored on it, read in the same anchor program
360
+ // and emitted on the files the first emit parsed.
361
+ const plan = plannedBackfill(opts) ? backfillRerun(opts.anchors, first.resolved, opts.backfillTexts) : undefined;
362
+ if (plan) {
363
+ try {
364
+ const again = analysis.resolveAgain(plan.anchors, new Set(plan.backfilled));
365
+ progress('emit', 'emitting the backfilled surface');
366
+ backfill = { plan, surface: emitSurface(again.resolved, emitCtx), errors: again.errors };
367
+ }
368
+ catch (err) {
369
+ console.error(`[sidecar] capture ${packageName}: backfill surface not written: ${err instanceof Error ? err.message : String(err)}`);
370
+ }
371
+ }
372
+ }
373
+ finally {
374
+ // The anchor programs, and the files the emits parsed, are held only
375
+ // until the backfill has read them.
376
+ analysis = undefined;
377
+ emitCtx.host = undefined;
378
+ scratch.guard.remove(staging);
379
+ }
380
+ // ---- What the checkout installs (shared by both stubs) ----
381
+ const dependencyRoot = deno?.config.workspaceRoot ?? repoRoot;
382
+ const nodeModulesPresent = fs.existsSync(path.join(dependencyRoot, 'node_modules'));
383
+ const declared = deno || !nodeModulesPresent
384
+ ? { unresolved: [], runtimeDeclared: 0, runtimeResolved: 0 }
385
+ : declaredDependencyResolution(dependencyRoot);
386
+ const unresolvedDependencies = declared.unresolved;
387
+ // Bare: no node_modules, or every declared runtime dependency dangles (a
388
+ // missing pnpm store). One missing package, or missing devDependencies,
389
+ // leaves the installed ones usable (carrick#2999).
390
+ const bareCheckout = !deno &&
391
+ (!nodeModulesPresent || (declared.runtimeDeclared > 0 && declared.runtimeResolved === 0));
392
+ if (unresolvedDependencies.length > 0) {
393
+ console.error(`[sidecar] capture ${packageName}: declared dependencies do not resolve` +
394
+ `${bareCheckout ? ' (bare checkout)' : ''}: ${unresolvedDependencies.join(', ')}`);
395
+ }
396
+ const stubCtx = {
397
+ guard,
398
+ packageName,
399
+ staging,
400
+ entryDir,
401
+ surfaceDeclaration,
402
+ augmentationSources,
403
+ parsed,
404
+ projectConfigPath,
405
+ deno,
406
+ repoRoot,
407
+ labelRoot: opts.scanRoot ?? repoRoot,
408
+ };
409
+ let stub;
410
+ try {
411
+ stub = writeStub(first, stubDir, stubCtx);
412
+ }
413
+ catch (err) {
414
+ if (err instanceof StubFailure)
415
+ return fail(stubDir, packageName, [err.message]);
416
+ throw err;
417
+ }
418
+ let second;
419
+ if (backfill) {
420
+ try {
421
+ second = writeStub(backfill.surface, backfillDir, stubCtx);
422
+ }
423
+ catch (err) {
424
+ console.error(`[sidecar] capture ${packageName}: backfill stub not written: ${err instanceof Error ? err.message : String(err)}`);
425
+ guard.remove(backfillDir);
426
+ }
427
+ }
428
+ // ---- Capture-time self-check (per-alias closure attribution) ----
429
+ progress('self-check', 'checking the stub');
430
+ const hostFor = (installs) => deno || bound || Object.keys(installs).length > 0
431
+ ? (options) => boundedCompilerHost(withInstalledPackages(options, installs, deno ? deno.host(options) : undefined), bound)
432
+ : undefined;
433
+ const checkArgs = (written, compilerHost) => ({
434
+ guard: written.guard,
435
+ stubDir: written.stubDir,
436
+ surfaces: [{ surfaceAbsPath: written.surfaceAbsPath, resolved: written.resolved }],
437
+ pinned: written.pinned,
438
+ bareCheckout,
439
+ repoRoot: dependencyRoot,
440
+ compilerHost,
441
+ });
442
+ let aliases;
443
+ let secondAliases;
444
+ if (!second) {
445
+ [aliases] = selfCheckStub(checkArgs(stub, hostFor(stub.installs)));
446
+ }
447
+ else {
448
+ ({ first: aliases, second: secondAliases } = selfCheckBoth(stub, second, checkArgs, hostFor));
449
+ }
450
+ const result = finishStub(stub, aliases, {
451
+ packageName,
452
+ bareCheckout,
453
+ unresolvedDependencies,
454
+ errors: [...errors, ...analysisErrors, ...first.errors],
455
+ });
456
+ if (!second || !secondAliases || !backfill) {
457
+ if (second)
458
+ guard.remove(second.stubDir);
459
+ return result;
460
+ }
461
+ return {
462
+ ...result,
463
+ backfill: {
464
+ backfilled: backfill.plan.backfilled,
465
+ result: finishStub(second, secondAliases, {
466
+ packageName,
467
+ bareCheckout,
468
+ unresolvedDependencies,
469
+ errors: [...errors, ...backfill.errors, ...backfill.surface.errors],
470
+ }),
471
+ },
472
+ };
473
+ }
474
+ /** Whether this capture may write a backfilled second stub (carrick#2041). */
475
+ function plannedBackfill(opts) {
476
+ return (opts.backfillOutDir !== undefined &&
477
+ opts.backfillTexts !== undefined &&
478
+ Object.keys(opts.backfillTexts).length > 0);
479
+ }
480
+ /**
481
+ * Phase B for one surface: write the entry that aliases each resolved anchor,
482
+ * emit its declarations, and demote the aliases a partial emit leaves
483
+ * dangling. Throws when the emit wrote nothing.
484
+ */
485
+ function emitSurface(resolved, ctx) {
313
486
  const entryLines = ['// Generated by Carrick capture v2. Deleted after emit.'];
314
487
  for (const anchor of resolved) {
315
488
  const comment = anchor.failureReason
@@ -317,45 +490,24 @@ export function captureStub(opts) {
317
490
  : '';
318
491
  entryLines.push(`export type ${anchor.request.alias} = ${anchor.aliasText};${comment}`);
319
492
  }
320
- const scratch = WriteGuard.scratch('carrick-capture-v2-');
321
- const staging = scratch.dir;
322
493
  let written;
323
494
  try {
324
- progress('emit', 'emitting declarations');
325
- guard.writeFile(entryPath, entryLines.join('\n') + '\n');
326
- const emitOptions = sidecarCompilerOptions({
327
- ...parsed.options,
328
- // The load-bearing trio: emit declarations without checking, so
329
- // type-error-laden and bare (no node_modules) checkouts still emit.
330
- noCheck: true,
331
- declaration: true,
332
- emitDeclarationOnly: true,
333
- noEmit: false,
334
- declarationMap: false,
335
- composite: false,
336
- incremental: false,
337
- outDir: staging,
338
- rootDir: entryDir,
339
- });
495
+ ctx.progress('emit', 'emitting declarations');
496
+ ctx.guard.writeFile(ctx.entryPath, entryLines.join('\n') + '\n');
340
497
  written = emitDeclarations({
341
- rootNames: [entryPath, ...augmentationSources],
342
- options: emitOptions,
343
- host: programHost(emitOptions, deno, bound),
344
- staging,
345
- entryDir,
498
+ rootNames: ctx.rootNames,
499
+ options: ctx.options,
500
+ host: ctx.host,
501
+ staging: ctx.staging,
502
+ entryDir: ctx.entryDir,
346
503
  });
347
504
  }
348
- catch (err) {
349
- return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
350
- }
351
505
  finally {
352
- if (fs.existsSync(entryPath))
353
- guard.unlink(entryPath);
354
- scratch.guard.remove(staging);
506
+ if (fs.existsSync(ctx.entryPath))
507
+ ctx.guard.unlink(ctx.entryPath);
355
508
  }
356
509
  const { emitted, declarationSources, sourceByEmitted } = written;
357
- const emitPartial = written.partial;
358
- errors.push(...written.diagnostics);
510
+ const errors = [...written.diagnostics];
359
511
  // ---- Partial-emit recovery ----
360
512
  // The corpus-2 notifications-svc shape: one file's declaration emit was
361
513
  // skipped but the rest of the tree emitted fine. Keep the tree; demote any
@@ -366,18 +518,33 @@ export function captureStub(opts) {
366
518
  // `unknown` at the surface, so the check phase's IsUnknown probe gate (or
367
519
  // the poison rule, for unemitted modules still referenced by kept files)
368
520
  // decays it to unverifiable — it can never read compatible.
369
- if (emitPartial) {
521
+ if (written.partial) {
370
522
  errors.push(`declaration emit was partial: kept ${emitted.size} emitted file(s); ` +
371
523
  'aliases referencing unemitted modules are demoted to structural_fallback');
372
524
  resolved = demoteDanglingAliases({
373
525
  resolved,
374
526
  emitted,
375
527
  declarationSources,
376
- staging,
377
- entryDir,
378
- surfaceDeclaration,
528
+ staging: ctx.staging,
529
+ entryDir: ctx.entryDir,
530
+ surfaceDeclaration: ctx.surfaceDeclaration,
379
531
  });
380
532
  }
533
+ return { resolved, emitted, declarationSources, sourceByEmitted, errors };
534
+ }
535
+ /** A stub that cannot be written: the capture fails with this message alone. */
536
+ class StubFailure extends Error {
537
+ }
538
+ /**
539
+ * Write one surface's stub package into `stubDir`: the emitted tree with its
540
+ * specifiers rewritten, the pins, the recorded dependency edges,
541
+ * `package.json` and the tsconfig snapshot. The self-check and the manifest
542
+ * follow.
543
+ */
544
+ function writeStub(surface, stubDir, ctx) {
545
+ const { emitted, declarationSources, sourceByEmitted } = surface;
546
+ let resolved = surface.resolved;
547
+ const { guard, deno, parsed } = ctx;
381
548
  // ---- Relocate the emitted tree into the stub package ----
382
549
  const typesDir = path.join(stubDir, 'types');
383
550
  guard.remove(stubDir);
@@ -386,11 +553,16 @@ export function captureStub(opts) {
386
553
  const stubGuard = guard.narrow(stubDir);
387
554
  // A declaration for a source outside rootDir arrives at the source's own
388
555
  // path; it is placed under the tree too (carrick#1770).
389
- const placed = placeEmittedTree({ emitted, staging, entryDir, surfaceDeclaration });
556
+ const placed = placeEmittedTree({
557
+ emitted,
558
+ staging: ctx.staging,
559
+ entryDir: ctx.entryDir,
560
+ surfaceDeclaration: ctx.surfaceDeclaration,
561
+ });
390
562
  const emittedFiles = [];
391
563
  let surfaceAbsPath = '';
392
564
  for (const fileName of emitted.keys()) {
393
- const stagingRel = path.relative(staging, fileName).split(path.sep).join('/');
565
+ const stagingRel = path.relative(ctx.staging, fileName).split(path.sep).join('/');
394
566
  const rel = placed.relOf.get(fileName);
395
567
  const text = placed.textOf.get(fileName);
396
568
  if (rel !== stagingRel) {
@@ -407,7 +579,7 @@ export function captureStub(opts) {
407
579
  surfaceAbsPath = dest;
408
580
  }
409
581
  if (!surfaceAbsPath) {
410
- return fail(stubDir, packageName, ['no surface.d.ts produced by emit']);
582
+ throw new StubFailure('no surface.d.ts produced by emit');
411
583
  }
412
584
  // Verbatim copies of in-repo declaration sources (see declarationSources).
413
585
  for (const [rel, text] of declarationSources) {
@@ -420,14 +592,14 @@ export function captureStub(opts) {
420
592
  }
421
593
  // Tree-relative names of augmentation files that made it into the tree
422
594
  // (.ts augmentations arrive via declaration emit, .d.ts ones verbatim).
423
- const augmentationFiles = augmentationSources
595
+ const augmentationFiles = ctx.augmentationSources
424
596
  .map((abs) => {
425
597
  const noDts = abs.replace(/\.d\.ts$/, '');
426
598
  const noExt = noDts === abs ? abs.replace(/\.(ts|tsx|mts|cts)$/, '') : noDts;
427
599
  const outside = placed.outside.get(path.resolve(noExt));
428
600
  if (outside !== undefined)
429
601
  return outside;
430
- const rel = path.relative(entryDir, noExt).split(path.sep).join('/');
602
+ const rel = path.relative(ctx.entryDir, noExt).split(path.sep).join('/');
431
603
  return `${rel}.d.ts`;
432
604
  })
433
605
  .filter((rel) => emittedFiles.includes(rel))
@@ -438,7 +610,7 @@ export function captureStub(opts) {
438
610
  denoRewrites = deno?.rewrite(stubGuard, typesDir, emittedFiles, sourceByEmitted) ?? 0;
439
611
  }
440
612
  catch (err) {
441
- return fail(stubDir, packageName, [err instanceof Error ? err.message : String(err)]);
613
+ throw new StubFailure(err instanceof Error ? err.message : String(err));
442
614
  }
443
615
  const rewritten = rewriteEmittedSpecifiers({
444
616
  guard: stubGuard,
@@ -446,8 +618,8 @@ export function captureStub(opts) {
446
618
  typesDir,
447
619
  files: emittedFiles,
448
620
  options: parsed.options,
449
- configPath: projectConfigPath,
450
- entryDir,
621
+ configPath: ctx.projectConfigPath,
622
+ entryDir: ctx.entryDir,
451
623
  });
452
624
  const specifierRewrites = denoRewrites + placed.rewrites + rewritten.rewrites;
453
625
  // What the rewrite could not map still names a machine path (carrick#2943).
@@ -455,7 +627,7 @@ export function captureStub(opts) {
455
627
  files: emittedFiles.map((rel) => path.join(typesDir, rel)),
456
628
  surfaceAbsPath,
457
629
  tree: stubGuard.narrow(typesDir),
458
- labelRoot: opts.scanRoot ?? repoRoot,
630
+ labelRoot: ctx.labelRoot,
459
631
  });
460
632
  if (machinePaths.size > 0) {
461
633
  resolved = resolved.map((anchor) => {
@@ -486,8 +658,8 @@ export function captureStub(opts) {
486
658
  // remains the bare-checkout fallback. Both paths pin only
487
659
  // the directly-referenced externals; what those depend on is recorded
488
660
  // from the installed tree below (RESOLUTION_FILE).
489
- const installed = installedVersions(repoRoot, externalSpecs);
490
- const lockVersions = lockfileVersions(repoRoot);
661
+ const installed = installedVersions(ctx.repoRoot, externalSpecs);
662
+ const lockVersions = lockfileVersions(ctx.repoRoot);
491
663
  for (const name of Object.keys(deno?.pinned ?? {}))
492
664
  externalSpecs.add(name);
493
665
  // A package an absolute specifier was rewritten into carries the version
@@ -511,30 +683,15 @@ export function captureStub(opts) {
511
683
  // installed rather than the newest version in range (carrick#2091).
512
684
  const resolution = deno
513
685
  ? { edges: {}, unrecorded: 0 }
514
- : installedResolutionEdges(repoRoot, pinned);
686
+ : installedResolutionEdges(ctx.repoRoot, pinned);
515
687
  const edgeCount = Object.values(resolution.edges).reduce((n, children) => n + Object.keys(children).length, 0);
516
688
  if (edgeCount > 0) {
517
689
  stubGuard.writeFile(path.join(stubDir, RESOLUTION_FILE), JSON.stringify({ edges: resolution.edges }, null, 2) + '\n');
518
690
  }
519
- console.error(`[sidecar] capture ${packageName}: ${edgeCount} dependency edge(s) recorded from the installed tree, ` +
691
+ console.error(`[sidecar] capture ${ctx.packageName}: ${edgeCount} dependency edge(s) recorded from the installed tree, ` +
520
692
  `${resolution.unrecorded} left to the registry`);
521
- const dependencyRoot = deno?.config.workspaceRoot ?? repoRoot;
522
- const nodeModulesPresent = fs.existsSync(path.join(dependencyRoot, 'node_modules'));
523
- const declared = deno || !nodeModulesPresent
524
- ? { unresolved: [], runtimeDeclared: 0, runtimeResolved: 0 }
525
- : declaredDependencyResolution(dependencyRoot);
526
- const unresolvedDependencies = declared.unresolved;
527
- // Bare: no node_modules, or every declared runtime dependency dangles (a
528
- // missing pnpm store). One missing package, or missing devDependencies,
529
- // leaves the installed ones usable (carrick#2999).
530
- const bareCheckout = !deno &&
531
- (!nodeModulesPresent || (declared.runtimeDeclared > 0 && declared.runtimeResolved === 0));
532
- if (unresolvedDependencies.length > 0) {
533
- console.error(`[sidecar] capture ${packageName}: declared dependencies do not resolve` +
534
- `${bareCheckout ? ' (bare checkout)' : ''}: ${unresolvedDependencies.join(', ')}`);
535
- }
536
693
  stubGuard.writeFile(path.join(stubDir, 'package.json'), JSON.stringify({
537
- name: packageName,
694
+ name: ctx.packageName,
538
695
  version: '0.0.0-carrick',
539
696
  private: true,
540
697
  types: './types/surface.d.ts',
@@ -548,43 +705,136 @@ export function captureStub(opts) {
548
705
  module: parsed.options.module !== undefined ? ts.ModuleKind[parsed.options.module] : undefined,
549
706
  target: parsed.options.target !== undefined ? ts.ScriptTarget[parsed.options.target] : undefined,
550
707
  }, null, 2) + '\n');
551
- // ---- Capture-time self-check (per-alias closure attribution) ----
552
- progress('self-check', 'checking the stub');
553
- const aliases = selfCheckStub({
554
- guard: stubGuard,
708
+ return {
555
709
  stubDir,
710
+ guard: stubGuard,
556
711
  surfaceAbsPath,
557
712
  resolved,
713
+ emittedFiles,
714
+ augmentationFiles,
715
+ specifierRewrites,
558
716
  pinned,
559
- bareCheckout,
560
- repoRoot: dependencyRoot,
561
- compilerHost: deno || bound || Object.keys(rewritten.installs).length > 0
562
- ? (options) => boundedCompilerHost(withInstalledPackages(options, rewritten.installs, deno ? deno.host(options) : undefined), bound)
563
- : undefined,
564
- });
717
+ unpinned,
718
+ installs: rewritten.installs,
719
+ };
720
+ }
721
+ /**
722
+ * The name the backfilled surface is checked under, beside the first, when
723
+ * both stubs hold the same tree. No emitted declaration is named so: an
724
+ * emitted name keeps its source's extension stem, and this one has two dots
725
+ * no source file name would end with.
726
+ */
727
+ const JOINT_SURFACE = 'surface.carrick-backfill.d.ts';
728
+ /**
729
+ * Self-check both stubs of a backfill (carrick#2041).
730
+ *
731
+ * When the two stubs hold the same tree beside their surfaces, both surfaces
732
+ * are checked in one program over the first stub's tree, which is what the
733
+ * check costs: every declaration of the tree and of the installed packages it
734
+ * reaches. Each surface is a module of its own and nothing imports either, so
735
+ * neither changes what the other's aliases read, and each alias's closure is
736
+ * walked from its own surface. What the repair pass rewrote in the shared
737
+ * tree is copied into the second stub, which holds the same files.
738
+ *
739
+ * Otherwise (the backfilled aliases were the only route to some module, so
740
+ * the trees differ) each stub is checked in a program of its own, which is
741
+ * what the stub would be checked in alone; the two programs share the files
742
+ * they parse outside the stubs.
743
+ */
744
+ function selfCheckBoth(first, second, checkArgs, hostFor) {
745
+ const typesOf = (written) => path.join(written.stubDir, 'types');
746
+ if (sameTreeBesideSurface(first, second)) {
747
+ const joint = path.join(typesOf(first), JOINT_SURFACE);
748
+ first.guard.writeFile(joint, fs.readFileSync(second.surfaceAbsPath, 'utf8'));
749
+ let records;
750
+ try {
751
+ const installs = { ...second.installs, ...first.installs };
752
+ records = selfCheckStub({
753
+ ...checkArgs(first, hostFor(installs)),
754
+ surfaces: [
755
+ { surfaceAbsPath: first.surfaceAbsPath, resolved: first.resolved },
756
+ { surfaceAbsPath: joint, resolved: second.resolved },
757
+ ],
758
+ pinned: { ...second.pinned, ...first.pinned },
759
+ });
760
+ }
761
+ catch (err) {
762
+ // The first stub is checked alone, as it would be with no backfill.
763
+ console.error(`[sidecar] backfill self-check failed, first stub checked alone: ${err instanceof Error ? err.message : String(err)}`);
764
+ if (fs.existsSync(joint))
765
+ first.guard.unlink(joint);
766
+ return { first: selfCheckStub(checkArgs(first, hostFor(first.installs)))[0], second: undefined };
767
+ }
768
+ finally {
769
+ if (fs.existsSync(joint))
770
+ first.guard.unlink(joint);
771
+ }
772
+ for (const rel of second.emittedFiles) {
773
+ if (rel === 'surface.d.ts')
774
+ continue;
775
+ const text = fs.readFileSync(path.join(typesOf(first), rel), 'utf8');
776
+ const dest = path.join(typesOf(second), rel);
777
+ if (fs.readFileSync(dest, 'utf8') !== text)
778
+ second.guard.writeFile(dest, text);
779
+ }
780
+ return { first: records[0], second: records[1] };
781
+ }
782
+ const inStubs = (file) => {
783
+ const abs = path.resolve(file);
784
+ return [first.stubDir, second.stubDir].some((dir) => abs === dir || abs.startsWith(dir + path.sep));
785
+ };
786
+ const parsedOnce = new Map();
787
+ const sharing = (installs) => {
788
+ const host = hostFor(installs);
789
+ return (options) => sharingHost(host?.(options) ?? ts.createCompilerHost(options), inStubs, parsedOnce);
790
+ };
791
+ const [firstRecords] = selfCheckStub(checkArgs(first, sharing(first.installs)));
792
+ let secondRecords;
793
+ try {
794
+ [secondRecords] = selfCheckStub(checkArgs(second, sharing(second.installs)));
795
+ }
796
+ catch (err) {
797
+ console.error(`[sidecar] backfill self-check failed: ${err instanceof Error ? err.message : String(err)}`);
798
+ }
799
+ return { first: firstRecords, second: secondRecords };
800
+ }
801
+ /** Whether two stubs hold the same files, byte for byte, beside `surface.d.ts`. */
802
+ function sameTreeBesideSurface(first, second) {
803
+ const besides = (written) => written.emittedFiles.filter((rel) => rel !== 'surface.d.ts').sort();
804
+ const a = besides(first);
805
+ const b = besides(second);
806
+ if (a.length !== b.length || a.some((rel, i) => rel !== b[i]))
807
+ return false;
808
+ if (a.includes(JOINT_SURFACE))
809
+ return false;
810
+ return a.every((rel) => fs.readFileSync(path.join(first.stubDir, 'types', rel), 'utf8') ===
811
+ fs.readFileSync(path.join(second.stubDir, 'types', rel), 'utf8'));
812
+ }
813
+ /** Write a stub's manifest and answer it. */
814
+ function finishStub(written, aliases, args) {
565
815
  const fidelity = computeFidelity(aliases);
566
- stubGuard.writeFile(path.join(stubDir, 'carrick-manifest.json'), JSON.stringify({
567
- package_name: packageName,
816
+ written.guard.writeFile(path.join(written.stubDir, 'carrick-manifest.json'), JSON.stringify({
817
+ package_name: args.packageName,
568
818
  ts_version: ts.version,
569
- bare_checkout: bareCheckout,
819
+ bare_checkout: args.bareCheckout,
570
820
  aliases,
571
821
  fidelity,
572
822
  }, null, 2) + '\n');
573
823
  return {
574
824
  success: true,
575
- stub_dir: stubDir,
576
- package_name: packageName,
577
- emitted_files: emittedFiles.map((rel) => `types/${rel}`).sort(),
578
- pinned_dependencies: pinned,
579
- unpinned_externals: unpinned,
825
+ stub_dir: written.stubDir,
826
+ package_name: args.packageName,
827
+ emitted_files: written.emittedFiles.map((rel) => `types/${rel}`).sort(),
828
+ pinned_dependencies: written.pinned,
829
+ unpinned_externals: written.unpinned,
580
830
  aliases,
581
831
  fidelity,
582
- augmentation_files: augmentationFiles.sort(),
583
- specifier_rewrites: specifierRewrites,
584
- bare_checkout: bareCheckout,
585
- unresolved_dependencies: unresolvedDependencies,
832
+ augmentation_files: written.augmentationFiles.sort(),
833
+ specifier_rewrites: written.specifierRewrites,
834
+ bare_checkout: args.bareCheckout,
835
+ unresolved_dependencies: args.unresolvedDependencies,
586
836
  ts_version: ts.version,
587
- errors,
837
+ errors: args.errors,
588
838
  };
589
839
  }
590
840
  /** How many unresolved packages a capture result names. */
@@ -784,36 +1034,47 @@ function rewriteSurfaceAliasesToUnknown(text, demoted) {
784
1034
  * a print that imports a module), so it is demoted with the reason, and cannot
785
1035
  * self-check clean.
786
1036
  */
787
- function resolveAnchorsByOwner(opts, groups, emit, ctx, errors) {
788
- const resolved = new Array(opts.anchors.length);
1037
+ function resolveAnchorsByOwner(opts, groups, emit, ctx) {
1038
+ const analyses = new Map();
789
1039
  for (const [owner, indexes] of groups) {
790
1040
  const anchors = indexes.map((index) => opts.anchors[index]);
791
- const group = resolveAnchors({ ...opts, anchors }, owner.parsed, ctx, undefined, owner);
792
- let demoted = 0;
793
- group.forEach((anchor, position) => {
794
- const index = indexes[position];
795
- const namesModule = anchor.request.kind === 'symbol' ||
796
- anchor.request.kind === 'handler_return' ||
797
- collectSpecifiers(anchor.aliasText).size > 0;
798
- if (owner === emit || anchor.failureReason !== undefined || !namesModule || emitsAlike(owner, emit)) {
799
- resolved[index] = anchor;
800
- return;
1041
+ analyses.set(owner, resolveAnchors({ ...opts, anchors }, owner.parsed, ctx, undefined, owner));
1042
+ }
1043
+ // Each owner's anchors as its program read them, under the one emit.
1044
+ const underEmit = (read) => {
1045
+ const resolved = new Array(opts.anchors.length);
1046
+ const errors = [];
1047
+ for (const [owner, indexes] of groups) {
1048
+ let demoted = 0;
1049
+ read(owner, analyses.get(owner), indexes).forEach((anchor, position) => {
1050
+ const index = indexes[position];
1051
+ const namesModule = anchor.request.kind === 'symbol' ||
1052
+ anchor.request.kind === 'handler_return' ||
1053
+ collectSpecifiers(anchor.aliasText).size > 0;
1054
+ if (owner === emit || anchor.failureReason !== undefined || !namesModule || emitsAlike(owner, emit)) {
1055
+ resolved[index] = anchor;
1056
+ return;
1057
+ }
1058
+ demoted += 1;
1059
+ resolved[index] = {
1060
+ request: anchor.request,
1061
+ aliasText: 'unknown',
1062
+ serialization: 'structural_fallback',
1063
+ failureReason: `typed under ${owner.configPath}, the project that owns its file, whose options differ ` +
1064
+ `from ${emit.configPath}, which emits the surface; the module it names would be declared under the wrong options`,
1065
+ };
1066
+ });
1067
+ if (owner !== emit) {
1068
+ errors.push(`${indexes.length} anchor(s) typed under ${owner.configPath}, the project that owns their files` +
1069
+ (demoted > 0 ? `; ${demoted} demoted because the surface is emitted under ${emit.configPath}` : ''));
801
1070
  }
802
- demoted += 1;
803
- resolved[index] = {
804
- request: anchor.request,
805
- aliasText: 'unknown',
806
- serialization: 'structural_fallback',
807
- failureReason: `typed under ${owner.configPath}, the project that owns its file, whose options differ ` +
808
- `from ${emit.configPath}, which emits the surface; the module it names would be declared under the wrong options`,
809
- };
810
- });
811
- if (owner !== emit) {
812
- errors.push(`${indexes.length} anchor(s) typed under ${owner.configPath}, the project that owns their files` +
813
- (demoted > 0 ? `; ${demoted} demoted because the surface is emitted under ${emit.configPath}` : ''));
814
1071
  }
815
- }
816
- return resolved;
1072
+ return { resolved, errors };
1073
+ };
1074
+ return {
1075
+ ...underEmit((_owner, analysis) => analysis.resolved),
1076
+ resolveAgain: (anchors, backfilled) => underEmit((_owner, analysis, indexes) => analysis.resolveAgain(indexes.map((index) => anchors[index]), backfilled).resolved),
1077
+ };
817
1078
  }
818
1079
  /**
819
1080
  * The compiler host a capture program is built on: the Deno graph's, else the
@@ -926,25 +1187,50 @@ function resolveAnchors(opts, parsed, ctx, deno, owner) {
926
1187
  };
927
1188
  // A literal anchor whose text is a bare identifier resolves through a
928
1189
  // sibling symbol anchor's module when one names the same symbol.
929
- const siblingSymbolSpecs = new Map();
930
- for (const anchor of opts.anchors) {
931
- if (anchor.kind !== 'symbol')
932
- continue;
933
- if (!siblingSymbolSpecs.has(anchor.symbol_name)) {
934
- siblingSymbolSpecs.set(anchor.symbol_name, entryRelativeSpecifier(ctx.entryDir, ctx.repoRoot, anchor.source_file, resolveFromEntry));
1190
+ const siblingSymbolSpecsOf = (anchors) => {
1191
+ const specs = new Map();
1192
+ for (const anchor of anchors) {
1193
+ if (anchor.kind !== 'symbol')
1194
+ continue;
1195
+ if (!specs.has(anchor.symbol_name)) {
1196
+ specs.set(anchor.symbol_name, entryRelativeSpecifier(ctx.entryDir, ctx.repoRoot, anchor.source_file, resolveFromEntry));
1197
+ }
935
1198
  }
936
- }
937
- return opts.anchors.map((request, index) => {
938
- const anchor = resolveAnchor(program, request, {
939
- repoRoot: ctx.repoRoot,
940
- entryDir: ctx.entryDir,
941
- placeholder: placeholders.get(request.alias),
942
- siblingSymbolSpecs,
943
- resolveFromEntry,
944
- });
1199
+ return specs;
1200
+ };
1201
+ const siblingSymbolSpecs = siblingSymbolSpecsOf(opts.anchors);
1202
+ const resolveIn = (request, specs) => resolveAnchor(program, request, {
1203
+ repoRoot: ctx.repoRoot,
1204
+ entryDir: ctx.entryDir,
1205
+ placeholder: placeholders.get(request.alias),
1206
+ siblingSymbolSpecs: specs,
1207
+ resolveFromEntry,
1208
+ });
1209
+ const resolved = opts.anchors.map((request, index) => {
1210
+ const anchor = resolveIn(request, siblingSymbolSpecs);
945
1211
  ctx.progress('anchors', `${index + 1} of ${opts.anchors.length}`);
946
1212
  return anchor;
947
1213
  });
1214
+ return {
1215
+ resolved,
1216
+ errors: [],
1217
+ // The program is held by this closure until the capture drops it.
1218
+ resolveAgain: (anchors, backfilled) => {
1219
+ const specs = siblingSymbolSpecsOf(anchors);
1220
+ return {
1221
+ resolved: anchors.map((request, index) => {
1222
+ // A backfilled alias is a literal now, and a literal whose bare
1223
+ // name a backfilled symbol anchor resolved reads through another
1224
+ // sibling, or none. Every other anchor reads as it did.
1225
+ const text = request.kind === 'literal' ? request.type_text.trim() : undefined;
1226
+ const reread = backfilled.has(request.alias) ||
1227
+ (text !== undefined && siblingSymbolSpecs.get(text) !== specs.get(text));
1228
+ return reread ? resolveIn(request, specs) : resolved[index];
1229
+ }),
1230
+ errors: [],
1231
+ };
1232
+ },
1233
+ };
948
1234
  }
949
1235
  finally {
950
1236
  if (fs.existsSync(ctx.entryPath))