@stateward/core 1.2.0 → 1.2.2

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.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Calls of the platform that do not throw on values their types allow: the closed list the proofs
3
+ * share. An entry holds only on the platform's own types, as the type checker sees them: the value
4
+ * a method is called on is typed by the platform's type itself (not an interface or a class of the
5
+ * project, and not a type the project extends), and the arguments' types make the call safe
6
+ * (`String(x)` on a primitive, `join` on an array of primitives). Every other call of the platform
7
+ * or a package may throw (`new URL("x")`, `[].reduce(add)`, `JSON.parse(text)`, `n.toString(36)`,
8
+ * `headers.set(…)`). A function of the project is not on the list: a proof reads it, or counts it
9
+ * as a call that may throw. Core knows no library; these are the language's own built-ins.
10
+ */
11
+ import ts from "typescript";
12
+ /** Global functions, by name. */
13
+ const GLOBALS = new Map([
14
+ ["setTimeout", "any"],
15
+ ["clearTimeout", "any"],
16
+ ["setInterval", "any"],
17
+ ["clearInterval", "any"],
18
+ ["queueMicrotask", "any"],
19
+ ["String", "primitive"],
20
+ ["Number", "primitive"],
21
+ ["Boolean", "any"],
22
+ ["isNaN", "number"],
23
+ ["isFinite", "number"],
24
+ ["parseInt", "primitive"],
25
+ ["parseFloat", "primitive"],
26
+ ]);
27
+ /** Constructors, by the platform's name of the constructor's type. */
28
+ const CONSTRUCTORS = new Map([
29
+ ["PromiseConstructor", "any"],
30
+ ["MapConstructor", "none"],
31
+ ["SetConstructor", "primitive-array"],
32
+ ["WeakMapConstructor", "none"],
33
+ ["WeakSetConstructor", "none"],
34
+ ["ErrorConstructor", "primitive"],
35
+ ["DateConstructor", "primitive"],
36
+ ["AbortControllerConstructor", "none"],
37
+ ]);
38
+ /** Methods, by the platform's name of the type they are called on, then by name. */
39
+ const METHOD_TABLE = {
40
+ Console: [["*", "any"]],
41
+ Math: [["*", "number"]],
42
+ ObjectConstructor: [
43
+ ["keys", "known"],
44
+ ["values", "known"],
45
+ ["entries", "known"],
46
+ ["freeze", "any"],
47
+ ["is", "any"],
48
+ ],
49
+ ArrayConstructor: [
50
+ ["isArray", "any"],
51
+ ["from", "iterated"],
52
+ ],
53
+ DateConstructor: [["now", "none"]],
54
+ NumberConstructor: [
55
+ ["isFinite", "any"],
56
+ ["isNaN", "any"],
57
+ ["isInteger", "any"],
58
+ ["isSafeInteger", "any"],
59
+ ["parseInt", "primitive"],
60
+ ["parseFloat", "primitive"],
61
+ ],
62
+ PromiseConstructor: [
63
+ ["resolve", "primitive"],
64
+ ["allSettled", "any"],
65
+ ],
66
+ Promise: [
67
+ ["then", "any"],
68
+ ["catch", "any"],
69
+ ["finally", "any"],
70
+ ],
71
+ AbortController: [["abort", "any"]],
72
+ Array: arrayMethods(),
73
+ ReadonlyArray: arrayMethods(),
74
+ Map: mapMethods(),
75
+ ReadonlyMap: [
76
+ ["get", "any"],
77
+ ["has", "any"],
78
+ ["keys", "none"],
79
+ ["values", "none"],
80
+ ["entries", "none"],
81
+ ],
82
+ Set: [
83
+ ["add", "any"],
84
+ ["has", "any"],
85
+ ["delete", "any"],
86
+ ["clear", "none"],
87
+ ["keys", "none"],
88
+ ["values", "none"],
89
+ ["entries", "none"],
90
+ ["forEach", "any"],
91
+ ],
92
+ ReadonlySet: [
93
+ ["has", "any"],
94
+ ["keys", "none"],
95
+ ["values", "none"],
96
+ ["entries", "none"],
97
+ ],
98
+ WeakMap: [
99
+ ["get", "any"],
100
+ ["set", "any"],
101
+ ["has", "any"],
102
+ ["delete", "any"],
103
+ ],
104
+ WeakSet: [
105
+ ["add", "any"],
106
+ ["has", "any"],
107
+ ["delete", "any"],
108
+ ],
109
+ String: [
110
+ ["toUpperCase", "none"],
111
+ ["toLowerCase", "none"],
112
+ ["trim", "none"],
113
+ ["trimStart", "none"],
114
+ ["trimEnd", "none"],
115
+ ["startsWith", "primitive"],
116
+ ["endsWith", "primitive"],
117
+ ["includes", "primitive"],
118
+ ["indexOf", "primitive"],
119
+ ["split", "primitive-or-callback"],
120
+ ["replace", "primitive-or-callback"],
121
+ ["replaceAll", "primitive"],
122
+ ["padStart", "primitive"],
123
+ ["padEnd", "primitive"],
124
+ ["charAt", "primitive"],
125
+ ["charCodeAt", "primitive"],
126
+ ["substring", "primitive"],
127
+ ["slice", "primitive"],
128
+ ["at", "primitive"],
129
+ ["concat", "primitive"],
130
+ ["toString", "none"],
131
+ ],
132
+ // The getters of a date: an invalid date gives `NaN`, it does not throw (`toISOString` does).
133
+ Date: [
134
+ "getTime",
135
+ "getFullYear",
136
+ "getMonth",
137
+ "getDate",
138
+ "getDay",
139
+ "getHours",
140
+ "getMinutes",
141
+ "getSeconds",
142
+ "getMilliseconds",
143
+ "getTimezoneOffset",
144
+ "getUTCFullYear",
145
+ "getUTCMonth",
146
+ "getUTCDate",
147
+ "getUTCDay",
148
+ "getUTCHours",
149
+ "getUTCMinutes",
150
+ "getUTCSeconds",
151
+ "getUTCMilliseconds",
152
+ ].map((name) => [name, "none"]),
153
+ Number: [
154
+ ["toFixed", "digits"],
155
+ ["toString", "none"],
156
+ ["valueOf", "none"],
157
+ ],
158
+ Boolean: [
159
+ ["toString", "none"],
160
+ ["valueOf", "none"],
161
+ ],
162
+ };
163
+ const METHODS = new Map(Object.entries(METHOD_TABLE).map(([owner, methods]) => [
164
+ owner,
165
+ new Map(methods),
166
+ ]));
167
+ function arrayMethods() {
168
+ return [
169
+ ["map", "any"],
170
+ ["filter", "any"],
171
+ ["forEach", "any"],
172
+ ["some", "any"],
173
+ ["every", "any"],
174
+ ["find", "any"],
175
+ ["findIndex", "any"],
176
+ ["findLast", "any"],
177
+ ["findLastIndex", "any"],
178
+ ["includes", "any"],
179
+ ["indexOf", "any"],
180
+ ["lastIndexOf", "any"],
181
+ ["slice", "any"],
182
+ ["push", "any"],
183
+ ["pop", "none"],
184
+ ["shift", "none"],
185
+ ["unshift", "any"],
186
+ ["flat", "any"],
187
+ ["flatMap", "any"],
188
+ ["keys", "none"],
189
+ ["values", "none"],
190
+ ["entries", "none"],
191
+ ["at", "any"],
192
+ ["reverse", "none"],
193
+ ];
194
+ }
195
+ function mapMethods() {
196
+ return [
197
+ ["get", "any"],
198
+ ["set", "any"],
199
+ ["has", "any"],
200
+ ["delete", "any"],
201
+ ["clear", "none"],
202
+ ["keys", "none"],
203
+ ["values", "none"],
204
+ ["entries", "none"],
205
+ ["forEach", "any"],
206
+ ];
207
+ }
208
+ function stripped(expression) {
209
+ let node = expression;
210
+ while (ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node)) {
211
+ node = node.expression;
212
+ }
213
+ return node;
214
+ }
215
+ function isWrittenFunction(node) {
216
+ const inner = stripped(node);
217
+ return ts.isArrowFunction(inner) || ts.isFunctionExpression(inner);
218
+ }
219
+ function argumentsAllowed(call, allowed, types) {
220
+ const given = call.arguments ?? [];
221
+ if (given.some(ts.isSpreadElement))
222
+ return false;
223
+ switch (allowed) {
224
+ case "any":
225
+ return true;
226
+ case "none":
227
+ return given.length === 0;
228
+ case "primitive":
229
+ // A value typed `never` is in code the types say does not run (`String(unexpected)`).
230
+ return given.every((one) => types.isPrimitive(one) || types.typeTextOf(one) === "never");
231
+ case "number":
232
+ return given.every((one) => types.isNumber(one));
233
+ case "primitive-array":
234
+ return given.every((one) => types.arrayElementsOf(one) === "primitives");
235
+ case "primitive-or-callback":
236
+ return given.every((one) => types.isPrimitive(one) ||
237
+ isWrittenFunction(one) ||
238
+ types.platformTypeOf(one) === "RegExp");
239
+ case "known":
240
+ return given.length === 1 && given.every((one) => !OPEN_TYPES.has(types.typeTextOf(one)));
241
+ case "digits":
242
+ return given.length === 1 && given.every(isDigits);
243
+ case "iterated":
244
+ return (given.length === 1 &&
245
+ given.every((one) => types.arrayElementsOf(one) !== undefined || isCollectionIterator(one, types)));
246
+ }
247
+ }
248
+ /** Types that say nothing of the value. */
249
+ const OPEN_TYPES = new Set(["any", "unknown"]);
250
+ /** A whole number literal from 0 to 100, as `toFixed` accepts. */
251
+ function isDigits(node) {
252
+ const inner = stripped(node);
253
+ if (!ts.isNumericLiteral(inner))
254
+ return false;
255
+ const value = Number(inner.text);
256
+ return Number.isInteger(value) && value >= 0 && value <= 100;
257
+ }
258
+ /** The collections whose `keys()`, `values()` and `entries()` iterate without running code. */
259
+ const COLLECTIONS = new Set(["Map", "ReadonlyMap", "Set", "ReadonlySet"]);
260
+ /**
261
+ * Whether an expression is `keys()`, `values()` or `entries()` called on the platform's own
262
+ * `Map` or `Set` (`m.values()`): an iterator that runs no code of the project.
263
+ */
264
+ function isCollectionIterator(node, types) {
265
+ const call = stripped(node);
266
+ if (!ts.isCallExpression(call) || call.arguments.length > 0)
267
+ return false;
268
+ const callee = stripped(call.expression);
269
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name))
270
+ return false;
271
+ const owner = types.platformTypeOf(stripped(callee.expression));
272
+ return (["keys", "values", "entries"].includes(callee.name.text) &&
273
+ owner !== undefined &&
274
+ COLLECTIONS.has(owner) &&
275
+ types.isPlatformName(callee.name));
276
+ }
277
+ /**
278
+ * Whether a `for…of` over an expression runs no code of the project and cannot throw: over the
279
+ * platform's array, a string, or an iterator of a `Map` or `Set` (`for (const v of m.values())`).
280
+ */
281
+ export function iteratesPlainly(node, types) {
282
+ return (types.arrayElementsOf(node) !== undefined ||
283
+ types.platformTypeOf(node) === "String" ||
284
+ isCollectionIterator(node, types));
285
+ }
286
+ /** The methods of an array whose arguments decide whether they can throw. */
287
+ function arrayCallIsSafe(call, name, receiver, types) {
288
+ const given = call.arguments;
289
+ switch (name) {
290
+ // Converts each element to a string.
291
+ case "join":
292
+ case "toString":
293
+ return (types.arrayElementsOf(receiver) === "primitives" &&
294
+ given.every((one) => types.isPrimitive(one)));
295
+ // An empty array with no first value throws.
296
+ case "reduce":
297
+ case "reduceRight":
298
+ return given.length === 2;
299
+ // With no comparer, each element is converted to a string.
300
+ case "sort":
301
+ return given.length === 1 || types.arrayElementsOf(receiver) === "primitives";
302
+ // Reads `Symbol.isConcatSpreadable` of each argument.
303
+ case "concat":
304
+ return given.every((one) => types.isPrimitive(one) || types.arrayElementsOf(one) !== undefined);
305
+ default:
306
+ return undefined;
307
+ }
308
+ }
309
+ /**
310
+ * Whether a call or `new` is on the closed list of the platform's calls that do not throw, on the
311
+ * platform's own types: `console.log(…)`, `Math.max(a, b)` on numbers, `Object.keys(…)` on a
312
+ * known type, `new Map()`, `list.push(…)` on an array, `String(x)` on a primitive, `d.getTime()`,
313
+ * `n.toFixed(2)`, `Array.from(xs)` on an array, a string method on a branded string. The caller checks what a
314
+ * callback given to the call does.
315
+ */
316
+ export function isSafePlatformCall(node, types) {
317
+ const callee = stripped(node.expression);
318
+ if (ts.isNewExpression(node)) {
319
+ const owner = types.platformTypeOf(callee);
320
+ const allowed = owner === undefined ? undefined : CONSTRUCTORS.get(owner);
321
+ return allowed !== undefined && argumentsAllowed(node, allowed, types);
322
+ }
323
+ if (ts.isIdentifier(callee)) {
324
+ const allowed = GLOBALS.get(callee.text);
325
+ return (allowed !== undefined &&
326
+ types.isPlatformName(callee) &&
327
+ argumentsAllowed(node, allowed, types));
328
+ }
329
+ if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name))
330
+ return false;
331
+ const name = callee.name.text;
332
+ const receiver = stripped(callee.expression);
333
+ const owner = types.platformTypeOf(receiver);
334
+ if (owner === undefined || !types.isPlatformName(callee.name))
335
+ return false;
336
+ if (owner === "Array" || owner === "ReadonlyArray") {
337
+ const decided = arrayCallIsSafe(node, name, receiver, types);
338
+ if (decided !== undefined)
339
+ return decided;
340
+ }
341
+ const methods = METHODS.get(owner);
342
+ const allowed = methods?.get(name) ?? methods?.get("*");
343
+ return allowed !== undefined && argumentsAllowed(node, allowed, types);
344
+ }
345
+ //# sourceMappingURL=safe-calls.js.map
@@ -0,0 +1,37 @@
1
+ import type { RuleResult } from "./cache.js";
2
+ import type { StatedDeclaration, StatedGuarantee, TypeQueries } from "./types.js";
3
+ import type ts from "typescript";
4
+ /** The rule id of a guarantee no plugin lists (`unlistedGuarantees`): core states it, no rule runs it. */
5
+ export declare const STATED_RULE_ID = "stateward/stated";
6
+ /**
7
+ * The id of a stated declaration: `<file>#<offset>` of where its node starts, the place a plugin
8
+ * lists it at (`StatedGuarantee.location`). A finding names the guarantees it is against by it
9
+ * (`Finding.guarantees`).
10
+ */
11
+ export declare function declarationId(at: {
12
+ readonly file: string;
13
+ readonly start: number;
14
+ }): string;
15
+ /**
16
+ * The declarations of one file that state a guarantee in their written type, read from the cache
17
+ * entry when it has them, else from the program (`read` gives the file's queries and source, and
18
+ * is only called then). `stored` is true when this call added them to `results`.
19
+ */
20
+ export declare function fileStated(results: Map<string, RuleResult>, read: () => {
21
+ types: TypeQueries;
22
+ sourceFile: ts.SourceFile;
23
+ } | undefined): {
24
+ stated: readonly StatedDeclaration[];
25
+ stored: boolean;
26
+ };
27
+ /** The reason a synthesised guarantee reads "not checked": no rule checks the marker there. */
28
+ export declare function noRuleChecks(marker: string): string;
29
+ /**
30
+ * A guarantee for each stated declaration (and each guarantee it states) that no plugin lists:
31
+ * a rule that proves it would list it, so nothing here proves it, and it reads "not checked"
32
+ * (never "unused", never "proven") until a rule does, or a finding is against it. A plugin lists a
33
+ * declaration at where it starts, so a listed guarantee of the same name that starts inside the
34
+ * declaration's head is the same one.
35
+ */
36
+ export declare function unlistedGuarantees(scanned: readonly StatedDeclaration[], listed: readonly StatedGuarantee[]): StatedGuarantee[];
37
+ //# sourceMappingURL=stated.d.ts.map
package/dist/stated.js ADDED
@@ -0,0 +1,123 @@
1
+ import { summaryOf, summaryValue } from "./cache.js";
2
+ /**
3
+ * Where a file's stated declarations are kept in its entry of the cache (`results`), under the
4
+ * same fingerprint as its findings: that covers the file's text and what it imports, which is all
5
+ * a written type depends on. Like the ignore comments, it is not a rule's result.
6
+ */
7
+ const STATED_KEY = "stateward/stated";
8
+ /** The rule id of a guarantee no plugin lists (`unlistedGuarantees`): core states it, no rule runs it. */
9
+ export const STATED_RULE_ID = "stateward/stated";
10
+ /**
11
+ * The id of a stated declaration: `<file>#<offset>` of where its node starts, the place a plugin
12
+ * lists it at (`StatedGuarantee.location`). A finding names the guarantees it is against by it
13
+ * (`Finding.guarantees`).
14
+ */
15
+ export function declarationId(at) {
16
+ return `${at.file}#${String(at.start)}`;
17
+ }
18
+ function isRecord(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value);
20
+ }
21
+ function parseOne(value) {
22
+ if (!isRecord(value))
23
+ return undefined;
24
+ const { file, start, headEnd, end, name, marker, guarantees } = value;
25
+ if (typeof file !== "string" ||
26
+ typeof start !== "number" ||
27
+ typeof headEnd !== "number" ||
28
+ typeof end !== "number" ||
29
+ typeof name !== "string" ||
30
+ typeof marker !== "string" ||
31
+ !isList(guarantees) ||
32
+ !guarantees.every((one) => typeof one === "string")) {
33
+ return undefined;
34
+ }
35
+ return { file, start, headEnd, end, name, marker, guarantees };
36
+ }
37
+ function isList(value) {
38
+ return Array.isArray(value);
39
+ }
40
+ function parseAll(value) {
41
+ if (!isList(value))
42
+ return undefined;
43
+ const found = [];
44
+ for (const item of value) {
45
+ const one = parseOne(item);
46
+ if (one === undefined)
47
+ return undefined;
48
+ found.push(one);
49
+ }
50
+ return found;
51
+ }
52
+ /**
53
+ * The declarations of one file that state a guarantee in their written type, read from the cache
54
+ * entry when it has them, else from the program (`read` gives the file's queries and source, and
55
+ * is only called then). `stored` is true when this call added them to `results`.
56
+ */
57
+ export function fileStated(results, read) {
58
+ const kept = results.get(STATED_KEY);
59
+ if (kept !== undefined) {
60
+ if (kept.summary === undefined)
61
+ return { stated: [], stored: false };
62
+ const parsed = parseAll(summaryValue(kept.summary));
63
+ if (parsed !== undefined)
64
+ return { stated: parsed, stored: false };
65
+ }
66
+ const opened = read();
67
+ const stated = opened === undefined ? [] : opened.types.statedDeclarationsIn(opened.sourceFile);
68
+ results.set(STATED_KEY, stated.length === 0
69
+ ? { findings: [] }
70
+ : {
71
+ findings: [],
72
+ summary: summaryOf(stated.map((one) => ({
73
+ file: one.file,
74
+ start: one.start,
75
+ headEnd: one.headEnd,
76
+ end: one.end,
77
+ name: one.name,
78
+ marker: one.marker,
79
+ guarantees: [...one.guarantees],
80
+ }))),
81
+ });
82
+ return { stated, stored: true };
83
+ }
84
+ /** The reason a synthesised guarantee reads "not checked": no rule checks the marker there. */
85
+ export function noRuleChecks(marker) {
86
+ return `\`${marker}\` is stated on a declaration no rule checks: state it where its pack's page shows`;
87
+ }
88
+ /**
89
+ * A guarantee for each stated declaration (and each guarantee it states) that no plugin lists:
90
+ * a rule that proves it would list it, so nothing here proves it, and it reads "not checked"
91
+ * (never "unused", never "proven") until a rule does, or a finding is against it. A plugin lists a
92
+ * declaration at where it starts, so a listed guarantee of the same name that starts inside the
93
+ * declaration's head is the same one.
94
+ */
95
+ export function unlistedGuarantees(scanned, listed) {
96
+ const found = [];
97
+ for (const one of scanned) {
98
+ for (const name of one.guarantees) {
99
+ const known = listed.some((guarantee) => guarantee.guarantee === name &&
100
+ guarantee.location.file === one.file &&
101
+ guarantee.location.start >= one.start &&
102
+ guarantee.location.start <= one.headEnd);
103
+ if (known)
104
+ continue;
105
+ const location = { file: one.file, start: one.start, end: one.end };
106
+ found.push({
107
+ guarantee: name,
108
+ source: { kind: "marker" },
109
+ marker: one.marker,
110
+ name: one.name,
111
+ declaration: declarationId(location),
112
+ location,
113
+ ruleId: STATED_RULE_ID,
114
+ promise: "nothing yet: no rule proves it",
115
+ covers: { one: "place", many: "places" },
116
+ covered: [],
117
+ unchecked: [{ location, reason: noRuleChecks(one.marker) }],
118
+ });
119
+ }
120
+ }
121
+ return found;
122
+ }
123
+ //# sourceMappingURL=stated.js.map
@@ -8,4 +8,20 @@ export declare function typeErrors(dir: string): string;
8
8
  export declare function typeErrorsOfTexts(texts: readonly string[]): ReadonlyMap<string, string>;
9
9
  /** The type errors of one text (see `typeErrorsOfTexts`), "" when it compiles. */
10
10
  export declare function typeErrorsOfText(text: string): string;
11
+ /** A reference the language service finds: the file and the offset its name starts at. */
12
+ export type ServiceReference = {
13
+ readonly file: string;
14
+ readonly start: number;
15
+ };
16
+ /**
17
+ * What the language service's find-references gives for the declaration that starts at `start`
18
+ * in `file` (its name: a function, a variable, a property, a parameter or a type alias; each name
19
+ * of an array destructuring), in the project of `tsconfig`: every reference that is not the declaration's own
20
+ * name. A test oracle for the
21
+ * reference ledger, which is built without a language service.
22
+ */
23
+ export declare function serviceReferences(tsconfig: string, declarations: readonly {
24
+ readonly file: string;
25
+ readonly start: number;
26
+ }[]): ReadonlyMap<string, readonly ServiceReference[]>;
11
27
  //# sourceMappingURL=testing-tsc.d.ts.map
@@ -122,4 +122,90 @@ function typeErrorsOfNamed(texts, nameOf) {
122
122
  export function typeErrorsOfText(text) {
123
123
  return typeErrorsOfNamed([text], () => "a.ts").get(text) ?? "";
124
124
  }
125
+ /**
126
+ * What the language service's find-references gives for the declaration that starts at `start`
127
+ * in `file` (its name: a function, a variable, a property, a parameter or a type alias; each name
128
+ * of an array destructuring), in the project of `tsconfig`: every reference that is not the declaration's own
129
+ * name. A test oracle for the
130
+ * reference ledger, which is built without a language service.
131
+ */
132
+ export function serviceReferences(tsconfig, declarations) {
133
+ const read = ts.readConfigFile(tsconfig, (file) => ts.sys.readFile(file));
134
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, path.dirname(tsconfig));
135
+ const versions = new Map(parsed.fileNames.map((file) => [file, "0"]));
136
+ const host = {
137
+ getScriptFileNames: () => parsed.fileNames,
138
+ getScriptVersion: (file) => versions.get(file) ?? "0",
139
+ getScriptSnapshot: (file) => {
140
+ const text = ts.sys.readFile(file);
141
+ return text === undefined ? undefined : ts.ScriptSnapshot.fromString(text);
142
+ },
143
+ getCurrentDirectory: () => path.dirname(tsconfig),
144
+ getCompilationSettings: () => parsed.options,
145
+ getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options),
146
+ fileExists: (file) => ts.sys.fileExists(file),
147
+ readFile: (file) => ts.sys.readFile(file),
148
+ readDirectory: (...args) => ts.sys.readDirectory(...args),
149
+ directoryExists: (dir) => ts.sys.directoryExists(dir),
150
+ getDirectories: (dir) => ts.sys.getDirectories(dir),
151
+ };
152
+ const service = ts.createLanguageService(host);
153
+ const program = service.getProgram();
154
+ const found = new Map();
155
+ for (const declaration of declarations) {
156
+ const sourceFile = program?.getSourceFile(declaration.file);
157
+ const name = sourceFile === undefined ? undefined : nameAt(sourceFile, declaration.start);
158
+ if (sourceFile === undefined || name === undefined) {
159
+ throw new Error(`no declaration at ${declaration.file}#${String(declaration.start)}`);
160
+ }
161
+ // `const [saving, setSaving] = …`: each name of the pattern is the declaration's.
162
+ const names = ts.isArrayBindingPattern(name)
163
+ ? name.elements.flatMap((element) => ts.isBindingElement(element) && ts.isIdentifier(element.name) ? [element.name] : [])
164
+ : [name];
165
+ const own = new Set(names.map((one) => one.getStart(sourceFile)));
166
+ const references = [];
167
+ for (const one of names) {
168
+ for (const symbol of service.findReferences(declaration.file, one.getStart(sourceFile)) ??
169
+ []) {
170
+ for (const reference of symbol.references) {
171
+ const start = reference.textSpan.start;
172
+ if (reference.fileName === declaration.file && own.has(start))
173
+ continue;
174
+ // A string key (`store["saving"]`) is found inside its quotes; the ledger has the literal.
175
+ const text = program?.getSourceFile(reference.fileName)?.text ?? "";
176
+ const quoted = start > 0 && (text[start - 1] === '"' || text[start - 1] === "'");
177
+ const at = quoted && text[start + reference.textSpan.length] === text[start - 1];
178
+ references.push({ file: reference.fileName, start: at ? start - 1 : start });
179
+ }
180
+ }
181
+ }
182
+ found.set(`${declaration.file}#${String(declaration.start)}`, references);
183
+ }
184
+ service.dispose();
185
+ return found;
186
+ }
187
+ /** The name of the declaration that starts at `start`, or that is named there. */
188
+ function nameAt(sourceFile, start) {
189
+ let found;
190
+ const visit = (node) => {
191
+ if (found !== undefined)
192
+ return;
193
+ if ((ts.isFunctionDeclaration(node) ||
194
+ ts.isMethodDeclaration(node) ||
195
+ ts.isMethodSignature(node) ||
196
+ ts.isVariableDeclaration(node) ||
197
+ ts.isPropertyDeclaration(node) ||
198
+ ts.isPropertySignature(node) ||
199
+ ts.isParameter(node) ||
200
+ ts.isTypeAliasDeclaration(node)) &&
201
+ node.name !== undefined &&
202
+ (node.getStart(sourceFile) === start || node.name.getStart(sourceFile) === start)) {
203
+ found = node.name;
204
+ return;
205
+ }
206
+ ts.forEachChild(node, visit);
207
+ };
208
+ visit(sourceFile);
209
+ return found;
210
+ }
125
211
  //# sourceMappingURL=testing-tsc.js.map
package/dist/testing.d.ts CHANGED
@@ -30,5 +30,6 @@ export declare class MessageStandardError extends Error {
30
30
  }
31
31
  /** Throws a `MessageStandardError` listing every violation in `findings`; use it in rule tests. */
32
32
  export declare function expectMessageStandard(findings: readonly Finding[]): void;
33
- export { typeErrors, typeErrorsOfText, typeErrorsOfTexts } from "./testing-tsc.js";
33
+ export { serviceReferences, typeErrors, typeErrorsOfText, typeErrorsOfTexts, } from "./testing-tsc.js";
34
+ export type { ServiceReference } from "./testing-tsc.js";
34
35
  //# sourceMappingURL=testing.d.ts.map
package/dist/testing.js CHANGED
@@ -214,5 +214,5 @@ export function expectMessageStandard(findings) {
214
214
  throw new MessageStandardError(`${String(violations.length)} message standard violation(s):\n${violations.join("\n")}`);
215
215
  }
216
216
  }
217
- export { typeErrors, typeErrorsOfText, typeErrorsOfTexts } from "./testing-tsc.js";
217
+ export { serviceReferences, typeErrors, typeErrorsOfText, typeErrorsOfTexts, } from "./testing-tsc.js";
218
218
  //# sourceMappingURL=testing.js.map
package/dist/timing.d.ts CHANGED
@@ -50,6 +50,11 @@ export type RunTiming = {
50
50
  readonly typeMs: number;
51
51
  /** Dependency fingerprints for the results cache. */
52
52
  readonly fingerprintMs: number;
53
+ /**
54
+ * The reference ledger: every reference to each stated declaration, in the files whose ledger is
55
+ * not in the cache (its type questions included).
56
+ */
57
+ readonly ledgerMs: number;
53
58
  /** Everything else: syntax and import findings, ignore comments, sorting, the cache. */
54
59
  readonly otherMs: number;
55
60
  /** The second pass's time (not part of the check's result), when there was one. */
@@ -61,6 +66,8 @@ export type TimingRecorder = {
61
66
  /** The time of building programs, added to `programMs`. */
62
67
  program(ms: number): void;
63
68
  fingerprint(ms: number): void;
69
+ /** The time of the reference ledger on one file, added to `ledgerMs`. */
70
+ ledger(ms: number): void;
64
71
  /** Runs `run` as `ruleId`'s file side on one file and records its cost. */
65
72
  fileSide<T>(ruleId: string, kind: "file" | "project", run: () => T): T;
66
73
  /** Counts one result of `ruleId` reused from the cache. */