@diffci.com/diffci 0.3.23 → 0.3.25

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 (55) hide show
  1. package/dist-client/src/client/agent-setup.d.ts +23 -0
  2. package/dist-client/src/client/agent-setup.js +111 -0
  3. package/dist-client/src/client/cli.js +26 -8
  4. package/dist-client/src/client/failure-baseline.js +0 -0
  5. package/dist-client/src/client/full-command.d.ts +10 -0
  6. package/dist-client/src/client/full-command.js +22 -0
  7. package/dist-client/src/client/hook.d.ts +1 -0
  8. package/dist-client/src/client/hook.js +9 -0
  9. package/dist-client/src/client/mcp.js +10 -4
  10. package/dist-client/src/client/observe.js +10 -5
  11. package/dist-client/src/client/verify.js +18 -3
  12. package/dist-client/src/client/workflow-templates.d.ts +2 -2
  13. package/dist-client/src/client/workflow-templates.js +2 -2
  14. package/node_modules/@diffci.com/core/README.md +7 -0
  15. package/node_modules/@diffci.com/core/dist/cache/graph-cache.d.ts +1 -1
  16. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js +3 -1
  17. package/node_modules/@diffci.com/core/dist/cache/graph-cache.js.map +1 -1
  18. package/node_modules/@diffci.com/core/dist/git/git-diff.js +16 -0
  19. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  20. package/node_modules/@diffci.com/core/dist/planner/test-command.d.ts +4 -0
  21. package/node_modules/@diffci.com/core/dist/planner/test-command.js +127 -20
  22. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  23. package/node_modules/@diffci.com/core/dist/repo/analyzer.js +9 -2
  24. package/node_modules/@diffci.com/core/dist/repo/analyzer.js.map +1 -1
  25. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +22 -2
  26. package/node_modules/@diffci.com/core/dist/repo/file-references.js +70 -10
  27. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  28. package/node_modules/@diffci.com/core/dist/repo/graph.js +231 -28
  29. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  30. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +28 -0
  31. package/node_modules/@diffci.com/core/dist/repo/impact.js +167 -11
  32. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  33. package/node_modules/@diffci.com/core/dist/repo/test-discovery.d.ts +5 -1
  34. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +55 -6
  35. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  36. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +7 -0
  37. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.d.ts +2 -2
  38. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +7 -5
  39. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  40. package/node_modules/@diffci.com/core/src/cache/graph-cache.ts +3 -1
  41. package/node_modules/@diffci.com/core/src/git/git-diff.ts +13 -0
  42. package/node_modules/@diffci.com/core/src/planner/test-command.ts +125 -16
  43. package/node_modules/@diffci.com/core/src/repo/analyzer.ts +9 -2
  44. package/node_modules/@diffci.com/core/src/repo/file-references.ts +74 -11
  45. package/node_modules/@diffci.com/core/src/repo/graph.ts +206 -30
  46. package/node_modules/@diffci.com/core/src/repo/impact.ts +169 -12
  47. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +52 -8
  48. package/node_modules/@diffci.com/core/src/repo/types.ts +7 -0
  49. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +8 -6
  50. package/node_modules/source-map-js/lib/quick-sort.js +10 -1
  51. package/node_modules/source-map-js/lib/source-map-consumer.js +51 -3
  52. package/node_modules/source-map-js/lib/source-map-generator.js +6 -4
  53. package/node_modules/source-map-js/lib/source-node.js +7 -0
  54. package/node_modules/source-map-js/package.json +1 -1
  55. package/package.json +2 -2
@@ -2,13 +2,13 @@ import { extname, posix } from "node:path";
2
2
  import { isGoDiscoveryIgnoredPath } from "./adapters/go.js";
3
3
  import { inVuePackage } from "./vue-scope.js";
4
4
  import type { ChangedFile, GitDelta } from "../git/types.js";
5
- import type { DependencyGraph, DependencyGraphNode, DependencyGraphResult, EntryPoint, RepositoryProfile } from "./types.js";
5
+ import type { DependencyGraph, DependencyGraphNode, DependencyGraphResult, EntryPoint, RepositoryProfile, UnresolvedDependency } from "./types.js";
6
6
  import type { ChangedImpact, EntryPointImpact, ImpactEvidence, ImpactEvidencePath, ImpactReason, ImpactResult, ImpactRiskSignal, TestImpact } from "./impact-types.js";
7
7
  import { refineConfidenceForDelta } from "./graph.js";
8
8
  import { repositoryLayout, UNKNOWN_REPOSITORY_LAYOUT, type RepositoryLayout } from "./layout.js";
9
9
  import { DEFAULT_TEST_FILE_MATCHER, matchesGlob as matchesTestGlob, testDiscoveryErrors, testFileMatcherForProfile } from "./test-discovery.js";
10
10
  import { resolveTestFixtureOwners } from "./test-fixture-ownership.js";
11
- import { infrastructureRole, isImplicitlyLoadedFile, isWorkerConfig, resolveFileReferences, suiteMayRunWorkers, testScriptClosure } from "./file-references.js";
11
+ import { directoryWalkers, DIRECTING_EXTENSIONS, infrastructureRole, listsDirectories, loadsWithoutNaming, isImplicitlyLoadedFile, isWorkerConfig, resolveFileReferences, suiteMayRunWorkers, testScriptClosure } from "./file-references.js";
12
12
  import { workflowFeedsTests } from "./workflow-test-steps.js";
13
13
  import { modelTestScriptUniverse, type ScriptUniverse } from "./script-universe.js";
14
14
  import { compiledProjects, type CompiledProject } from "./compiled-projects.js";
@@ -21,6 +21,8 @@ const NEXT_ENTRY_NAMES = new Set(["page","layout","route","api","loading","error
21
21
  function isLockfile(filePath: string): boolean { return /(?:^|\/)(?:package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?)$/.test(filePath); }
22
22
  function isSourceFilePath(filePath: string): boolean { return SOURCE_EXTENSIONS.has(extname(filePath).toLowerCase()); }
23
23
  function isAssetFilePath(filePath: string): boolean { return ASSET_EXTENSIONS.has(extname(filePath).toLowerCase()); }
24
+ /** Vitest's default `typecheck.include`: tests whose outcome is the type checker's. */
25
+ const TYPE_TEST_FILE = /\.(?:test|spec)-d\.[cm]?[jt]sx?$/;
24
26
  // "Is this a test?" is answered by the profile's test patterns (src/repo/test-discovery.ts) - one shared
25
27
  // definition with analyzer discovery and graph node flags. Module-level helpers receive it explicitly.
26
28
  type IsTestFile = (filePath: string) => boolean;
@@ -68,6 +70,8 @@ function isDatabaseFile(filePath: string): boolean { const DATABASE_DIRS = new S
68
70
  */
69
71
  function classifyNextEntryPoint(filePath: string, layout: RepositoryLayout): EntryPoint["kind"] | undefined { if (!layout.isNextApp) return undefined; if (!isSourceFilePath(filePath)) return undefined; const base = posix.basename(filePath, extname(filePath)); const lower = base.toLowerCase(); if (lower === "page") return "next-page"; if (lower === "layout") return "next-layout"; if (lower === "route") return "next-route"; if (lower === "api" && filePath.includes("/api/")) return "next-api"; if (lower === "loading") return "next-loading"; if (lower === "error") return "next-error"; if (lower === "template") return "next-template"; if (lower === "not-found") return "next-error"; if (lower === "middleware") return "next-api"; return undefined; }
70
72
  function allChangePaths(file: ChangedFile): string[] { return file.oldPath ? [file.path, file.oldPath] : [file.path]; }
73
+ /** The module an extensionless import of `path` names: `a/x.ts` -> `a/x`, `a/x/index.ts` -> `a/x`. */
74
+ function moduleKey(path: string): string { const stem = path.replace(/\.[^./]+$/, ""); return posix.basename(stem) === "index" ? posix.dirname(stem) : stem; }
71
75
  function nodeByPath(graph: DependencyGraph, path: string): DependencyGraphNode | undefined { return graph.nodes.find((n) => n.path === path); }
72
76
  function hasNode(graph: DependencyGraph, path: string): boolean { return nodeByPath(graph, path) !== undefined; }
73
77
  function isEntryPoint(profile: RepositoryProfile, path: string): EntryPoint | undefined { return profile.entryPoints.find((e) => e.path === path); }
@@ -260,6 +264,18 @@ export class ImpactAnalyzer {
260
264
  private selectTestPhases = false;
261
265
  private testPhases = new Set<string>();
262
266
  private workersOutsideSuite: boolean | undefined;
267
+ private runtimeTestSelection = false;
268
+ private unresolved: readonly UnresolvedDependency[] = [];
269
+ private walkerTests: string[] | undefined;
270
+
271
+ /** Dependents whose tests a change to `path` can affect. When the graph allows runtime selection
272
+ * (DependencyGraphResult.runtimeTestSelection) an `import type` edge selects only type tests. */
273
+ private testDependents(graph: DependencyGraph, path: string, dependents: readonly string[]): ReadonlySet<string> {
274
+ if (!this.runtimeTestSelection || !graph.transitiveRuntimeDependentsOf) return new Set(dependents);
275
+ const selected = new Set(graph.transitiveRuntimeDependentsOf(path));
276
+ for (const dependent of dependents) if (TYPE_TEST_FILE.test(dependent)) selected.add(dependent);
277
+ return selected;
278
+ }
263
279
 
264
280
  /** True when nothing in the repository runs a Worker (file-references.ts, suiteMayRunWorkers); false,
265
281
  * which keeps wrangler configs global, whenever repository contents are unavailable. */
@@ -281,6 +297,9 @@ export class ImpactAnalyzer {
281
297
  this.selectTestPhases = options.selectTestPhases === true;
282
298
  this.testPhases = new Set();
283
299
  this.workersOutsideSuite = undefined;
300
+ this.walkerTests = undefined;
301
+ this.runtimeTestSelection = graphResult.runtimeTestSelection === true;
302
+ this.unresolved = graphResult.unresolved ?? [];
284
303
  this.sortedRepositoryFiles = options.repositoryFiles ? [...options.repositoryFiles].sort() : [];
285
304
  this.compiledProjectCache = undefined;
286
305
  // One read per file per analysis, however many changed files ask who reads them.
@@ -545,7 +564,11 @@ export class ImpactAnalyzer {
545
564
  .filter((ref) => ref.resolution === "external-package" && packageRoot(ref.specifier) === name)
546
565
  .map((ref) => ref.importer))].sort();
547
566
  if (importers.length === 0) {
548
- fail(`${dependencyChange(name)} and no repository source imports it; full validation required`);
567
+ const blocker = this.resolveUnimportedPackage(name, changedFile, closureBodies, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence);
568
+ if (blocker) {
569
+ evidence.push(makeEvidence("DEPENDENCY", changedFile, `${name}: ${blocker}`));
570
+ fail(`${dependencyChange(name)} and no repository source imports it; full validation required`);
571
+ }
549
572
  continue;
550
573
  }
551
574
  const quoted = new RegExp(`["'\`]${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/[^"'\`]*)?["'\`]`);
@@ -575,6 +598,67 @@ export class ImpactAnalyzer {
575
598
  }
576
599
  }
577
600
 
601
+ /**
602
+ * A changed dependency no repository code imports (2026-11-04). Usually a CLI the repository runs by
603
+ * its executable's name: bumping `@diffci.com/diffci`, run as `diffci`, made all 601 DentalPresence
604
+ * tests run. Such a package reaches the suite only by being run or loaded, so it narrows when
605
+ * package-lock.json records its executables and every file naming the package or one of them
606
+ * resolves: a test is selected, graph code selects its dependent tests, and any other code or
607
+ * directing file must itself resolve by reference. Returns why it cannot narrow: the executables are
608
+ * unknown, the name suggests tooling loads it by convention (types, plugins, presets, test runners),
609
+ * or the test script, a file tooling loads, or a test-feeding workflow step names it.
610
+ */
611
+ private resolveUnimportedPackage(
612
+ name: string,
613
+ changedFile: string,
614
+ closureBodies: readonly string[],
615
+ graph: DependencyGraph,
616
+ profile: RepositoryProfile,
617
+ affectedSources: Map<string, ImpactEvidence[]>,
618
+ affectedEntryPoints: Map<string, EntryPointImpact>,
619
+ affectedTests: Map<string, TestImpact>,
620
+ affectedScripts: Map<string, ImpactEvidence[]>,
621
+ evidence: ImpactEvidence[],
622
+ ): string | undefined {
623
+ if (/(?:^@types\/|types|plugin|preset|config|loader|register|polyfill|setup|eslint|prettier|stylelint|babel|postcss|tailwind|jest|vitest|mocha|ava|playwright|cypress|typescript|ts-node|^tsx$|swc|esbuild|vite|webpack|rollup)/i.test(name)) {
624
+ return "tooling may load it by naming convention";
625
+ }
626
+ if (!this.repositoryFiles?.has("package-lock.json")) return "its executables are unknown without package-lock.json";
627
+ let bin: unknown;
628
+ try {
629
+ const lock = JSON.parse(this.readRepositoryFile!("package-lock.json") ?? "") as { packages?: Record<string, { bin?: unknown }> };
630
+ bin = lock.packages?.[`node_modules/${name}`]?.bin;
631
+ } catch { return "package-lock.json could not be parsed"; }
632
+ const bins = typeof bin === "string" ? [name.split("/").pop()!] : bin && typeof bin === "object" ? Object.keys(bin) : [];
633
+ if (bins.length === 0) return "it has no executable, so only tooling can load it";
634
+ const escape = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
635
+ const named = new RegExp(`(?:^|[\\s"'\`=/(])(?:${[name, ...bins].map(escape).join("|")})(?=$|[\\s"'\`/@),;:])`, "m");
636
+ if (closureBodies.some((body) => named.test(body))) return "the test script runs it";
637
+ const scripts = profile.packageJson.scripts;
638
+ for (const path of this.sortedRepositoryFiles) {
639
+ if (path === "package.json" || isLockfile(path) || this.layout.isDocumentationPath(path)) continue;
640
+ const content = this.readRepositoryFile!(path);
641
+ if (content === undefined || !named.test(content)) continue;
642
+ if (isImplicitlyLoadedFile(path) || loadsWithoutNaming(path) || posix.basename(path) === "package.json") return `${path} names it and tooling loads that file`;
643
+ if (path.startsWith(".github/")) {
644
+ if (path.startsWith(".github/actions/") || (/^\.github\/workflows\//.test(path) && workflowFeedsTests(content, named, scripts))) return `${path} runs it before tests`;
645
+ continue;
646
+ }
647
+ if (isSourceFilePath(path) && this.isTestFile(path)) {
648
+ evidence.push(makeEvidence("DEPENDENCY", changedFile, `${path} names ${name}`, path));
649
+ this.addAffectedTest(changedFile, path, graph, affectedTests, "DEPENDENCY", evidence);
650
+ } else if (isSourceFilePath(path) && hasNode(graph, path)) {
651
+ evidence.push(makeEvidence("DEPENDENCY", changedFile, `${path} names ${name}`, path));
652
+ this.processSourceChange(path, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence);
653
+ } else if (isSourceFilePath(path) || DIRECTING_EXTENSIONS.test(path)) {
654
+ if (!this.resolveByReference(path, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence, { implicitReadersUnresolvable: true })) {
655
+ return `${path} names it and its own readers could not be resolved`;
656
+ }
657
+ }
658
+ }
659
+ return undefined;
660
+ }
661
+
578
662
  private processChangedPath(
579
663
  changedPath: string,
580
664
  changedImpact: ChangedImpact,
@@ -595,6 +679,17 @@ export class ImpactAnalyzer {
595
679
  this.processAssetChange(changedPath, graph, profile, affectedAssets, affectedEntryPoints, affectedTests, affectedSources, evidence);
596
680
  return;
597
681
  }
682
+ // Non-code files are resolved by reference below, directories included; code is not, so a test that
683
+ // lists the directory a code file is in is added here (file-references.ts, directoryWalkers).
684
+ if (isSourceFilePath(changedPath) && this.readRepositoryFile) {
685
+ const read = this.readRepositoryFile;
686
+ this.walkerTests ??= this.sortedRepositoryFiles.filter((path) => this.isTestFile(path) && listsDirectories(read(path)));
687
+ for (const test of directoryWalkers(changedPath, this.walkerTests, this.readRepositoryFile)) {
688
+ if (test === changedPath) continue;
689
+ evidence.push(makeEvidence("FILE_REFERENCE", changedPath, `${test} lists a directory containing ${changedPath}`, test));
690
+ this.addAffectedTest(changedPath, test, graph, affectedTests, "FILE_REFERENCE", evidence);
691
+ }
692
+ }
598
693
  const category = changedImpact.category;
599
694
  if (changedPath === this.dependencyLockfile) {
600
695
  // Dependency selection does not cover a test that reads the lockfile's bytes. Unlike general
@@ -605,6 +700,18 @@ export class ImpactAnalyzer {
605
700
  if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
606
701
  return;
607
702
  }
703
+ // A workspace package's manifest edit beyond version and metadata fields (git-diff.ts clears those)
704
+ // changes what the package installs, runs or exports, which reaches every package importing it.
705
+ // Readers that name the file are only the package's own tests, so they cannot bound it (2026-11-03).
706
+ const workspaceManifest = changedPath.endsWith("/package.json") && !changedPath.split("/").includes("node_modules")
707
+ && !this.contentCleared.has(changedPath) && changedImpact.file.changeType !== "added";
708
+ if (workspaceManifest) {
709
+ const message = `Workspace package manifest changed dependencies, scripts or resolution fields: ${changedPath}; full validation required`;
710
+ evidence.push(makeEvidence("UNKNOWN_FILE", changedPath, message));
711
+ riskSignals.push({ level: "critical", reason: "DEPENDENCY_MANIFEST", message, paths: [changedPath] });
712
+ if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
713
+ return;
714
+ }
608
715
  if (category === "test-fixture") {
609
716
  // Resolved per change PATH (a rename's old path resolves independently); an unresolvable side
610
717
  // degrades to the unknown-file fallback below rather than being silently dropped.
@@ -631,7 +738,9 @@ export class ImpactAnalyzer {
631
738
  return;
632
739
  }
633
740
  if (category === "docs") return;
634
- if (isAssetFilePath(changedPath) && !hasNode(graph, changedPath) && changedImpact.file.changeType !== "deleted" && !isDocumentationFile(changedPath, this.layout) && !isLockfile(changedPath)) {
741
+ // A rename's old path is gone at HEAD like a deleted file (`X.module.css` -> `X.css`).
742
+ const removed = changedImpact.file.changeType === "deleted" || (changedPath === changedImpact.file.oldPath && changedImpact.file.changeType === "renamed");
743
+ if (isAssetFilePath(changedPath) && !hasNode(graph, changedPath) && !removed && !isDocumentationFile(changedPath, this.layout) && !isLockfile(changedPath)) {
635
744
  // An asset no module imports can still be read from disk by a test. It used to select nothing
636
745
  // and require nothing, which is a silent skip; it now needs reader evidence like any other
637
746
  // non-code file (2026-10-21).
@@ -643,7 +752,8 @@ export class ImpactAnalyzer {
643
752
  return;
644
753
  }
645
754
  if (isAssetFilePath(changedPath)) {
646
- if (changedImpact.file.changeType === "deleted" && !hasNode(graph, changedPath)) {
755
+ if (removed && !hasNode(graph, changedPath)) {
756
+ if (this.resolveRemovedFile(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
647
757
  const message = `Deleted source/asset ${changedPath} not present in HEAD dependency graph; legacy dependents cannot be determined`;
648
758
  evidence.push(makeEvidence("DELETED_FILE_UNKNOWABLE_GRAPH", changedPath, message));
649
759
  riskSignals.push({ level: "critical", reason: "DELETED_FILE_UNKNOWABLE_GRAPH", message, paths: [changedPath] });
@@ -683,6 +793,7 @@ export class ImpactAnalyzer {
683
793
  return;
684
794
  }
685
795
  if (changedImpact.file.changeType === "deleted" && !hasNode(graph, changedPath)) {
796
+ if (this.resolveRemovedFile(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence)) return;
686
797
  const message = `Deleted source/asset ${changedPath} not present in HEAD dependency graph; legacy dependents cannot be determined`;
687
798
  evidence.push(makeEvidence("DELETED_FILE_UNKNOWABLE_GRAPH", changedPath, message));
688
799
  riskSignals.push({ level: "critical", reason: "DELETED_FILE_UNKNOWABLE_GRAPH", message, paths: [changedPath] });
@@ -692,6 +803,45 @@ export class ImpactAnalyzer {
692
803
  this.processSourceChange(changedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence);
693
804
  }
694
805
 
806
+ /**
807
+ * A file gone at HEAD that the HEAD graph has no node for (2026-11-04). Its old importers cannot be
808
+ * listed, but each one is either changed in this delta (its import was edited or removed, so it is
809
+ * analysed as a changed file), still imports the missing path (an unresolved import), or now resolves
810
+ * the same specifier to a sibling (`./x` from a deleted `x.ts` to a surviving `x/index.ts`). The last
811
+ * two are found here; anything else observes the absence only by naming the file, which the reference
812
+ * resolver checks without its directories. A directory listing is not modelled, as for an added asset
813
+ * the graph does import, nor is a tsconfig `paths` fallback that now resolves to another directory. Previously every such file fell back: the LobeHub catch replay's StyleX
814
+ * migration renames `X.module.css` to `X.css` and 16 of 47 verify commits ran the full suite for it.
815
+ */
816
+ private resolveRemovedFile(
817
+ removedPath: string,
818
+ graph: DependencyGraph,
819
+ profile: RepositoryProfile,
820
+ affectedSources: Map<string, ImpactEvidence[]>,
821
+ affectedEntryPoints: Map<string, EntryPointImpact>,
822
+ affectedTests: Map<string, TestImpact>,
823
+ affectedScripts: Map<string, ImpactEvidence[]>,
824
+ evidence: ImpactEvidence[],
825
+ ): boolean {
826
+ if (this.repositoryFiles?.has(removedPath)) return false;
827
+ const key = moduleKey(removedPath);
828
+ const names = new Set([posix.basename(removedPath), posix.basename(removedPath.replace(/\.[^./]+$/, "")), posix.basename(key)]);
829
+ // Conservative: any unresolved import whose last segment could name the file blocks, wherever it is.
830
+ const importer = this.unresolved.find((ref) => !ref.computed && names.has(posix.basename(ref.specifier.split(/[?#]/)[0]!)));
831
+ if (importer) {
832
+ evidence.push(makeEvidence("UNKNOWN_FILE", removedPath, `${importer.importer} imports ${importer.specifier}, which may have resolved to the removed ${removedPath}`));
833
+ return false;
834
+ }
835
+ if (!this.resolveByReference(removedPath, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence, { implicitReadersUnresolvable: true, removed: true })) return false;
836
+ for (const node of graph.nodes) {
837
+ if (node.path === removedPath || moduleKey(node.path) !== key) continue;
838
+ evidence.push(makeEvidence("DELETED_FILE_LEGACY_DEPENDENTS", removedPath, `${node.path} may now resolve imports of the removed ${removedPath}`, node.path));
839
+ this.processSourceChange(node.path, graph, profile, affectedSources, affectedEntryPoints, affectedTests, affectedScripts, evidence);
840
+ }
841
+ evidence.push(makeEvidence("DELETED_FILE_LEGACY_DEPENDENTS", removedPath, `No HEAD import can still reach the removed ${removedPath}; its former importers are changed files`));
842
+ return true;
843
+ }
844
+
695
845
  /** Projects some test compiles (src/repo/compiled-projects.ts), computed once per analysis and only
696
846
  * when file contents are available. */
697
847
  private compiledProjectsFor(graph: DependencyGraph): CompiledProject[] {
@@ -738,7 +888,7 @@ export class ImpactAnalyzer {
738
888
  affectedTests: Map<string, TestImpact>,
739
889
  affectedScripts: Map<string, ImpactEvidence[]>,
740
890
  evidence: ImpactEvidence[],
741
- { implicitReadersUnresolvable = false, allowNoReaders = false }: { implicitReadersUnresolvable?: boolean; allowNoReaders?: boolean } = {},
891
+ { implicitReadersUnresolvable = false, allowNoReaders = false, removed = false }: { implicitReadersUnresolvable?: boolean; allowNoReaders?: boolean; removed?: boolean } = {},
742
892
  ): boolean {
743
893
  if (!this.repositoryFiles || !this.readRepositoryFile) return false;
744
894
  if (isImplicitlyLoadedFile(changedPath) && !(isWorkerConfig(changedPath) && this.workerConfigsOutsideSuite())) return false;
@@ -755,6 +905,7 @@ export class ImpactAnalyzer {
755
905
  contentCleared: this.contentCleared,
756
906
  implicitReadersUnresolvable,
757
907
  allowNoReaders,
908
+ removed,
758
909
  testPhases: this.selectTestPhases,
759
910
  workerConfigsOutsideSuite: this.workerConfigsOutsideSuite(),
760
911
  });
@@ -774,11 +925,13 @@ export class ImpactAnalyzer {
774
925
  for (const code of resolution.code) {
775
926
  if (!affectedSources.has(code)) affectedSources.set(code, []);
776
927
  affectedSources.get(code)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${code} reads ${changedPath}`, code));
777
- for (const dependent of graph.transitiveDependentsOf(code)) {
778
- if (this.isTestFile(dependent)) this.addAffectedTest(changedPath, dependent, graph, affectedTests, "FILE_REFERENCE", evidence);
928
+ const codeDependents = graph.transitiveDependentsOf(code);
929
+ const testDependents = this.testDependents(graph, code, codeDependents);
930
+ for (const dependent of codeDependents) {
931
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) this.addAffectedTest(changedPath, dependent, graph, affectedTests, "FILE_REFERENCE", evidence);
779
932
  else if (nodeByPath(graph, dependent)?.isEntryPoint) this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "FILE_REFERENCE", changedPath, evidence);
780
933
  }
781
- for (const scriptPath of collectScriptsAmong([code, ...graph.transitiveDependentsOf(code)], this.isTestFile, this.layout)) {
934
+ for (const scriptPath of collectScriptsAmong([code, ...codeDependents], this.isTestFile, this.layout)) {
782
935
  if (!affectedScripts.has(scriptPath)) affectedScripts.set(scriptPath, []);
783
936
  affectedScripts.get(scriptPath)!.push(makeEvidence("FILE_REFERENCE", changedPath, `${changedPath} is read by script ${scriptPath}`, scriptPath));
784
937
  }
@@ -800,11 +953,12 @@ export class ImpactAnalyzer {
800
953
  affectedAssets.get(assetPath)!.push(makeEvidence("ASSET_DEPENDENCY", assetPath, `Changed asset: ${assetPath}`));
801
954
  if (!hasNode(graph, assetPath)) return;
802
955
  const dependents = graph.transitiveDependentsOf(assetPath);
956
+ const testDependents = this.testDependents(graph, assetPath, dependents);
803
957
  for (const dependent of dependents) {
804
958
  if (nodeByPath(graph, dependent)?.isEntryPoint) {
805
959
  this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "ASSET_DEPENDENCY", assetPath, evidence);
806
960
  }
807
- if (this.isTestFile(dependent)) {
961
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) {
808
962
  this.addAffectedTest(assetPath, dependent, graph, affectedTests, "ASSET_DEPENDENCY", evidence);
809
963
  }
810
964
  if (isSourceFilePath(dependent) && !this.isTestFile(dependent)) {
@@ -847,6 +1001,7 @@ export class ImpactAnalyzer {
847
1001
  }
848
1002
 
849
1003
  const dependents = graph.transitiveDependentsOf(sourcePath);
1004
+ const testDependents = this.testDependents(graph, sourcePath, dependents);
850
1005
  for (const dependent of dependents) {
851
1006
  if (!this.isTestFile(dependent)) {
852
1007
  if (!affectedSources.has(dependent)) affectedSources.set(dependent, []);
@@ -855,7 +1010,7 @@ export class ImpactAnalyzer {
855
1010
  if (nodeByPath(graph, dependent)?.isEntryPoint) {
856
1011
  this.addAffectedEntryPoint(dependent, profile, affectedEntryPoints, "DEPENDENCY", sourcePath, evidence);
857
1012
  }
858
- if (this.isTestFile(dependent)) {
1013
+ if (this.isTestFile(dependent) && testDependents.has(dependent)) {
859
1014
  this.addAffectedTest(sourcePath, dependent, graph, affectedTests, "DEPENDENCY", evidence);
860
1015
  }
861
1016
  }
@@ -1042,7 +1197,9 @@ export class ImpactAnalyzer {
1042
1197
  if (!fallbackReasons.includes(message)) fallbackReasons.push(message);
1043
1198
  continue;
1044
1199
  }
1045
- const runners = [importer, ...graph.transitiveDependentsOf(importer)].filter((path) => this.isTestFile(path));
1200
+ const importerDependents = graph.transitiveDependentsOf(importer);
1201
+ const testDependents = this.testDependents(graph, importer, importerDependents);
1202
+ const runners = [importer, ...importerDependents.filter((path) => testDependents.has(path))].filter((path) => this.isTestFile(path));
1046
1203
  for (const test of runners) this.addAffectedTest(importer, test, graph, affectedTests, "COMPUTED_IMPORT", evidence);
1047
1204
  evidence.push(makeEvidence("COMPUTED_IMPORT", importer, `${importer} loads a computed module specifier; the ${runners.length} test(s) that run it are selected`));
1048
1205
  }
@@ -30,8 +30,9 @@ export type TestFamily = "unit" | "snapshot" | "e2e" | "integration" | "benchmar
30
30
  export interface TestRunnerConfig {
31
31
  /** A known unsupported declaration that makes even a nonempty test universe incomplete. */
32
32
  discoveryError?: string;
33
- /** Inline Vitest projects; undefined means no projects, null means ambiguous. */
34
- projects?: { name: string; includes: string[]; runtimeSelectionSafe: boolean }[] | null;
33
+ /** Inline Vitest projects; undefined means no projects, null means ambiguous. `excludes` holds the
34
+ * root `test.exclude` and the project's own, which `extends: true` concatenates. */
35
+ projects?: { name: string; includes: string[]; excludes?: string[]; runtimeSelectionSafe: boolean }[] | null;
35
36
  runtimeSelectionUnsafe?: boolean;
36
37
  /** Repo-relative config file, e.g. "vitest.e2e.config.ts". */
37
38
  file: string;
@@ -116,7 +117,9 @@ function inlineProjects(source: string): TestRunnerConfig["projects"] {
116
117
  let found: ts.Node[] = [];
117
118
  let sharedState = false;
118
119
  const visit = (node: ts.Node): void => {
119
- if (ts.isPropertyAssignment(node) && node.name.getText(ast) === "projects") found.push(node.initializer);
120
+ // Only `test.projects`: plugin options use the same name (LobeHub's `tsconfigPaths({ projects })`).
121
+ if (ts.isPropertyAssignment(node) && node.name.getText(ast) === "projects" && ts.isObjectLiteralExpression(node.parent)
122
+ && ts.isPropertyAssignment(node.parent.parent) && node.parent.parent.name.getText(ast) === "test") found.push(node.initializer);
120
123
  if (ts.isPropertyAssignment(node) && node.name.getText(ast) === "isolate" && node.initializer.kind !== ts.SyntaxKind.TrueKeyword) sharedState = true;
121
124
  ts.forEachChild(node, visit);
122
125
  };
@@ -127,27 +130,68 @@ function inlineProjects(source: string): TestRunnerConfig["projects"] {
127
130
  if (!ts.isObjectLiteralExpression(node)) return;
128
131
  const values = new Map<string, ts.Expression>();
129
132
  for (const property of node.properties) {
130
- if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) || values.has(property.name.text)) return;
131
- values.set(property.name.text, property.initializer);
133
+ // `{ alias, exclude }` shorthand names a binding of the same name.
134
+ const value = ts.isPropertyAssignment(property) ? property.initializer : ts.isShorthandPropertyAssignment(property) ? property.name : undefined;
135
+ if (!value || !property.name || !ts.isIdentifier(property.name) || values.has(property.name.text)) return;
136
+ values.set(property.name.text, value);
137
+ }
138
+ return values;
139
+ };
140
+ // Top-level `const exclude = ['...']`, which configs spread into projects (2026-11-04, LobeHub).
141
+ const constArrays = new Map<string, ts.ArrayLiteralExpression>();
142
+ for (const statement of ast.statements) {
143
+ if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
144
+ for (const declaration of statement.declarationList.declarations) {
145
+ if (ts.isIdentifier(declaration.name) && declaration.initializer && ts.isArrayLiteralExpression(declaration.initializer)) constArrays.set(declaration.name.text, declaration.initializer);
146
+ }
147
+ }
148
+ const strings = (node: ts.Expression, depth = 0): string[] | undefined => {
149
+ if (depth > 4) return;
150
+ if (ts.isIdentifier(node)) return constArrays.has(node.text) ? strings(constArrays.get(node.text)!, depth + 1) : undefined;
151
+ if (!ts.isArrayLiteralExpression(node)) return;
152
+ const values: string[] = [];
153
+ for (const element of node.elements) {
154
+ const lifted = ts.isStringLiteral(element) ? [element.text] : ts.isSpreadElement(element) ? strings(element.expression, depth + 1) : undefined;
155
+ if (!lifted) return;
156
+ values.push(...lifted);
132
157
  }
133
158
  return values;
134
159
  };
135
160
  const projects: NonNullable<TestRunnerConfig["projects"]> = [];
136
161
  const inherited = properties(found[0].parent.parent);
137
- const inheritedSafe = inherited && [...inherited.keys()].every(key => ["projects", "coverage", "setupFiles", "globalSetup", "isolate"].includes(key));
162
+ // Root options that only shape how each file is loaded or reported. Running a subset of files under
163
+ // them runs each file exactly as the full run would (2026-11-04: LobeHub's root sets alias, deps,
164
+ // environment, exclude, globals and server.deps beside setupFiles and coverage).
165
+ const inheritedSafe = inherited && [...inherited.keys()].every(key => ["projects", "coverage", "setupFiles", "globalSetup", "isolate", "alias", "deps", "environment", "exclude", "globals", "server"].includes(key));
166
+ const inheritedExclude = inherited?.get("exclude");
167
+ const rootExcludes = inheritedExclude ? strings(inheritedExclude) : [];
168
+ if (!rootExcludes) return null;
138
169
  for (const element of found[0].elements) {
139
170
  const project = properties(element);
140
171
  const test = project?.get("test");
141
172
  const fields = test && properties(test);
142
173
  const name = fields?.get("name");
143
174
  const include = fields?.get("include");
144
- if (!project || project.size !== 2 || project.get("extends")?.kind !== ts.SyntaxKind.TrueKeyword || !fields || !name || !ts.isStringLiteral(name) || !/^[\w-]+$/.test(name.text) || !include || !ts.isArrayLiteralExpression(include) || !include.elements.length || include.elements.some(value => !ts.isStringLiteral(value))) return null;
175
+ const exclude = fields?.get("exclude");
176
+ // `extends: true` concatenates arrays, so a project without `include` takes the root's, and with no
177
+ // root include Vitest's default. A root include is not modelled.
178
+ const includes = include ? strings(include) : inherited?.has("include") ? undefined : [VITEST_DEFAULT_INCLUDE];
179
+ const excludes = exclude ? strings(exclude) : [];
180
+ if (!project || project.size !== 2 || project.get("extends")?.kind !== ts.SyntaxKind.TrueKeyword || !fields || !name || !ts.isStringLiteral(name) || !/^[\w-]+$/.test(name.text) || !includes?.length || !excludes) return null;
145
181
  if (projects.some(value => value.name === name.text)) return null;
146
- projects.push({ name: name.text, includes: include.elements.map(value => (value as ts.StringLiteral).text), runtimeSelectionSafe: Boolean(inheritedSafe) && !sharedState && [...fields.keys()].every(key => ["name", "include", "isolate"].includes(key)) });
182
+ projects.push({
183
+ name: name.text,
184
+ includes,
185
+ ...(rootExcludes.length || excludes.length ? { excludes: [...new Set([...rootExcludes, ...excludes])] } : {}),
186
+ runtimeSelectionSafe: Boolean(inheritedSafe) && !sharedState && [...fields.keys()].every(key => ["name", "include", "exclude", "environment", "isolate"].includes(key)),
187
+ });
147
188
  }
148
189
  return projects.length ? projects : null;
149
190
  }
150
191
 
192
+ /** Vitest's own `test.include` default. */
193
+ export const VITEST_DEFAULT_INCLUDE = "**/*.{test,spec}.?(c|m)[jt]s?(x)";
194
+
151
195
  export interface TestDiscovery {
152
196
  configs: TestRunnerConfig[];
153
197
  /**
@@ -171,6 +171,9 @@ export interface DependencyGraph {
171
171
  dependentsOf(filePath: string): string[];
172
172
  transitiveDependenciesOf(filePath: string): string[];
173
173
  transitiveDependentsOf(filePath: string): string[];
174
+ /** Dependents through edges that exist at runtime (`import type` excluded). Absent means unknown, and
175
+ * callers fall back to transitiveDependentsOf. */
176
+ transitiveRuntimeDependentsOf?(filePath: string): string[];
174
177
  }
175
178
 
176
179
  export interface UnresolvedDependency {
@@ -248,4 +251,8 @@ export interface DependencyGraphResult {
248
251
  * rather than assuming COMPLETE, matching computeConfidence()'s own priority (project-reference use
249
252
  * caps confidence even when nothing else flags a problem). Previously computed but never exposed. */
250
253
  resolvedViaProjectReferences: boolean;
254
+ /** Tests may be selected through runtime edges alone: every test runner found compiles without type
255
+ * checking, so an `import type` edge cannot change a test's outcome (2026-11-03). Absent or false
256
+ * means type-only edges select tests too. */
257
+ runtimeTestSelection?: boolean;
251
258
  }
@@ -75,16 +75,18 @@ function commandRunsTests(text: string, scripts: Readonly<Record<string, string>
75
75
  * authoritative, not part of the suite DiffCI selects from. One dogfood repository's deploy workflow runs two such
76
76
  * checks, and counting them blocked every site HTML change in its replayed history.
77
77
  *
78
- * So the answer is true when a job step matching `names` is, or precedes, a step that runs the test
78
+ * So the answer is true when a job step `names` matches is, or precedes, a step that runs the test
79
79
  * command or a test runner, or an action not known to be test-free; when a reusable-workflow job or
80
80
  * job-level configuration names it in a job that runs tests; and whenever the YAML cannot be read.
81
81
  */
82
- export function workflowFeedsTests(workflowText: string, names: RegExp, scripts: Readonly<Record<string, string>> = {}): boolean {
82
+ export function workflowFeedsTests(workflowText: string, names: RegExp | ((text: string) => boolean), scripts: Readonly<Record<string, string>> = {}): boolean {
83
83
  let document: unknown;
84
84
  try { document = parse(workflowText); } catch { return true; }
85
85
  if (!document || typeof document !== "object") return true;
86
+ // A word-level matcher reads steps as JSON text, whose escapes (`\n`, `\"`) would join into words.
87
+ const named = typeof names === "function" ? (text: string) => names(text.replace(/\\[nrt]/g, " ").replace(/\\"/g, '"')) : (text: string) => names.test(text);
86
88
  const jobs = (document as { jobs?: unknown }).jobs;
87
- if (!jobs || typeof jobs !== "object") return names.test(workflowText);
89
+ if (!jobs || typeof jobs !== "object") return named(workflowText);
88
90
  const testStep = (step: unknown): boolean => {
89
91
  if (!step || typeof step !== "object") return true;
90
92
  const { uses, run } = step as { uses?: unknown; run?: unknown };
@@ -99,11 +101,11 @@ export function workflowFeedsTests(workflowText: string, names: RegExp, scripts:
99
101
  if (!job || typeof job !== "object") return true;
100
102
  if (jobDisabled(job)) continue;
101
103
  const { steps, uses, ...configuration } = job as { steps?: unknown; uses?: unknown };
102
- if (uses !== undefined) { if (names.test(JSON.stringify(job))) return true; continue; }
104
+ if (uses !== undefined) { if (named(JSON.stringify(job))) return true; continue; }
103
105
  if (!Array.isArray(steps)) return true;
104
- const firstNaming = steps.findIndex((step) => names.test(JSON.stringify(step)));
106
+ const firstNaming = steps.findIndex((step) => named(JSON.stringify(step)));
105
107
  const jobRunsTests = steps.some(testStep);
106
- if (jobRunsTests && names.test(JSON.stringify(configuration))) return true;
108
+ if (jobRunsTests && named(JSON.stringify(configuration))) return true;
107
109
  if (firstNaming !== -1 && steps.slice(firstNaming).some(testStep)) return true;
108
110
  }
109
111
  return false;
@@ -112,6 +112,15 @@ function cloneSort(comparator) {
112
112
  return templateFn(comparator);
113
113
  }
114
114
 
115
+ let isEvalAllowed = (function () {
116
+ try {
117
+ new Function('return 0')();
118
+ return true;
119
+ } catch {
120
+ return false;
121
+ }
122
+ })();
123
+
115
124
  /**
116
125
  * Sort the given array in-place with the given comparator function.
117
126
  *
@@ -123,7 +132,7 @@ function cloneSort(comparator) {
123
132
 
124
133
  let sortCache = new WeakMap();
125
134
  exports.quickSort = function (ary, comparator, start = 0) {
126
- let doQuickSort = sortCache.get(comparator);
135
+ let doQuickSort = isEvalAllowed ? sortCache.get(comparator) : SortTemplate(comparator);
127
136
  if (doQuickSort === void 0) {
128
137
  doQuickSort = cloneSort(comparator);
129
138
  sortCache.set(comparator, doQuickSort);
@@ -11,6 +11,14 @@ var ArraySet = require('./array-set').ArraySet;
11
11
  var base64VLQ = require('./base64-vlq');
12
12
  var quickSort = require('./quick-sort').quickSort;
13
13
 
14
+ // Upper bound for a section's `offset.line` in an indexed source map. A flat
15
+ // map spends one ';' per generated line, so a tiny indexed map with a huge
16
+ // offset.line turns into a huge amount of work and memory once its mappings
17
+ // are copied into a SourceMapGenerator (CVE-2026-93749). Ten million lines is
18
+ // far beyond any real generated file. Columns are VLQ-encoded as deltas and
19
+ // don't amplify, so they only need to be valid integers.
20
+ var MAX_SECTION_OFFSET_LINE = 1e7;
21
+
14
22
  function SourceMapConsumer(aSourceMap, aSourceMapURL) {
15
23
  var sourceMap = aSourceMap;
16
24
  if (typeof aSourceMap === 'string') {
@@ -935,6 +943,7 @@ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
935
943
  line: -1,
936
944
  column: 0
937
945
  };
946
+ var maxOffsetLine = 0;
938
947
  this._sections = sections.map(function (s) {
939
948
  if (s.url) {
940
949
  // The url field will require support for asynchronicity.
@@ -945,12 +954,32 @@ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
945
954
  var offsetLine = util.getArg(offset, 'line');
946
955
  var offsetColumn = util.getArg(offset, 'column');
947
956
 
957
+ if (!isValidOffset(offsetLine) || !isValidOffset(offsetColumn)) {
958
+ throw new Error('Section offset line and column must be non-negative integers.');
959
+ }
960
+ if (offsetLine > MAX_SECTION_OFFSET_LINE) {
961
+ throw new Error('Section offset line must not exceed ' + MAX_SECTION_OFFSET_LINE + '.');
962
+ }
963
+
948
964
  if (offsetLine < lastOffset.line ||
949
965
  (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
950
966
  throw new Error('Section offsets must be ordered and non-overlapping.');
951
967
  }
952
968
  lastOffset = offset;
953
969
 
970
+ var consumer = new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL);
971
+
972
+ // Offsets of a nested indexed map add up with this one, so apply the
973
+ // bound to the total.
974
+ var totalOffsetLine = offsetLine + (consumer._maxOffsetLine || 0);
975
+ if (totalOffsetLine > MAX_SECTION_OFFSET_LINE) {
976
+ throw new Error('Section offset line must not exceed ' + MAX_SECTION_OFFSET_LINE +
977
+ ', including offsets of nested sections.');
978
+ }
979
+ if (totalOffsetLine > maxOffsetLine) {
980
+ maxOffsetLine = totalOffsetLine;
981
+ }
982
+
954
983
  return {
955
984
  generatedOffset: {
956
985
  // The offset fields are 0-based, but we use 1-based indices when
@@ -958,9 +987,24 @@ function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) {
958
987
  generatedLine: offsetLine + 1,
959
988
  generatedColumn: offsetColumn + 1
960
989
  },
961
- consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL)
990
+ consumer: consumer
962
991
  }
963
992
  });
993
+
994
+ // The largest offset.line of any section, including nested sections.
995
+ this._maxOffsetLine = maxOffsetLine;
996
+ }
997
+
998
+ /**
999
+ * Section offsets come from untrusted input and are used as line/column
1000
+ * numbers, so only accept non-negative safe integers (rejects NaN, Infinity,
1001
+ * strings, fractions, etc).
1002
+ */
1003
+ function isValidOffset(aValue) {
1004
+ return typeof aValue === 'number' &&
1005
+ aValue >= 0 &&
1006
+ aValue <= 9007199254740991 && // Number.MAX_SAFE_INTEGER
1007
+ Math.floor(aValue) === aValue;
964
1008
  }
965
1009
 
966
1010
  IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
@@ -978,8 +1022,12 @@ Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
978
1022
  get: function () {
979
1023
  var sources = [];
980
1024
  for (var i = 0; i < this._sections.length; i++) {
981
- for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
982
- sources.push(this._sections[i].consumer.sources[j]);
1025
+ // Read the getter once per section: for a nested indexed map it is
1026
+ // itself this getter, and re-reading it per item is exponential in the
1027
+ // nesting depth (CVE-2026-93749).
1028
+ var sectionSources = this._sections[i].consumer.sources;
1029
+ for (var j = 0; j < sectionSources.length; j++) {
1030
+ sources.push(sectionSources[j]);
983
1031
  }
984
1032
  }
985
1033
  return sources;
@@ -348,10 +348,12 @@ SourceMapGenerator.prototype._serializeMappings =
348
348
 
349
349
  if (mapping.generatedLine !== previousGeneratedLine) {
350
350
  previousGeneratedColumn = 0;
351
- while (mapping.generatedLine !== previousGeneratedLine) {
352
- next += ';';
353
- previousGeneratedLine++;
354
- }
351
+ // One ';' per skipped line. Build large gaps with a single flat
352
+ // string: appending ';' one by one creates a rope node per line, which
353
+ // can exhaust the heap for a big gap (CVE-2026-93749).
354
+ var lineDelta = mapping.generatedLine - previousGeneratedLine;
355
+ next += lineDelta === 1 ? ';' : ';'.repeat(lineDelta);
356
+ previousGeneratedLine = mapping.generatedLine;
355
357
  }
356
358
  else {
357
359
  if (i > 0) {
@@ -113,6 +113,13 @@ SourceNode.fromStringWithSourceMap =
113
113
  // to the SourceNode without any mapping.
114
114
  // Each line is added as separate string.
115
115
  while (lastGeneratedLine < mapping.generatedLine) {
116
+ if (remainingLinesIndex >= remainingLines.length) {
117
+ // The generated code is exhausted. Skip the rest instead of adding
118
+ // empty lines one by one: a mapping may point far past the end of
119
+ // the code (e.g. an indexed map section with a huge offset.line).
120
+ lastGeneratedLine = mapping.generatedLine;
121
+ break;
122
+ }
116
123
  node.add(shiftNextLine());
117
124
  lastGeneratedLine++;
118
125
  }