@cplieger/deadset-ts 7.2.0-dev.4 → 8.0.0-dev.1

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 (122) hide show
  1. package/dist/src/analysis.js +106 -10
  2. package/dist/src/augmentations.js +21 -8
  3. package/dist/src/automatic-types.js +189 -0
  4. package/dist/src/base-url.js +18 -0
  5. package/dist/src/components.js +7 -6
  6. package/dist/src/config.js +1 -0
  7. package/dist/src/configuration-files.js +50 -12
  8. package/dist/src/conformance-record.js +2 -2
  9. package/dist/src/convention-rows.js +75 -0
  10. package/dist/src/conventions.js +101 -5
  11. package/dist/src/decorator.js +21 -18
  12. package/dist/src/dependencies.js +183 -28
  13. package/dist/src/discover.js +132 -11
  14. package/dist/src/entry-point-gaps.js +7 -10
  15. package/dist/src/entry-points.js +112 -11
  16. package/dist/src/findings/completion.js +116 -21
  17. package/dist/src/findings/dependencies-and-module-machinery.js +71 -25
  18. package/dist/src/findings/emitters.js +1 -1
  19. package/dist/src/findings/intra-function.js +44 -13
  20. package/dist/src/findings/non-code-artifacts.js +66 -33
  21. package/dist/src/findings/unused-declarations.js +21 -1
  22. package/dist/src/findings/visibility-narrowing.js +22 -3
  23. package/dist/src/generated-file.js +11 -0
  24. package/dist/src/git-ignore.js +86 -0
  25. package/dist/src/graph.js +4 -1
  26. package/dist/src/import-bindings.js +97 -0
  27. package/dist/src/indexed-access.js +130 -28
  28. package/dist/src/interface-satisfaction.js +30 -12
  29. package/dist/src/intra-function-parts.js +297 -45
  30. package/dist/src/inventory.js +52 -8
  31. package/dist/src/kinds.js +13 -13
  32. package/dist/src/matrix.js +18 -9
  33. package/dist/src/mdx-entries.js +197 -0
  34. package/dist/src/module-declarations.js +9 -13
  35. package/dist/src/overrides.js +41 -10
  36. package/dist/src/print.js +1 -0
  37. package/dist/src/ref.js +10 -0
  38. package/dist/src/references.js +4 -1
  39. package/dist/src/report.js +4 -2
  40. package/dist/src/resolve.js +2 -0
  41. package/dist/src/roots.js +110 -38
  42. package/dist/src/schema.js +1 -0
  43. package/dist/src/serialization-contract.js +54 -8
  44. package/dist/src/session.js +7 -0
  45. package/dist/src/source-files.js +39 -14
  46. package/dist/src/suppress-file.js +10 -2
  47. package/dist/src/suppress-inline.js +18 -2
  48. package/dist/src/suppress.js +7 -5
  49. package/dist/src/sweep.js +27 -10
  50. package/dist/src/symbol-keys.js +103 -2
  51. package/dist/src/test-support.js +121 -17
  52. package/dist/src/type-errors.js +34 -7
  53. package/dist/src/type-parameter-reads.js +172 -0
  54. package/dist/src/verbs/analyze.js +16 -0
  55. package/dist/src/verbs/explain.js +4 -2
  56. package/dist/src/version.js +1 -1
  57. package/dist/src/workflow-steps.js +119 -22
  58. package/dist/src/workspace-programs.js +7 -3
  59. package/dist/src/workspace-resolution.js +53 -10
  60. package/jsr.json +1 -1
  61. package/package.json +2 -2
  62. package/src/analysis.ts +143 -10
  63. package/src/augmentations.ts +21 -10
  64. package/src/automatic-types.ts +246 -0
  65. package/src/base-url.ts +24 -0
  66. package/src/components.ts +7 -6
  67. package/src/config.ts +3 -0
  68. package/src/configuration-files.ts +66 -12
  69. package/src/conformance-record.ts +2 -2
  70. package/src/convention-rows.ts +103 -0
  71. package/src/conventions.ts +121 -7
  72. package/src/decorator.ts +28 -18
  73. package/src/dependencies.ts +247 -41
  74. package/src/discover.ts +156 -13
  75. package/src/entry-point-gaps.ts +8 -11
  76. package/src/entry-points.ts +133 -11
  77. package/src/finding.ts +10 -0
  78. package/src/findings/completion.ts +147 -24
  79. package/src/findings/dependencies-and-module-machinery.ts +90 -28
  80. package/src/findings/emitters.ts +1 -1
  81. package/src/findings/intra-function.ts +56 -14
  82. package/src/findings/non-code-artifacts.ts +81 -41
  83. package/src/findings/unused-declarations.ts +25 -1
  84. package/src/findings/visibility-narrowing.ts +32 -3
  85. package/src/generated-file.ts +16 -0
  86. package/src/git-ignore.ts +98 -0
  87. package/src/graph.ts +6 -0
  88. package/src/host.ts +5 -9
  89. package/src/import-bindings.ts +128 -0
  90. package/src/indexed-access.ts +152 -30
  91. package/src/interface-satisfaction.ts +33 -13
  92. package/src/intra-function-parts.ts +394 -59
  93. package/src/inventory.ts +71 -7
  94. package/src/kinds.ts +13 -13
  95. package/src/matrix.ts +32 -14
  96. package/src/mdx-entries.ts +241 -0
  97. package/src/module-declarations.ts +11 -13
  98. package/src/overrides.ts +51 -12
  99. package/src/print.ts +1 -0
  100. package/src/ref.ts +12 -0
  101. package/src/references.ts +10 -1
  102. package/src/report.ts +16 -3
  103. package/src/resolve.ts +3 -0
  104. package/src/roots.ts +163 -45
  105. package/src/schema.ts +1 -0
  106. package/src/serialization-contract.ts +55 -4
  107. package/src/session.ts +7 -0
  108. package/src/source-files.ts +66 -16
  109. package/src/suppress-file.ts +12 -1
  110. package/src/suppress-inline.ts +18 -1
  111. package/src/suppress.ts +9 -5
  112. package/src/sweep.ts +32 -11
  113. package/src/symbol-keys.ts +129 -2
  114. package/src/test-support.ts +149 -16
  115. package/src/type-errors.ts +38 -6
  116. package/src/type-parameter-reads.ts +227 -0
  117. package/src/verbs/analyze.ts +22 -0
  118. package/src/verbs/explain.ts +5 -2
  119. package/src/version.ts +1 -1
  120. package/src/workflow-steps.ts +127 -22
  121. package/src/workspace-programs.ts +7 -3
  122. package/src/workspace-resolution.ts +62 -10
package/src/inventory.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import {
2
+ isArrayBindingPattern,
3
+ isBindingElement,
2
4
  isClassDeclaration,
3
5
  isComputedPropertyName,
4
6
  isConstructorDeclaration,
@@ -16,6 +18,7 @@ import {
16
18
  isModuleBlock,
17
19
  isModuleDeclaration,
18
20
  isNamespaceExport,
21
+ isObjectBindingPattern,
19
22
  isParameterDeclaration,
20
23
  isParenthesizedTypeNode,
21
24
  isPrivateIdentifier,
@@ -28,7 +31,9 @@ import {
28
31
  isUnionTypeNode,
29
32
  isVariableStatement,
30
33
  ModifierFlags,
34
+ type BindingElement,
31
35
  type ClassDeclaration,
36
+ type Identifier,
32
37
  type Node,
33
38
  type SourceFile,
34
39
  } from "@typescript/native/ast";
@@ -168,6 +173,12 @@ export interface Inventory {
168
173
  readonly byName: ReadonlyMap<string, readonly string[]>;
169
174
  /** Each `declare module` declaration whose name is a string literal, by id, to that name. */
170
175
  readonly modules: ReadonlyMap<string, string>;
176
+ /**
177
+ * The ids of the ambient declarations: those of a declaration file, and those a `declare`
178
+ * modifier carries or a declaration carrying one holds. They describe code the target
179
+ * does not implement.
180
+ */
181
+ readonly ambient: ReadonlySet<string>;
171
182
  /**
172
183
  * Each enum member's dependents, by id: the later members of its declaration with no
173
184
  * initializer, up to the first one with an initializer, whose values its deletion moves.
@@ -296,6 +307,19 @@ function modifiersOf(node: Node): number {
296
307
  return (node as { readonly modifierFlags?: number }).modifierFlags ?? 0;
297
308
  }
298
309
 
310
+ /** Whether a declaration is ambient: in a declaration file, or under a `declare` modifier. */
311
+ function isAmbient(file: SourceFile, node: Node): boolean {
312
+ if (file.isDeclarationFile) {
313
+ return true;
314
+ }
315
+ for (let at: Node | undefined = node; at !== undefined; at = at.parent as Node | undefined) {
316
+ if ((modifiersOf(at) & ModifierFlags.Ambient) !== 0) {
317
+ return true;
318
+ }
319
+ }
320
+ return false;
321
+ }
322
+
299
323
  /** The type parameters one node declares, and none for a node that declares none. */
300
324
  function typeParametersOf(node: Node): readonly Node[] {
301
325
  if (
@@ -454,6 +478,37 @@ function visibilityOf(node: Node, name: Node | undefined): Visibility {
454
478
  return "public";
455
479
  }
456
480
 
481
+ /**
482
+ * The binding elements of a destructuring declaration that each declare a name of their
483
+ * own, at any depth, but one with a default, whose removal skips the default's
484
+ * evaluation, and one beside a rest element of its object pattern, whose removal
485
+ * changes what the rest holds.
486
+ */
487
+ function patternElements(
488
+ name: Node,
489
+ ): readonly { readonly element: BindingElement; readonly name: Identifier }[] {
490
+ if (!isObjectBindingPattern(name) && !isArrayBindingPattern(name)) {
491
+ return [];
492
+ }
493
+ const rest =
494
+ isObjectBindingPattern(name) &&
495
+ name.elements.some((element) => element.dotDotDotToken !== undefined);
496
+ return name.elements.flatMap((element) => {
497
+ if (
498
+ !isBindingElement(element) ||
499
+ element.initializer !== undefined ||
500
+ (rest && element.dotDotDotToken === undefined)
501
+ ) {
502
+ return [];
503
+ }
504
+ const bound = element.name;
505
+ if (bound === undefined) {
506
+ return [];
507
+ }
508
+ return isIdentifier(bound) ? [{ element, name: bound }] : patternElements(bound);
509
+ });
510
+ }
511
+
457
512
  /** The name node of one declaration, for the kinds that carry one. */
458
513
  function nameNodeOf(node: Node): Node | undefined {
459
514
  return (node as { readonly name?: Node }).name;
@@ -781,15 +836,19 @@ export function inventory<Brand>(
781
836
  if (isVariableStatement(node)) {
782
837
  for (const declaration of node.declarationList.declarations) {
783
838
  const component = componentOf(declaration.name);
784
- if (component === undefined) {
785
- // A destructuring pattern declares binding elements, which the reference
786
- // grammar does not represent; the statement stands for them.
839
+ if (component !== undefined) {
840
+ declare(declaration, owner, "variable", declaration.name, {
841
+ component,
842
+ localName: undefined,
843
+ });
787
844
  continue;
788
845
  }
789
- declare(declaration, owner, "variable", declaration.name, {
790
- component,
791
- localName: undefined,
792
- });
846
+ for (const { element, name } of patternElements(declaration.name)) {
847
+ declare(element, owner, "variable", name, {
848
+ component: { text: name.text, computed: false },
849
+ localName: undefined,
850
+ });
851
+ }
793
852
  }
794
853
  return;
795
854
  }
@@ -1067,6 +1126,11 @@ export function inventory<Brand>(
1067
1126
  .map((symbol) => symbol.id),
1068
1127
  byName: namesOf(building),
1069
1128
  modules: new Map(modules.map(([record, name]) => [positionKey(record.position), name])),
1129
+ ambient: new Set(
1130
+ building
1131
+ .filter((record) => isAmbient(record.file, record.node))
1132
+ .map((record) => positionKey(record.position)),
1133
+ ),
1070
1134
  dependents,
1071
1135
  };
1072
1136
  }
package/src/kinds.ts CHANGED
@@ -52,7 +52,7 @@ const ROWS: readonly KindRow[] = [
52
52
  code: "DS1002",
53
53
  name: "unused-unexported",
54
54
  languages: ["go", "ts"],
55
- rule: "An unexported symbol with no reference in the target. A symbol referenced only from its own declaration site counts as unreferenced.",
55
+ rule: "An unexported symbol with no reference in the target. A symbol referenced only from its own declaration site counts as unreferenced. In TypeScript a name an import declaration binds, or an `import x = require()` declaration that is not exported, is such a symbol of its file, reported at the binding when nothing in the file reads it: a use in a type position, in a local export or in a type, a link or a `@see` tag of a doc comment reads it, and so does JSX the compiler turns into calls of a factory it names. A binding of a declaration file or of a component file is not judged, nor one of a generated file while generated files are excluded. In Go a constant or a type a function body declares, a function literal's body included, that nothing in that body names outside its own specification is reported under this code, under the reference of the enclosing declaration, as `grammar/symbol-ref.md` states for a declaration inside a function body, at the local declaration's own position, with `symbol.kind` `constant` or `type` and the liveness relation `reference-counting`.",
56
56
  defaultSeverity: "deny",
57
57
  maxClass: "certain",
58
58
  fixability: "deletable",
@@ -76,7 +76,7 @@ const ROWS: readonly KindRow[] = [
76
76
  code: "DS1004",
77
77
  name: "test-only-use",
78
78
  languages: ["go", "ts"],
79
- rule: "A symbol with zero production references and at least one test reference: an unused-exported, unused-unexported or unused-member candidate whose test reference count is not zero, reported once under this code. A reference from a consumer's test files is a test reference unless the configuration counts consumer tests as production. A reference from test-support code, a package or file that only tests reach, is a test reference. A declaration of test-support code that test code references is reported under this code at the reachability class possible, as grammar/analysis.md states. Such a declaration that is an interface is reported under DS1201 instead.",
79
+ rule: "A symbol with zero production references and at least one test reference: an unused-exported, unused-unexported or unused-member candidate whose test reference count is not zero, reported once under this code. A reference from a consumer's test files is a test reference unless the configuration counts consumer tests as production. A reference from test-support code, a package or file that only tests reach and that carries test evidence of its own language, is a test reference. A declaration of test-support code is test code and is no subject of this code, as grammar/analysis.md states. An interface method whose only calls and selections through the interface are in test code, and that DS1203's precondition does not exempt, is reported under this code. The methods implementing it are not reported with it, because the test reaches them through it.",
80
80
  defaultSeverity: "deny",
81
81
  maxClass: "certain",
82
82
  fixability: "deletable",
@@ -87,7 +87,7 @@ const ROWS: readonly KindRow[] = [
87
87
  code: "DS1005",
88
88
  name: "test-of-dead-code",
89
89
  languages: ["go", "ts"],
90
- rule: "A test symbol whose set of referenced target symbols is non-empty and every member of that set is reported dead. A test that references at least one live target symbol is never reported, no notion of a test's subject and no name matching enters the rule, and the message states the rule. The test joins the dead component of the symbols it references, and it and each of them count as referencing each other, so the test is a member of their cycle and never a dead symbol outside it.",
90
+ rule: "A test symbol whose set of referenced target symbols is non-empty and every member of that set is reported dead. In TypeScript an ambient declaration, one a declaration file holds or one a `declare` modifier carries or a declaration carrying one holds, describes code the target does not implement, so it is no target symbol of that set. A test that references at least one live target symbol is never reported, no notion of a test's subject and no name matching enters the rule, and the message states the rule. The test joins the dead component of the symbols it references, and it and each of them count as referencing each other, so the test is a member of their cycle and never a dead symbol outside it.",
91
91
  defaultSeverity: "deny",
92
92
  maxClass: "certain",
93
93
  fixability: "deletable",
@@ -146,7 +146,7 @@ const ROWS: readonly KindRow[] = [
146
146
  languages: ["ts"],
147
147
  rule: "An exported declaration used only inside its own file, reported as a candidate for removing the export keyword. The finding names the narrower visibility the references support.",
148
148
  precondition:
149
- "Closed world only. Reported in a file that is not an entry file and that either belongs to a project whose consumer set the configuration declares complete or is reached by no manifest export. A declared cross-language edge counts as a reference from outside the file. Where the edge's other side is unknown to the analyzer, the finding is emitted pending. A symbol the rule of DS1301 holds for is not reported under this code, whatever severity the configuration gives DS1301, because the write-only finding names the defect to fix first.",
149
+ 'Closed world only. Reported in a file that is not an entry file, a file only a configuration string or a script token names being none, because each runs the file and reads no name it exports, and a test file being one only for the exports its test runner calls, as grammar/analysis.md "Test code" states, and that either belongs to a project whose consumer set the configuration declares complete or is reached by no manifest export. A declared cross-language edge counts as a reference from outside the file. Where the edge\'s other side is unknown to the analyzer, the finding is emitted pending. A symbol the rule of DS1301 holds for is not reported under this code, whatever severity the configuration gives DS1301, because the write-only finding names the defect to fix first.',
150
150
  defaultSeverity: "warn",
151
151
  maxClass: "certain",
152
152
  fixability: "narrowable",
@@ -167,9 +167,9 @@ const ROWS: readonly KindRow[] = [
167
167
  code: "DS1203",
168
168
  name: "uncalled-interface-method",
169
169
  languages: ["go", "ts"],
170
- rule: "An interface method that no call site invokes or selects through the interface, whatever the number of implementations. The finding names the concrete implementations and their positions. Each method that implements it and that nothing else keeps is reported under the code its own references select. Such a method counts as referenced by the interface method alone, so it belongs to this finding's dead component, whose root member is the interface method.",
170
+ rule: "An interface method that no call site invokes or selects through the interface, whatever the number of implementations. A call or selection in test code is no call for this rule, and an interface method only test code calls is DS1004's. The finding names the concrete implementations and their positions. Each method that implements it and that nothing else keeps is reported under the code its own references select. Such a method counts as referenced by the interface method alone, so it belongs to this finding's dead component, whose root member is the interface method.",
171
171
  precondition:
172
- "In Go, every method of an interface that declares an unexported method is exempt. That is the sum-type shape, whose method set exists to restrict the implementors, and a TypeScript interface cannot take it because it declares no member less visible than itself. In both languages, every marker method is exempt, an interface method whose every implementation carries an empty body.",
172
+ "In Go, every method of an exported interface whose method set holds an unexported method is exempt, a method of an interface it embeds included. An unexported interface restricts no implementor outside its package, so a method only it holds is judged. That is the sum-type shape, whose method set exists to restrict the implementors, and a TypeScript interface cannot take it because it declares no member less visible than itself. In both languages, every marker method is exempt, an interface method whose every implementation carries an empty body.",
173
173
  defaultSeverity: "warn",
174
174
  maxClass: "certain",
175
175
  fixability: "manual",
@@ -181,7 +181,7 @@ const ROWS: readonly KindRow[] = [
181
181
  languages: ["go"],
182
182
  rule: "A compile-time satisfaction assertion whose interface no symbol uses as a type.",
183
183
  precondition:
184
- "In a library, an assertion whose interface is published API, an exported interface of a package outside programs can import, has the reachability class possible, whatever consumers the run declares and loads. The assertion checks a promise the published API makes, that the type satisfies the published interface, and that promise is made to every program that imports the package, not only to the consumers the run declares. A loaded consumer that names the interface as a type uses it, and the assertion is not reported.",
184
+ "In a library, an assertion whose interface and whose concrete type are both published API, each an exported declaration of a package outside programs can import, is not reported: it states to every importer a promise of the published API. An assertion whose interface alone is published API has the reachability class possible, whatever consumers the run declares and loads. The assertion checks a promise the published API makes, that the type satisfies the published interface, and that promise is made to every program that imports the package, not only to the consumers the run declares. A loaded consumer that names the interface as a type uses it, and the assertion is not reported.",
185
185
  defaultSeverity: "deny",
186
186
  maxClass: "certain",
187
187
  fixability: "deletable",
@@ -191,7 +191,7 @@ const ROWS: readonly KindRow[] = [
191
191
  code: "DS1301",
192
192
  name: "write-only-symbol",
193
193
  languages: ["go", "ts"],
194
- rule: "A package-level or module-level variable, struct field, class member, type member or collection that production code writes and never reads. In production mode a read from a test file counts as no read. A write from a loaded consumer's code counts as a read, because the deletion the finding names would break a consumer the target does not own. A write in a consumer's test file counts as a read in the run that counts test references. It counts in a production sweep only where the configuration counts consumer tests as production. A comparison of struct values reads every field of the type: in Go, a value of a struct type used as an operand of `==` or `!=`, as a map key, or as a `switch` tag or `case` expression is a read of every field of that type, transitively through the fields of every struct type it holds, recorded at the comparison, because equality reads every field and a field that decides equality carries information. In Go a type argument the program instantiates a type parameter with, where the parameter's constraint is `comparable` or embeds it, is compared as an operand of `==` of that type is, recorded at the instantiation, so the struct values `slices.Equal`, `slices.Index` or `maps.Equal` compares have every field read. `reflect.DeepEqual` is not a comparison under this rule. In Go, a conversion the compiler accepts between two struct types, or between two pointer types that are not named types and whose base types are struct types, reads every field of the two struct types where their struct type literals are distinct, recorded at the conversion, because the conversion is legal only while their fields are identical, ignoring tags, and so no field of either can be deleted alone. It reads in the same way every field of each pair of distinct struct type literals the identity of the two types compares in turn: through each field's type, and from there through the element, key, base, parameter and result types of the type literals it reaches, through the method signatures of an interface type literal, and through the type arguments of an instantiated generic type. A field reached there has no reference of its own, as grammar/symbol-ref.md states, so it is never a subject and those reads hold no finding back. It stops at a defined type, whose fields the conversion does not read, because a defined type is identical to itself whatever fields it declares. A pair whose two sides are one struct type literal, the two struct types themselves included, as where one type is declared from the other or the conversion is to the operand's own type, reads nothing, because a field deleted from that literal leaves both sides identical. Where the operand's type or the conversion's type is a type parameter, the struct type its constraint's core type is takes that side's place, and a type parameter operand reads in the same way the fields of each struct type argument an instantiation the program holds gives it, an instantiation made through another generic declaration's own type parameters included. A conversion to any other type, an interface type among them, reads no field under this rule. In TypeScript a comparison of two object references reads no member, because `===` compares identity and never a member. A TypeScript parameter property, a constructor parameter that carries a modifier, declares a member of its class that the constructor writes with its argument, so the member is judged under this rule, and under every rule that reads a class member, as a member the class body declares is. In TypeScript a property of an object literal writes the member of the same name that the literal's contextual type declares, whether or not the compiler checks the literal for excess properties. Where that contextual type is a union or an intersection, the property writes the member of that name on each constituent that declares one. So a literal that a declaration annotates, a function returns, a call passes or a `satisfies` expression checks writes the members of the type it is given. An object literal handed to a callee the target does not implement has its members read, as grammar/analysis.md states. A store through the value a field or a member holds reads that field or member rather than writing it, because the store lands in storage every other holder of the value reads. In Go that store is an assignment, an increment, a compound assignment or a `delete` whose target is reached through a struct field holding a map, a slice or a pointer. Examples are `s.f[k] = v`, `s.f.x = v` and `delete(s.f, k)`. The same store through a field holding an array or a struct is a store into the field itself. TypeScript holds every object by reference, so an element or property store through a member's value reads the member. The finding names each write position, so the deletion set is visible. Deleting the subject and its writes also deletes every declaration whose only uses they hold. Such a declaration is a type parameter of the subject's declaring type that the subject's type alone names, an import binding the writes alone use, or a declaration whose every use is in the type annotation of the subject or of another subject this rule reports, or in the writes those findings name. The finding's message names each such declaration, and no finding is reported about the declaration itself.",
194
+ rule: "A package-level or module-level variable, struct field, class member, type member or collection that production code writes and never reads. In production mode a read from a test file counts as no read. A write from a loaded consumer's code counts as a read, because the deletion the finding names would break a consumer the target does not own. A write in a consumer's test file counts as a read in the run that counts test references. It counts in a production sweep only where the configuration counts consumer tests as production. In Go a read counts only from a declaration that is live under the finding's liveness relation, which is reference counting: a read from a declaration nothing references, whose own finding has the reachability class `certain`, is no read, so a declaration that only such declarations read is reported where a declaration something references writes it. A comparison of struct values reads every field of the type: in Go, a value of a struct type used as an operand of `==` or `!=`, as a map key, or as a `switch` tag or `case` expression is a read of every field of that type, transitively through the fields of every struct type it holds, recorded at the comparison, because equality reads every field and a field that decides equality carries information. In Go a type argument the program instantiates a type parameter with, where the parameter's constraint is `comparable` or embeds it, is compared as an operand of `==` of that type is, recorded at the instantiation, so the struct values `slices.Equal`, `slices.Index` or `maps.Equal` compares have every field read. `reflect.DeepEqual` is not a comparison under this rule. In Go, a conversion the compiler accepts between two struct types, or between two pointer types that are not named types and whose base types are struct types, reads every field of the two struct types where their struct type literals are distinct, recorded at the conversion, because the conversion is legal only while their fields are identical, ignoring tags, and so no field of either can be deleted alone. It reads in the same way every field of each pair of distinct struct type literals the identity of the two types compares in turn: through each field's type, and from there through the element, key, base, parameter and result types of the type literals it reaches, through the method signatures of an interface type literal, and through the type arguments of an instantiated generic type. A field reached there has no reference of its own, as grammar/symbol-ref.md states, so it is never a subject and those reads hold no finding back. It stops at a defined type, whose fields the conversion does not read, because a defined type is identical to itself whatever fields it declares. A pair whose two sides are one struct type literal, the two struct types themselves included, as where one type is declared from the other or the conversion is to the operand's own type, reads nothing, because a field deleted from that literal leaves both sides identical. Where the operand's type or the conversion's type is a type parameter, the struct type its constraint's core type is takes that side's place, and a type parameter operand reads in the same way the fields of each struct type argument an instantiation the program holds gives it, an instantiation made through another generic declaration's own type parameters included. A conversion to any other type, an interface type among them, reads no field under this rule. In TypeScript a comparison of two object references reads no member, because `===` compares identity and never a member. A TypeScript parameter property, a constructor parameter that carries a modifier, declares a member of its class that the constructor writes with its argument, so the member is judged under this rule, and under every rule that reads a class member, as a member the class body declares is. In TypeScript a property of an object literal writes the member of the same name that the literal's contextual type declares, whether or not the compiler checks the literal for excess properties. Where that contextual type is a union or an intersection, the property writes the member of that name on each constituent that declares one. So a literal that a declaration annotates, a function returns, a call passes or a `satisfies` expression checks writes the members of the type it is given. An object literal handed to a callee the target does not implement has its members read, as grammar/analysis.md states. A store through the value a field or a member holds reads that field or member rather than writing it, because the store lands in storage every other holder of the value reads. In Go that store is an assignment, an increment, a compound assignment or a `delete` whose target is reached through a struct field holding a map, a slice or a pointer. Examples are `s.f[k] = v`, `s.f.x = v` and `delete(s.f, k)`. The same store through a field holding an array or a struct is a store into the field itself. TypeScript holds every object by reference, so an element or property store through a member's value reads the member. The finding names each write position, so the deletion set is visible. Deleting the subject and its writes also deletes every declaration whose only uses they hold. Such a declaration is a type parameter of the subject's declaring type that the subject's type alone names, an import binding the writes alone use, or a declaration whose every use is in the type annotation of the subject or of another subject this rule reports, or in the writes those findings name. The finding's message names each such declaration, and no finding is reported about the declaration itself.",
195
195
  defaultSeverity: "deny",
196
196
  maxClass: "certain",
197
197
  fixability: "deletable",
@@ -236,7 +236,7 @@ const ROWS: readonly KindRow[] = [
236
236
  code: "DS1502",
237
237
  name: "file-never-imported",
238
238
  languages: ["go", "ts"],
239
- rule: "A source file that no import reaches, that no root names, and in which no declared cross-language edge names a declaration. An import written in a loaded consumer reaches a file of the target as an import written in the target does. An edge's side names a declaration as a root names one, so a file holding a declaration an edge names is evaluated with the edge rather than reported: whether that declaration is dead is the edge evaluation's to say, and the merge resolves it against the paired side.",
239
+ rule: "A source file that no import from live code reaches, that no root names, and in which no declared cross-language edge names a declaration: an import counts where it is written in a file a root, a live declaration or such an import keeps, or in a live declaration, so a file only dead code imports is reported, under reachability. An import written in a loaded consumer reaches a file of the target as an import written in the target does. An edge's side names a declaration as a root names one, so a file holding a declaration an edge names is evaluated with the edge rather than reported: whether that declaration is dead is the edge evaluation's to say, and the merge resolves it against the paired side.",
240
240
  defaultSeverity: "deny",
241
241
  maxClass: "certain",
242
242
  fixability: "deletable",
@@ -246,9 +246,9 @@ const ROWS: readonly KindRow[] = [
246
246
  code: "DS1601",
247
247
  name: "unused-dependency",
248
248
  languages: ["go", "ts"],
249
- rule: "A directly declared dependency that no import in the target needs. On the Go side, a direct require whose module provides no package any target package or test variant imports. On the TypeScript side, a manifest dependency, development dependency or peer dependency the project's import closure does not need. A deletion finding whose fix would remove the last use of a dependency names that dependency.",
249
+ rule: "A directly declared dependency that no import in the target needs. On the Go side, a direct require whose module provides no package any target package or test variant imports. On the TypeScript side, a manifest dependency, development dependency or peer dependency the project's import closure does not need. A deletion finding whose fix would remove the last use of a dependency names that dependency. On the TypeScript side, a needed dependency whose every use is written inside declarations that are members of the run's dead components, or at the top level of a file reported under DS1502, that no command runs and that no needed dependency used otherwise names as a peer, is reported as well, dead only through that code: at the reachability class possible where one of those declarations belongs to a library's published API, and found under reachability alone where one of those declarations or files is, so at probable unless ts.roots_complete is true. A use the configuration makes, a use an unanswered specifier may make and an import none of whose bindings is used are uses by live code.",
250
250
  precondition:
251
- "On the Go side the rule is the semantics of `go mod tidy -diff` exactly: a requirement marked indirect is never reported, because it exists to pin a transitive version and removing it changes the build list. On the TypeScript side the import closure is the files of the run's projects, and a call of `import.meta.resolve` or of `require.resolve` in them, whatever `require` names, whose first argument is a string literal or a template literal with no substitution needs each dependency an import of that specifier needs. Four more dependencies are needed: one whose command a script entry or a workflow step runs, one that a string of a configuration file names, and one that a string names under a manifest key or a package key of an applied convention row, each as grammar/analysis.md states, and one that a needed dependency names as a peer, as stated below. A command no script entry and no workflow step runs needs nothing. A declared dependency that the installed manifest of a needed declared dependency names in its peerDependencies is needed, and so on until no further dependency joins. A peer dependency is a package the needed dependency expects beside it at a version its manifest states, whether or not it imports the package, and the project's declaration is what keeps that package present at a version the project chooses, so removing the declaration can break the needed dependency where nothing the analysis reads imports the peer. A peer that peerDependenciesMeta marks optional is needed in the same way, because the needed dependency's manifest still names it as a package it works with, and a package manager may leave an optional peer out where the project does not declare it, so the project's declaration is what keeps it present for the needed dependency. A declared dependency that only dependencies nothing needs name as a peer is needed by nothing. A dependency of a manifest whose directory holds source only in configurations the run lists in configurations_not_built is reported at the reachability class possible, because the source that may import it was not analyzed. An installed manifest is the package's manifest in the nearest node_modules directory at or above the directory of the manifest that declares the dependency, and a dependency with none is decided by the import closure alone. On the TypeScript side, the dependencies judged are those of every manifest grammar/analysis.md says the analysis reads, a nested package's among them, each read against its own directory: a dependency is needed by a use written in a file at or below the directory of the manifest that declares it, by a use no one file holds, and as a peer of a needed dependency of the same manifest or of a manifest below it. A dependency a nested package's manifest declares whose installed manifest the analysis cannot find is not judged, because no run requires a nested package to be installed and its commands and peers cannot be read, while a workspace member's and the target's own are judged as above.",
251
+ "On the Go side the rule is the semantics of `go mod tidy -diff` exactly: a requirement marked indirect is never reported, because it exists to pin a transitive version and removing it changes the build list. On the TypeScript side the import closure is the files of the run's projects, and a call of `import.meta.resolve` or of `require.resolve` in them, whatever `require` names, whose first argument is a string literal or a template literal with no substitution needs each dependency an import of that specifier needs. A `@types/<name>` package in a type root of a compiler configuration that lists no `types`, a `node_modules/@types` directory at or above the configuration's directory or a `typeRoots` entry naming one, is needed by a use, in a file of that configuration, of a global name or an ambient module that one of the package's declaration files declares, which resolves to no declaration of the program: a compiler before version 6 includes every package of the type roots where `types` is not listed, and version 6 and later include none, so the program the analysis builds holds none of those declarations. A package's declaration files are the file its `types` or `typings` names, else its `index.d.ts`, and each file a `/// <reference path>` of one of them reaches inside the package. A global is a top-level declaration of such a file that is no module, or a declaration of a `declare global` block of one that is, and an ambient module is a `declare module` with a string name of a file that is no module. A name that names a member, a property or a label is no use of a global. Four more dependencies are needed: one whose command a script entry, a workflow step or a git hook runs, one that a string of a configuration file names, and one that a string names under a manifest key or a package key of an applied convention row, each as grammar/analysis.md states, and one that a needed dependency names as a peer, as stated below. A command no script entry, workflow step or git hook runs needs nothing. A declared dependency that the installed manifest of a needed declared dependency names in its peerDependencies is needed, and so on until no further dependency joins. A peer dependency is a package the needed dependency expects beside it at a version its manifest states, whether or not it imports the package, and the project's declaration is what keeps that package present at a version the project chooses, so removing the declaration can break the needed dependency where nothing the analysis reads imports the peer. A peer that peerDependenciesMeta marks optional is needed in the same way, because the needed dependency's manifest still names it as a package it works with, and a package manager may leave an optional peer out where the project does not declare it, so the project's declaration is what keeps it present for the needed dependency. A declared dependency that only dependencies nothing needs name as a peer is needed by nothing. A dependency of a manifest whose directory holds source only in configurations the run lists in configurations_not_built is reported at the reachability class possible, because the source that may import it was not analyzed. An installed manifest is the package's manifest in the nearest node_modules directory at or above the directory of the manifest that declares the dependency, and a dependency with none is decided by the import closure alone. On the TypeScript side, the dependencies judged are those of every manifest grammar/analysis.md says the analysis reads, a nested package's among them, each read against its own directory: a dependency is needed by a use written in a file at or below the directory of the manifest that declares it where no manifest between them declares a dependency of the same name, so a use below a nested manifest that declares the same dependency needs that nested manifest's declaration only, by a use no one file holds, and as a peer of a needed dependency of the same manifest or of a manifest below it. A dependency a nested package's manifest declares whose installed manifest the analysis cannot find is not judged, because no run requires a nested package to be installed and its commands and peers cannot be read, while a workspace member's and the target's own are judged as above.",
252
252
  defaultSeverity: "deny",
253
253
  maxClass: "certain",
254
254
  fixability: "manual",
@@ -332,7 +332,7 @@ const ROWS: readonly KindRow[] = [
332
332
  languages: ["go", "ts"],
333
333
  rule: "A parameter with no reference inside its function body, on a function whose signature is free to change.",
334
334
  precondition:
335
- "The signature must be free, defined as follows: the function is not a method retained by interface satisfaction, is not a method whose name and signature are those of a method of an exported interface type declared by a package outside the target that the import closure holds, is not used as a value, is not a go:linkname or cgo target, is not a function the Go test driver runs (a test, benchmark or fuzz test of a test file, or TestMain), and is not a stub whose body is empty or only panics. A function literal or function expression that initializes a variable the program only calls, never passing, storing, returning or assigning it, is called by name and is not used as a value. A parameter its body never names is dead whatever the callers, so a published declaration of a library is reported too, with the fixability the vocabulary gives the kind: the signature change is a breaking change. In TypeScript a caller may pass a function used as a value more arguments than it declares parameters, so in such a function whose signature is free but for that use, a parameter its body never reads is reported when its body reads no parameter after it, and an unread parameter before the last read one is not. A parameter of a TypeScript function expression or arrow function that the compiler gives a contextual type is not reported when it carries a type annotation, because the inference of the call that holds the function may read the annotation, or when it is an object binding pattern, because the pattern reads each property it names from the argument and the code that hands the argument may act on that read. No name such a pattern binds is reported either. Any other TypeScript parameter that is a binding pattern is judged by the names it binds: each name the body never reads is reported wherever the pattern stands, because removing it from the pattern moves no argument, except a name beside a rest element of the same object pattern, whose removal changes what that element holds, and the pattern counts as a read parameter when the body reads any name it binds. A rest parameter is judged as the last parameter. A TypeScript `this` parameter declares the type of `this` and receives no argument, so it is never reported. A TypeScript constructor is used as a value where its class is used as a value other than as the callee of a `new` expression or the class an `extends` clause names, and its signature is not free where its class carries a decorator or a parameter of the constructor carries one, because the code that decorator or a container runs may construct the class. A parameter property is read by the write to its member the constructor makes, so it is never reported under this kind, and its member is judged under DS1301. No name exempts a parameter. A TypeScript parameter whose name starts with an underscore is judged as any other is, and a Go parameter named by the blank identifier declares no name a body could read and is never reported.",
335
+ "The signature must be free, defined as follows: the function is not a method retained by interface satisfaction, is not a method whose name and signature are those of a method of an exported interface type declared by a package outside the target that the import closure holds, is not used as a value, is not a go:linkname or cgo target, is not a go-fuzz entry point, is not a function the Go test driver runs (a test, benchmark or fuzz test of a test file, or TestMain), and is not a stub whose body is empty or only panics. A function literal or function expression that initializes a variable the program only calls, never passing, storing, returning or assigning it, is called by name and is not used as a value. In Go a function literal that is the callee of the call it is written in, the call of a `go` or a `defer` statement included, is not used as a value, wherever the literal is written. A parameter its body never names is dead whatever the callers, so a published declaration of a library is reported too, with the fixability the vocabulary gives the kind: the signature change is a breaking change. In TypeScript a caller may pass a function used as a value more arguments than it declares parameters, so in such a function whose signature is free but for that use, a parameter its body never reads is reported for deletion when its body reads no parameter after it, and an unread parameter before the last read one is reported for a rename to its name with a leading underscore, which keeps every argument in place and which the compilers' unused-parameter rules read as declared unread, unless its name already starts with one. A parameter of a TypeScript function expression or arrow function that the compiler gives a contextual type, and that carries a type annotation, is not reported for deletion where the inference of the call holding the function may read the annotation, being where the callee is generic and its parameter type at the function's place names a type parameter at the parameter's place, or where the function is written inside an object literal such a call is passed, and it is reported for deletion at `probable` where it carries an annotation no such inference reads, because nothing in the program shows that an outside reader ignores it. Such a parameter is not reported when it is an object binding pattern, because the pattern reads each property it names from the argument and the code that hands the argument may act on that read. No name such a pattern binds is reported either. Any other TypeScript parameter that is a binding pattern is judged by the names it binds: each name the body never reads is reported wherever the pattern stands, because removing it from the pattern moves no argument, except a name beside a rest element of the same object pattern, whose removal changes what that element holds, and the pattern counts as a read parameter when the body reads any name it binds. A rest parameter is judged as the last parameter. A TypeScript `this` parameter declares the type of `this` and receives no argument, so it is never reported. A TypeScript constructor is used as a value where its class is used as a value other than as the callee of a `new` expression or the class an `extends` clause names, and its signature is not free where its class carries a decorator or a parameter of the constructor carries one, because the code that decorator or a container runs may construct the class. A parameter property is read by the write to its member the constructor makes, so it is never reported under this kind, and its member is judged under DS1301. A TypeScript name a parameter binds, whole or through a binding pattern, that starts with an underscore is never reported, because a leading underscore is the spelling unused-parameter rules read as declared unread, and no other name exempts a parameter. A Go parameter named by the blank identifier declares no name a body could read and is never reported.",
336
336
  defaultSeverity: "warn",
337
337
  maxClass: "certain",
338
338
  fixability: "manual",
@@ -382,7 +382,7 @@ const ROWS: readonly KindRow[] = [
382
382
  languages: ["go", "ts"],
383
383
  rule: "A write to a local variable with no read before the next write to it or the end of its scope, computed on the same read-and-write classification the write-only-symbol kind uses. The finding names the write position.",
384
384
  precondition:
385
- "In TypeScript the binding of a catch clause is a local variable the clause writes when it catches, so a binding that is a name and that the clause's block never reads is a dead store, positioned at the binding: the clause written with no binding behaves the same.",
385
+ "In TypeScript the binding of a catch clause is a local variable the clause writes when it catches, so a binding that is a name and that the clause's block never reads is a dead store, positioned at the binding: the clause written with no binding behaves the same. A TypeScript local is a name a `let` or `const` declaration of a block binds, or a `var` declaration of a block of a function, a name an object or array binding pattern of one binds at any depth included, except a name with a default, whose removal skips the default's evaluation, and a name beside a rest element of its object pattern, whose removal changes what the rest holds. A `var` of a block nested in its function's body is judged in that block, its last write kept because the function scope reads on past the block's end, and is no subject where a nested function of its function names it. A local a nested function reads is no subject, because the function may read it at any time, and every write to a local nothing reads is dead, one a nested function makes included, each positioned at the name it writes. The variable a `let` or `const` declaration of a `for…of` or `for…in` statement binds is written at each iteration, so one the loop body never reads is a dead store positioned at the binding, except a name that starts with an underscore, because a loop must bind a name and that spelling declares it unread. In Go a function literal a package-level variable's initializer holds is a function body of its own, and a finding about one of its stores carries the reference of the variable the literal initializes, which for a blank variable is its package's, as `grammar/symbol-ref.md` states for a blank-identifier declaration. In Go a range statement stores its key and its value at the start of every iteration, and an empty range stores neither. In Go a function literal reads each variable it names where it is written, and a store that a literal naming its variable may precede on some path of the control-flow graph, the literal of an earlier iteration of a loop included, is not dead, because a call of the literal the graph does not order may read it. A store no such literal precedes is judged as any other. A literal that is the callee of the call it is written in, outside a `go` or `defer` statement, runs there, so it reads its variables at that call and precedes no later store.",
386
386
  defaultSeverity: "deny",
387
387
  maxClass: "certain",
388
388
  fixability: "deletable",
package/src/matrix.ts CHANGED
@@ -30,6 +30,8 @@ export interface Configured {
30
30
  readonly testFiles: readonly string[];
31
31
  /** The paths of the test-support files, which only test code imports. */
32
32
  readonly supportFiles?: readonly string[] | undefined;
33
+ /** The ids of the ambient declarations, which describe code the target does not implement. */
34
+ readonly ambient?: ReadonlySet<string> | undefined;
33
35
  /**
34
36
  * The paths of the workspace-package files the configuration holds but does not
35
37
  * compile itself. Their declarations count in its graph and its verdict on them is no
@@ -160,7 +162,7 @@ export function matrixOf(per: readonly Configured[]): Matrix {
160
162
  return {
161
163
  configurations: per.map((one) => one.configuration),
162
164
  graphs: per.map((one) =>
163
- graphOf(one.symbols, one.references, one.roots, one.testFiles, one.supportFiles),
165
+ graphOf(one.symbols, one.references, one.roots, one.testFiles, one.supportFiles, one.ambient),
164
166
  ),
165
167
  union: graphOf(
166
168
  symbols,
@@ -168,6 +170,7 @@ export function matrixOf(per: readonly Configured[]): Matrix {
168
170
  per.flatMap((one) => one.roots),
169
171
  [...new Set(per.flatMap((one) => one.testFiles))],
170
172
  [...new Set(per.flatMap((one) => one.supportFiles ?? []))],
173
+ new Set(per.flatMap((one) => [...(one.ambient ?? [])])),
171
174
  ),
172
175
  heldIn: symbols.map((symbol) => holders.get(symbol.id) ?? []),
173
176
  dependents,
@@ -199,10 +202,7 @@ export function sweepMatrix(matrix: Matrix, input: SweepInput): SweepResult {
199
202
  );
200
203
 
201
204
  const union = matrix.union;
202
- const dead = union.symbols.map(() => false);
203
- const testOfDeadCode = union.symbols.map(() => false);
204
205
  const heldBy: (string | undefined)[] = union.symbols.map(() => undefined);
205
- const unreferencedTest = union.symbols.map(() => false);
206
206
  const testReached = reachedWithTheTests(union, [
207
207
  ...input.marked,
208
208
  ...(input.exempt ?? []).map((record) => record.id),
@@ -223,6 +223,7 @@ export function sweepMatrix(matrix: Matrix, input: SweepInput): SweepResult {
223
223
  (edge) =>
224
224
  union.test[edge.to] === true ||
225
225
  union.support[edge.to] === true ||
226
+ union.ambient[edge.to] === true ||
226
227
  union.subject[edge.to] !== true ||
227
228
  judged[edge.to] !== undefined,
228
229
  );
@@ -239,10 +240,7 @@ export function sweepMatrix(matrix: Matrix, input: SweepInput): SweepResult {
239
240
  heldBy[union.parent[at] ?? OUTSIDE] ??
240
241
  (union.support[at] === true && testRefs > 0 && !admitted ? symbol.id : undefined);
241
242
  const unreferenced = union.test[at] === true && !admitted && testReached[at] !== true;
242
- dead[at] = true;
243
- testOfDeadCode[at] = admitted;
244
243
  heldBy[at] = heldByTests;
245
- unreferencedTest[at] = unreferenced;
246
244
  const productionRefs = union.made[at]?.production ?? 0;
247
245
  const counted = all.every((candidate) => candidate.relation === "reference-counting");
248
246
  candidates.push({
@@ -264,16 +262,36 @@ export function sweepMatrix(matrix: Matrix, input: SweepInput): SweepResult {
264
262
  return {
265
263
  liveUnder,
266
264
  candidates,
267
- components: componentsOf(
268
- union,
269
- dead.map((one, at) => one && heldBy[at] === undefined),
270
- testOfDeadCode,
271
- unreferencedTest,
272
- positionsOf(union, matrix.dependents, liveUnder),
273
- ),
265
+ components: deadComponents(matrix, { liveUnder, candidates }, new Set()),
274
266
  };
275
267
  }
276
268
 
269
+ /**
270
+ * The dead components of one sweep over the union, with the file declarations at `files`
271
+ * dead as well: a file that is deleted whole takes the declarations it holds and every
272
+ * dead declaration only its top level references with it.
273
+ */
274
+ export function deadComponents(
275
+ matrix: Matrix,
276
+ result: Pick<SweepResult, "liveUnder" | "candidates">,
277
+ files: ReadonlySet<number>,
278
+ ): readonly Component[] {
279
+ const union = matrix.union;
280
+ const byId = new Map(result.candidates.map((candidate) => [candidate.id, candidate]));
281
+ const candidateAt = (at: number): MatrixCandidate | undefined =>
282
+ byId.get(union.symbols[at]?.id ?? "");
283
+ return componentsOf(
284
+ union,
285
+ union.symbols.map((_symbol, at) => {
286
+ const candidate = candidateAt(at);
287
+ return files.has(at) || (candidate !== undefined && candidate.heldByTests === undefined);
288
+ }),
289
+ union.symbols.map((_symbol, at) => candidateAt(at)?.testOfDeadCode === true),
290
+ union.symbols.map((_symbol, at) => candidateAt(at)?.unreferencedTest === true),
291
+ positionsOf(union, matrix.dependents, result.liveUnder),
292
+ );
293
+ }
294
+
277
295
  /**
278
296
  * The file declarations at `paths`, below the target root, that one sweep holds live
279
297
  * under both relations, the rule a judged declaration is live by.
@@ -0,0 +1,241 @@
1
+ /**
2
+ * The files the import declarations of the target's Markdown and MDX documents load. A
3
+ * document is read as text: a line outside a fenced code block that starts with `import`
4
+ * is an import declaration, which an MDX compiler hoists into the module it builds.
5
+ */
6
+
7
+ import type { SourceFile } from "@typescript/native/ast";
8
+ import { resolveRelativeSpecifier } from "./configuration-files.ts";
9
+ import type { Host } from "./host.ts";
10
+ import { dirnamePath, joinPath, resolvePath } from "./paths.ts";
11
+ import type { SourceFiles } from "./source-files.ts";
12
+
13
+ /** One file a document imports, the specifier that named it, and the export names it reads. */
14
+ interface DocumentEntry {
15
+ readonly file: SourceFile;
16
+ readonly source: string;
17
+ /** The export names the import reads, or undefined for a namespace import, which reads them all. */
18
+ readonly names: readonly string[] | undefined;
19
+ }
20
+
21
+ /** The directories no document is read below. */
22
+ const SKIPPED: ReadonlySet<string> = new Set(["node_modules", ".git"]);
23
+
24
+ /** The extensions of a document whose imports an MDX compiler reads. */
25
+ const DOCUMENT = /\.mdx?$/u;
26
+
27
+ /** A fence line, its marker run and what follows it captured. */
28
+ const FENCE = /^ {0,3}(`{3,}|~{3,})(.*)$/u;
29
+
30
+ /** A string literal in either quote, its escapes included. */
31
+ const STRING = String.raw`"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'`;
32
+
33
+ /** An import declaration at the start of a line, its clause and its specifier captured. */
34
+ const IMPORT_LINE = new RegExp(
35
+ String.raw`^import\s+(?:((?:[^"'\n]|${STRING})*?)\s+from\s*)?["']([^"'\n]+)["']`,
36
+ "u",
37
+ );
38
+
39
+ /** The braces of an import clause, what they hold captured. */
40
+ const BRACES = new RegExp(String.raw`\{((?:[^}"']|${STRING})*)\}`, "u");
41
+
42
+ /** One comma-separated part of a clause's braces. */
43
+ const PART = new RegExp(String.raw`(?:[^,"']|${STRING})+`, "gu");
44
+
45
+ /** A named import of a clause's braces: the exported name and an optional local alias. */
46
+ const NAMED_IMPORT = new RegExp(String.raw`^([\w$]+|${STRING})(?:\s+as\s+[\w$]+)?$`, "u");
47
+
48
+ /** The single-character escapes of a string literal and the character each stands for. */
49
+ const SINGLE_ESCAPES: ReadonlyMap<string, string> = new Map([
50
+ ["b", "\b"],
51
+ ["f", "\f"],
52
+ ["n", "\n"],
53
+ ["r", "\r"],
54
+ ["t", "\t"],
55
+ ["v", "\v"],
56
+ ["0", "\0"],
57
+ ["'", "'"],
58
+ ['"', '"'],
59
+ ["\\", "\\"],
60
+ ]);
61
+
62
+ /**
63
+ * One escape of a string literal: two hexadecimal digits, a code unit, a code point, or one
64
+ * character and the digit after it.
65
+ */
66
+ const ESCAPE = /\\(?:x([\da-fA-F]{2})|u([\da-fA-F]{4})|u\{([\da-fA-F]+)\}|(.)(\d?))/gu;
67
+
68
+ /** What one escape stands for, or undefined for one a module cannot hold. */
69
+ function unescaped([, hex, unit, point, single, digit]: RegExpExecArray): string | undefined {
70
+ if (single === undefined) {
71
+ const code = Number.parseInt(hex ?? unit ?? point ?? "", 16);
72
+ return code <= 0x10ffff ? String.fromCodePoint(code) : undefined;
73
+ }
74
+ return /[1-9xu]/u.test(single) || (single === "0" && digit !== "")
75
+ ? undefined
76
+ : `${SINGLE_ESCAPES.get(single) ?? single}${digit ?? ""}`;
77
+ }
78
+
79
+ /**
80
+ * The value of a quoted export name, its escapes decoded, or undefined for an escape this
81
+ * reading does not decode. A module is strict code, so no legacy octal escape is valid.
82
+ */
83
+ function quotedName(literal: string): string | undefined {
84
+ const body = literal.slice(1, -1);
85
+ let value = "";
86
+ let from = 0;
87
+ for (const escape of body.matchAll(ESCAPE)) {
88
+ const decoded = unescaped(escape);
89
+ if (decoded === undefined) {
90
+ return undefined;
91
+ }
92
+ value += body.slice(from, escape.index) + decoded;
93
+ from = escape.index + escape[0].length;
94
+ }
95
+ return value + body.slice(from);
96
+ }
97
+
98
+ /**
99
+ * The export names one import clause reads: `default` for a default binding and each name
100
+ * its braces list, or undefined for a namespace import, which reads every export, and for
101
+ * a clause this reading does not parse, which may read any.
102
+ */
103
+ function clauseNames(clause: string): readonly string[] | undefined {
104
+ const braces = BRACES.exec(clause);
105
+ const head = (braces === null ? clause : clause.slice(0, braces.index))
106
+ .replace(/,\s*$/u, "")
107
+ .trim();
108
+ if (head.includes("*")) {
109
+ return undefined;
110
+ }
111
+ const names = head === "" ? [] : ["default"];
112
+ if (head !== "" && !/^[\w$]+$/u.test(head)) {
113
+ return undefined;
114
+ }
115
+ for (const part of (braces?.[1]?.match(PART) ?? []).map((one) => one.trim())) {
116
+ const named = NAMED_IMPORT.exec(part);
117
+ if (part === "") {
118
+ continue;
119
+ }
120
+ if (named?.[1] === undefined) {
121
+ return undefined;
122
+ }
123
+ const name = /^["']/u.test(named[1]) ? quotedName(named[1]) : named[1];
124
+ if (name === undefined) {
125
+ return undefined;
126
+ }
127
+ names.push(name);
128
+ }
129
+ return names;
130
+ }
131
+
132
+ /** Every document below `dir`, outside every skipped directory, by absolute path. */
133
+ function documents(host: Host, dir: string): readonly string[] {
134
+ let entries;
135
+ try {
136
+ entries = host.readDirectory(dir);
137
+ } catch {
138
+ return [];
139
+ }
140
+ const found: string[] = [];
141
+ for (const entry of entries) {
142
+ const path = joinPath(dir, entry.name);
143
+ if (entry.directory) {
144
+ if (!SKIPPED.has(entry.name)) {
145
+ found.push(...documents(host, path));
146
+ }
147
+ } else if (DOCUMENT.test(entry.name)) {
148
+ found.push(path);
149
+ }
150
+ }
151
+ return found.sort();
152
+ }
153
+
154
+ /** The relative specifiers one document's import lines name, its fenced code blocks skipped. */
155
+ function importedBy(
156
+ text: string,
157
+ ): readonly { readonly specifier: string; readonly names: readonly string[] | undefined }[] {
158
+ const found: { specifier: string; names: readonly string[] | undefined }[] = [];
159
+ let open: string | undefined;
160
+ for (const line of text.split(/\r?\n/u)) {
161
+ const fence = FENCE.exec(line);
162
+ const marker = fence?.[1];
163
+ if (marker !== undefined && open === undefined) {
164
+ open = marker;
165
+ continue;
166
+ }
167
+ // https://spec.commonmark.org/0.31.2/#fenced-code-blocks: only a run of the opening
168
+ // character, at least as long and followed by nothing, closes a fence.
169
+ if (
170
+ marker !== undefined &&
171
+ open !== undefined &&
172
+ marker.startsWith(open.slice(0, 1)) &&
173
+ marker.length >= open.length &&
174
+ fence?.[2]?.trim() === ""
175
+ ) {
176
+ open = undefined;
177
+ continue;
178
+ }
179
+ const matched = open === undefined ? IMPORT_LINE.exec(line) : null;
180
+ const specifier = matched?.[2];
181
+ if (specifier?.startsWith("./") === true || specifier?.startsWith("../") === true) {
182
+ found.push({ specifier, names: clauseNames(matched?.[1] ?? "") });
183
+ }
184
+ }
185
+ return found;
186
+ }
187
+
188
+ /** One document below a target root, by absolute path, and what its import lines name. */
189
+ interface DocumentImports {
190
+ readonly path: string;
191
+ readonly imports: ReturnType<typeof importedBy>;
192
+ }
193
+
194
+ /**
195
+ * The documents each host's target roots hold, which every project of a run reads alike,
196
+ * kept for the host's life as {@link Host} allows.
197
+ */
198
+ const documentsOf = new WeakMap<Host, Map<string, readonly DocumentImports[]>>();
199
+
200
+ /** Every readable document below `root` and the import lines it writes, read once per host. */
201
+ function documentImports(host: Host, root: string): readonly DocumentImports[] {
202
+ const byRoot = documentsOf.get(host) ?? new Map<string, readonly DocumentImports[]>();
203
+ documentsOf.set(host, byRoot);
204
+ const known = byRoot.get(root);
205
+ if (known !== undefined) {
206
+ return known;
207
+ }
208
+ const found = documents(host, root).flatMap((path) => {
209
+ try {
210
+ return [{ path, imports: importedBy(host.readFile(path)) }];
211
+ } catch {
212
+ return [];
213
+ }
214
+ });
215
+ byRoot.set(root, found);
216
+ return found;
217
+ }
218
+
219
+ /**
220
+ * Every own file one document below the target root imports by a relative specifier,
221
+ * read against the document's directory, on disk or through the emit mapping.
222
+ */
223
+ export function documentEntries(
224
+ host: Host,
225
+ targetRoot: string,
226
+ files: SourceFiles,
227
+ ): readonly DocumentEntry[] {
228
+ const root = resolvePath(host.workingDirectory(), targetRoot);
229
+ const found: DocumentEntry[] = [];
230
+ for (const { path, imports } of documentImports(host, root)) {
231
+ const dir = dirnamePath(path);
232
+ for (const { specifier, names } of imports) {
233
+ const reached = resolveRelativeSpecifier(host, dir, specifier);
234
+ const held = reached === undefined ? undefined : files.byName.get(reached);
235
+ for (const file of held === undefined ? files.named(resolvePath(dir, specifier)) : [held]) {
236
+ found.push({ file, source: specifier, names });
237
+ }
238
+ }
239
+ }
240
+ return found;
241
+ }