@noego/trust 0.4.0 → 0.5.0-dev.0
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.
- package/README.md +926 -13
- package/dist/baseline-B0AplCuF.d.ts +362 -0
- package/dist/chunk-NG4KYWVW.js +6154 -0
- package/dist/chunk-NG4KYWVW.js.map +1 -0
- package/dist/chunk-OSSITT3R.js +156 -0
- package/dist/chunk-OSSITT3R.js.map +1 -0
- package/dist/chunk-V72KWVWP.js +2820 -0
- package/dist/chunk-V72KWVWP.js.map +1 -0
- package/dist/cli/index.js +1140 -63
- package/dist/cli/index.js.map +1 -1
- package/dist/core/index.d.ts +127 -0
- package/dist/core/index.js +115 -0
- package/dist/core/index.js.map +1 -0
- package/dist/eslint/index.d.ts +73 -167
- package/dist/eslint/index.js +320 -32
- package/dist/eslint/index.js.map +1 -1
- package/package.json +7 -4
- package/dist/chunk-YJYGTNJD.js +0 -2168
- package/dist/chunk-YJYGTNJD.js.map +0 -1
|
@@ -0,0 +1,2820 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ACCEPT_DIRECTIVE,
|
|
3
|
+
ACCEPT_DIRECTIVE_MESSAGES,
|
|
4
|
+
CATCH_ORIGIN,
|
|
5
|
+
DEFAULT_RULE_SETTINGS,
|
|
6
|
+
DIRECTIVE_ORIGIN,
|
|
7
|
+
DROPPED_RESULT_MESSAGES,
|
|
8
|
+
DROPPED_RESULT_RULE,
|
|
9
|
+
FLOATING_PROMISE_MESSAGE,
|
|
10
|
+
FLOATING_PROMISE_ORIGIN,
|
|
11
|
+
FLOATING_PROMISE_RULE,
|
|
12
|
+
MISUSED_PROMISE_MESSAGES,
|
|
13
|
+
MISUSED_PROMISE_RULE,
|
|
14
|
+
OriginResolver,
|
|
15
|
+
REDUNDANT_GUARD_MESSAGES,
|
|
16
|
+
REDUNDANT_GUARD_ORIGIN,
|
|
17
|
+
REDUNDANT_GUARD_RULE,
|
|
18
|
+
THROW_MESSAGES,
|
|
19
|
+
THROW_ORIGIN,
|
|
20
|
+
THROW_RULE,
|
|
21
|
+
TYPE_CLAIM_MESSAGES,
|
|
22
|
+
TYPE_CLAIM_RULE,
|
|
23
|
+
UNTRUSTED_CALL_MESSAGES,
|
|
24
|
+
UNTRUSTED_CALL_RULE,
|
|
25
|
+
UNTRUSTED_ENTRY_LABELS,
|
|
26
|
+
UNTRUSTED_VALUE_MESSAGES,
|
|
27
|
+
UNTRUSTED_VALUE_RULE,
|
|
28
|
+
Zones,
|
|
29
|
+
directiveDirectlyAbove,
|
|
30
|
+
directiveProblem,
|
|
31
|
+
fillMessage,
|
|
32
|
+
formatFailureKinds,
|
|
33
|
+
formatMessage,
|
|
34
|
+
isAcceptDirective,
|
|
35
|
+
isInsideValidator,
|
|
36
|
+
isMarkedValidator,
|
|
37
|
+
isRuleEnabled,
|
|
38
|
+
isTrustPackageFile,
|
|
39
|
+
nodeBelow,
|
|
40
|
+
realpathOrSelf,
|
|
41
|
+
trustDirectivesIn
|
|
42
|
+
} from "./chunk-NG4KYWVW.js";
|
|
43
|
+
|
|
44
|
+
// src/core/guard.ts
|
|
45
|
+
function unparen(ts, node) {
|
|
46
|
+
let current = node;
|
|
47
|
+
while (ts.isParenthesizedExpression(current)) current = current.expression;
|
|
48
|
+
return current;
|
|
49
|
+
}
|
|
50
|
+
function esParent(ts, node) {
|
|
51
|
+
let parent = node.parent;
|
|
52
|
+
while (parent && ts.isParenthesizedExpression(parent)) parent = parent.parent;
|
|
53
|
+
return parent;
|
|
54
|
+
}
|
|
55
|
+
function inOptionalChain(ts, node) {
|
|
56
|
+
return (node.flags & ts.NodeFlags.OptionalChain) !== 0;
|
|
57
|
+
}
|
|
58
|
+
function asPlainCall(ts, node) {
|
|
59
|
+
const inner = unparen(ts, node);
|
|
60
|
+
return ts.isCallExpression(inner) && !inOptionalChain(ts, inner) ? inner : null;
|
|
61
|
+
}
|
|
62
|
+
function isFunctionBoundary(ts, node) {
|
|
63
|
+
return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isConstructorDeclaration(node) || ts.isGetAccessorDeclaration(node) || ts.isSetAccessorDeclaration(node);
|
|
64
|
+
}
|
|
65
|
+
function isLoopOrSwitch(ts, node) {
|
|
66
|
+
return ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node) || ts.isSwitchStatement(node);
|
|
67
|
+
}
|
|
68
|
+
function collectExits(ts, node, exits2) {
|
|
69
|
+
if (isFunctionBoundary(ts, node)) return;
|
|
70
|
+
if (ts.isReturnStatement(node) || ts.isThrowStatement(node)) exits2.push(node);
|
|
71
|
+
ts.forEachChild(node, (child) => collectExits(ts, child, exits2));
|
|
72
|
+
}
|
|
73
|
+
function containsBreakFor(ts, node, isRoot = true) {
|
|
74
|
+
if (isFunctionBoundary(ts, node)) return false;
|
|
75
|
+
if (!isRoot && isLoopOrSwitch(ts, node)) return false;
|
|
76
|
+
if (ts.isBreakStatement(node) && !node.label) return true;
|
|
77
|
+
return ts.forEachChild(node, (child) => containsBreakFor(ts, child, false) || void 0) ?? false;
|
|
78
|
+
}
|
|
79
|
+
function alwaysExits(ts, statement) {
|
|
80
|
+
if (!statement) return false;
|
|
81
|
+
if (ts.isReturnStatement(statement) || ts.isThrowStatement(statement)) return true;
|
|
82
|
+
if (ts.isBlock(statement)) return statement.statements.some((child) => alwaysExits(ts, child));
|
|
83
|
+
if (ts.isIfStatement(statement)) return alwaysExits(ts, statement.thenStatement) && alwaysExits(ts, statement.elseStatement);
|
|
84
|
+
if (ts.isSwitchStatement(statement)) {
|
|
85
|
+
const clauses = statement.caseBlock.clauses;
|
|
86
|
+
if (!clauses.some((clause) => ts.isDefaultClause(clause))) return false;
|
|
87
|
+
if (containsBreakFor(ts, statement)) return false;
|
|
88
|
+
return clauses[clauses.length - 1].statements.some((child) => alwaysExits(ts, child));
|
|
89
|
+
}
|
|
90
|
+
if (ts.isTryStatement(statement)) {
|
|
91
|
+
if (alwaysExits(ts, statement.finallyBlock)) return true;
|
|
92
|
+
const handler = statement.catchClause;
|
|
93
|
+
return alwaysExits(ts, statement.tryBlock) && (!handler || alwaysExits(ts, handler.block));
|
|
94
|
+
}
|
|
95
|
+
if (ts.isLabeledStatement(statement)) return alwaysExits(ts, statement.statement);
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function catchProblem(handler, context) {
|
|
99
|
+
const ts = context.ts;
|
|
100
|
+
const exits2 = [];
|
|
101
|
+
collectExits(ts, handler.block, exits2);
|
|
102
|
+
const param = handler.variableDeclaration?.name;
|
|
103
|
+
const paramName = param && ts.isIdentifier(param) ? param.text : null;
|
|
104
|
+
for (const exit of exits2) {
|
|
105
|
+
if (ts.isThrowStatement(exit)) return "rethrow";
|
|
106
|
+
const argument = exit.expression ? unparen(ts, exit.expression) : void 0;
|
|
107
|
+
if (!argument || !context.isResultErr(argument)) return "notResultErr";
|
|
108
|
+
const call = paramName ? asPlainCall(ts, argument) : null;
|
|
109
|
+
if (call && context.isErrCall(call)) {
|
|
110
|
+
const first = call.arguments[0];
|
|
111
|
+
const value = first ? unparen(ts, first) : void 0;
|
|
112
|
+
if (value && ts.isIdentifier(value) && value.text === paramName) return "rawCatchValue";
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return alwaysExits(ts, handler.block) ? null : "notAllPaths";
|
|
116
|
+
}
|
|
117
|
+
function guardOf(node, context) {
|
|
118
|
+
const ts = context.ts;
|
|
119
|
+
let child = node;
|
|
120
|
+
let current = node.parent;
|
|
121
|
+
while (current) {
|
|
122
|
+
if (isFunctionBoundary(ts, current)) {
|
|
123
|
+
const call = esParent(ts, current);
|
|
124
|
+
if (call && ts.isCallExpression(call) && call.arguments[0] && unparen(ts, call.arguments[0]) === current) {
|
|
125
|
+
const kind = context.trustTryKind(call);
|
|
126
|
+
if (kind) return { status: "guarded", via: kind === "sync" ? "sync-callback" : "async-callback" };
|
|
127
|
+
}
|
|
128
|
+
return { status: "unguarded" };
|
|
129
|
+
}
|
|
130
|
+
if (ts.isTryStatement(current) && current.tryBlock === child) {
|
|
131
|
+
const handler = current.catchClause;
|
|
132
|
+
if (handler) {
|
|
133
|
+
const problem = catchProblem(handler, context);
|
|
134
|
+
return problem ? { status: "badCatch", problem } : { status: "guarded", via: "try" };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
child = current;
|
|
138
|
+
current = current.parent;
|
|
139
|
+
}
|
|
140
|
+
return { status: "unguarded" };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// src/eslint/policy.ts
|
|
144
|
+
function isPresetSource(source) {
|
|
145
|
+
return source.startsWith("preset:");
|
|
146
|
+
}
|
|
147
|
+
function entryMatches(entry, origin, base) {
|
|
148
|
+
if (origin === entry) return true;
|
|
149
|
+
if (!origin.startsWith(entry)) return false;
|
|
150
|
+
const next = origin[entry.length];
|
|
151
|
+
if (base !== void 0 && entry.length < base.length) return next === "/";
|
|
152
|
+
return next === "/" || next === "." || next === "#";
|
|
153
|
+
}
|
|
154
|
+
function bestMatch(entries, origin, base) {
|
|
155
|
+
let best;
|
|
156
|
+
for (const entry of entries) {
|
|
157
|
+
if (entryMatches(entry, origin, base) && (best === void 0 || entry.length > best.length)) best = entry;
|
|
158
|
+
}
|
|
159
|
+
return best;
|
|
160
|
+
}
|
|
161
|
+
function decide(levels, lists, origin, base) {
|
|
162
|
+
for (const level of levels) {
|
|
163
|
+
const { trust, distrust } = lists(level);
|
|
164
|
+
const distrusted = bestMatch(distrust, origin, base);
|
|
165
|
+
const trusted = bestMatch(trust, origin, base);
|
|
166
|
+
if (trusted && (!distrusted || trusted.length > distrusted.length)) {
|
|
167
|
+
return { trusted: true, by: { source: level.source, entry: trusted } };
|
|
168
|
+
}
|
|
169
|
+
if (distrusted) return { trusted: false, distrustedBy: { source: level.source, entry: distrusted } };
|
|
170
|
+
}
|
|
171
|
+
return { trusted: false };
|
|
172
|
+
}
|
|
173
|
+
var TrustPolicy = class {
|
|
174
|
+
constructor(ts, checker, config, extraTrust = []) {
|
|
175
|
+
this.ts = ts;
|
|
176
|
+
this.checker = checker;
|
|
177
|
+
this.zones = new Zones(config.rootDir, config.passthrough, config.ignore);
|
|
178
|
+
this.origins = new OriginResolver(ts, this.zones);
|
|
179
|
+
this.rules = config.rules;
|
|
180
|
+
const fromOptions = { source: "rule options", trust: extraTrust, distrust: [], typeTrust: [], typeDistrust: [] };
|
|
181
|
+
this.levels = extraTrust.length > 0 ? [fromOptions, ...config.levels] : config.levels;
|
|
182
|
+
}
|
|
183
|
+
ts;
|
|
184
|
+
checker;
|
|
185
|
+
zones;
|
|
186
|
+
origins;
|
|
187
|
+
/** The config's per-rule settings (`rules`): which opt-in rules run and which callbacks are sources. */
|
|
188
|
+
rules;
|
|
189
|
+
levels;
|
|
190
|
+
/** Throw trust of an origin: the `trust` / `distrust` lists of the chain (see `decide`). */
|
|
191
|
+
lookup(origin, base) {
|
|
192
|
+
return decide(this.levels, (level) => level, origin, base);
|
|
193
|
+
}
|
|
194
|
+
/** Type trust of an origin: the `trust_type` / `distrust_type` lists of the chain, resolved the same way. */
|
|
195
|
+
lookupType(origin, base) {
|
|
196
|
+
return decide(this.levels, (level) => ({ trust: level.typeTrust, distrust: level.typeDistrust }), origin, base);
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* The `trust_type` entry of the project's own config files that type-trusts `declaration` (member or
|
|
200
|
+
* package level), else null. Entries of built-in presets (`preset:<name>` levels: js, node, web,
|
|
201
|
+
* web_strict, svelte) never count, and a `distrust_type` that wins along the chain takes it back. Only
|
|
202
|
+
* this unlocks a caller-chosen generic return (`container.get<Foo>('x')`, type-claims.ts): a broad preset
|
|
203
|
+
* entry such as `js:Array` must not silently bless a cast. Checked code is looked up too, so a user entry
|
|
204
|
+
* naming a first-party origin (`local:ui/scope.ts#resolveSyncInScope`) unlocks its generic returns.
|
|
205
|
+
*/
|
|
206
|
+
userTypeTrustOf(declaration) {
|
|
207
|
+
if (isTrustPackageFile(declaration.getSourceFile().fileName)) return null;
|
|
208
|
+
const origin = this.origins.originOf(declaration);
|
|
209
|
+
const decision = this.lookupType(origin.origin, origin.kind === "external" ? origin.base : void 0);
|
|
210
|
+
return decision.trusted && !isPresetSource(decision.by.source) ? decision.by : null;
|
|
211
|
+
}
|
|
212
|
+
/** Whether the types `declaration` states are trusted (see TypeVerdict). */
|
|
213
|
+
typeVerdictOf(declaration) {
|
|
214
|
+
const origin = this.origins.originOf(declaration);
|
|
215
|
+
if (origin.kind === "local" && origin.zone === "checked") return { kind: "first-party", origin };
|
|
216
|
+
if (isTrustPackageFile(declaration.getSourceFile().fileName)) return { kind: "trust-package", origin };
|
|
217
|
+
const decision = this.lookupType(origin.origin, origin.kind === "external" ? origin.base : void 0);
|
|
218
|
+
if (decision.trusted) return { kind: "type-trusted", origin, by: decision.by };
|
|
219
|
+
return decision.distrustedBy ? { kind: "type-untrusted", origin, distrustedBy: decision.distrustedBy } : { kind: "type-untrusted", origin };
|
|
220
|
+
}
|
|
221
|
+
classify(node) {
|
|
222
|
+
const resolved = this.calleeDeclaration(node);
|
|
223
|
+
if (!resolved) return { kind: "unresolved" };
|
|
224
|
+
const origin = this.origins.originOf(resolved.declaration);
|
|
225
|
+
if (origin.kind === "local" && origin.zone === "checked") return { kind: "first-party", origin };
|
|
226
|
+
if (origin.kind === "local" && origin.zone === "ignore") return { kind: "calls-ignored", origin };
|
|
227
|
+
const decision = this.lookup(origin.origin, origin.kind === "external" ? origin.base : void 0);
|
|
228
|
+
if (!decision.trusted && decision.distrustedBy) return { kind: "untrusted", origin, distrustedBy: decision.distrustedBy };
|
|
229
|
+
if (resolved.signature && this.returnsResult(resolved.signature)) return { kind: "returns-result", origin };
|
|
230
|
+
if (decision.trusted) return { kind: "trusted", origin, by: decision.by };
|
|
231
|
+
return { kind: "untrusted", origin };
|
|
232
|
+
}
|
|
233
|
+
calleeDeclaration(node) {
|
|
234
|
+
const ts = this.ts;
|
|
235
|
+
const signature = this.checker.getResolvedSignature(node);
|
|
236
|
+
const fromSignature = signature?.declaration && !ts.isJSDocSignature(signature.declaration) ? signature.declaration : void 0;
|
|
237
|
+
const anonymous = !fromSignature || ts.isCallSignatureDeclaration(fromSignature) || ts.isConstructSignatureDeclaration(fromSignature) || ts.isFunctionTypeNode(fromSignature);
|
|
238
|
+
if (fromSignature && !anonymous) return { declaration: fromSignature, signature };
|
|
239
|
+
let symbol = this.checker.getSymbolAtLocation(node.expression);
|
|
240
|
+
if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = this.checker.getAliasedSymbol(symbol);
|
|
241
|
+
const fromSymbol = symbol?.declarations?.[0];
|
|
242
|
+
const sameFile = fromSymbol && fromSignature && fromSymbol.getSourceFile() === fromSignature.getSourceFile();
|
|
243
|
+
const declaration = !fromSignature || sameFile ? fromSymbol : fromSignature;
|
|
244
|
+
return declaration ? { declaration, signature } : null;
|
|
245
|
+
}
|
|
246
|
+
/** Declared return type is Result / Promise<Result> from @noego/trust (every union member is Ok or Err). */
|
|
247
|
+
returnsResult(signature) {
|
|
248
|
+
const returnType = this.checker.getReturnTypeOfSignature(signature);
|
|
249
|
+
const awaited = this.checker.getAwaitedType(returnType) ?? returnType;
|
|
250
|
+
return this.isResultType(awaited);
|
|
251
|
+
}
|
|
252
|
+
isResultType(type) {
|
|
253
|
+
const members2 = type.isUnion() ? type.types : [type];
|
|
254
|
+
return members2.length > 0 && members2.every((member) => this.resultVariant(member) !== null);
|
|
255
|
+
}
|
|
256
|
+
/** True when every member of the type is an `Err` from @noego/trust. */
|
|
257
|
+
isErrType(type) {
|
|
258
|
+
const members2 = type.isUnion() ? type.types : [type];
|
|
259
|
+
return members2.length > 0 && members2.every((member) => this.resultVariant(member) === "err");
|
|
260
|
+
}
|
|
261
|
+
/** 'ok' | 'err' when the type is @noego/trust's Ok/Err (by the declaration of its `ok` property). */
|
|
262
|
+
resultVariant(type) {
|
|
263
|
+
const property = type.getProperty("ok");
|
|
264
|
+
const declaration = property?.valueDeclaration ?? property?.declarations?.[0];
|
|
265
|
+
if (!property || !declaration || !isTrustPackageFile(declaration.getSourceFile().fileName)) return null;
|
|
266
|
+
const discriminant = this.checker.typeToString(this.checker.getTypeOfSymbol(property));
|
|
267
|
+
if (discriminant === "true") return "ok";
|
|
268
|
+
if (discriminant === "false") return "err";
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
/** Name of the @noego/trust function a call resolves to (`err`, `tryResult`, …), else null. */
|
|
272
|
+
trustFunctionName(node) {
|
|
273
|
+
const resolved = this.calleeDeclaration(node);
|
|
274
|
+
if (!resolved || !isTrustPackageFile(resolved.declaration.getSourceFile().fileName)) return null;
|
|
275
|
+
const name = resolved.declaration.name;
|
|
276
|
+
return name && this.ts.isIdentifier(name) ? name.text : null;
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
|
|
280
|
+
// src/core/dropped-results.ts
|
|
281
|
+
var ANY_KIND = "*";
|
|
282
|
+
function droppedResultContext(ts, checker, policy) {
|
|
283
|
+
return { ts, checker, policy, kindCache: /* @__PURE__ */ new WeakMap() };
|
|
284
|
+
}
|
|
285
|
+
function droppedResultData(dropped) {
|
|
286
|
+
return { subject: dropped.subject, kinds: formatFailureKinds(dropped.kinds, ANY_KIND) };
|
|
287
|
+
}
|
|
288
|
+
function droppedResultMessage(dropped) {
|
|
289
|
+
return fillMessage(DROPPED_RESULT_MESSAGES[dropped.origin], droppedResultData(dropped));
|
|
290
|
+
}
|
|
291
|
+
var NOTHING = /* @__PURE__ */ new Set();
|
|
292
|
+
var ELEMENT_METHODS = /* @__PURE__ */ new Set([
|
|
293
|
+
"filter",
|
|
294
|
+
"slice",
|
|
295
|
+
"concat",
|
|
296
|
+
"reverse",
|
|
297
|
+
"sort",
|
|
298
|
+
"toSorted",
|
|
299
|
+
"toReversed",
|
|
300
|
+
"toSpliced",
|
|
301
|
+
"flat",
|
|
302
|
+
"find",
|
|
303
|
+
"findLast",
|
|
304
|
+
"at"
|
|
305
|
+
]);
|
|
306
|
+
var PREDICATE_METHODS = /* @__PURE__ */ new Set([
|
|
307
|
+
"filter",
|
|
308
|
+
"find",
|
|
309
|
+
"findLast",
|
|
310
|
+
"findIndex",
|
|
311
|
+
"findLastIndex",
|
|
312
|
+
"some",
|
|
313
|
+
"every",
|
|
314
|
+
"sort",
|
|
315
|
+
"toSorted"
|
|
316
|
+
]);
|
|
317
|
+
var SUBJECT_LIMIT = 60;
|
|
318
|
+
function members(type) {
|
|
319
|
+
return type.isUnion() ? type.types : [type];
|
|
320
|
+
}
|
|
321
|
+
function union(a, b) {
|
|
322
|
+
if (a.size === 0) return b;
|
|
323
|
+
if (b.size === 0) return a;
|
|
324
|
+
return /* @__PURE__ */ new Set([...a, ...b]);
|
|
325
|
+
}
|
|
326
|
+
function merge(a, b) {
|
|
327
|
+
if (!a) return b ? new Map(b) : null;
|
|
328
|
+
const merged = new Map(a);
|
|
329
|
+
if (!b) return merged;
|
|
330
|
+
for (const [symbol, right] of b) {
|
|
331
|
+
const left = merged.get(symbol);
|
|
332
|
+
merged.set(symbol, left ? { kinds: union(left.kinds, right.kinds), err: left.err && right.err } : right);
|
|
333
|
+
}
|
|
334
|
+
return merged;
|
|
335
|
+
}
|
|
336
|
+
function mergeAll(states) {
|
|
337
|
+
return states.reduce((merged, state) => merge(merged, state), null);
|
|
338
|
+
}
|
|
339
|
+
function argumentsOf(call) {
|
|
340
|
+
return call.arguments ?? [];
|
|
341
|
+
}
|
|
342
|
+
function within(node, container) {
|
|
343
|
+
return node.pos >= container.pos && node.end <= container.end;
|
|
344
|
+
}
|
|
345
|
+
function errKinds(context, type, kinds) {
|
|
346
|
+
const { ts, checker, policy } = context;
|
|
347
|
+
let fallible = false;
|
|
348
|
+
for (const member of members(checker.getAwaitedType(type) ?? type)) {
|
|
349
|
+
if (policy.resultVariant(member) !== "err") continue;
|
|
350
|
+
const error = member.getProperty("error");
|
|
351
|
+
const errorType = error ? checker.getTypeOfSymbol(error) : void 0;
|
|
352
|
+
if (errorType && errorType.flags & ts.TypeFlags.Never) continue;
|
|
353
|
+
fallible = true;
|
|
354
|
+
if (!errorType) {
|
|
355
|
+
kinds.add(ANY_KIND);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
for (const failure of members(errorType)) {
|
|
359
|
+
const kind = failure.getProperty("kind");
|
|
360
|
+
const kindType = kind ? checker.getTypeOfSymbol(kind) : void 0;
|
|
361
|
+
if (!kindType) {
|
|
362
|
+
kinds.add(ANY_KIND);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
for (const literal of members(kindType)) kinds.add(literal.isStringLiteral() ? literal.value : ANY_KIND);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return fallible;
|
|
369
|
+
}
|
|
370
|
+
function failureKinds(context, type) {
|
|
371
|
+
const cached = context.kindCache.get(type);
|
|
372
|
+
if (cached !== void 0) return cached;
|
|
373
|
+
const { ts, checker, policy } = context;
|
|
374
|
+
let result = null;
|
|
375
|
+
if (!(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never))) {
|
|
376
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
377
|
+
let fallible = errKinds(context, type, kinds);
|
|
378
|
+
for (const member of members(checker.getAwaitedType(type) ?? type)) {
|
|
379
|
+
if (member.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any) || policy.resultVariant(member) !== null) continue;
|
|
380
|
+
const element = checker.getIndexTypeOfType(member, ts.IndexKind.Number);
|
|
381
|
+
if (element && errKinds(context, element, kinds)) fallible = true;
|
|
382
|
+
}
|
|
383
|
+
result = fallible ? kinds : null;
|
|
384
|
+
}
|
|
385
|
+
context.kindCache.set(type, result);
|
|
386
|
+
return result;
|
|
387
|
+
}
|
|
388
|
+
function subjectOf(node, sourceFile) {
|
|
389
|
+
const text = node.getText(sourceFile).replace(/\s+/g, " ").trim();
|
|
390
|
+
return text.length > SUBJECT_LIMIT ? `${text.slice(0, SUBJECT_LIMIT - 1)}\u2026` : text;
|
|
391
|
+
}
|
|
392
|
+
function isOwner(ts, node) {
|
|
393
|
+
return isFunctionBoundary(ts, node) || ts.isClassStaticBlockDeclaration(node);
|
|
394
|
+
}
|
|
395
|
+
function stringLiteral(ts, node) {
|
|
396
|
+
const inner = unparen(ts, node);
|
|
397
|
+
return ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner) ? inner.text : void 0;
|
|
398
|
+
}
|
|
399
|
+
function isPlainOrLogicalAssignment(ts, operator) {
|
|
400
|
+
return operator === ts.SyntaxKind.EqualsToken || operator === ts.SyntaxKind.QuestionQuestionEqualsToken || operator === ts.SyntaxKind.BarBarEqualsToken || operator === ts.SyntaxKind.AmpersandAmpersandEqualsToken;
|
|
401
|
+
}
|
|
402
|
+
function isEquality(ts, operator) {
|
|
403
|
+
return operator === ts.SyntaxKind.EqualsEqualsEqualsToken || operator === ts.SyntaxKind.ExclamationEqualsEqualsToken || operator === ts.SyntaxKind.EqualsEqualsToken || operator === ts.SyntaxKind.ExclamationEqualsToken;
|
|
404
|
+
}
|
|
405
|
+
function isNullish(ts, node) {
|
|
406
|
+
const inner = unparen(ts, node);
|
|
407
|
+
return inner.kind === ts.SyntaxKind.NullKeyword || ts.isIdentifier(inner) && inner.text === "undefined";
|
|
408
|
+
}
|
|
409
|
+
function booleanLiteral(ts, node) {
|
|
410
|
+
const inner = unparen(ts, node);
|
|
411
|
+
if (inner.kind === ts.SyntaxKind.TrueKeyword) return true;
|
|
412
|
+
if (inner.kind === ts.SyntaxKind.FalseKeyword) return false;
|
|
413
|
+
return void 0;
|
|
414
|
+
}
|
|
415
|
+
var DropWalk = class {
|
|
416
|
+
constructor(context, owner, found) {
|
|
417
|
+
this.context = context;
|
|
418
|
+
this.owner = owner;
|
|
419
|
+
this.found = found;
|
|
420
|
+
this.ts = context.ts;
|
|
421
|
+
this.checker = context.checker;
|
|
422
|
+
this.sourceFile = owner.getSourceFile();
|
|
423
|
+
this.functionScope = context.ts.isSourceFile(owner) ? owner : owner.body ?? owner;
|
|
424
|
+
}
|
|
425
|
+
context;
|
|
426
|
+
owner;
|
|
427
|
+
found;
|
|
428
|
+
ts;
|
|
429
|
+
checker;
|
|
430
|
+
sourceFile;
|
|
431
|
+
tracked = /* @__PURE__ */ new Map();
|
|
432
|
+
/** `const failure = r.error`: alias symbol → r. */
|
|
433
|
+
errorAliases = /* @__PURE__ */ new Map();
|
|
434
|
+
/** A variable whose value takes failures along (`const failed = { error: r.error }`) → those variables. */
|
|
435
|
+
failureCarriers = /* @__PURE__ */ new Map();
|
|
436
|
+
targets = [];
|
|
437
|
+
reported = /* @__PURE__ */ new Set();
|
|
438
|
+
/** Where `var` declarations live. */
|
|
439
|
+
functionScope;
|
|
440
|
+
run() {
|
|
441
|
+
const ts = this.ts;
|
|
442
|
+
const owner = this.owner;
|
|
443
|
+
if (ts.isSourceFile(owner)) {
|
|
444
|
+
this.statements(owner.statements, /* @__PURE__ */ new Map(), owner);
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const body = owner.body;
|
|
448
|
+
if (!body) return;
|
|
449
|
+
const state = /* @__PURE__ */ new Map();
|
|
450
|
+
if (!ts.isClassStaticBlockDeclaration(owner) && !this.isPredicateCallback(owner)) {
|
|
451
|
+
for (const parameter of owner.parameters) this.declare(parameter.name, body, state, true);
|
|
452
|
+
}
|
|
453
|
+
if (ts.isBlock(body)) {
|
|
454
|
+
this.block(body, state);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
this.visit(body, state);
|
|
458
|
+
this.checkReturn(body, body, state);
|
|
459
|
+
}
|
|
460
|
+
/** The function is the predicate of `xs.filter(…)` / `find` / `some` / …: it looks at elements its receiver keeps. */
|
|
461
|
+
isPredicateCallback(owner) {
|
|
462
|
+
const ts = this.ts;
|
|
463
|
+
if (!ts.isArrowFunction(owner) && !ts.isFunctionExpression(owner)) return false;
|
|
464
|
+
const call = owner.parent;
|
|
465
|
+
if (!ts.isCallExpression(call) || !call.arguments.includes(owner)) return false;
|
|
466
|
+
const callee = unparen(ts, call.expression);
|
|
467
|
+
return ts.isPropertyAccessExpression(callee) && PREDICATE_METHODS.has(callee.name.text);
|
|
468
|
+
}
|
|
469
|
+
// ---- reporting ----
|
|
470
|
+
report(origin, at, subject, kinds) {
|
|
471
|
+
const start = typeof at === "number" ? at : at.getStart(this.sourceFile);
|
|
472
|
+
this.found.push({ origin, start, subject, kinds: [...kinds].sort() });
|
|
473
|
+
}
|
|
474
|
+
reportVariable(origin, at, symbol, kinds) {
|
|
475
|
+
this.report(origin, at, this.tracked.get(symbol)?.name ?? symbol.name, kinds);
|
|
476
|
+
}
|
|
477
|
+
/** Reports and forgets the variables living in `scope` (or, with `inside`, anywhere inside it) that can still fail. */
|
|
478
|
+
leaveScope(scope, state, at, inside = false, keep) {
|
|
479
|
+
if (!state) return null;
|
|
480
|
+
const left = new Map(state);
|
|
481
|
+
for (const [symbol, info] of this.tracked) {
|
|
482
|
+
const leaving = inside ? within(info.scope, scope) : info.scope === scope;
|
|
483
|
+
if (!leaving || keep?.(info)) continue;
|
|
484
|
+
const value = left.get(symbol);
|
|
485
|
+
if (value && value.kinds.size > 0) this.reportVariable("end", at, symbol, value.kinds);
|
|
486
|
+
left.delete(symbol);
|
|
487
|
+
}
|
|
488
|
+
return left;
|
|
489
|
+
}
|
|
490
|
+
// ---- types ----
|
|
491
|
+
kindsOf(node) {
|
|
492
|
+
return failureKinds(this.context, this.checker.getTypeAtLocation(node));
|
|
493
|
+
}
|
|
494
|
+
typeKinds(type) {
|
|
495
|
+
return type ? failureKinds(this.context, type) : null;
|
|
496
|
+
}
|
|
497
|
+
trackedSymbol(node, state) {
|
|
498
|
+
const inner = unparen(this.ts, node);
|
|
499
|
+
if (!this.ts.isIdentifier(inner)) return null;
|
|
500
|
+
const symbol = this.checker.getSymbolAtLocation(inner);
|
|
501
|
+
return symbol && state.has(symbol) ? symbol : null;
|
|
502
|
+
}
|
|
503
|
+
isDecideOrTranslate(call) {
|
|
504
|
+
if (!this.ts.isCallExpression(call)) return false;
|
|
505
|
+
const name = this.context.policy.trustFunctionName(call);
|
|
506
|
+
return name === "decide" || name === "translate";
|
|
507
|
+
}
|
|
508
|
+
/** The declared (not instantiated) type of the parameter that receives argument `index`. */
|
|
509
|
+
declaredParameterType(call, index) {
|
|
510
|
+
const ts = this.ts;
|
|
511
|
+
const declaration = this.checker.getResolvedSignature(call)?.getDeclaration();
|
|
512
|
+
if (!declaration || ts.isJSDocSignature(declaration)) return void 0;
|
|
513
|
+
const parameters = declaration.parameters;
|
|
514
|
+
const last = parameters[parameters.length - 1];
|
|
515
|
+
if (last?.dotDotDotToken && index >= parameters.length - 1) {
|
|
516
|
+
const restType = this.checker.getTypeAtLocation(last);
|
|
517
|
+
return this.checker.getIndexTypeOfType(restType, ts.IndexKind.Number);
|
|
518
|
+
}
|
|
519
|
+
const parameter = parameters[index];
|
|
520
|
+
return parameter ? this.checker.getTypeAtLocation(parameter) : void 0;
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* The type of the parameter that receives argument `index` at this call: type parameters filled in, so
|
|
524
|
+
* `resolve` of a `new Promise<Result<…>>`, `map.set(id, pending)` on a `Map<string, Promise<Result<…>>>` or
|
|
525
|
+
* `Result.ok(() => …)` take a Result here.
|
|
526
|
+
*/
|
|
527
|
+
instantiatedParameterType(call, index) {
|
|
528
|
+
const ts = this.ts;
|
|
529
|
+
const signature = this.checker.getResolvedSignature(call);
|
|
530
|
+
if (!signature) return void 0;
|
|
531
|
+
const parameters = signature.getParameters();
|
|
532
|
+
const last = parameters[parameters.length - 1];
|
|
533
|
+
const lastDeclaration = last?.valueDeclaration;
|
|
534
|
+
const isRest = lastDeclaration !== void 0 && ts.isParameter(lastDeclaration) && lastDeclaration.dotDotDotToken !== void 0;
|
|
535
|
+
if (isRest && index >= parameters.length - 1) {
|
|
536
|
+
return this.checker.getIndexTypeOfType(this.checker.getTypeOfSymbolAtLocation(last, call), ts.IndexKind.Number);
|
|
537
|
+
}
|
|
538
|
+
const parameter = parameters[index];
|
|
539
|
+
return parameter ? this.checker.getTypeOfSymbolAtLocation(parameter, call) : void 0;
|
|
540
|
+
}
|
|
541
|
+
/** A Result, or a function returning one. */
|
|
542
|
+
takesResult(type) {
|
|
543
|
+
if (!type) return false;
|
|
544
|
+
if (this.typeKinds(type)) return true;
|
|
545
|
+
return members(type).some((member) => member.getCallSignatures().some((signature) => this.typeKinds(signature.getReturnType()) !== null));
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* The callee takes the failure over: its parameter is a Result (or a function returning one), as declared or as
|
|
549
|
+
* this call fills in its type parameters. `console.log(…)` (`any`) and `String(…)` (`unknown`) take nothing.
|
|
550
|
+
*/
|
|
551
|
+
acceptsArgument(call, argument) {
|
|
552
|
+
const index = argumentsOf(call).indexOf(argument);
|
|
553
|
+
if (index < 0) return false;
|
|
554
|
+
return this.takesResult(this.declaredParameterType(call, index)) || this.takesResult(this.instantiatedParameterType(call, index));
|
|
555
|
+
}
|
|
556
|
+
/** `results.push(f())`: the receiver is itself a collection of Results, so the value is kept in it. */
|
|
557
|
+
receiverKeeps(call) {
|
|
558
|
+
const callee = this.ts.isCallExpression(call) ? unparen(this.ts, call.expression) : void 0;
|
|
559
|
+
return callee !== void 0 && this.ts.isPropertyAccessExpression(callee) && this.kindsOf(callee.expression) !== null;
|
|
560
|
+
}
|
|
561
|
+
// ---- flow of a value to the place its fate is decided ----
|
|
562
|
+
/** The expression `child`'s value flows into unchanged (wrappers, branches, collections, calls returning it), else null. */
|
|
563
|
+
flowsInto(child) {
|
|
564
|
+
const ts = this.ts;
|
|
565
|
+
const parent = child.parent;
|
|
566
|
+
if (!parent) return null;
|
|
567
|
+
if (ts.isParenthesizedExpression(parent) || ts.isAwaitExpression(parent) || ts.isAsExpression(parent) || ts.isNonNullExpression(parent) || ts.isSatisfiesExpression(parent) || ts.isTypeAssertionExpression(parent)) {
|
|
568
|
+
return parent;
|
|
569
|
+
}
|
|
570
|
+
if (ts.isConditionalExpression(parent)) return child === parent.condition ? null : parent;
|
|
571
|
+
if (ts.isBinaryExpression(parent)) {
|
|
572
|
+
const operator = parent.operatorToken.kind;
|
|
573
|
+
if (operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken) return parent;
|
|
574
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken || operator === ts.SyntaxKind.CommaToken) return child === parent.right ? parent : null;
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
if (ts.isArrayLiteralExpression(parent)) return parent;
|
|
578
|
+
if (ts.isSpreadElement(parent) && ts.isArrayLiteralExpression(parent.parent)) return parent;
|
|
579
|
+
if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && argumentsOf(parent).includes(child)) {
|
|
580
|
+
if (this.isDecideOrTranslate(parent)) return null;
|
|
581
|
+
return this.kindsOf(parent) !== null ? parent : null;
|
|
582
|
+
}
|
|
583
|
+
return null;
|
|
584
|
+
}
|
|
585
|
+
/**
|
|
586
|
+
* A value that can fail and is already held somewhere (a variable, a field, an element; awaited or not): one no
|
|
587
|
+
* call, `new` or `await` of a call makes here, whose failure is followed (or dropped) where it is held.
|
|
588
|
+
*/
|
|
589
|
+
isHeldFallible(node) {
|
|
590
|
+
const ts = this.ts;
|
|
591
|
+
let inner = unparen(ts, node);
|
|
592
|
+
while (ts.isAwaitExpression(inner) || ts.isAsExpression(inner) || ts.isNonNullExpression(inner) || ts.isSatisfiesExpression(inner) || ts.isTypeAssertionExpression(inner)) {
|
|
593
|
+
inner = unparen(ts, inner.expression);
|
|
594
|
+
}
|
|
595
|
+
if (!ts.isIdentifier(inner) && !ts.isPropertyAccessExpression(inner) && !ts.isElementAccessExpression(inner)) return false;
|
|
596
|
+
return this.kindsOf(node) !== null;
|
|
597
|
+
}
|
|
598
|
+
carrier(node) {
|
|
599
|
+
let current = node;
|
|
600
|
+
for (let next = this.flowsInto(current); next; next = this.flowsInto(current)) current = next;
|
|
601
|
+
return current;
|
|
602
|
+
}
|
|
603
|
+
/** What happens to the value of `carrier` (the top of its flow) where it ends up. */
|
|
604
|
+
fate(carrier) {
|
|
605
|
+
const ts = this.ts;
|
|
606
|
+
const parent = carrier.parent;
|
|
607
|
+
if (!parent) return "discarded";
|
|
608
|
+
if (ts.isExpressionStatement(parent) || ts.isVoidExpression(parent)) return "discarded";
|
|
609
|
+
if (ts.isVariableDeclaration(parent)) {
|
|
610
|
+
if (parent.initializer !== carrier) return "read";
|
|
611
|
+
return ts.isObjectBindingPattern(parent.name) ? "discarded" : "track";
|
|
612
|
+
}
|
|
613
|
+
if (ts.isExportAssignment(parent)) return "track";
|
|
614
|
+
if (ts.isReturnStatement(parent) || ts.isYieldExpression(parent)) return "return";
|
|
615
|
+
if (ts.isArrowFunction(parent) && parent.body === carrier) return "return";
|
|
616
|
+
if (ts.isBinaryExpression(parent) && isPlainOrLogicalAssignment(ts, parent.operatorToken.kind)) {
|
|
617
|
+
if (parent.right !== carrier) return "read";
|
|
618
|
+
const target = unparen(ts, parent.left);
|
|
619
|
+
if (ts.isIdentifier(target) || ts.isArrayLiteralExpression(target)) return "track";
|
|
620
|
+
return this.kindsOf(target) !== null ? "track" : "stored";
|
|
621
|
+
}
|
|
622
|
+
if (ts.isBinaryExpression(parent) && isEquality(ts, parent.operatorToken.kind)) {
|
|
623
|
+
const other = parent.left === carrier ? parent.right : parent.left;
|
|
624
|
+
if (this.isHeldFallible(other)) return "read";
|
|
625
|
+
}
|
|
626
|
+
if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && argumentsOf(parent).includes(carrier)) {
|
|
627
|
+
if (this.isDecideOrTranslate(parent)) return parent.arguments?.[0] === carrier ? "consume" : "argument";
|
|
628
|
+
if (this.acceptsArgument(parent, carrier) || this.receiverKeeps(parent)) return "consume";
|
|
629
|
+
return "argument";
|
|
630
|
+
}
|
|
631
|
+
if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === carrier) {
|
|
632
|
+
const call = parent.parent;
|
|
633
|
+
const predicate = ts.isPropertyAccessExpression(parent) && PREDICATE_METHODS.has(parent.name.text);
|
|
634
|
+
const handsOver = !predicate && ts.isCallExpression(call) && call.expression === parent && call.arguments.some((argument) => isOwner(ts, unparen(ts, argument)));
|
|
635
|
+
return handsOver ? "consume" : "discarded";
|
|
636
|
+
}
|
|
637
|
+
if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.expression === carrier) return "consume";
|
|
638
|
+
if (ts.isPropertyDeclaration(parent) && parent.initializer === carrier) return "track";
|
|
639
|
+
if (ts.isPropertyAssignment(parent) && parent.initializer === carrier && ts.isExpression(carrier)) {
|
|
640
|
+
if (this.typeKinds(this.checker.getContextualType(carrier)) !== null) return "track";
|
|
641
|
+
}
|
|
642
|
+
if (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isSpreadAssignment(parent) || ts.isSpreadElement(parent) || ts.isJsxExpression(parent) || ts.isParameter(parent)) {
|
|
643
|
+
return "stored";
|
|
644
|
+
}
|
|
645
|
+
return "discarded";
|
|
646
|
+
}
|
|
647
|
+
// ---- expressions ----
|
|
648
|
+
/** Visits the expressions under `node` (not into nested functions) in source order, deciding the fate of each value that can fail. */
|
|
649
|
+
visit(node, state) {
|
|
650
|
+
const ts = this.ts;
|
|
651
|
+
if (ts.isTypeNode(node)) return;
|
|
652
|
+
if (node !== this.owner && isOwner(ts, node)) {
|
|
653
|
+
this.handedFunction(node);
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
657
|
+
this.visit(node.right, state);
|
|
658
|
+
this.visit(node.left, state);
|
|
659
|
+
this.assign(node, state);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
ts.forEachChild(node, (child) => this.visit(child, state));
|
|
663
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isTaggedTemplateExpression(node)) this.temporary(node);
|
|
664
|
+
else if (ts.isIdentifier(node)) this.reference(node, state);
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* `results.filter(…)`, `[...map.values()].slice(1)`: a method that only hands back elements its receiver
|
|
668
|
+
* already holds. The failures belong to the receiver (followed, or not, where it lives); the derived
|
|
669
|
+
* collection is not a new one.
|
|
670
|
+
*/
|
|
671
|
+
derivedFromReceiver(node) {
|
|
672
|
+
const ts = this.ts;
|
|
673
|
+
if (!ts.isCallExpression(node)) return false;
|
|
674
|
+
const callee = unparen(ts, node.expression);
|
|
675
|
+
if (!ts.isPropertyAccessExpression(callee) || !ELEMENT_METHODS.has(callee.name.text)) return false;
|
|
676
|
+
return this.kindsOf(callee.expression) !== null;
|
|
677
|
+
}
|
|
678
|
+
/** A call's value: reported where it is dropped; followed when it is kept in a variable. */
|
|
679
|
+
temporary(node) {
|
|
680
|
+
if (!this.kindsOf(node) || this.derivedFromReceiver(node)) return;
|
|
681
|
+
const carrier = this.carrier(node);
|
|
682
|
+
const fate = this.fate(carrier);
|
|
683
|
+
if (fate !== "discarded" && fate !== "argument" && fate !== "stored") return;
|
|
684
|
+
if (fate !== "discarded" && this.returnedWithin(carrier)) return;
|
|
685
|
+
if (this.reported.has(carrier)) return;
|
|
686
|
+
this.reported.add(carrier);
|
|
687
|
+
this.report(fate, carrier, subjectOf(carrier, this.sourceFile), this.kindsOf(carrier) ?? this.kindsOf(node) ?? NOTHING);
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* `return this.reply('status', await svc.status())`, `return { result: f() }`: the value sits inside the
|
|
691
|
+
* returned value (an argument of a call, or a property, that is itself returned), so its failure goes out with
|
|
692
|
+
* it. A call that returns nothing (`return log(f())`) carries nothing.
|
|
693
|
+
*/
|
|
694
|
+
returnedWithin(node) {
|
|
695
|
+
const ts = this.ts;
|
|
696
|
+
let current = node;
|
|
697
|
+
for (let parent = current.parent; parent; current = parent, parent = parent.parent) {
|
|
698
|
+
if (ts.isReturnStatement(parent)) return true;
|
|
699
|
+
if (ts.isArrowFunction(parent)) return parent.body === current;
|
|
700
|
+
if (ts.isStatement(parent) || isOwner(ts, parent)) return false;
|
|
701
|
+
if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && argumentsOf(parent).includes(current)) {
|
|
702
|
+
const returned = this.checker.getTypeAtLocation(parent);
|
|
703
|
+
if (returned.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined)) return false;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return false;
|
|
707
|
+
}
|
|
708
|
+
/** A followed variable read: handed over (alias, return, decide, a Result parameter) or just read. */
|
|
709
|
+
reference(node, state) {
|
|
710
|
+
const symbol = this.trackedSymbol(node, state);
|
|
711
|
+
if (!symbol) return;
|
|
712
|
+
const fate = this.fate(this.carrier(node));
|
|
713
|
+
if (fate === "track" || fate === "consume" || fate === "return") state.set(symbol, { kinds: NOTHING, err: state.get(symbol)?.err ?? false });
|
|
714
|
+
}
|
|
715
|
+
/** A function written inline as an argument: its failure is dropped when the callee takes no Result back. */
|
|
716
|
+
handedFunction(node) {
|
|
717
|
+
const ts = this.ts;
|
|
718
|
+
if (!ts.isArrowFunction(node) && !ts.isFunctionExpression(node)) return;
|
|
719
|
+
const call = node.parent;
|
|
720
|
+
if (!(ts.isCallExpression(call) || ts.isNewExpression(call)) || !argumentsOf(call).includes(node)) return;
|
|
721
|
+
if (this.isDecideOrTranslate(call)) return;
|
|
722
|
+
const signature = this.checker.getSignatureFromDeclaration(node);
|
|
723
|
+
const kinds = signature ? this.typeKinds(this.checker.getReturnTypeOfSignature(signature)) : null;
|
|
724
|
+
if (!kinds || this.kindsOf(call) !== null || this.acceptsArgument(call, node)) return;
|
|
725
|
+
this.report("callback", node, subjectOf(call.expression, this.sourceFile), kinds);
|
|
726
|
+
}
|
|
727
|
+
assign(node, state) {
|
|
728
|
+
const ts = this.ts;
|
|
729
|
+
const target = unparen(ts, node.left);
|
|
730
|
+
const names = ts.isIdentifier(target) ? [target] : ts.isArrayLiteralExpression(target) ? target.elements.filter(ts.isIdentifier) : [];
|
|
731
|
+
for (const name of names) {
|
|
732
|
+
const symbol = this.checker.getSymbolAtLocation(name);
|
|
733
|
+
if (!symbol || !this.tracked.has(symbol)) continue;
|
|
734
|
+
const current = state.get(symbol);
|
|
735
|
+
if (current && current.kinds.size > 0) this.reportVariable("overwritten", node, symbol, current.kinds);
|
|
736
|
+
const kinds = ts.isIdentifier(target) ? this.kindsOf(node.right) : this.kindsOf(name);
|
|
737
|
+
state.set(symbol, { kinds: kinds ?? NOTHING, err: false });
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Starts following the variables `name` binds that can fail (a module-level variable is never followed). With an
|
|
742
|
+
* `initializer`, what can fail is what the initializer holds (`let scope: Result<…> | null = null` holds nothing yet).
|
|
743
|
+
*/
|
|
744
|
+
declare(name, scope, state, assigned, initializer) {
|
|
745
|
+
const ts = this.ts;
|
|
746
|
+
if (ts.isSourceFile(this.owner)) return;
|
|
747
|
+
if (ts.isIdentifier(name)) {
|
|
748
|
+
const symbol = this.checker.getSymbolAtLocation(name);
|
|
749
|
+
const kinds = symbol ? this.kindsOf(name) : null;
|
|
750
|
+
if (!symbol || !kinds) return;
|
|
751
|
+
this.tracked.set(symbol, { name: name.text, scope });
|
|
752
|
+
if (assigned) state.set(symbol, { kinds: initializer ? this.kindsOf(initializer) ?? NOTHING : kinds, err: false });
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
for (const element of name.elements) {
|
|
756
|
+
if (!ts.isOmittedExpression(element)) this.declare(element.name, scope, state, assigned);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
declarations(list, scope, state) {
|
|
760
|
+
const ts = this.ts;
|
|
761
|
+
const blockScoped = (list.flags & (ts.NodeFlags.Let | ts.NodeFlags.Const | ts.NodeFlags.Using | ts.NodeFlags.AwaitUsing)) !== 0;
|
|
762
|
+
for (const declaration of list.declarations) {
|
|
763
|
+
if (declaration.initializer) {
|
|
764
|
+
this.visit(declaration.initializer, state);
|
|
765
|
+
this.recordErrorAlias(declaration, state);
|
|
766
|
+
}
|
|
767
|
+
const initializer = ts.isIdentifier(declaration.name) ? declaration.initializer : void 0;
|
|
768
|
+
this.declare(declaration.name, blockScoped ? scope : this.functionScope, state, declaration.initializer !== void 0, initializer);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/**
|
|
772
|
+
* `const failure = r.error`: `failure.kind` names r's kinds. Any variable whose initializer takes a failure along
|
|
773
|
+
* (`const failed = { message: r.error.message }`) carries it: returning that variable carries r's failure out.
|
|
774
|
+
*/
|
|
775
|
+
recordErrorAlias(declaration, state) {
|
|
776
|
+
const ts = this.ts;
|
|
777
|
+
const initializer = declaration.initializer ? unparen(ts, declaration.initializer) : void 0;
|
|
778
|
+
if (!initializer || !ts.isIdentifier(declaration.name)) return;
|
|
779
|
+
const alias = this.checker.getSymbolAtLocation(declaration.name);
|
|
780
|
+
if (!alias) return;
|
|
781
|
+
if (ts.isPropertyAccessExpression(initializer) && initializer.name.text === "error") {
|
|
782
|
+
const owner = this.trackedSymbol(initializer.expression, state);
|
|
783
|
+
if (owner) this.errorAliases.set(alias, owner);
|
|
784
|
+
}
|
|
785
|
+
const owners = /* @__PURE__ */ new Set();
|
|
786
|
+
const collect = (node) => {
|
|
787
|
+
if (isOwner(ts, node)) return;
|
|
788
|
+
if (ts.isIdentifier(node) && this.carriesFailure(node)) {
|
|
789
|
+
const owner = this.trackedSymbol(node, state);
|
|
790
|
+
if (owner) owners.add(owner);
|
|
791
|
+
const viaAlias = this.checker.getSymbolAtLocation(node);
|
|
792
|
+
for (const carried of viaAlias && this.failureCarriers.get(viaAlias) || []) owners.add(carried);
|
|
793
|
+
}
|
|
794
|
+
ts.forEachChild(node, collect);
|
|
795
|
+
};
|
|
796
|
+
collect(initializer);
|
|
797
|
+
if (owners.size > 0) this.failureCarriers.set(alias, owners);
|
|
798
|
+
}
|
|
799
|
+
// ---- narrowing ----
|
|
800
|
+
/** `r.ok` on a followed variable. */
|
|
801
|
+
okCheck(node, state) {
|
|
802
|
+
const inner = unparen(this.ts, node);
|
|
803
|
+
if (!this.ts.isPropertyAccessExpression(inner) || inner.name.text !== "ok") return null;
|
|
804
|
+
return this.trackedSymbol(inner.expression, state);
|
|
805
|
+
}
|
|
806
|
+
/** `r.error.kind` on a followed variable, or `failure.kind` on an alias of its `error`. */
|
|
807
|
+
kindCheck(node, state) {
|
|
808
|
+
const ts = this.ts;
|
|
809
|
+
const inner = unparen(ts, node);
|
|
810
|
+
if (!ts.isPropertyAccessExpression(inner) || inner.name.text !== "kind") return null;
|
|
811
|
+
const error = unparen(ts, inner.expression);
|
|
812
|
+
if (ts.isIdentifier(error)) {
|
|
813
|
+
const alias = this.checker.getSymbolAtLocation(error);
|
|
814
|
+
const owner = alias ? this.errorAliases.get(alias) : void 0;
|
|
815
|
+
return owner && state.has(owner) ? owner : null;
|
|
816
|
+
}
|
|
817
|
+
if (!ts.isPropertyAccessExpression(error) || error.name.text !== "error") return null;
|
|
818
|
+
return this.trackedSymbol(error.expression, state);
|
|
819
|
+
}
|
|
820
|
+
withOk(state, symbol, isOk) {
|
|
821
|
+
const narrowed = new Map(state);
|
|
822
|
+
const current = state.get(symbol);
|
|
823
|
+
if (current) narrowed.set(symbol, isOk ? { kinds: NOTHING, err: false } : { kinds: current.kinds, err: true });
|
|
824
|
+
return narrowed;
|
|
825
|
+
}
|
|
826
|
+
/** A branch that names `kind` handles it; the other branch keeps the kinds that are not `kind`. */
|
|
827
|
+
withKind(state, symbol, kind, isKind) {
|
|
828
|
+
const narrowed = new Map(state);
|
|
829
|
+
const current = state.get(symbol);
|
|
830
|
+
if (current) {
|
|
831
|
+
const rest = new Set(current.kinds);
|
|
832
|
+
rest.delete(kind);
|
|
833
|
+
narrowed.set(symbol, isKind ? { kinds: NOTHING, err: true } : { kinds: rest, err: true });
|
|
834
|
+
}
|
|
835
|
+
return narrowed;
|
|
836
|
+
}
|
|
837
|
+
/** The state a branch starts with: narrowed by its condition, and its own copy (a branch's declarations stay in it). */
|
|
838
|
+
branch(condition, state, outcome) {
|
|
839
|
+
return new Map(this.narrow(condition, state, outcome));
|
|
840
|
+
}
|
|
841
|
+
narrow(condition, state, outcome) {
|
|
842
|
+
const ts = this.ts;
|
|
843
|
+
const node = unparen(ts, condition);
|
|
844
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) return this.narrow(node.operand, state, !outcome);
|
|
845
|
+
if (ts.isBinaryExpression(node)) {
|
|
846
|
+
const operator = node.operatorToken.kind;
|
|
847
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken) {
|
|
848
|
+
const left = this.narrow(node.left, state, true);
|
|
849
|
+
if (outcome) return this.narrow(node.right, left, true);
|
|
850
|
+
return merge(this.narrow(node.left, state, false), this.narrow(node.right, left, false)) ?? state;
|
|
851
|
+
}
|
|
852
|
+
if (operator === ts.SyntaxKind.BarBarToken) {
|
|
853
|
+
const left = this.narrow(node.left, state, false);
|
|
854
|
+
if (!outcome) return this.narrow(node.right, left, false);
|
|
855
|
+
return merge(this.narrow(node.left, state, true), this.narrow(node.right, left, true)) ?? state;
|
|
856
|
+
}
|
|
857
|
+
if (operator === ts.SyntaxKind.InKeyword && stringLiteral(ts, node.left) !== void 0) {
|
|
858
|
+
const shape = this.trackedSymbol(node.right, state);
|
|
859
|
+
const key = stringLiteral(ts, node.left);
|
|
860
|
+
if (shape && (key === "ok" || key === "error" || key === "value")) {
|
|
861
|
+
if (key === "ok") return outcome ? state : this.withNothing(state, shape);
|
|
862
|
+
return key === "error" ? this.withOk(state, shape, !outcome) : this.withOk(state, shape, outcome);
|
|
863
|
+
}
|
|
864
|
+
return state;
|
|
865
|
+
}
|
|
866
|
+
const equal = operator === ts.SyntaxKind.EqualsEqualsEqualsToken || operator === ts.SyntaxKind.EqualsEqualsToken;
|
|
867
|
+
const unequal = operator === ts.SyntaxKind.ExclamationEqualsEqualsToken || operator === ts.SyntaxKind.ExclamationEqualsToken;
|
|
868
|
+
if (equal || unequal) {
|
|
869
|
+
const holds = equal ? outcome : !outcome;
|
|
870
|
+
for (const [side, other] of [
|
|
871
|
+
[node.left, node.right],
|
|
872
|
+
[node.right, node.left]
|
|
873
|
+
]) {
|
|
874
|
+
const ok2 = this.okCheck(side, state);
|
|
875
|
+
const value = booleanLiteral(ts, other);
|
|
876
|
+
if (ok2 && value !== void 0) return this.withOk(state, ok2, value === holds);
|
|
877
|
+
const kindOf = this.kindCheck(side, state);
|
|
878
|
+
const kind = stringLiteral(ts, other);
|
|
879
|
+
if (kindOf && kind !== void 0) return this.withKind(state, kindOf, kind, holds);
|
|
880
|
+
const nullable = this.trackedSymbol(side, state);
|
|
881
|
+
if (nullable && isNullish(ts, other)) return holds ? this.withNothing(state, nullable) : state;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
return state;
|
|
885
|
+
}
|
|
886
|
+
const ok = this.okCheck(node, state);
|
|
887
|
+
if (ok) return this.withOk(state, ok, outcome);
|
|
888
|
+
const truthy = this.trackedSymbol(node, state);
|
|
889
|
+
return truthy && !outcome ? this.withNothing(state, truthy) : state;
|
|
890
|
+
}
|
|
891
|
+
withNothing(state, symbol) {
|
|
892
|
+
const narrowed = new Map(state);
|
|
893
|
+
if (narrowed.has(symbol)) narrowed.set(symbol, { kinds: NOTHING, err: false });
|
|
894
|
+
return narrowed;
|
|
895
|
+
}
|
|
896
|
+
// ---- statements ----
|
|
897
|
+
block(block, state) {
|
|
898
|
+
const out = this.statements(block.statements, state, block);
|
|
899
|
+
return this.leaveScope(block, out, block.end - 1);
|
|
900
|
+
}
|
|
901
|
+
statements(list, state, scope) {
|
|
902
|
+
let current = state;
|
|
903
|
+
for (const statement of list) {
|
|
904
|
+
if (!current) break;
|
|
905
|
+
current = this.statement(statement, current, scope);
|
|
906
|
+
}
|
|
907
|
+
return current;
|
|
908
|
+
}
|
|
909
|
+
statement(node, state, scope, label) {
|
|
910
|
+
const ts = this.ts;
|
|
911
|
+
if (ts.isBlock(node)) return this.block(node, state);
|
|
912
|
+
if (ts.isVariableStatement(node)) {
|
|
913
|
+
this.declarations(node.declarationList, scope, state);
|
|
914
|
+
return state;
|
|
915
|
+
}
|
|
916
|
+
if (ts.isExpressionStatement(node)) {
|
|
917
|
+
this.visit(node.expression, state);
|
|
918
|
+
return state;
|
|
919
|
+
}
|
|
920
|
+
if (ts.isIfStatement(node)) {
|
|
921
|
+
this.visit(node.expression, state);
|
|
922
|
+
const whenTrue = this.statement(node.thenStatement, this.branch(node.expression, state, true), scope);
|
|
923
|
+
const otherwise = this.branch(node.expression, state, false);
|
|
924
|
+
const whenFalse = node.elseStatement ? this.statement(node.elseStatement, otherwise, scope) : otherwise;
|
|
925
|
+
return merge(whenTrue, whenFalse);
|
|
926
|
+
}
|
|
927
|
+
if (ts.isReturnStatement(node)) {
|
|
928
|
+
if (node.expression) this.visit(node.expression, state);
|
|
929
|
+
this.checkReturn(node, node.expression, state);
|
|
930
|
+
return null;
|
|
931
|
+
}
|
|
932
|
+
if (ts.isThrowStatement(node)) {
|
|
933
|
+
this.visit(node.expression, state);
|
|
934
|
+
return null;
|
|
935
|
+
}
|
|
936
|
+
if (ts.isBreakStatement(node) || ts.isContinueStatement(node)) return this.jump(node, state);
|
|
937
|
+
if (ts.isSwitchStatement(node)) return this.switchStatement(node, state, label);
|
|
938
|
+
if (ts.isTryStatement(node)) return this.tryStatement(node, state);
|
|
939
|
+
if (ts.isLabeledStatement(node)) return this.labeled(node, state, scope);
|
|
940
|
+
if (ts.isForStatement(node) || ts.isForOfStatement(node) || ts.isForInStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node)) {
|
|
941
|
+
return this.loop(node, state, label);
|
|
942
|
+
}
|
|
943
|
+
this.visit(node, state);
|
|
944
|
+
return state;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Every variable that can still fail is dropped unless the return passes it up or carries it out:
|
|
948
|
+
* - the returned value can fail and names the variable (`return r`, `return r.ok ? x : r`);
|
|
949
|
+
* - the returned value carries the failure itself, whatever its type (`return this.failed(r.error)`,
|
|
950
|
+
* `return reply(r)`): the error goes out with the response (`r.ok` / `r.value` alone do not carry it);
|
|
951
|
+
* - the return passes a failure up on a path where a followed value is known to be an `Err`
|
|
952
|
+
* (`if (!a.ok) return a;` also covers a `b` not checked yet: the first failure goes up).
|
|
953
|
+
*/
|
|
954
|
+
checkReturn(at, expression, state) {
|
|
955
|
+
const ts = this.ts;
|
|
956
|
+
const passes = expression !== void 0 && this.kindsOf(expression) !== null;
|
|
957
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
958
|
+
const carried = /* @__PURE__ */ new Set();
|
|
959
|
+
const collect = (node) => {
|
|
960
|
+
if (isOwner(ts, node)) return;
|
|
961
|
+
if (ts.isIdentifier(node)) {
|
|
962
|
+
const symbol = this.checker.getSymbolAtLocation(node);
|
|
963
|
+
if (symbol) {
|
|
964
|
+
referenced.add(symbol);
|
|
965
|
+
if (this.carriesFailure(node)) carried.add(symbol);
|
|
966
|
+
const owner = this.errorAliases.get(symbol);
|
|
967
|
+
if (owner) carried.add(owner);
|
|
968
|
+
for (const carrier of this.failureCarriers.get(symbol) ?? []) carried.add(carrier);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
ts.forEachChild(node, collect);
|
|
972
|
+
};
|
|
973
|
+
if (expression) collect(expression);
|
|
974
|
+
const returnsErr = passes && expression !== void 0 && this.isErrOnly(expression);
|
|
975
|
+
const failing = returnsErr || [...state].some(([symbol, value]) => value.err && (passes || carried.has(symbol)));
|
|
976
|
+
for (const [symbol, value] of state) {
|
|
977
|
+
if (value.kinds.size === 0) continue;
|
|
978
|
+
if (passes && referenced.has(symbol) || carried.has(symbol) || failing) continue;
|
|
979
|
+
this.reportVariable("return", at, symbol, value.kinds);
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
/** The expression's type (awaited) is only `Err` members: TypeScript has narrowed it to a failure. */
|
|
983
|
+
isErrOnly(expression) {
|
|
984
|
+
const type = this.checker.getTypeAtLocation(expression);
|
|
985
|
+
return this.context.policy.isErrType(this.checker.getAwaitedType(type) ?? type);
|
|
986
|
+
}
|
|
987
|
+
/** A read of a variable that takes its failure along: the variable itself, or its `error` (not `.ok` / `.value`). */
|
|
988
|
+
carriesFailure(node) {
|
|
989
|
+
const ts = this.ts;
|
|
990
|
+
let current = node;
|
|
991
|
+
while (ts.isParenthesizedExpression(current.parent) || ts.isNonNullExpression(current.parent) || ts.isAsExpression(current.parent)) current = current.parent;
|
|
992
|
+
const parent = current.parent;
|
|
993
|
+
if (ts.isPropertyAccessExpression(parent) && parent.expression === current) return parent.name.text === "error";
|
|
994
|
+
if (ts.isElementAccessExpression(parent) && parent.expression === current) return false;
|
|
995
|
+
return true;
|
|
996
|
+
}
|
|
997
|
+
jump(node, state) {
|
|
998
|
+
const ts = this.ts;
|
|
999
|
+
const label = node.label?.text;
|
|
1000
|
+
const isBreak = ts.isBreakStatement(node);
|
|
1001
|
+
let target;
|
|
1002
|
+
for (let index = this.targets.length - 1; index >= 0 && !target; index -= 1) {
|
|
1003
|
+
const candidate = this.targets[index];
|
|
1004
|
+
if (label !== void 0 ? candidate.label === label : isBreak ? candidate.kind !== "labeled" : candidate.kind === "loop") target = candidate;
|
|
1005
|
+
}
|
|
1006
|
+
if (!target) return null;
|
|
1007
|
+
const to = target;
|
|
1008
|
+
const keeps = (info) => !isBreak && ts.isForStatement(to.node) && info.scope === to.node;
|
|
1009
|
+
const left = this.leaveScope(to.node, state, node, true, keeps) ?? state;
|
|
1010
|
+
(isBreak ? to.breaks : to.continues).push(left);
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
labeled(node, state, scope) {
|
|
1014
|
+
const ts = this.ts;
|
|
1015
|
+
const inner = node.statement;
|
|
1016
|
+
const isLoop = ts.isForStatement(inner) || ts.isForOfStatement(inner) || ts.isForInStatement(inner) || ts.isWhileStatement(inner) || ts.isDoStatement(inner);
|
|
1017
|
+
if (isLoop || ts.isSwitchStatement(inner)) return this.statement(inner, state, scope, node.label.text);
|
|
1018
|
+
const target = { node, label: node.label.text, kind: "labeled", breaks: [], continues: [] };
|
|
1019
|
+
this.targets.push(target);
|
|
1020
|
+
const out = this.statement(inner, state, scope);
|
|
1021
|
+
this.targets.pop();
|
|
1022
|
+
return mergeAll([out, ...target.breaks]);
|
|
1023
|
+
}
|
|
1024
|
+
switchStatement(node, state, label) {
|
|
1025
|
+
const ts = this.ts;
|
|
1026
|
+
this.visit(node.expression, state);
|
|
1027
|
+
const kindOf = this.kindCheck(node.expression, state);
|
|
1028
|
+
const labels = node.caseBlock.clauses.flatMap((clause) => {
|
|
1029
|
+
const kind = ts.isCaseClause(clause) ? stringLiteral(ts, clause.expression) : void 0;
|
|
1030
|
+
return kind === void 0 ? [] : [kind];
|
|
1031
|
+
});
|
|
1032
|
+
const rest = () => {
|
|
1033
|
+
if (!kindOf) return new Map(state);
|
|
1034
|
+
let narrowed = state;
|
|
1035
|
+
for (const kind of labels) narrowed = this.withKind(narrowed, kindOf, kind, false);
|
|
1036
|
+
return narrowed;
|
|
1037
|
+
};
|
|
1038
|
+
const target = { node, label, kind: "switch", breaks: [], continues: [] };
|
|
1039
|
+
this.targets.push(target);
|
|
1040
|
+
let fallthrough = null;
|
|
1041
|
+
let hasDefault = false;
|
|
1042
|
+
for (const clause of node.caseBlock.clauses) {
|
|
1043
|
+
let entry;
|
|
1044
|
+
if (ts.isCaseClause(clause)) {
|
|
1045
|
+
this.visit(clause.expression, state);
|
|
1046
|
+
const kind = stringLiteral(ts, clause.expression);
|
|
1047
|
+
entry = kindOf && kind !== void 0 ? this.withKind(state, kindOf, kind, true) : new Map(state);
|
|
1048
|
+
} else {
|
|
1049
|
+
hasDefault = true;
|
|
1050
|
+
entry = rest();
|
|
1051
|
+
}
|
|
1052
|
+
fallthrough = this.statements(clause.statements, merge(entry, fallthrough) ?? entry, node.caseBlock);
|
|
1053
|
+
}
|
|
1054
|
+
this.targets.pop();
|
|
1055
|
+
const out = mergeAll([fallthrough, ...target.breaks, hasDefault ? null : rest()]);
|
|
1056
|
+
return this.leaveScope(node.caseBlock, out, node.end - 1);
|
|
1057
|
+
}
|
|
1058
|
+
loop(node, state, label) {
|
|
1059
|
+
const ts = this.ts;
|
|
1060
|
+
let entry = new Map(state);
|
|
1061
|
+
let skip = entry;
|
|
1062
|
+
if (ts.isForStatement(node)) {
|
|
1063
|
+
if (node.initializer && ts.isVariableDeclarationList(node.initializer)) this.declarations(node.initializer, node, entry);
|
|
1064
|
+
else if (node.initializer) this.visit(node.initializer, entry);
|
|
1065
|
+
if (node.condition) {
|
|
1066
|
+
this.visit(node.condition, entry);
|
|
1067
|
+
skip = this.branch(node.condition, entry, false);
|
|
1068
|
+
entry = this.branch(node.condition, entry, true);
|
|
1069
|
+
} else {
|
|
1070
|
+
skip = null;
|
|
1071
|
+
}
|
|
1072
|
+
} else if (ts.isForOfStatement(node) || ts.isForInStatement(node)) {
|
|
1073
|
+
this.visit(node.expression, entry);
|
|
1074
|
+
skip = new Map(entry);
|
|
1075
|
+
if (ts.isVariableDeclarationList(node.initializer)) {
|
|
1076
|
+
for (const declaration of node.initializer.declarations) this.declare(declaration.name, node, entry, true);
|
|
1077
|
+
} else {
|
|
1078
|
+
this.visit(node.initializer, entry);
|
|
1079
|
+
}
|
|
1080
|
+
} else if (ts.isWhileStatement(node)) {
|
|
1081
|
+
this.visit(node.expression, entry);
|
|
1082
|
+
skip = this.branch(node.expression, entry, false);
|
|
1083
|
+
entry = this.branch(node.expression, entry, true);
|
|
1084
|
+
} else {
|
|
1085
|
+
skip = null;
|
|
1086
|
+
}
|
|
1087
|
+
const target = { node, label, kind: "loop", breaks: [], continues: [] };
|
|
1088
|
+
this.targets.push(target);
|
|
1089
|
+
let out = this.statement(node.statement, entry, node);
|
|
1090
|
+
this.targets.pop();
|
|
1091
|
+
const repeat = mergeAll([out, ...target.continues]);
|
|
1092
|
+
if (ts.isForStatement(node) && node.incrementor && repeat) this.visit(node.incrementor, repeat);
|
|
1093
|
+
if (ts.isDoStatement(node) && repeat) this.visit(node.expression, repeat);
|
|
1094
|
+
if (ts.isForOfStatement(node) || ts.isForInStatement(node)) out = this.leaveScope(node, out, node.statement.end - 1);
|
|
1095
|
+
const exit = mergeAll([skip, out, ...target.continues, ...target.breaks]);
|
|
1096
|
+
return ts.isForStatement(node) ? this.leaveScope(node, exit, node.end - 1) : exit;
|
|
1097
|
+
}
|
|
1098
|
+
tryStatement(node, state) {
|
|
1099
|
+
const tried = this.block(node.tryBlock, new Map(state));
|
|
1100
|
+
let caught = null;
|
|
1101
|
+
if (node.catchClause) caught = this.block(node.catchClause.block, new Map(state));
|
|
1102
|
+
const out = node.catchClause ? merge(tried, caught) : tried;
|
|
1103
|
+
if (!node.finallyBlock) return out;
|
|
1104
|
+
const finished = this.block(node.finallyBlock, out ?? new Map(state));
|
|
1105
|
+
return out ? finished : null;
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
function droppedResultsIn(sourceFile, context) {
|
|
1109
|
+
const ts = context.ts;
|
|
1110
|
+
const found = [];
|
|
1111
|
+
new DropWalk(context, sourceFile, found).run();
|
|
1112
|
+
const visit = (node) => {
|
|
1113
|
+
if (isOwner(ts, node)) new DropWalk(context, node, found).run();
|
|
1114
|
+
ts.forEachChild(node, visit);
|
|
1115
|
+
};
|
|
1116
|
+
ts.forEachChild(sourceFile, visit);
|
|
1117
|
+
return found.sort((a, b) => a.start - b.start);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
// src/core/rules.ts
|
|
1121
|
+
var PROMISE_COMBINATORS = /* @__PURE__ */ new Set(["all", "allSettled", "race", "any"]);
|
|
1122
|
+
function typedGuardContext(ts, checker, policy) {
|
|
1123
|
+
return {
|
|
1124
|
+
ts,
|
|
1125
|
+
isResultErr: (expression) => policy.isErrType(checker.getTypeAtLocation(expression)),
|
|
1126
|
+
isErrCall: (call) => policy.trustFunctionName(call) === "err",
|
|
1127
|
+
trustTryKind: (call) => {
|
|
1128
|
+
const name = policy.trustFunctionName(call);
|
|
1129
|
+
if (name === "tryResult") return "sync";
|
|
1130
|
+
if (name === "tryResultAsync") return "async";
|
|
1131
|
+
return null;
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
function isIdentifierNamed(ts, node, name) {
|
|
1136
|
+
return ts.isIdentifier(node) && node.text === name;
|
|
1137
|
+
}
|
|
1138
|
+
function isNamedErrCall(ts, node) {
|
|
1139
|
+
const call = asPlainCall(ts, node);
|
|
1140
|
+
if (!call) return false;
|
|
1141
|
+
const callee = unparen(ts, call.expression);
|
|
1142
|
+
if (ts.isIdentifier(callee)) return callee.text === "err";
|
|
1143
|
+
if (!ts.isPropertyAccessExpression(callee)) return false;
|
|
1144
|
+
return isIdentifierNamed(ts, unparen(ts, callee.expression), "Result") && isIdentifierNamed(ts, callee.name, "err");
|
|
1145
|
+
}
|
|
1146
|
+
function namedTryKind(ts, call) {
|
|
1147
|
+
const callee = unparen(ts, call.expression);
|
|
1148
|
+
if (ts.isIdentifier(callee)) {
|
|
1149
|
+
if (callee.text === "tryResult") return "sync";
|
|
1150
|
+
if (callee.text === "tryResultAsync") return "async";
|
|
1151
|
+
return null;
|
|
1152
|
+
}
|
|
1153
|
+
if (!ts.isPropertyAccessExpression(callee)) return null;
|
|
1154
|
+
const object = unparen(ts, callee.expression);
|
|
1155
|
+
if (!ts.isIdentifier(object) || object.text !== "Trust" && object.text !== "Result" || !ts.isIdentifier(callee.name)) return null;
|
|
1156
|
+
if (callee.name.text === "try") return "sync";
|
|
1157
|
+
if (callee.name.text === "tryAsync") return "async";
|
|
1158
|
+
return null;
|
|
1159
|
+
}
|
|
1160
|
+
function nameBasedGuardContext(ts) {
|
|
1161
|
+
return {
|
|
1162
|
+
ts,
|
|
1163
|
+
isResultErr: (expression) => isNamedErrCall(ts, expression),
|
|
1164
|
+
isErrCall: (call) => isNamedErrCall(ts, call),
|
|
1165
|
+
trustTryKind: (call) => namedTryKind(ts, call)
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
function throwProblem(node, context) {
|
|
1169
|
+
const guard = guardOf(node, context);
|
|
1170
|
+
if (guard.status === "unguarded") return "escapes";
|
|
1171
|
+
if (guard.status === "badCatch") return guard.problem;
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
function chainTop(ts, node) {
|
|
1175
|
+
let current = node;
|
|
1176
|
+
for (; ; ) {
|
|
1177
|
+
const member = esParent(ts, current);
|
|
1178
|
+
const call = member && esParent(ts, member);
|
|
1179
|
+
const isMember = member && (ts.isPropertyAccessExpression(member) || ts.isElementAccessExpression(member));
|
|
1180
|
+
if (isMember && unparen(ts, member.expression) === current && call && ts.isCallExpression(call) && unparen(ts, call.expression) === member) {
|
|
1181
|
+
current = call;
|
|
1182
|
+
} else {
|
|
1183
|
+
return current;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
function isPromiseCombinator(ts, call) {
|
|
1188
|
+
if (!call || !ts.isCallExpression(call)) return false;
|
|
1189
|
+
const callee = unparen(ts, call.expression);
|
|
1190
|
+
if (!ts.isPropertyAccessExpression(callee)) return false;
|
|
1191
|
+
return isIdentifierNamed(ts, unparen(ts, callee.expression), "Promise") && ts.isIdentifier(callee.name) && PROMISE_COMBINATORS.has(callee.name.text);
|
|
1192
|
+
}
|
|
1193
|
+
function isConsumed(ts, expression, guard) {
|
|
1194
|
+
const top = chainTop(ts, expression);
|
|
1195
|
+
if (inOptionalChain(ts, top)) return false;
|
|
1196
|
+
const parent = esParent(ts, top);
|
|
1197
|
+
if (!parent) return false;
|
|
1198
|
+
if (ts.isAwaitExpression(parent)) return true;
|
|
1199
|
+
if (ts.isArrayLiteralExpression(parent)) {
|
|
1200
|
+
const combinator = esParent(ts, parent);
|
|
1201
|
+
return isPromiseCombinator(ts, combinator) && isConsumed(ts, combinator, guard);
|
|
1202
|
+
}
|
|
1203
|
+
if (guard.status === "guarded" && guard.via === "async-callback") {
|
|
1204
|
+
if (ts.isReturnStatement(parent)) return true;
|
|
1205
|
+
if (ts.isArrowFunction(parent) && unparen(ts, parent.body) === top) return true;
|
|
1206
|
+
}
|
|
1207
|
+
return false;
|
|
1208
|
+
}
|
|
1209
|
+
function untrustedCallProblem(node, policy, checker, context) {
|
|
1210
|
+
const ts = context.ts;
|
|
1211
|
+
const verdict = policy.classify(node);
|
|
1212
|
+
if (verdict.kind === "calls-ignored") return { messageId: "callsIgnored", origin: verdict.origin.origin };
|
|
1213
|
+
if (verdict.kind !== "untrusted") return null;
|
|
1214
|
+
const origin = verdict.origin.origin;
|
|
1215
|
+
const guard = guardOf(node, context);
|
|
1216
|
+
if (guard.status === "unguarded") return { messageId: "unguarded", origin };
|
|
1217
|
+
if (guard.status === "badCatch") return { messageId: guard.problem, origin };
|
|
1218
|
+
if (checker.getTypeAtLocation(node).getProperty("then") && !isConsumed(ts, node, guard)) return { messageId: "notAwaited", origin };
|
|
1219
|
+
return null;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// src/core/promise-rules.ts
|
|
1223
|
+
function unionParts(type) {
|
|
1224
|
+
return type.isUnion() ? type.types : [type];
|
|
1225
|
+
}
|
|
1226
|
+
function hasCallableThen(checker, type, node) {
|
|
1227
|
+
const then = checker.getApparentType(type).getProperty("then");
|
|
1228
|
+
if (!then) return false;
|
|
1229
|
+
return checker.getTypeOfSymbolAtLocation(then, node).getCallSignatures().length > 0;
|
|
1230
|
+
}
|
|
1231
|
+
function isSometimesThenable(checker, type, node) {
|
|
1232
|
+
return unionParts(type).some((part) => hasCallableThen(checker, part, node));
|
|
1233
|
+
}
|
|
1234
|
+
function isAlwaysThenable(checker, type, node) {
|
|
1235
|
+
return unionParts(type).every((part) => hasCallableThen(checker, part, node));
|
|
1236
|
+
}
|
|
1237
|
+
function isAssignment(ts, node) {
|
|
1238
|
+
return ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment;
|
|
1239
|
+
}
|
|
1240
|
+
function isHandledChain(ts, node) {
|
|
1241
|
+
if (!ts.isCallExpression(node)) return false;
|
|
1242
|
+
const callee = unparen(ts, node.expression);
|
|
1243
|
+
if (!ts.isPropertyAccessExpression(callee) || !ts.isIdentifier(callee.name)) return false;
|
|
1244
|
+
if (callee.name.text === "finally") return isHandledChain(ts, unparen(ts, callee.expression));
|
|
1245
|
+
if (callee.name.text === "catch") return true;
|
|
1246
|
+
return callee.name.text === "then" && node.arguments.length >= 2;
|
|
1247
|
+
}
|
|
1248
|
+
function isFloatingPromise(ts, checker, statement) {
|
|
1249
|
+
const expression = unparen(ts, statement.expression);
|
|
1250
|
+
if (ts.isAwaitExpression(expression) || ts.isVoidExpression(expression) || ts.isYieldExpression(expression) || isAssignment(ts, expression) || isHandledChain(ts, expression)) {
|
|
1251
|
+
return false;
|
|
1252
|
+
}
|
|
1253
|
+
return isSometimesThenable(checker, checker.getTypeAtLocation(expression), expression);
|
|
1254
|
+
}
|
|
1255
|
+
function isLogical(ts, node) {
|
|
1256
|
+
if (!ts.isBinaryExpression(node)) return false;
|
|
1257
|
+
const kind = node.operatorToken.kind;
|
|
1258
|
+
return kind === ts.SyntaxKind.AmpersandAmpersandToken || kind === ts.SyntaxKind.BarBarToken || kind === ts.SyntaxKind.QuestionQuestionToken;
|
|
1259
|
+
}
|
|
1260
|
+
function isConditionPosition(ts, node) {
|
|
1261
|
+
const parent = esParent(ts, node);
|
|
1262
|
+
if (!parent) return false;
|
|
1263
|
+
const self = (candidate) => candidate !== void 0 && unparen(ts, candidate) === node;
|
|
1264
|
+
if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) return self(parent.expression);
|
|
1265
|
+
if (ts.isForStatement(parent)) return self(parent.condition);
|
|
1266
|
+
if (ts.isConditionalExpression(parent)) return self(parent.condition);
|
|
1267
|
+
if (ts.isPrefixUnaryExpression(parent)) return parent.operator === ts.SyntaxKind.ExclamationToken;
|
|
1268
|
+
if (isLogical(ts, parent)) return self(parent.left) || isConditionPosition(ts, parent);
|
|
1269
|
+
return false;
|
|
1270
|
+
}
|
|
1271
|
+
function conditionOperands(ts, node) {
|
|
1272
|
+
let operands = [];
|
|
1273
|
+
if (ts.isIfStatement(node) || ts.isWhileStatement(node) || ts.isDoStatement(node)) operands = [node.expression];
|
|
1274
|
+
else if (ts.isForStatement(node)) operands = [node.condition];
|
|
1275
|
+
else if (ts.isConditionalExpression(node)) operands = [node.condition];
|
|
1276
|
+
else if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) operands = [node.operand];
|
|
1277
|
+
else if (isLogical(ts, node)) operands = isConditionPosition(ts, node) ? [node.left, node.right] : [node.left];
|
|
1278
|
+
return operands.filter((operand) => operand !== void 0 && !isLogical(ts, unparen(ts, operand)));
|
|
1279
|
+
}
|
|
1280
|
+
function isPromiseCondition(checker, operand) {
|
|
1281
|
+
return isAlwaysThenable(checker, checker.getTypeAtLocation(operand), operand);
|
|
1282
|
+
}
|
|
1283
|
+
function returnsThenable(checker, type, node) {
|
|
1284
|
+
return unionParts(type).some(
|
|
1285
|
+
(part) => part.getCallSignatures().some((signature) => isSometimesThenable(checker, signature.getReturnType(), node))
|
|
1286
|
+
);
|
|
1287
|
+
}
|
|
1288
|
+
function returnsVoid(ts, type) {
|
|
1289
|
+
return unionParts(type).some(
|
|
1290
|
+
(part) => part.getCallSignatures().some((signature) => (signature.getReturnType().flags & ts.TypeFlags.Void) !== 0)
|
|
1291
|
+
);
|
|
1292
|
+
}
|
|
1293
|
+
function parameterType(ts, checker, signature, index, node) {
|
|
1294
|
+
const parameters = signature.getParameters();
|
|
1295
|
+
const last = parameters[parameters.length - 1];
|
|
1296
|
+
const lastDeclaration = last?.valueDeclaration;
|
|
1297
|
+
const isRest = lastDeclaration !== void 0 && ts.isParameter(lastDeclaration) && lastDeclaration.dotDotDotToken !== void 0;
|
|
1298
|
+
if (isRest && index >= parameters.length - 1) {
|
|
1299
|
+
const restType = checker.getTypeOfSymbolAtLocation(last, node);
|
|
1300
|
+
return checker.getIndexTypeOfType(restType, ts.IndexKind.Number);
|
|
1301
|
+
}
|
|
1302
|
+
const parameter = parameters[index];
|
|
1303
|
+
return parameter ? checker.getTypeOfSymbolAtLocation(parameter, node) : void 0;
|
|
1304
|
+
}
|
|
1305
|
+
function asyncVoidCallbacks(ts, checker, call) {
|
|
1306
|
+
const args = call.arguments ?? [];
|
|
1307
|
+
if (args.length === 0) return [];
|
|
1308
|
+
const signature = checker.getResolvedSignature(call);
|
|
1309
|
+
if (!signature) return [];
|
|
1310
|
+
return args.filter((argument, index) => {
|
|
1311
|
+
if (ts.isSpreadElement(argument)) return false;
|
|
1312
|
+
if (!returnsThenable(checker, checker.getTypeAtLocation(argument), argument)) return false;
|
|
1313
|
+
const expected = parameterType(ts, checker, signature, index, call);
|
|
1314
|
+
return expected !== void 0 && returnsVoid(ts, expected);
|
|
1315
|
+
});
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// src/core/accept.ts
|
|
1319
|
+
var ACCEPTED_RULES = [THROW_RULE, UNTRUSTED_CALL_RULE, FLOATING_PROMISE_RULE, MISUSED_PROMISE_RULE];
|
|
1320
|
+
var ACCEPT_PROBLEMS = {
|
|
1321
|
+
block: "is a block comment, not a `//` line comment",
|
|
1322
|
+
reason: "gives no reason",
|
|
1323
|
+
misplaced: "is not directly above a statement it can accept (a declaration is not one)",
|
|
1324
|
+
stale: `has no ${ACCEPTED_RULES.slice(0, -1).join(", ")} or ${ACCEPTED_RULES[ACCEPTED_RULES.length - 1]} finding in the statement below it`
|
|
1325
|
+
};
|
|
1326
|
+
function acceptReason(directive) {
|
|
1327
|
+
return directive.body.slice(ACCEPT_DIRECTIVE.length).trim();
|
|
1328
|
+
}
|
|
1329
|
+
function failurePathFindingsAt(node, context) {
|
|
1330
|
+
const { ts, checker, policy, guardContext } = context;
|
|
1331
|
+
const found = [];
|
|
1332
|
+
if (ts.isExpressionStatement(node) && isFloatingPromise(ts, checker, node)) {
|
|
1333
|
+
found.push({ node, rule: FLOATING_PROMISE_RULE, origin: FLOATING_PROMISE_ORIGIN, message: FLOATING_PROMISE_MESSAGE });
|
|
1334
|
+
}
|
|
1335
|
+
for (const operand of conditionOperands(ts, node)) {
|
|
1336
|
+
if (isPromiseCondition(checker, operand)) found.push({ node: operand, rule: MISUSED_PROMISE_RULE, origin: "condition", message: MISUSED_PROMISE_MESSAGES.condition });
|
|
1337
|
+
}
|
|
1338
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
|
|
1339
|
+
for (const argument of asyncVoidCallbacks(ts, checker, node)) {
|
|
1340
|
+
found.push({ node: argument, rule: MISUSED_PROMISE_RULE, origin: "void-callback", message: MISUSED_PROMISE_MESSAGES["void-callback"] });
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
if (ts.isThrowStatement(node)) {
|
|
1344
|
+
const messageId = throwProblem(node, guardContext);
|
|
1345
|
+
if (messageId) found.push({ node, rule: THROW_RULE, origin: THROW_ORIGIN, message: THROW_MESSAGES[messageId] });
|
|
1346
|
+
} else if (ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword || ts.isNewExpression(node)) {
|
|
1347
|
+
const problem = untrustedCallProblem(node, policy, checker, guardContext);
|
|
1348
|
+
if (problem) found.push({ node, rule: UNTRUSTED_CALL_RULE, origin: problem.origin, message: formatMessage(UNTRUSTED_CALL_MESSAGES[problem.messageId], problem.origin) });
|
|
1349
|
+
}
|
|
1350
|
+
return found;
|
|
1351
|
+
}
|
|
1352
|
+
function isAcceptable(ts, node) {
|
|
1353
|
+
return ts.isExpressionStatement(node) || ts.isVariableStatement(node) || ts.isReturnStatement(node) || ts.isThrowStatement(node) || ts.isIfStatement(node) || ts.isDoStatement(node) || ts.isWhileStatement(node) || ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node) || ts.isSwitchStatement(node) || ts.isExportAssignment(node);
|
|
1354
|
+
}
|
|
1355
|
+
function isBoundary(ts, node) {
|
|
1356
|
+
return isFunctionBoundary(ts, node) || ts.isClassLike(node) || ts.isClassStaticBlockDeclaration(node);
|
|
1357
|
+
}
|
|
1358
|
+
function statementOf(ts, node) {
|
|
1359
|
+
for (let current = node; current && !ts.isSourceFile(current); current = current.parent) {
|
|
1360
|
+
if (current !== node && isBoundary(ts, current)) return null;
|
|
1361
|
+
if (ts.isStatement(current)) return current;
|
|
1362
|
+
}
|
|
1363
|
+
return null;
|
|
1364
|
+
}
|
|
1365
|
+
function acceptingDirective(ts, statement) {
|
|
1366
|
+
if (!isAcceptable(ts, statement)) return null;
|
|
1367
|
+
const directive = directiveDirectlyAbove(ts, statement);
|
|
1368
|
+
if (!directive || directive.kind !== "line" || !isAcceptDirective(directive) || !acceptReason(directive)) return null;
|
|
1369
|
+
return directive;
|
|
1370
|
+
}
|
|
1371
|
+
function acceptanceOf(ts, node) {
|
|
1372
|
+
const statement = statementOf(ts, node);
|
|
1373
|
+
const directive = statement && acceptingDirective(ts, statement);
|
|
1374
|
+
return statement && directive ? { statement, directive, reason: acceptReason(directive) } : null;
|
|
1375
|
+
}
|
|
1376
|
+
function findingsOfStatement(statement, context) {
|
|
1377
|
+
const { ts } = context;
|
|
1378
|
+
const found = [];
|
|
1379
|
+
const visit = (node) => {
|
|
1380
|
+
for (const finding of failurePathFindingsAt(node, context)) {
|
|
1381
|
+
if (statementOf(ts, finding.node) === statement) found.push(finding);
|
|
1382
|
+
}
|
|
1383
|
+
ts.forEachChild(node, visit);
|
|
1384
|
+
};
|
|
1385
|
+
visit(statement);
|
|
1386
|
+
return found;
|
|
1387
|
+
}
|
|
1388
|
+
function acceptProblem(ts, sourceFile, directive, context) {
|
|
1389
|
+
if (directive.kind !== "line") return "block";
|
|
1390
|
+
if (!acceptReason(directive)) return "reason";
|
|
1391
|
+
const below = nodeBelow(ts, sourceFile, directive);
|
|
1392
|
+
if (!below || !isAcceptable(ts, below) || directiveDirectlyAbove(ts, below)?.pos !== directive.pos) return "misplaced";
|
|
1393
|
+
if (!context) return null;
|
|
1394
|
+
return findingsOfStatement(below, context).length > 0 ? null : "stale";
|
|
1395
|
+
}
|
|
1396
|
+
function clip(text, max) {
|
|
1397
|
+
const flat = text.replace(/\s+/g, " ");
|
|
1398
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
1399
|
+
}
|
|
1400
|
+
function acceptDirectiveFindings(ts, sourceFile, context) {
|
|
1401
|
+
const found = [];
|
|
1402
|
+
for (const directive of trustDirectivesIn(ts, sourceFile)) {
|
|
1403
|
+
if (!isAcceptDirective(directive)) continue;
|
|
1404
|
+
const problem = acceptProblem(ts, sourceFile, directive, context);
|
|
1405
|
+
if (problem) found.push({ directive, messageId: "directive", data: { text: clip(directive.text, 40), problem: ACCEPT_PROBLEMS[problem] } });
|
|
1406
|
+
}
|
|
1407
|
+
return found;
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
// src/core/redundant-guards.ts
|
|
1411
|
+
var ORIGIN_LIMIT = 3;
|
|
1412
|
+
function redundantGuardData(guard) {
|
|
1413
|
+
const calls = guard.origins.length === 0 ? "nothing inside can throw (no call, or only calls declared to return a Result)" : `every call inside is trusted (${guard.origins.map((origin) => `"${origin}"`).join(", ")})`;
|
|
1414
|
+
return { guard: guard.guard, calls };
|
|
1415
|
+
}
|
|
1416
|
+
function redundantGuardMessage(guard) {
|
|
1417
|
+
return fillMessage(REDUNDANT_GUARD_MESSAGES.redundant, redundantGuardData(guard));
|
|
1418
|
+
}
|
|
1419
|
+
function isInlineArgument(ts, node) {
|
|
1420
|
+
if (!ts.isArrowFunction(node) && !ts.isFunctionExpression(node)) return false;
|
|
1421
|
+
let current = node;
|
|
1422
|
+
while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
|
|
1423
|
+
const parent = current.parent;
|
|
1424
|
+
return (ts.isCallExpression(parent) || ts.isNewExpression(parent)) && (parent.arguments ?? []).some((argument) => argument === current);
|
|
1425
|
+
}
|
|
1426
|
+
function openToThen(constraint, context) {
|
|
1427
|
+
const { ts } = context;
|
|
1428
|
+
if (constraint.isUnion()) return constraint.types.some((member) => openToThen(member, context));
|
|
1429
|
+
const open = ts.TypeFlags.Object | ts.TypeFlags.NonPrimitive | ts.TypeFlags.Intersection | ts.TypeFlags.Instantiable | ts.TypeFlags.Any | ts.TypeFlags.Unknown;
|
|
1430
|
+
return (constraint.flags & open) !== 0;
|
|
1431
|
+
}
|
|
1432
|
+
function thenable(type, context, opaque, seen = /* @__PURE__ */ new Set()) {
|
|
1433
|
+
const { ts, checker } = context;
|
|
1434
|
+
if (seen.has(type)) return false;
|
|
1435
|
+
seen.add(type);
|
|
1436
|
+
if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) return opaque;
|
|
1437
|
+
if (type.isUnionOrIntersection()) return type.types.some((member) => thenable(member, context, opaque, seen));
|
|
1438
|
+
if (type.flags & ts.TypeFlags.Instantiable) {
|
|
1439
|
+
const constraint = checker.getBaseConstraintOfType(type);
|
|
1440
|
+
if (!constraint || constraint === type) return opaque;
|
|
1441
|
+
return thenable(constraint, context, opaque, seen) || opaque && openToThen(constraint, context);
|
|
1442
|
+
}
|
|
1443
|
+
const then = checker.getPropertyOfType(checker.getApparentType(type), "then");
|
|
1444
|
+
return then !== void 0 && checker.getTypeOfSymbol(then).getCallSignatures().length > 0;
|
|
1445
|
+
}
|
|
1446
|
+
function isValueRead(ts, node) {
|
|
1447
|
+
if (!ts.isIdentifier(node) && !ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) return false;
|
|
1448
|
+
if (ts.isShorthandPropertyAssignment(node.parent)) return true;
|
|
1449
|
+
if (node.parent.name === node) return false;
|
|
1450
|
+
let current = node;
|
|
1451
|
+
while (ts.isParenthesizedExpression(current.parent)) current = current.parent;
|
|
1452
|
+
const parent = current.parent;
|
|
1453
|
+
if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && parent.expression === current) return false;
|
|
1454
|
+
return !(ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.left === current);
|
|
1455
|
+
}
|
|
1456
|
+
function returnedValues(ts, fn) {
|
|
1457
|
+
if (!ts.isBlock(fn.body)) return [fn.body];
|
|
1458
|
+
const values = [];
|
|
1459
|
+
const visit = (node) => {
|
|
1460
|
+
if (isFunctionBoundary(ts, node) || ts.isClassLike(node)) return;
|
|
1461
|
+
if (ts.isReturnStatement(node) && node.expression) values.push(node.expression);
|
|
1462
|
+
ts.forEachChild(node, visit);
|
|
1463
|
+
};
|
|
1464
|
+
ts.forEachChild(fn.body, visit);
|
|
1465
|
+
return values;
|
|
1466
|
+
}
|
|
1467
|
+
function mayReturnThenable(node, context) {
|
|
1468
|
+
const { ts, checker } = context;
|
|
1469
|
+
const inner = unparen(ts, node);
|
|
1470
|
+
if (ts.isConditionalExpression(inner)) return mayReturnThenable(inner.whenTrue, context) || mayReturnThenable(inner.whenFalse, context);
|
|
1471
|
+
if (ts.isBinaryExpression(inner)) {
|
|
1472
|
+
const operator = inner.operatorToken.kind;
|
|
1473
|
+
if (operator === ts.SyntaxKind.CommaToken) return mayReturnThenable(inner.right, context);
|
|
1474
|
+
if (operator === ts.SyntaxKind.QuestionQuestionToken || operator === ts.SyntaxKind.BarBarToken || operator === ts.SyntaxKind.AmpersandAmpersandToken) {
|
|
1475
|
+
return mayReturnThenable(inner.left, context) || mayReturnThenable(inner.right, context);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
if (ts.isCallExpression(inner) || ts.isNewExpression(inner) || ts.isAwaitExpression(inner)) return false;
|
|
1479
|
+
return thenable(checker.getTypeAtLocation(inner), context, true);
|
|
1480
|
+
}
|
|
1481
|
+
function isPromiseAdoption(node, context) {
|
|
1482
|
+
const { ts, checker } = context;
|
|
1483
|
+
const callee = unparen(ts, node.expression);
|
|
1484
|
+
if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== "resolve") return false;
|
|
1485
|
+
const owner = checker.getResolvedSignature(node)?.declaration?.parent;
|
|
1486
|
+
return owner !== void 0 && ts.isInterfaceDeclaration(owner) && owner.name.text === "PromiseConstructor";
|
|
1487
|
+
}
|
|
1488
|
+
function cannotFail(body, context) {
|
|
1489
|
+
const { ts, policy } = context;
|
|
1490
|
+
const origins = /* @__PURE__ */ new Set();
|
|
1491
|
+
let fails = false;
|
|
1492
|
+
const visit = (node) => {
|
|
1493
|
+
if (fails) return;
|
|
1494
|
+
if (ts.isTypeNode(node) && !ts.isExpressionWithTypeArguments(node)) return;
|
|
1495
|
+
if (node !== body && isFunctionBoundary(ts, node) && !isInlineArgument(ts, node)) return;
|
|
1496
|
+
if (isValueRead(ts, node) && thenable(context.checker.getTypeAtLocation(node), context, false)) {
|
|
1497
|
+
fails = true;
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
if (ts.isCallExpression(node) && isPromiseAdoption(node, context) && node.arguments.some((argument) => mayReturnThenable(argument, context))) {
|
|
1501
|
+
fails = true;
|
|
1502
|
+
return;
|
|
1503
|
+
}
|
|
1504
|
+
if (ts.isThrowStatement(node)) {
|
|
1505
|
+
fails = true;
|
|
1506
|
+
return;
|
|
1507
|
+
}
|
|
1508
|
+
if (ts.isAwaitExpression(node)) {
|
|
1509
|
+
const awaited = unparen(ts, node.expression);
|
|
1510
|
+
if (!ts.isCallExpression(awaited) && !ts.isNewExpression(awaited)) {
|
|
1511
|
+
fails = true;
|
|
1512
|
+
return;
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
if (ts.isForOfStatement(node) && node.awaitModifier) {
|
|
1516
|
+
fails = true;
|
|
1517
|
+
return;
|
|
1518
|
+
}
|
|
1519
|
+
if (ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword || ts.isNewExpression(node)) {
|
|
1520
|
+
const verdict = policy.classify(node);
|
|
1521
|
+
if (verdict.kind === "untrusted" || verdict.kind === "unresolved" || verdict.kind === "calls-ignored") {
|
|
1522
|
+
fails = true;
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
if (verdict.kind === "first-party") {
|
|
1526
|
+
const signature = context.checker.getResolvedSignature(node);
|
|
1527
|
+
if (!signature || !policy.returnsResult(signature)) {
|
|
1528
|
+
fails = true;
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
if (verdict.kind === "trusted") origins.add(verdict.origin.origin);
|
|
1533
|
+
}
|
|
1534
|
+
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
1535
|
+
fails = true;
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
ts.forEachChild(node, visit);
|
|
1539
|
+
};
|
|
1540
|
+
visit(body);
|
|
1541
|
+
if (!fails && (ts.isArrowFunction(body) || ts.isFunctionExpression(body))) {
|
|
1542
|
+
fails = returnedValues(ts, body).some((value) => mayReturnThenable(value, context));
|
|
1543
|
+
}
|
|
1544
|
+
return fails ? null : origins;
|
|
1545
|
+
}
|
|
1546
|
+
function redundantGuardsIn(sourceFile, context) {
|
|
1547
|
+
const { ts, guardContext } = context;
|
|
1548
|
+
const found = [];
|
|
1549
|
+
const visit = (node) => {
|
|
1550
|
+
if (ts.isCallExpression(node)) {
|
|
1551
|
+
const kind = guardContext.trustTryKind(node);
|
|
1552
|
+
const callback = node.arguments[0] ? unparen(ts, node.arguments[0]) : void 0;
|
|
1553
|
+
if (kind && callback && (ts.isArrowFunction(callback) || ts.isFunctionExpression(callback))) {
|
|
1554
|
+
const origins = cannotFail(callback, context);
|
|
1555
|
+
if (origins) {
|
|
1556
|
+
found.push({ start: node.getStart(sourceFile), guard: kind === "sync" ? "Trust.try" : "Trust.tryAsync", origins: [...origins].sort().slice(0, ORIGIN_LIMIT) });
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
if (ts.isTryStatement(node) && node.catchClause && catchProblem(node.catchClause, guardContext) === null) {
|
|
1561
|
+
const origins = cannotFail(node.tryBlock, context);
|
|
1562
|
+
if (origins) found.push({ start: node.getStart(sourceFile), guard: "try", origins: [...origins].sort().slice(0, ORIGIN_LIMIT) });
|
|
1563
|
+
}
|
|
1564
|
+
ts.forEachChild(node, visit);
|
|
1565
|
+
};
|
|
1566
|
+
visit(sourceFile);
|
|
1567
|
+
return found;
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1570
|
+
// src/core/type-claims.ts
|
|
1571
|
+
function claimSpan(claim2, sourceFile) {
|
|
1572
|
+
return claim2.at ?? { start: claim2.node.getStart(sourceFile), end: claim2.node.getEnd() };
|
|
1573
|
+
}
|
|
1574
|
+
var contexts = /* @__PURE__ */ new WeakMap();
|
|
1575
|
+
var policyContexts = /* @__PURE__ */ new WeakMap();
|
|
1576
|
+
function typeClaimContext(ts, checker, insideValidator, policy) {
|
|
1577
|
+
const trustsChosenReturn = policy ? (node) => calleeIsUserTypeTrusted(node, policy) : void 0;
|
|
1578
|
+
if (insideValidator) return { ts, checker, isInsideValidator: insideValidator, provenBodies: /* @__PURE__ */ new WeakMap(), trustsChosenReturn };
|
|
1579
|
+
const known = policy ? policyContexts.get(policy) : contexts.get(checker);
|
|
1580
|
+
if (known) return known;
|
|
1581
|
+
const context = { ts, checker, isInsideValidator: (node) => isInsideValidator(ts, node), provenBodies: /* @__PURE__ */ new WeakMap(), trustsChosenReturn };
|
|
1582
|
+
if (policy) policyContexts.set(policy, context);
|
|
1583
|
+
else contexts.set(checker, context);
|
|
1584
|
+
return context;
|
|
1585
|
+
}
|
|
1586
|
+
function calleeIsUserTypeTrusted(node, policy) {
|
|
1587
|
+
const resolved = policy.calleeDeclaration(node);
|
|
1588
|
+
return resolved !== null && policy.userTypeTrustOf(resolved.declaration) !== null;
|
|
1589
|
+
}
|
|
1590
|
+
function typeClaimMessage(claim2) {
|
|
1591
|
+
return fillMessage(TYPE_CLAIM_MESSAGES[claim2.origin], claim2.data);
|
|
1592
|
+
}
|
|
1593
|
+
var MAX_TEXT = 80;
|
|
1594
|
+
var MAX_TYPE_DEPTH = 4;
|
|
1595
|
+
function clip2(text, max = MAX_TEXT) {
|
|
1596
|
+
const flat = text.replace(/\s+/g, " ");
|
|
1597
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
1598
|
+
}
|
|
1599
|
+
function typeText(context, type) {
|
|
1600
|
+
return clip2(context.checker.typeToString(type));
|
|
1601
|
+
}
|
|
1602
|
+
function claim(node, origin, data) {
|
|
1603
|
+
return { node, origin, data };
|
|
1604
|
+
}
|
|
1605
|
+
function isAny(ts, type) {
|
|
1606
|
+
return (type.flags & ts.TypeFlags.Any) !== 0;
|
|
1607
|
+
}
|
|
1608
|
+
function isAnyOrUnknown(ts, type) {
|
|
1609
|
+
return (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
|
|
1610
|
+
}
|
|
1611
|
+
function isUnresolved(ts, type) {
|
|
1612
|
+
if (!isAny(ts, type)) return false;
|
|
1613
|
+
const name = type.intrinsicName;
|
|
1614
|
+
return name === "error" || name === "unresolved";
|
|
1615
|
+
}
|
|
1616
|
+
function withoutFreshness(context, type) {
|
|
1617
|
+
const { ts, checker } = context;
|
|
1618
|
+
const fresh = (type.flags & ts.TypeFlags.Object) !== 0 && (type.objectFlags & ts.ObjectFlags.FreshLiteral) !== 0;
|
|
1619
|
+
return fresh ? checker.getWidenedType(type) : type;
|
|
1620
|
+
}
|
|
1621
|
+
function unwrap(ts, node) {
|
|
1622
|
+
let current = unparen(ts, node);
|
|
1623
|
+
while (ts.isNonNullExpression(current)) current = unparen(ts, current.expression);
|
|
1624
|
+
return current;
|
|
1625
|
+
}
|
|
1626
|
+
function accessTarget(ts, node) {
|
|
1627
|
+
if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) || ts.isNewExpression(node)) return node.expression;
|
|
1628
|
+
if (ts.isCallExpression(node)) return node.expression.kind === ts.SyntaxKind.ImportKeyword ? null : node.expression;
|
|
1629
|
+
if (ts.isTaggedTemplateExpression(node)) return node.tag;
|
|
1630
|
+
return null;
|
|
1631
|
+
}
|
|
1632
|
+
function isCallLike(ts, node) {
|
|
1633
|
+
return ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isTaggedTemplateExpression(node);
|
|
1634
|
+
}
|
|
1635
|
+
function isAnyAccess(node, context) {
|
|
1636
|
+
const target = accessTarget(context.ts, node);
|
|
1637
|
+
return target !== null && isAny(context.ts, context.checker.getTypeAtLocation(target));
|
|
1638
|
+
}
|
|
1639
|
+
function isExplicitAnyCast(ts, node) {
|
|
1640
|
+
return ts.isAssertionExpression(node) && node.type.kind === ts.SyntaxKind.AnyKeyword;
|
|
1641
|
+
}
|
|
1642
|
+
function isReportedAtItsSource(node, context) {
|
|
1643
|
+
const inner = unwrap(context.ts, node);
|
|
1644
|
+
return isAnyAccess(inner, context) || isExplicitAnyCast(context.ts, inner);
|
|
1645
|
+
}
|
|
1646
|
+
function isPlainAssignment(ts, node) {
|
|
1647
|
+
if (!ts.isBinaryExpression(node)) return false;
|
|
1648
|
+
const kind = node.operatorToken.kind;
|
|
1649
|
+
return kind === ts.SyntaxKind.EqualsToken || kind === ts.SyntaxKind.BarBarEqualsToken || kind === ts.SyntaxKind.AmpersandAmpersandEqualsToken || kind === ts.SyntaxKind.QuestionQuestionEqualsToken;
|
|
1650
|
+
}
|
|
1651
|
+
function typedOperands(ts, node) {
|
|
1652
|
+
if (ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isPropertyDeclaration(node) || ts.isBindingElement(node) || ts.isPropertyAssignment(node)) {
|
|
1653
|
+
return node.initializer ? [node.initializer] : [];
|
|
1654
|
+
}
|
|
1655
|
+
if (ts.isShorthandPropertyAssignment(node)) return [node.name];
|
|
1656
|
+
if (ts.isSpreadAssignment(node)) return [node.expression];
|
|
1657
|
+
if (isPlainAssignment(ts, node)) return [node.right];
|
|
1658
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
|
|
1659
|
+
return (node.arguments ?? []).map((argument) => ts.isSpreadElement(argument) ? argument.expression : argument);
|
|
1660
|
+
}
|
|
1661
|
+
if (ts.isReturnStatement(node) || ts.isYieldExpression(node) || ts.isJsxExpression(node)) return node.expression ? [node.expression] : [];
|
|
1662
|
+
if (ts.isArrowFunction(node)) return ts.isBlock(node.body) ? [] : [node.body];
|
|
1663
|
+
if (ts.isArrayLiteralExpression(node)) {
|
|
1664
|
+
return node.elements.filter((element) => !ts.isOmittedExpression(element)).map((element) => ts.isSpreadElement(element) ? element.expression : element);
|
|
1665
|
+
}
|
|
1666
|
+
if (ts.isAssertionExpression(node)) return ts.isConstTypeReference(node.type) ? [] : [node.expression];
|
|
1667
|
+
if (ts.isSatisfiesExpression(node)) return [node.expression];
|
|
1668
|
+
return [];
|
|
1669
|
+
}
|
|
1670
|
+
function isIntrinsicTagName(name) {
|
|
1671
|
+
return /^[a-z]/.test(name) || name.includes("-");
|
|
1672
|
+
}
|
|
1673
|
+
function isValueUse(ts, node) {
|
|
1674
|
+
const parent = node.parent;
|
|
1675
|
+
if (ts.isVariableDeclaration(parent) || ts.isParameter(parent) || ts.isPropertyDeclaration(parent) || ts.isBindingElement(parent) || ts.isPropertyAssignment(parent) || ts.isEnumMember(parent)) {
|
|
1676
|
+
return parent.initializer === node;
|
|
1677
|
+
}
|
|
1678
|
+
if (ts.isShorthandPropertyAssignment(parent)) return true;
|
|
1679
|
+
if (ts.isJsxOpeningElement(parent) || ts.isJsxSelfClosingElement(parent)) return parent.tagName === node && !isIntrinsicTagName(node.text);
|
|
1680
|
+
switch (parent.kind) {
|
|
1681
|
+
case ts.SyntaxKind.ExpressionStatement:
|
|
1682
|
+
case ts.SyntaxKind.IfStatement:
|
|
1683
|
+
case ts.SyntaxKind.DoStatement:
|
|
1684
|
+
case ts.SyntaxKind.WhileStatement:
|
|
1685
|
+
case ts.SyntaxKind.ForStatement:
|
|
1686
|
+
case ts.SyntaxKind.ForInStatement:
|
|
1687
|
+
case ts.SyntaxKind.ForOfStatement:
|
|
1688
|
+
case ts.SyntaxKind.ReturnStatement:
|
|
1689
|
+
case ts.SyntaxKind.WithStatement:
|
|
1690
|
+
case ts.SyntaxKind.SwitchStatement:
|
|
1691
|
+
case ts.SyntaxKind.CaseClause:
|
|
1692
|
+
case ts.SyntaxKind.ThrowStatement:
|
|
1693
|
+
case ts.SyntaxKind.ExportAssignment:
|
|
1694
|
+
case ts.SyntaxKind.TemplateSpan:
|
|
1695
|
+
case ts.SyntaxKind.ComputedPropertyName:
|
|
1696
|
+
case ts.SyntaxKind.Decorator:
|
|
1697
|
+
case ts.SyntaxKind.JsxExpression:
|
|
1698
|
+
case ts.SyntaxKind.JsxSpreadAttribute:
|
|
1699
|
+
case ts.SyntaxKind.SpreadAssignment:
|
|
1700
|
+
return true;
|
|
1701
|
+
default:
|
|
1702
|
+
return ts.isExpression(parent) && parent.name !== node && !ts.isPartOfTypeNode(node);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
function isValueExpression(ts, node) {
|
|
1706
|
+
if (ts.isIdentifier(node)) return isValueUse(ts, node);
|
|
1707
|
+
if (!ts.isExpression(node) || node.kind <= ts.SyntaxKind.LastToken) return false;
|
|
1708
|
+
if (ts.isOmittedExpression(node) || ts.isExpressionWithTypeArguments(node) || ts.isLiteralTypeNode(node.parent)) return false;
|
|
1709
|
+
return !ts.isPartOfTypeNode(node);
|
|
1710
|
+
}
|
|
1711
|
+
function doesNotResolve(node, context) {
|
|
1712
|
+
const { ts, checker } = context;
|
|
1713
|
+
if (ts.isTypeNode(node)) {
|
|
1714
|
+
if (ts.isExpressionWithTypeArguments(node) && !ts.isPartOfTypeNode(node)) return false;
|
|
1715
|
+
return isUnresolved(ts, checker.getTypeFromTypeNode(node));
|
|
1716
|
+
}
|
|
1717
|
+
return isValueExpression(ts, node) && isUnresolved(ts, checker.getTypeAtLocation(node));
|
|
1718
|
+
}
|
|
1719
|
+
function containsUnresolved(node, context) {
|
|
1720
|
+
return doesNotResolve(node, context) || (context.ts.forEachChild(node, (child) => containsUnresolved(child, context) || void 0) ?? false);
|
|
1721
|
+
}
|
|
1722
|
+
function unresolvedClaim(node, context) {
|
|
1723
|
+
const { ts } = context;
|
|
1724
|
+
if (!doesNotResolve(node, context)) return null;
|
|
1725
|
+
if (ts.forEachChild(node, (child) => containsUnresolved(child, context) || void 0)) return null;
|
|
1726
|
+
const text = clip2(node.getText(), 40);
|
|
1727
|
+
if (ts.isTypeNode(node)) return claim(node, "unanalyzable", { what: "this type", reason: `"${text}" does not resolve` });
|
|
1728
|
+
return claim(node, "unanalyzable", { what: "this value", reason: `the type of "${text}" does not resolve` });
|
|
1729
|
+
}
|
|
1730
|
+
function unresolvedModuleClaim(node, context) {
|
|
1731
|
+
const { ts, checker } = context;
|
|
1732
|
+
const unresolvedModule = (specifier, what) => {
|
|
1733
|
+
if (!specifier || !ts.isStringLiteralLike(specifier) || checker.getSymbolAtLocation(specifier)) return null;
|
|
1734
|
+
return claim(node, "unanalyzable", { what, reason: `the module ${clip2(specifier.getText(), 40)} does not resolve` });
|
|
1735
|
+
};
|
|
1736
|
+
if (ts.isExportDeclaration(node)) return unresolvedModule(node.moduleSpecifier, "this re-export");
|
|
1737
|
+
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) return unresolvedModule(node.arguments[0], "this dynamic import");
|
|
1738
|
+
if (ts.isExportSpecifier(node) && !node.parent.parent.moduleSpecifier) {
|
|
1739
|
+
const local = checker.getExportSpecifierLocalTargetSymbol(node);
|
|
1740
|
+
const target = local && local.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(local) : local;
|
|
1741
|
+
if (!target || checker.isUnknownSymbol(target)) {
|
|
1742
|
+
return claim(node, "unanalyzable", { what: "this export", reason: `"${clip2(node.getText(), 40)}" does not resolve` });
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
return null;
|
|
1746
|
+
}
|
|
1747
|
+
function anyFlowClaim(operand, context) {
|
|
1748
|
+
const { ts, checker } = context;
|
|
1749
|
+
const node = unparen(ts, operand);
|
|
1750
|
+
const type = checker.getTypeAtLocation(node);
|
|
1751
|
+
if (!isAny(ts, type)) return null;
|
|
1752
|
+
const expected = checker.getContextualType(node);
|
|
1753
|
+
if (!expected || isAnyOrUnknown(ts, expected)) return null;
|
|
1754
|
+
if (isReportedAtItsSource(node, context)) return null;
|
|
1755
|
+
const position = `where "${typeText(context, expected)}" is expected`;
|
|
1756
|
+
if (isUnresolved(ts, type)) {
|
|
1757
|
+
if (containsUnresolved(node, context)) return null;
|
|
1758
|
+
return claim(node, "unanalyzable", { what: "this value", reason: `its type does not resolve, and it is used ${position}` });
|
|
1759
|
+
}
|
|
1760
|
+
return claim(node, "claim:any", { detail: `A value of type \`any\` is used ${position}` });
|
|
1761
|
+
}
|
|
1762
|
+
function anyAccessClaim(node, context) {
|
|
1763
|
+
const { ts, checker } = context;
|
|
1764
|
+
const target = accessTarget(ts, node);
|
|
1765
|
+
if (!target || ts.isPartOfTypeNode(node)) return null;
|
|
1766
|
+
const type = checker.getTypeAtLocation(target);
|
|
1767
|
+
if (!isAny(ts, type) || isReportedAtItsSource(target, context)) return null;
|
|
1768
|
+
const called = isCallLike(ts, node);
|
|
1769
|
+
if (isUnresolved(ts, type)) {
|
|
1770
|
+
if (containsUnresolved(target, context)) return null;
|
|
1771
|
+
return claim(node, "unanalyzable", {
|
|
1772
|
+
what: called ? "this call" : "this member access",
|
|
1773
|
+
reason: `the type of "${clip2(target.getText(), 40)}" does not resolve`
|
|
1774
|
+
});
|
|
1775
|
+
}
|
|
1776
|
+
return claim(node, "claim:any", { detail: called ? "A value of type `any` is called" : "A member of a value of type `any` is used" });
|
|
1777
|
+
}
|
|
1778
|
+
function assertionClaim(node, context) {
|
|
1779
|
+
const { ts, checker } = context;
|
|
1780
|
+
if (ts.isConstTypeReference(node.type)) return null;
|
|
1781
|
+
const what = "this type assertion";
|
|
1782
|
+
const target = checker.getTypeFromTypeNode(node.type);
|
|
1783
|
+
if (isUnresolved(ts, target)) {
|
|
1784
|
+
if (containsUnresolved(node.type, context)) return null;
|
|
1785
|
+
return claim(node, "unanalyzable", { what, reason: `its target type "${clip2(node.type.getText(), 40)}" does not resolve` });
|
|
1786
|
+
}
|
|
1787
|
+
if (isAnyOrUnknown(ts, target)) return null;
|
|
1788
|
+
const source = checker.getTypeAtLocation(node.expression);
|
|
1789
|
+
if (isAny(ts, source)) return null;
|
|
1790
|
+
if (typeof checker.isTypeAssignableTo !== "function") {
|
|
1791
|
+
return claim(node, "unanalyzable", { what, reason: "this TypeScript has no isTypeAssignableTo (5.4 or newer is needed)" });
|
|
1792
|
+
}
|
|
1793
|
+
if (checker.isTypeAssignableTo(withoutFreshness(context, source), target)) return null;
|
|
1794
|
+
return claim(node, "claim:as", { from: typeText(context, source), to: typeText(context, target) });
|
|
1795
|
+
}
|
|
1796
|
+
function typeMentions(context, type, parameter, depth = 0) {
|
|
1797
|
+
const { ts, checker } = context;
|
|
1798
|
+
if (type === parameter) return true;
|
|
1799
|
+
if (depth >= MAX_TYPE_DEPTH) return false;
|
|
1800
|
+
const next = (inner) => typeMentions(context, inner, parameter, depth + 1);
|
|
1801
|
+
if (type.aliasTypeArguments?.some(next)) return true;
|
|
1802
|
+
if (type.isUnionOrIntersection()) return type.types.some(next);
|
|
1803
|
+
if (type.flags & ts.TypeFlags.IndexedAccess) {
|
|
1804
|
+
const access = type;
|
|
1805
|
+
return next(access.objectType) || next(access.indexType);
|
|
1806
|
+
}
|
|
1807
|
+
if (!(type.flags & ts.TypeFlags.Object)) return false;
|
|
1808
|
+
const objectFlags = type.objectFlags;
|
|
1809
|
+
if (objectFlags & ts.ObjectFlags.Reference) return checker.getTypeArguments(type).some(next);
|
|
1810
|
+
if (!(objectFlags & ts.ObjectFlags.Anonymous)) return false;
|
|
1811
|
+
if (type.getCallSignatures().some((signature) => next(signature.getReturnType()))) return true;
|
|
1812
|
+
return type.getProperties().some((property) => next(checker.getTypeOfSymbol(property)));
|
|
1813
|
+
}
|
|
1814
|
+
function nodeMentions(context, root, declaration) {
|
|
1815
|
+
if (!root) return false;
|
|
1816
|
+
const { ts, checker } = context;
|
|
1817
|
+
const symbol = checker.getSymbolAtLocation(declaration.name);
|
|
1818
|
+
const visit = (node) => {
|
|
1819
|
+
if (ts.isIdentifier(node) && node.text === declaration.name.text && (!symbol || checker.getSymbolAtLocation(node) === symbol)) return true;
|
|
1820
|
+
return ts.forEachChild(node, (child) => visit(child) || void 0) ?? false;
|
|
1821
|
+
};
|
|
1822
|
+
return visit(root);
|
|
1823
|
+
}
|
|
1824
|
+
var returnOnlyCache = /* @__PURE__ */ new WeakMap();
|
|
1825
|
+
function returnOnlyTypeParameters(declaration, context) {
|
|
1826
|
+
const cached = returnOnlyCache.get(declaration);
|
|
1827
|
+
if (cached) return cached;
|
|
1828
|
+
const { checker } = context;
|
|
1829
|
+
const parameters = declaration.typeParameters ?? [];
|
|
1830
|
+
const inferred = declaration.type ? void 0 : checker.getSignatureFromDeclaration(declaration)?.getReturnType();
|
|
1831
|
+
const indexes = [];
|
|
1832
|
+
parameters.forEach((parameter, index) => {
|
|
1833
|
+
if (declaration.parameters.some((argument) => nodeMentions(context, argument.type, parameter))) return;
|
|
1834
|
+
const inReturn = declaration.type ? nodeMentions(context, declaration.type, parameter) : inferred !== void 0 && typeMentions(context, inferred, checker.getTypeAtLocation(parameter));
|
|
1835
|
+
if (inReturn) indexes.push(index);
|
|
1836
|
+
});
|
|
1837
|
+
returnOnlyCache.set(declaration, indexes);
|
|
1838
|
+
return indexes;
|
|
1839
|
+
}
|
|
1840
|
+
function sameType(checker, a, b) {
|
|
1841
|
+
if (a === b) return true;
|
|
1842
|
+
if (typeof checker.isTypeAssignableTo !== "function") return false;
|
|
1843
|
+
return checker.isTypeAssignableTo(a, b) && checker.isTypeAssignableTo(b, a);
|
|
1844
|
+
}
|
|
1845
|
+
function resolvedTypeArguments(node, signature, expected, checker) {
|
|
1846
|
+
if (typeof checker.getTypeArgumentsForResolvedSignature === "function") return checker.getTypeArgumentsForResolvedSignature(signature);
|
|
1847
|
+
if (expected === 0) return void 0;
|
|
1848
|
+
const written = node.typeArguments ?? [];
|
|
1849
|
+
return written.length === expected ? written.map((argument) => checker.getTypeFromTypeNode(argument)) : null;
|
|
1850
|
+
}
|
|
1851
|
+
function bodyProvesReturn(declaration, context) {
|
|
1852
|
+
if (!("body" in declaration) || !declaration.body) return false;
|
|
1853
|
+
const known = context.provenBodies.get(declaration);
|
|
1854
|
+
if (known) return known === "proven";
|
|
1855
|
+
context.provenBodies.set(declaration, "checking");
|
|
1856
|
+
const hasClaim = (node) => typeClaimsAt(node, context).length > 0 || (context.ts.forEachChild(node, (child) => hasClaim(child) || void 0) ?? false);
|
|
1857
|
+
const proven = !hasClaim(declaration);
|
|
1858
|
+
context.provenBodies.set(declaration, proven ? "proven" : "claimed");
|
|
1859
|
+
return proven;
|
|
1860
|
+
}
|
|
1861
|
+
function genericReturnClaim(node, context) {
|
|
1862
|
+
const found = chosenReturnClaim(node, context);
|
|
1863
|
+
if (found?.origin === "claim:generic-return" && context.trustsChosenReturn?.(node)) return null;
|
|
1864
|
+
return found;
|
|
1865
|
+
}
|
|
1866
|
+
function chosenReturnClaim(node, context) {
|
|
1867
|
+
const { ts, checker } = context;
|
|
1868
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword || node.expression.kind === ts.SyntaxKind.SuperKeyword) return null;
|
|
1869
|
+
const what = "this generic call";
|
|
1870
|
+
const callee = clip2(node.expression.getText(), 40);
|
|
1871
|
+
const signature = checker.getResolvedSignature(node);
|
|
1872
|
+
if (!signature) return claim(node, "unanalyzable", { what: "this call", reason: `no signature resolves for "${callee}"` });
|
|
1873
|
+
const declared = signature.getDeclaration();
|
|
1874
|
+
const declaration = declared && !ts.isJSDocSignature(declared) ? declared : void 0;
|
|
1875
|
+
const parameters = declaration?.typeParameters ?? [];
|
|
1876
|
+
const chosen = resolvedTypeArguments(node, signature, parameters.length, checker);
|
|
1877
|
+
if (chosen === void 0 || chosen !== null && chosen.length === 0) return null;
|
|
1878
|
+
if (!declaration || chosen !== null && chosen.length !== parameters.length) {
|
|
1879
|
+
return claim(node, "unanalyzable", { what, reason: `the declaration of the signature of "${callee}" is not available` });
|
|
1880
|
+
}
|
|
1881
|
+
const returnOnly = returnOnlyTypeParameters(declaration, context);
|
|
1882
|
+
if (returnOnly.length === 0 || bodyProvesReturn(declaration, context)) return null;
|
|
1883
|
+
for (const index of returnOnly) {
|
|
1884
|
+
const parameter = parameters[index];
|
|
1885
|
+
const name = parameter.name.text;
|
|
1886
|
+
if (chosen === null) return claim(node, "claim:generic-return", { parameter: name, callee, chosen: "the inferred type" });
|
|
1887
|
+
const type = chosen[index];
|
|
1888
|
+
if (isUnresolved(ts, type)) {
|
|
1889
|
+
if (containsUnresolved(node, context)) return null;
|
|
1890
|
+
return claim(node, "unanalyzable", { what, reason: `its type argument for "${name}" does not resolve` });
|
|
1891
|
+
}
|
|
1892
|
+
if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) continue;
|
|
1893
|
+
const fallback = parameter.default ?? parameter.constraint;
|
|
1894
|
+
if (fallback && sameType(checker, type, checker.getTypeFromTypeNode(fallback))) continue;
|
|
1895
|
+
return claim(node, "claim:generic-return", { parameter: name, callee, chosen: typeText(context, type) });
|
|
1896
|
+
}
|
|
1897
|
+
return null;
|
|
1898
|
+
}
|
|
1899
|
+
function picksOwnReturnType(node, context) {
|
|
1900
|
+
try {
|
|
1901
|
+
return genericReturnClaim(node, context)?.origin === "claim:generic-return";
|
|
1902
|
+
} catch {
|
|
1903
|
+
return false;
|
|
1904
|
+
}
|
|
1905
|
+
}
|
|
1906
|
+
function decide2(node, context) {
|
|
1907
|
+
const { ts, checker } = context;
|
|
1908
|
+
const claims = [];
|
|
1909
|
+
const add = (found) => {
|
|
1910
|
+
if (found) claims.push(found);
|
|
1911
|
+
};
|
|
1912
|
+
add(unresolvedClaim(node, context));
|
|
1913
|
+
add(unresolvedModuleClaim(node, context));
|
|
1914
|
+
for (const operand of typedOperands(ts, node)) add(anyFlowClaim(operand, context));
|
|
1915
|
+
if (node.kind === ts.SyntaxKind.AnyKeyword) add(claim(node, "claim:any", { detail: "Explicit `any`" }));
|
|
1916
|
+
else if (ts.isAssertionExpression(node)) add(assertionClaim(node, context));
|
|
1917
|
+
else if (ts.isNonNullExpression(node)) add(claim(node, "claim:non-null", { from: typeText(context, checker.getTypeAtLocation(node.expression)) }));
|
|
1918
|
+
else if (ts.isTypePredicateNode(node)) add(claim(node, "claim:predicate", { predicate: clip2(node.getText()) }));
|
|
1919
|
+
add(anyAccessClaim(node, context));
|
|
1920
|
+
if (ts.isCallExpression(node)) add(genericReturnClaim(node, context));
|
|
1921
|
+
return claims;
|
|
1922
|
+
}
|
|
1923
|
+
function typeClaimsAt(node, context) {
|
|
1924
|
+
let claims;
|
|
1925
|
+
try {
|
|
1926
|
+
claims = decide2(node, context);
|
|
1927
|
+
} catch (error) {
|
|
1928
|
+
const reason = `the type checker failed on it (${clip2(error instanceof Error ? error.message : String(error))})`;
|
|
1929
|
+
claims = [claim(node, "unanalyzable", { what: "this node", reason })];
|
|
1930
|
+
}
|
|
1931
|
+
return claims.filter((found) => !context.isInsideValidator(found.node));
|
|
1932
|
+
}
|
|
1933
|
+
var DIRECTIVE_PROBLEMS = {
|
|
1934
|
+
unknown: "is not a known directive",
|
|
1935
|
+
block: "is a block comment, not a `//` line comment",
|
|
1936
|
+
misplaced: "is not directly above a function"
|
|
1937
|
+
};
|
|
1938
|
+
function directiveClaims(ts, root) {
|
|
1939
|
+
const sourceFile = root.getSourceFile();
|
|
1940
|
+
const claims = [];
|
|
1941
|
+
for (const directive of trustDirectivesIn(ts, sourceFile)) {
|
|
1942
|
+
if (directive.pos < root.pos || directive.end > root.end || isAcceptDirective(directive)) continue;
|
|
1943
|
+
const problem = directiveProblem(ts, sourceFile, directive);
|
|
1944
|
+
if (!problem) continue;
|
|
1945
|
+
const data = { text: clip2(directive.text, 40), problem: DIRECTIVE_PROBLEMS[problem] };
|
|
1946
|
+
claims.push({ node: sourceFile, origin: "directive", data, at: { start: directive.pos, end: directive.end } });
|
|
1947
|
+
}
|
|
1948
|
+
return claims;
|
|
1949
|
+
}
|
|
1950
|
+
function typeClaimsIn(root, context) {
|
|
1951
|
+
const claims = directiveClaims(context.ts, root);
|
|
1952
|
+
const visit = (node) => {
|
|
1953
|
+
claims.push(...typeClaimsAt(node, context));
|
|
1954
|
+
context.ts.forEachChild(node, visit);
|
|
1955
|
+
};
|
|
1956
|
+
visit(root);
|
|
1957
|
+
return claims;
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
// src/core/untrusted-values.ts
|
|
1961
|
+
var contexts2 = /* @__PURE__ */ new WeakMap();
|
|
1962
|
+
function untrustedValueContext(ts, checker, policy) {
|
|
1963
|
+
let context = contexts2.get(policy);
|
|
1964
|
+
if (!context) {
|
|
1965
|
+
context = {
|
|
1966
|
+
ts,
|
|
1967
|
+
checker,
|
|
1968
|
+
policy,
|
|
1969
|
+
claims: typeClaimContext(ts, checker, void 0, policy),
|
|
1970
|
+
sources: /* @__PURE__ */ new WeakMap(),
|
|
1971
|
+
assignedSources: /* @__PURE__ */ new WeakMap(),
|
|
1972
|
+
assignments: /* @__PURE__ */ new WeakMap(),
|
|
1973
|
+
guards: /* @__PURE__ */ new WeakMap(),
|
|
1974
|
+
decision: { depth: 0, provisional: false, tentative: [] }
|
|
1975
|
+
};
|
|
1976
|
+
contexts2.set(policy, context);
|
|
1977
|
+
}
|
|
1978
|
+
return context;
|
|
1979
|
+
}
|
|
1980
|
+
function remember(cache, key, context, decide3) {
|
|
1981
|
+
const state = context.decision;
|
|
1982
|
+
const known = cache.get(key);
|
|
1983
|
+
if (known === "deciding" || known === "tentative") {
|
|
1984
|
+
state.provisional = true;
|
|
1985
|
+
return null;
|
|
1986
|
+
}
|
|
1987
|
+
if (known !== void 0) return known === "none" ? null : known;
|
|
1988
|
+
const outer = state.provisional;
|
|
1989
|
+
state.provisional = false;
|
|
1990
|
+
state.depth += 1;
|
|
1991
|
+
cache.set(key, "deciding");
|
|
1992
|
+
let source;
|
|
1993
|
+
try {
|
|
1994
|
+
source = decide3();
|
|
1995
|
+
} catch (error) {
|
|
1996
|
+
cache.delete(key);
|
|
1997
|
+
state.depth = 0;
|
|
1998
|
+
state.provisional = false;
|
|
1999
|
+
state.tentative.length = 0;
|
|
2000
|
+
throw error;
|
|
2001
|
+
}
|
|
2002
|
+
state.depth -= 1;
|
|
2003
|
+
const tentative = source === null && state.provisional;
|
|
2004
|
+
if (tentative) {
|
|
2005
|
+
cache.set(key, "tentative");
|
|
2006
|
+
state.tentative.push((confirmed) => confirmed ? cache.set(key, "none") : cache.delete(key));
|
|
2007
|
+
} else {
|
|
2008
|
+
cache.set(key, source ?? "none");
|
|
2009
|
+
}
|
|
2010
|
+
state.provisional = outer || tentative;
|
|
2011
|
+
if (state.depth === 0) {
|
|
2012
|
+
for (const settle of state.tentative) settle(source === null);
|
|
2013
|
+
state.tentative.length = 0;
|
|
2014
|
+
state.provisional = false;
|
|
2015
|
+
}
|
|
2016
|
+
return source;
|
|
2017
|
+
}
|
|
2018
|
+
var MAX_TEXT2 = 80;
|
|
2019
|
+
function clip3(text, max = MAX_TEXT2) {
|
|
2020
|
+
const flat = text.replace(/\s+/g, " ");
|
|
2021
|
+
return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat;
|
|
2022
|
+
}
|
|
2023
|
+
function typeText2(context, type) {
|
|
2024
|
+
return clip3(context.checker.typeToString(type));
|
|
2025
|
+
}
|
|
2026
|
+
function isOpaque(ts, type) {
|
|
2027
|
+
return (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
|
|
2028
|
+
}
|
|
2029
|
+
function claimsNothing(ts, type) {
|
|
2030
|
+
const empty = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never | ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Null;
|
|
2031
|
+
const members2 = type.isUnion() ? type.types : [type];
|
|
2032
|
+
return members2.every((member) => (member.flags & empty) !== 0 || member.getCallSignatures().length > 0 || member.getConstructSignatures().length > 0);
|
|
2033
|
+
}
|
|
2034
|
+
function isUnitType(ts, type) {
|
|
2035
|
+
if (type.isUnion()) return false;
|
|
2036
|
+
const unit = ts.TypeFlags.StringLiteral | ts.TypeFlags.NumberLiteral | ts.TypeFlags.BigIntLiteral | ts.TypeFlags.BooleanLiteral | ts.TypeFlags.EnumLiteral | ts.TypeFlags.UniqueESSymbol;
|
|
2037
|
+
return (type.flags & unit) !== 0;
|
|
2038
|
+
}
|
|
2039
|
+
function isFixedByDeclaration(declaration, context) {
|
|
2040
|
+
const { ts, checker } = context;
|
|
2041
|
+
if (ts.isEnumMember(declaration) || ts.isEnumDeclaration(declaration)) return true;
|
|
2042
|
+
if (!ts.isVariableDeclaration(declaration) || !ts.isIdentifier(declaration.name)) return false;
|
|
2043
|
+
if (!(ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const)) return false;
|
|
2044
|
+
const symbol = checker.getSymbolAtLocation(declaration.name);
|
|
2045
|
+
return symbol !== void 0 && isUnitType(ts, checker.getTypeOfSymbol(symbol));
|
|
2046
|
+
}
|
|
2047
|
+
function isDiscarded(ts, type) {
|
|
2048
|
+
const members2 = type.isUnion() ? type.types : [type];
|
|
2049
|
+
return members2.some((member) => (member.flags & ts.TypeFlags.Void) !== 0);
|
|
2050
|
+
}
|
|
2051
|
+
function declarationOf(ts, checker, symbol) {
|
|
2052
|
+
const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
2053
|
+
return target?.valueDeclaration ?? target?.declarations?.[0];
|
|
2054
|
+
}
|
|
2055
|
+
function callTypeVerdict(node, context) {
|
|
2056
|
+
const { ts, policy } = context;
|
|
2057
|
+
const resolved = policy.calleeDeclaration(node);
|
|
2058
|
+
if (!resolved) return { kind: "unresolved" };
|
|
2059
|
+
const verdict = policy.typeVerdictOf(resolved.declaration);
|
|
2060
|
+
if (isMarkedValidator(ts, resolved.declaration)) return { kind: "validator", origin: verdict.origin };
|
|
2061
|
+
if (verdict.kind === "type-untrusted") return verdict;
|
|
2062
|
+
if (ts.isCallExpression(node) && picksOwnReturnType(node, context.claims)) return { kind: "caller-chosen-generic", origin: verdict.origin };
|
|
2063
|
+
return verdict;
|
|
2064
|
+
}
|
|
2065
|
+
function callSource(node, context) {
|
|
2066
|
+
const { ts } = context;
|
|
2067
|
+
if (node.expression.kind === ts.SyntaxKind.ImportKeyword || node.expression.kind === ts.SyntaxKind.SuperKeyword) return null;
|
|
2068
|
+
const verdict = callTypeVerdict(node, context);
|
|
2069
|
+
if (verdict.kind === "type-untrusted") return { entry: "return", origin: verdict.origin.origin };
|
|
2070
|
+
if (verdict.kind === "caller-chosen-generic") return { entry: "generic-return", origin: verdict.origin.origin };
|
|
2071
|
+
return null;
|
|
2072
|
+
}
|
|
2073
|
+
function contextualSignatureDeclaration(fn, context) {
|
|
2074
|
+
const { ts, checker } = context;
|
|
2075
|
+
const expected = checker.getContextualType(fn);
|
|
2076
|
+
if (!expected) return null;
|
|
2077
|
+
const members2 = expected.isUnion() ? expected.types : [expected];
|
|
2078
|
+
for (const member of members2) {
|
|
2079
|
+
for (const signature of member.getCallSignatures()) {
|
|
2080
|
+
const declaration = signature.getDeclaration();
|
|
2081
|
+
if (declaration && !ts.isJSDocSignature(declaration)) return declaration;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
return null;
|
|
2085
|
+
}
|
|
2086
|
+
function bindingRoot(ts, declaration) {
|
|
2087
|
+
let current = declaration;
|
|
2088
|
+
while (ts.isBindingElement(current)) current = current.parent.parent;
|
|
2089
|
+
return current;
|
|
2090
|
+
}
|
|
2091
|
+
function declaredNameSource(declaration, context) {
|
|
2092
|
+
const { ts, policy } = context;
|
|
2093
|
+
const root = bindingRoot(ts, declaration);
|
|
2094
|
+
if (ts.isParameter(root)) {
|
|
2095
|
+
if (policy.rules.untrustedCallbacks === "off") return null;
|
|
2096
|
+
const fn = root.parent;
|
|
2097
|
+
if (!ts.isArrowFunction(fn) && !ts.isFunctionExpression(fn)) return null;
|
|
2098
|
+
const signature = contextualSignatureDeclaration(fn, context);
|
|
2099
|
+
if (!signature) return null;
|
|
2100
|
+
const verdict2 = policy.typeVerdictOf(signature);
|
|
2101
|
+
return verdict2.kind === "type-untrusted" ? { entry: "parameter", origin: verdict2.origin.origin } : null;
|
|
2102
|
+
}
|
|
2103
|
+
if (!ts.isVariableDeclaration(root)) return null;
|
|
2104
|
+
if (ts.isCatchClause(root.parent)) return { entry: "catch", origin: CATCH_ORIGIN };
|
|
2105
|
+
if (policy.zones.zoneOf(root.getSourceFile().fileName) === "checked") {
|
|
2106
|
+
if (root.type) return null;
|
|
2107
|
+
return (root.initializer ? carriedSource(root.initializer, context) : null) ?? assignedSource(declaration, root, context);
|
|
2108
|
+
}
|
|
2109
|
+
if (isFixedByDeclaration(declaration, context)) return null;
|
|
2110
|
+
const verdict = policy.typeVerdictOf(root);
|
|
2111
|
+
return verdict.kind === "type-untrusted" ? { entry: "read", origin: verdict.origin.origin } : null;
|
|
2112
|
+
}
|
|
2113
|
+
function assignedSource(declaration, root, context) {
|
|
2114
|
+
const { ts, checker } = context;
|
|
2115
|
+
if (ts.getCombinedNodeFlags(root) & ts.NodeFlags.Const) return null;
|
|
2116
|
+
const name = ts.isVariableDeclaration(declaration) || ts.isBindingElement(declaration) ? declaration.name : void 0;
|
|
2117
|
+
const symbol = name && ts.isIdentifier(name) ? checker.getSymbolAtLocation(name) : void 0;
|
|
2118
|
+
if (!symbol) return null;
|
|
2119
|
+
return remember(context.assignedSources, symbol, context, () => {
|
|
2120
|
+
for (const value of assignmentsIn(root.getSourceFile(), context).get(symbol) ?? []) {
|
|
2121
|
+
const source = carriedSource(value, context);
|
|
2122
|
+
if (source) return source;
|
|
2123
|
+
}
|
|
2124
|
+
return null;
|
|
2125
|
+
});
|
|
2126
|
+
}
|
|
2127
|
+
function assignmentsIn(file, context) {
|
|
2128
|
+
const { ts, checker } = context;
|
|
2129
|
+
const known = context.assignments.get(file);
|
|
2130
|
+
if (known) return known;
|
|
2131
|
+
const assigned = /* @__PURE__ */ new Map();
|
|
2132
|
+
const add = (symbol, value) => {
|
|
2133
|
+
if (!symbol) return;
|
|
2134
|
+
const values = assigned.get(symbol);
|
|
2135
|
+
if (values) values.push(value);
|
|
2136
|
+
else assigned.set(symbol, [value]);
|
|
2137
|
+
};
|
|
2138
|
+
const targets = (target, value) => {
|
|
2139
|
+
let inner = target;
|
|
2140
|
+
while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner)) inner = inner.expression;
|
|
2141
|
+
if (ts.isIdentifier(inner)) {
|
|
2142
|
+
add(checker.getSymbolAtLocation(inner), value);
|
|
2143
|
+
} else if (ts.isBinaryExpression(inner) && inner.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
|
|
2144
|
+
targets(inner.left, value);
|
|
2145
|
+
} else if (ts.isSpreadElement(inner)) {
|
|
2146
|
+
targets(inner.expression, value);
|
|
2147
|
+
} else if (ts.isArrayLiteralExpression(inner)) {
|
|
2148
|
+
for (const element of inner.elements) if (!ts.isOmittedExpression(element)) targets(element, value);
|
|
2149
|
+
} else if (ts.isObjectLiteralExpression(inner)) {
|
|
2150
|
+
for (const property of inner.properties) {
|
|
2151
|
+
if (ts.isPropertyAssignment(property)) targets(property.initializer, value);
|
|
2152
|
+
else if (ts.isSpreadAssignment(property)) targets(property.expression, value);
|
|
2153
|
+
else if (ts.isShorthandPropertyAssignment(property)) {
|
|
2154
|
+
const symbol = checker.getShorthandAssignmentValueSymbol(property);
|
|
2155
|
+
add(symbol, value);
|
|
2156
|
+
if (property.objectAssignmentInitializer) add(symbol, property.objectAssignmentInitializer);
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
};
|
|
2161
|
+
const { assignment } = operatorSets(ts);
|
|
2162
|
+
const visit = (node) => {
|
|
2163
|
+
if (ts.isBinaryExpression(node) && assignment.has(node.operatorToken.kind)) targets(node.left, node.right);
|
|
2164
|
+
ts.forEachChild(node, visit);
|
|
2165
|
+
};
|
|
2166
|
+
visit(file);
|
|
2167
|
+
context.assignments.set(file, assigned);
|
|
2168
|
+
return assigned;
|
|
2169
|
+
}
|
|
2170
|
+
function identifierSource(node, context) {
|
|
2171
|
+
const { ts, checker } = context;
|
|
2172
|
+
const symbol = ts.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
2173
|
+
const declaration = declarationOf(ts, checker, symbol);
|
|
2174
|
+
return declaration ? declaredNameSource(declaration, context) : null;
|
|
2175
|
+
}
|
|
2176
|
+
function accessSource(node, context) {
|
|
2177
|
+
const { ts, checker, policy } = context;
|
|
2178
|
+
const name = ts.isPropertyAccessExpression(node) ? node.name : node.argumentExpression;
|
|
2179
|
+
const named = ts.isPropertyAccessExpression(node) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name);
|
|
2180
|
+
const declaration = named ? declarationOf(ts, checker, checker.getSymbolAtLocation(name)) : void 0;
|
|
2181
|
+
if (!declaration) return carriedSource(node.expression, context);
|
|
2182
|
+
if (isFixedByDeclaration(declaration, context)) return null;
|
|
2183
|
+
const verdict = policy.typeVerdictOf(declaration);
|
|
2184
|
+
return verdict.kind === "type-untrusted" ? { entry: "read", origin: verdict.origin.origin } : null;
|
|
2185
|
+
}
|
|
2186
|
+
var BUILT_IN_GUARDS = /* @__PURE__ */ new Set(["js:Array.isArray"]);
|
|
2187
|
+
function guardCallOf(call, context) {
|
|
2188
|
+
const { ts, checker, policy } = context;
|
|
2189
|
+
if (call.expression.kind === ts.SyntaxKind.ImportKeyword || call.expression.kind === ts.SyntaxKind.SuperKeyword) return null;
|
|
2190
|
+
const signature = checker.getResolvedSignature(call);
|
|
2191
|
+
const predicate = signature ? checker.getTypePredicateOfSignature(signature) : void 0;
|
|
2192
|
+
const declaration = signature?.getDeclaration();
|
|
2193
|
+
if (!predicate || !declaration) return null;
|
|
2194
|
+
let argument;
|
|
2195
|
+
if (predicate.kind === ts.TypePredicateKind.Identifier || predicate.kind === ts.TypePredicateKind.AssertsIdentifier) {
|
|
2196
|
+
argument = call.arguments[predicate.parameterIndex];
|
|
2197
|
+
} else {
|
|
2198
|
+
let callee = call.expression;
|
|
2199
|
+
while (ts.isParenthesizedExpression(callee) || ts.isNonNullExpression(callee)) callee = callee.expression;
|
|
2200
|
+
argument = ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee) ? callee.expression : void 0;
|
|
2201
|
+
}
|
|
2202
|
+
if (!argument || ts.isSpreadElement(argument)) return null;
|
|
2203
|
+
const typeVerdict = policy.typeVerdictOf(declaration);
|
|
2204
|
+
const verdict = isMarkedValidator(ts, declaration) ? { kind: "validator", origin: typeVerdict.origin } : BUILT_IN_GUARDS.has(typeVerdict.origin.origin) ? { kind: "built-in", origin: typeVerdict.origin } : typeVerdict;
|
|
2205
|
+
const asserts = predicate.kind === ts.TypePredicateKind.AssertsIdentifier || predicate.kind === ts.TypePredicateKind.AssertsThis;
|
|
2206
|
+
return { call, argument, asserts, predicate: clip3(checker.typePredicateToString(predicate)), verdict };
|
|
2207
|
+
}
|
|
2208
|
+
function referenceKey(ts, node) {
|
|
2209
|
+
let inner = node;
|
|
2210
|
+
while (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner)) inner = inner.expression;
|
|
2211
|
+
if (ts.isIdentifier(inner)) return inner.text;
|
|
2212
|
+
if (inner.kind === ts.SyntaxKind.ThisKeyword) return "this";
|
|
2213
|
+
if (ts.isPropertyAccessExpression(inner)) {
|
|
2214
|
+
const object = referenceKey(ts, inner.expression);
|
|
2215
|
+
return object === null ? null : `${object}.${inner.name.text}`;
|
|
2216
|
+
}
|
|
2217
|
+
if (ts.isElementAccessExpression(inner) && (ts.isStringLiteralLike(inner.argumentExpression) || ts.isNumericLiteral(inner.argumentExpression))) {
|
|
2218
|
+
const object = referenceKey(ts, inner.expression);
|
|
2219
|
+
return object === null ? null : `${object}.${inner.argumentExpression.text}`;
|
|
2220
|
+
}
|
|
2221
|
+
return null;
|
|
2222
|
+
}
|
|
2223
|
+
function referenceRoot(node, context) {
|
|
2224
|
+
const { ts, checker } = context;
|
|
2225
|
+
let inner = node;
|
|
2226
|
+
for (; ; ) {
|
|
2227
|
+
if (ts.isParenthesizedExpression(inner) || ts.isNonNullExpression(inner) || ts.isPropertyAccessExpression(inner) || ts.isElementAccessExpression(inner)) {
|
|
2228
|
+
inner = inner.expression;
|
|
2229
|
+
} else {
|
|
2230
|
+
break;
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
if (!ts.isIdentifier(inner)) return void 0;
|
|
2234
|
+
return ts.isShorthandPropertyAssignment(inner.parent) ? checker.getShorthandAssignmentValueSymbol(inner.parent) : checker.getSymbolAtLocation(inner);
|
|
2235
|
+
}
|
|
2236
|
+
function guardsIn(file, context) {
|
|
2237
|
+
const { ts } = context;
|
|
2238
|
+
const known = context.guards.get(file);
|
|
2239
|
+
if (known) return known;
|
|
2240
|
+
const guards = /* @__PURE__ */ new Map();
|
|
2241
|
+
const visit = (node) => {
|
|
2242
|
+
if (ts.isCallExpression(node)) {
|
|
2243
|
+
const guard = guardCallOf(node, context);
|
|
2244
|
+
const key = guard ? referenceKey(ts, guard.argument) : null;
|
|
2245
|
+
if (guard && key !== null) {
|
|
2246
|
+
const list = guards.get(key);
|
|
2247
|
+
if (list) list.push(guard);
|
|
2248
|
+
else guards.set(key, [guard]);
|
|
2249
|
+
}
|
|
2250
|
+
}
|
|
2251
|
+
ts.forEachChild(node, visit);
|
|
2252
|
+
};
|
|
2253
|
+
visit(file);
|
|
2254
|
+
context.guards.set(file, guards);
|
|
2255
|
+
return guards;
|
|
2256
|
+
}
|
|
2257
|
+
function holdsWhen(condition, outcome, call, ts) {
|
|
2258
|
+
let inner = condition;
|
|
2259
|
+
while (ts.isParenthesizedExpression(inner)) inner = inner.expression;
|
|
2260
|
+
if (inner === call) return outcome;
|
|
2261
|
+
if (ts.isPrefixUnaryExpression(inner) && inner.operator === ts.SyntaxKind.ExclamationToken) return holdsWhen(inner.operand, !outcome, call, ts);
|
|
2262
|
+
if (ts.isBinaryExpression(inner)) {
|
|
2263
|
+
const kind = inner.operatorToken.kind;
|
|
2264
|
+
if (kind === ts.SyntaxKind.AmpersandAmpersandToken && outcome) return holdsWhen(inner.left, true, call, ts) || holdsWhen(inner.right, true, call, ts);
|
|
2265
|
+
if (kind === ts.SyntaxKind.BarBarToken && !outcome) return holdsWhen(inner.left, false, call, ts) || holdsWhen(inner.right, false, call, ts);
|
|
2266
|
+
}
|
|
2267
|
+
return false;
|
|
2268
|
+
}
|
|
2269
|
+
function exits(statement, ts) {
|
|
2270
|
+
if (ts.isReturnStatement(statement) || ts.isThrowStatement(statement) || ts.isBreakStatement(statement) || ts.isContinueStatement(statement)) return true;
|
|
2271
|
+
if (ts.isBlock(statement)) return statement.statements.length > 0 && exits(statement.statements[statement.statements.length - 1], ts);
|
|
2272
|
+
if (ts.isIfStatement(statement)) return statement.elseStatement !== void 0 && exits(statement.thenStatement, ts) && exits(statement.elseStatement, ts);
|
|
2273
|
+
return false;
|
|
2274
|
+
}
|
|
2275
|
+
function statementsBefore(parent, child, ts) {
|
|
2276
|
+
const list = ts.isBlock(parent) || ts.isSourceFile(parent) || ts.isModuleBlock(parent) || ts.isCaseClause(parent) || ts.isDefaultClause(parent) ? parent.statements : void 0;
|
|
2277
|
+
if (!list) return [];
|
|
2278
|
+
const index = list.indexOf(child);
|
|
2279
|
+
return index > 0 ? list.slice(0, index) : [];
|
|
2280
|
+
}
|
|
2281
|
+
function guardHolds(guard, node, ts) {
|
|
2282
|
+
const { call } = guard;
|
|
2283
|
+
for (let child = node, parent = node.parent; parent; child = parent, parent = parent.parent) {
|
|
2284
|
+
if (!guard.asserts) {
|
|
2285
|
+
if (ts.isIfStatement(parent) && child !== parent.expression && holdsWhen(parent.expression, child === parent.thenStatement, call, ts)) return true;
|
|
2286
|
+
if (ts.isConditionalExpression(parent) && child !== parent.condition && holdsWhen(parent.condition, child === parent.whenTrue, call, ts)) return true;
|
|
2287
|
+
if (ts.isBinaryExpression(parent) && child === parent.right) {
|
|
2288
|
+
const kind = parent.operatorToken.kind;
|
|
2289
|
+
if (kind === ts.SyntaxKind.AmpersandAmpersandToken && holdsWhen(parent.left, true, call, ts)) return true;
|
|
2290
|
+
if (kind === ts.SyntaxKind.BarBarToken && holdsWhen(parent.left, false, call, ts)) return true;
|
|
2291
|
+
}
|
|
2292
|
+
if (ts.isWhileStatement(parent) && child === parent.statement && holdsWhen(parent.expression, true, call, ts)) return true;
|
|
2293
|
+
if (ts.isForStatement(parent) && (child === parent.statement || child === parent.incrementor) && parent.condition && holdsWhen(parent.condition, true, call, ts)) {
|
|
2294
|
+
return true;
|
|
2295
|
+
}
|
|
2296
|
+
}
|
|
2297
|
+
for (const before of statementsBefore(parent, child, ts)) {
|
|
2298
|
+
if (guard.asserts) {
|
|
2299
|
+
let expression = ts.isExpressionStatement(before) ? before.expression : void 0;
|
|
2300
|
+
while (expression && (ts.isParenthesizedExpression(expression) || ts.isAwaitExpression(expression))) expression = expression.expression;
|
|
2301
|
+
if (expression === call) return true;
|
|
2302
|
+
} else if (ts.isIfStatement(before)) {
|
|
2303
|
+
const thenExits = exits(before.thenStatement, ts);
|
|
2304
|
+
const elseExits = before.elseStatement !== void 0 && exits(before.elseStatement, ts);
|
|
2305
|
+
if (thenExits && !elseExits && holdsWhen(before.expression, false, call, ts)) return true;
|
|
2306
|
+
if (elseExits && !thenExits && holdsWhen(before.expression, true, call, ts)) return true;
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
return false;
|
|
2311
|
+
}
|
|
2312
|
+
function guardSource(node, context) {
|
|
2313
|
+
const { ts, checker } = context;
|
|
2314
|
+
const key = referenceKey(ts, node);
|
|
2315
|
+
if (key === null) return null;
|
|
2316
|
+
const candidates = guardsIn(node.getSourceFile(), context).get(key);
|
|
2317
|
+
if (!candidates) return null;
|
|
2318
|
+
if (checker.getTypeAtLocation(node) === declaredType(node, context)) return null;
|
|
2319
|
+
const root = referenceRoot(node, context);
|
|
2320
|
+
for (const guard of candidates) {
|
|
2321
|
+
if (guard.verdict.kind !== "type-untrusted" || referenceRoot(guard.argument, context) !== root) continue;
|
|
2322
|
+
if (guard.argument === node || !guardHolds(guard, node, ts)) continue;
|
|
2323
|
+
return { entry: "guard", origin: guard.verdict.origin.origin };
|
|
2324
|
+
}
|
|
2325
|
+
return null;
|
|
2326
|
+
}
|
|
2327
|
+
function withGuard(node, source, context) {
|
|
2328
|
+
if (source && !claimsNothing(context.ts, declaredType(node, context))) return source;
|
|
2329
|
+
return guardSource(node, context) ?? source;
|
|
2330
|
+
}
|
|
2331
|
+
function decideSource(node, context) {
|
|
2332
|
+
const { ts } = context;
|
|
2333
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) return callSource(node, context);
|
|
2334
|
+
if (ts.isIdentifier(node)) return isValueUse(ts, node) ? withGuard(node, identifierSource(node, context), context) : null;
|
|
2335
|
+
if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) return ts.isPartOfTypeNode(node) ? null : withGuard(node, accessSource(node, context), context);
|
|
2336
|
+
return null;
|
|
2337
|
+
}
|
|
2338
|
+
function untrustedSourceOf(node, context) {
|
|
2339
|
+
return remember(context.sources, node, context, () => decideSource(node, context));
|
|
2340
|
+
}
|
|
2341
|
+
function isTransparent(ts, node) {
|
|
2342
|
+
return ts.isParenthesizedExpression(node) || ts.isNonNullExpression(node) || ts.isAwaitExpression(node) || ts.isAssertionExpression(node) || ts.isSatisfiesExpression(node);
|
|
2343
|
+
}
|
|
2344
|
+
function isOutsideBinding(node, context) {
|
|
2345
|
+
const { ts, checker, policy } = context;
|
|
2346
|
+
let inner = node;
|
|
2347
|
+
while (isTransparent(ts, inner)) inner = inner.expression;
|
|
2348
|
+
if (!ts.isIdentifier(inner)) return false;
|
|
2349
|
+
const declaration = declarationOf(ts, checker, checker.getSymbolAtLocation(inner));
|
|
2350
|
+
if (!declaration || !ts.isVariableDeclaration(declaration) || ts.isCatchClause(declaration.parent)) return false;
|
|
2351
|
+
return policy.zones.zoneOf(declaration.getSourceFile().fileName) !== "checked";
|
|
2352
|
+
}
|
|
2353
|
+
function isValueLogical(ts, kind) {
|
|
2354
|
+
return kind === ts.SyntaxKind.BarBarToken || kind === ts.SyntaxKind.QuestionQuestionToken || kind === ts.SyntaxKind.AmpersandAmpersandToken;
|
|
2355
|
+
}
|
|
2356
|
+
function carriedSource(expression, context) {
|
|
2357
|
+
const { ts } = context;
|
|
2358
|
+
if (isTransparent(ts, expression)) return carriedSource(expression.expression, context);
|
|
2359
|
+
if (ts.isConditionalExpression(expression)) return carriedSource(expression.whenTrue, context) ?? carriedSource(expression.whenFalse, context);
|
|
2360
|
+
if (ts.isBinaryExpression(expression)) {
|
|
2361
|
+
const kind = expression.operatorToken.kind;
|
|
2362
|
+
if (isValueLogical(ts, kind)) return carriedSource(expression.left, context) ?? carriedSource(expression.right, context);
|
|
2363
|
+
if (kind === ts.SyntaxKind.CommaToken || kind === ts.SyntaxKind.EqualsToken) return carriedSource(expression.right, context);
|
|
2364
|
+
if (operatorSets(ts).assignment.has(kind)) return carriedSource(expression.left, context) ?? carriedSource(expression.right, context);
|
|
2365
|
+
}
|
|
2366
|
+
return untrustedSourceOf(expression, context);
|
|
2367
|
+
}
|
|
2368
|
+
var EQUALITY = /* @__PURE__ */ new Set();
|
|
2369
|
+
var ASSIGNMENT = /* @__PURE__ */ new Set();
|
|
2370
|
+
function operatorSets(ts) {
|
|
2371
|
+
if (EQUALITY.size === 0) {
|
|
2372
|
+
for (const kind of [
|
|
2373
|
+
ts.SyntaxKind.EqualsEqualsEqualsToken,
|
|
2374
|
+
ts.SyntaxKind.ExclamationEqualsEqualsToken,
|
|
2375
|
+
ts.SyntaxKind.EqualsEqualsToken,
|
|
2376
|
+
ts.SyntaxKind.ExclamationEqualsToken
|
|
2377
|
+
]) {
|
|
2378
|
+
EQUALITY.add(kind);
|
|
2379
|
+
}
|
|
2380
|
+
for (const kind of [
|
|
2381
|
+
ts.SyntaxKind.EqualsToken,
|
|
2382
|
+
ts.SyntaxKind.BarBarEqualsToken,
|
|
2383
|
+
ts.SyntaxKind.AmpersandAmpersandEqualsToken,
|
|
2384
|
+
ts.SyntaxKind.QuestionQuestionEqualsToken
|
|
2385
|
+
]) {
|
|
2386
|
+
ASSIGNMENT.add(kind);
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
return { equality: EQUALITY, assignment: ASSIGNMENT };
|
|
2390
|
+
}
|
|
2391
|
+
function isArrayIsArray(call, context) {
|
|
2392
|
+
const resolved = context.ts.isCallExpression(call) ? context.policy.calleeDeclaration(call) : null;
|
|
2393
|
+
return resolved !== null && context.policy.origins.originOf(resolved.declaration).origin === "js:Array.isArray";
|
|
2394
|
+
}
|
|
2395
|
+
function isValidatorCall(call, context) {
|
|
2396
|
+
const resolved = context.policy.calleeDeclaration(call);
|
|
2397
|
+
return resolved !== null && isMarkedValidator(context.ts, resolved.declaration);
|
|
2398
|
+
}
|
|
2399
|
+
function isDestructuringTarget(ts, node) {
|
|
2400
|
+
let current = node;
|
|
2401
|
+
let inPattern = false;
|
|
2402
|
+
for (; ; ) {
|
|
2403
|
+
const parent = current.parent;
|
|
2404
|
+
if (ts.isParenthesizedExpression(parent) || ts.isSpreadElement(parent) || ts.isSpreadAssignment(parent)) {
|
|
2405
|
+
current = parent;
|
|
2406
|
+
} else if (ts.isArrayLiteralExpression(parent)) {
|
|
2407
|
+
current = parent;
|
|
2408
|
+
inPattern = true;
|
|
2409
|
+
} else if (ts.isPropertyAssignment(parent) && parent.initializer === current || ts.isShorthandPropertyAssignment(parent) && parent.name === current) {
|
|
2410
|
+
current = parent.parent;
|
|
2411
|
+
inPattern = true;
|
|
2412
|
+
} else if (inPattern && ts.isBinaryExpression(parent) && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken && parent.left === current) {
|
|
2413
|
+
return true;
|
|
2414
|
+
} else {
|
|
2415
|
+
return inPattern && (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.initializer === current;
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
function useOf(top, context, inLiteral) {
|
|
2420
|
+
const { ts, checker } = context;
|
|
2421
|
+
const parent = top.parent;
|
|
2422
|
+
const { equality, assignment } = operatorSets(ts);
|
|
2423
|
+
const ownType = () => typeText2(context, checker.getTypeAtLocation(top));
|
|
2424
|
+
if (isTransparent(ts, parent)) return useOf(parent, context, inLiteral);
|
|
2425
|
+
if (isDestructuringTarget(ts, top)) return null;
|
|
2426
|
+
if (ts.isExpressionStatement(parent) || ts.isVoidExpression(parent) || ts.isTypeOfExpression(parent) || ts.isDeleteExpression(parent)) return null;
|
|
2427
|
+
if (ts.isThrowStatement(parent) || ts.isSwitchStatement(parent) || ts.isCaseClause(parent)) return null;
|
|
2428
|
+
if (ts.isIfStatement(parent) || ts.isWhileStatement(parent) || ts.isDoStatement(parent)) return null;
|
|
2429
|
+
if (ts.isForStatement(parent)) return parent.condition === top ? null : "used in a loop header";
|
|
2430
|
+
if (ts.isPrefixUnaryExpression(parent)) return parent.operator === ts.SyntaxKind.ExclamationToken ? null : "used in an operation";
|
|
2431
|
+
if (ts.isConditionalExpression(parent)) return parent.condition === top ? null : useOf(parent, context, inLiteral);
|
|
2432
|
+
if (ts.isBinaryExpression(parent)) {
|
|
2433
|
+
const kind = parent.operatorToken.kind;
|
|
2434
|
+
if (equality.has(kind)) return null;
|
|
2435
|
+
if (kind === ts.SyntaxKind.InstanceOfKeyword) return parent.left === top ? null : "used as a constructor";
|
|
2436
|
+
if (kind === ts.SyntaxKind.InKeyword) return parent.right === top ? null : "used as a key";
|
|
2437
|
+
if (kind === ts.SyntaxKind.CommaToken) return parent.left === top ? null : useOf(parent, context, inLiteral);
|
|
2438
|
+
if (isValueLogical(ts, kind)) return useOf(parent, context, inLiteral);
|
|
2439
|
+
if (assignment.has(kind)) {
|
|
2440
|
+
if (parent.left === top) return null;
|
|
2441
|
+
const target = checker.getTypeAtLocation(parent.left);
|
|
2442
|
+
return isOpaque(ts, target) ? null : `assigned to "${typeText2(context, target)}"`;
|
|
2443
|
+
}
|
|
2444
|
+
return "used in an operation";
|
|
2445
|
+
}
|
|
2446
|
+
if (ts.isCallExpression(parent) || ts.isNewExpression(parent)) {
|
|
2447
|
+
if (parent.expression === top) return "called";
|
|
2448
|
+
if (isValidatorCall(parent, context) || isArrayIsArray(parent, context)) return null;
|
|
2449
|
+
const expected = checker.getContextualType(top);
|
|
2450
|
+
if (!expected) return "passed as an argument";
|
|
2451
|
+
return isOpaque(ts, expected) ? null : `passed where "${typeText2(context, expected)}" is expected`;
|
|
2452
|
+
}
|
|
2453
|
+
if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) {
|
|
2454
|
+
if (parent.expression !== top) return "used as a key";
|
|
2455
|
+
if (untrustedSourceOf(parent, context)) return null;
|
|
2456
|
+
if (isOutsideBinding(top, context)) return null;
|
|
2457
|
+
const member = ts.isPropertyAccessExpression(parent) ? parent.name.text : clip3(parent.argumentExpression.getText(), 40);
|
|
2458
|
+
return `read through its member "${member}"`;
|
|
2459
|
+
}
|
|
2460
|
+
if (ts.isVariableDeclaration(parent) || ts.isParameter(parent) || ts.isPropertyDeclaration(parent) || ts.isBindingElement(parent)) {
|
|
2461
|
+
if (parent.initializer !== top) return `used as "${ownType()}"`;
|
|
2462
|
+
if (ts.isVariableDeclaration(parent) && !parent.type) return inLiteral ? "stored in a value whose type is inferred" : null;
|
|
2463
|
+
const declared = checker.getTypeAtLocation(parent.name);
|
|
2464
|
+
return isOpaque(ts, declared) ? null : `stored as "${typeText2(context, declared)}"`;
|
|
2465
|
+
}
|
|
2466
|
+
if (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isArrayLiteralExpression(parent)) {
|
|
2467
|
+
const expected = checker.getContextualType(top);
|
|
2468
|
+
if (expected) return isOpaque(ts, expected) ? null : `stored where "${typeText2(context, expected)}" is expected`;
|
|
2469
|
+
const literal = ts.isArrayLiteralExpression(parent) ? parent : parent.parent;
|
|
2470
|
+
return useOf(literal, context, true);
|
|
2471
|
+
}
|
|
2472
|
+
if (ts.isReturnStatement(parent) || ts.isYieldExpression(parent) || ts.isArrowFunction(parent) && parent.body === top) {
|
|
2473
|
+
const expected = checker.getContextualType(top);
|
|
2474
|
+
if (expected && (isOpaque(ts, expected) || isDiscarded(ts, expected))) return null;
|
|
2475
|
+
return `returned as "${expected ? typeText2(context, expected) : ownType()}"`;
|
|
2476
|
+
}
|
|
2477
|
+
if (ts.isSpreadElement(parent) || ts.isSpreadAssignment(parent)) return "spread";
|
|
2478
|
+
if (ts.isForOfStatement(parent) || ts.isForInStatement(parent)) return parent.expression === top ? "iterated" : null;
|
|
2479
|
+
if (ts.isTemplateSpan(parent)) return "used in a template";
|
|
2480
|
+
if (ts.isPostfixUnaryExpression(parent)) return "used in an operation";
|
|
2481
|
+
return `used as "${ownType()}"`;
|
|
2482
|
+
}
|
|
2483
|
+
function withWrappers(ts, node) {
|
|
2484
|
+
let top = node;
|
|
2485
|
+
while (isTransparent(ts, top.parent)) top = top.parent;
|
|
2486
|
+
return top;
|
|
2487
|
+
}
|
|
2488
|
+
function declaredType(node, context) {
|
|
2489
|
+
const { ts, checker } = context;
|
|
2490
|
+
let symbol;
|
|
2491
|
+
if (ts.isIdentifier(node)) {
|
|
2492
|
+
symbol = ts.isShorthandPropertyAssignment(node.parent) ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
2493
|
+
} else if (ts.isPropertyAccessExpression(node)) {
|
|
2494
|
+
symbol = checker.getSymbolAtLocation(node.name);
|
|
2495
|
+
}
|
|
2496
|
+
const named = ts.SymbolFlags.Variable | ts.SymbolFlags.Property | ts.SymbolFlags.Accessor | ts.SymbolFlags.Alias;
|
|
2497
|
+
if (!symbol || !(symbol.flags & named)) return checker.getTypeAtLocation(node);
|
|
2498
|
+
const declared = checker.getTypeOfSymbol(symbol);
|
|
2499
|
+
const declaration = symbol.valueDeclaration;
|
|
2500
|
+
if (declared.flags & ts.TypeFlags.Any && declaration && ts.isVariableDeclaration(declaration) && !declaration.type) return checker.getTypeAtLocation(node);
|
|
2501
|
+
return declared;
|
|
2502
|
+
}
|
|
2503
|
+
function decideValue(node, context) {
|
|
2504
|
+
const { ts, checker } = context;
|
|
2505
|
+
const source = untrustedSourceOf(node, context);
|
|
2506
|
+
if (!source) return null;
|
|
2507
|
+
const top = withWrappers(ts, node);
|
|
2508
|
+
const type = checker.getTypeAtLocation(top);
|
|
2509
|
+
const value = { node, entry: source.entry, origin: source.origin, type: typeText2(context, type) };
|
|
2510
|
+
const declaredNothing = source.entry !== "guard" && claimsNothing(ts, declaredType(node, context));
|
|
2511
|
+
if (declaredNothing || claimsNothing(ts, type)) return { ...value, outcome: "no-claim", use: null };
|
|
2512
|
+
if (isInsideValidator(ts, node)) return { ...value, outcome: "validator", use: null };
|
|
2513
|
+
const use = useOf(node, context, false);
|
|
2514
|
+
return use === null ? { ...value, outcome: "allowed", use: null } : { ...value, outcome: "finding", use };
|
|
2515
|
+
}
|
|
2516
|
+
function untrustedValueAt(node, context) {
|
|
2517
|
+
return decideValue(node, context);
|
|
2518
|
+
}
|
|
2519
|
+
function untrustedValuesIn(root, context) {
|
|
2520
|
+
const values = [];
|
|
2521
|
+
const visit = (node) => {
|
|
2522
|
+
const value = untrustedValueAt(node, context);
|
|
2523
|
+
if (value) values.push(value);
|
|
2524
|
+
context.ts.forEachChild(node, visit);
|
|
2525
|
+
};
|
|
2526
|
+
visit(root);
|
|
2527
|
+
return values;
|
|
2528
|
+
}
|
|
2529
|
+
var MAX_HOPS = 8;
|
|
2530
|
+
function isInChecked(node, context) {
|
|
2531
|
+
return context.policy.zones.zoneOf(node.getSourceFile().fileName) === "checked";
|
|
2532
|
+
}
|
|
2533
|
+
function isBindCall(call, context) {
|
|
2534
|
+
const { ts, policy } = context;
|
|
2535
|
+
if (!ts.isPropertyAccessExpression(call.expression) || call.expression.name.text !== "bind") return false;
|
|
2536
|
+
const resolved = policy.calleeDeclaration(call);
|
|
2537
|
+
return resolved !== null && /^js:(Callable|Newable)?Function\.bind$/.test(policy.origins.originOf(resolved.declaration).origin);
|
|
2538
|
+
}
|
|
2539
|
+
function functionsOfSymbol(symbol, context, bound, hops) {
|
|
2540
|
+
const { ts, checker } = context;
|
|
2541
|
+
const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
|
|
2542
|
+
return (target?.declarations ?? []).flatMap((declaration) => functionsOfDeclaration(declaration, context, bound, hops));
|
|
2543
|
+
}
|
|
2544
|
+
function functionsOfDeclaration(declaration, context, bound, hops) {
|
|
2545
|
+
const { ts, checker } = context;
|
|
2546
|
+
if (hops > MAX_HOPS || !isInChecked(declaration, context)) return [];
|
|
2547
|
+
if (ts.isFunctionDeclaration(declaration) || ts.isMethodDeclaration(declaration)) return declaration.body ? [{ fn: declaration, bound }] : [];
|
|
2548
|
+
if (ts.isVariableDeclaration(declaration)) {
|
|
2549
|
+
const isConst = (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) !== 0;
|
|
2550
|
+
return isConst && declaration.initializer ? functionsOfExpression(declaration.initializer, context, bound, true, hops + 1) : [];
|
|
2551
|
+
}
|
|
2552
|
+
if (ts.isPropertyDeclaration(declaration) || ts.isPropertyAssignment(declaration)) {
|
|
2553
|
+
return declaration.initializer ? functionsOfExpression(declaration.initializer, context, bound, true, hops + 1) : [];
|
|
2554
|
+
}
|
|
2555
|
+
if (ts.isShorthandPropertyAssignment(declaration)) return functionsOfSymbol(checker.getShorthandAssignmentValueSymbol(declaration), context, bound, hops + 1);
|
|
2556
|
+
return [];
|
|
2557
|
+
}
|
|
2558
|
+
function functionsOfExpression(expression, context, bound, inline, hops) {
|
|
2559
|
+
const { ts, checker } = context;
|
|
2560
|
+
let inner = expression;
|
|
2561
|
+
while (isTransparent(ts, inner)) inner = inner.expression;
|
|
2562
|
+
if (ts.isArrowFunction(inner) || ts.isFunctionExpression(inner)) return inline ? [{ fn: inner, bound }] : [];
|
|
2563
|
+
if (hops > MAX_HOPS) return [];
|
|
2564
|
+
if (ts.isIdentifier(inner)) return functionsOfSymbol(checker.getSymbolAtLocation(inner), context, bound, hops + 1);
|
|
2565
|
+
if (ts.isPropertyAccessExpression(inner)) return functionsOfSymbol(checker.getSymbolAtLocation(inner.name), context, bound, hops + 1);
|
|
2566
|
+
if (ts.isCallExpression(inner) && isBindCall(inner, context)) {
|
|
2567
|
+
return functionsOfExpression(inner.expression.expression, context, bound + Math.max(0, inner.arguments.length - 1), true, hops + 1);
|
|
2568
|
+
}
|
|
2569
|
+
return [];
|
|
2570
|
+
}
|
|
2571
|
+
function functionsOfMember(member, context) {
|
|
2572
|
+
return (member?.declarations ?? []).flatMap((declaration) => functionsOfDeclaration(declaration, context, 0, 0));
|
|
2573
|
+
}
|
|
2574
|
+
function passedCount(ts, signature) {
|
|
2575
|
+
const declaration = signature.getDeclaration();
|
|
2576
|
+
const rest = declaration !== void 0 && !ts.isJSDocSignature(declaration) && declaration.parameters.some((parameter) => parameter.dotDotDotToken);
|
|
2577
|
+
return rest ? Number.POSITIVE_INFINITY : signature.getParameters().length;
|
|
2578
|
+
}
|
|
2579
|
+
function parameterType2(parameter, context) {
|
|
2580
|
+
const { ts, checker } = context;
|
|
2581
|
+
const type = checker.getTypeAtLocation(parameter.name);
|
|
2582
|
+
if (!(type.flags & ts.TypeFlags.TypeParameter)) return type;
|
|
2583
|
+
return checker.getBaseConstraintOfType(type) ?? null;
|
|
2584
|
+
}
|
|
2585
|
+
function callbackName(fn, context) {
|
|
2586
|
+
const { ts } = context;
|
|
2587
|
+
const holder = ts.isArrowFunction(fn) || ts.isFunctionExpression(fn) && !fn.name ? fn.parent : fn;
|
|
2588
|
+
const name = ts.isVariableDeclaration(holder) || ts.isPropertyDeclaration(holder) || ts.isPropertyAssignment(holder) || ts.isFunctionLike(holder) ? holder.name : void 0;
|
|
2589
|
+
if (!name) return "callback";
|
|
2590
|
+
const text = clip3(name.getText(), 40);
|
|
2591
|
+
const owner = holder.parent;
|
|
2592
|
+
return (ts.isMethodDeclaration(holder) || ts.isPropertyDeclaration(holder)) && ts.isClassLike(owner) && owner.name ? `${owner.name.text}.${text}` : text;
|
|
2593
|
+
}
|
|
2594
|
+
function handoffsOf(handed, expected, origin, node, context) {
|
|
2595
|
+
const { ts, policy } = context;
|
|
2596
|
+
const { fn, bound } = handed;
|
|
2597
|
+
if (isMarkedValidator(ts, fn)) return [];
|
|
2598
|
+
if (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) {
|
|
2599
|
+
const signature = contextualSignatureDeclaration(fn, context);
|
|
2600
|
+
if (signature && policy.typeVerdictOf(signature).kind === "type-untrusted") return [];
|
|
2601
|
+
}
|
|
2602
|
+
const parameters = fn.parameters.filter((parameter) => !(ts.isIdentifier(parameter.name) && parameter.name.text === "this")).slice(bound);
|
|
2603
|
+
const passed = passedCount(ts, expected);
|
|
2604
|
+
const found = [];
|
|
2605
|
+
parameters.forEach((parameter, index) => {
|
|
2606
|
+
if (index >= passed) return;
|
|
2607
|
+
const type = parameterType2(parameter, context);
|
|
2608
|
+
if (!type || claimsNothing(ts, type)) return;
|
|
2609
|
+
found.push({ node, origin, callback: callbackName(fn, context), parameter: clip3(parameter.name.getText(), 40), type: typeText2(context, type) });
|
|
2610
|
+
});
|
|
2611
|
+
return found;
|
|
2612
|
+
}
|
|
2613
|
+
function memberSignature(property, at, context) {
|
|
2614
|
+
const { checker } = context;
|
|
2615
|
+
return checker.getNonNullableType(checker.getTypeOfSymbolAtLocation(property, at)).getCallSignatures()[0];
|
|
2616
|
+
}
|
|
2617
|
+
function isObjectLike(ts, type) {
|
|
2618
|
+
const members2 = type.isUnion() ? type.types : [type];
|
|
2619
|
+
return members2.some((member) => (member.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection)) !== 0);
|
|
2620
|
+
}
|
|
2621
|
+
function argumentHandoffs(argument, origin, context) {
|
|
2622
|
+
const { ts, checker } = context;
|
|
2623
|
+
if (ts.isSpreadElement(argument)) return [];
|
|
2624
|
+
const contextual = checker.getContextualType(argument);
|
|
2625
|
+
if (!contextual || isOpaque(ts, contextual)) return [];
|
|
2626
|
+
const expected = checker.getNonNullableType(contextual);
|
|
2627
|
+
const signatures = (expected.isUnion() ? expected.types : [expected]).flatMap((member) => member.getCallSignatures());
|
|
2628
|
+
if (signatures.length > 0) {
|
|
2629
|
+
return functionsOfExpression(argument, context, 0, false, 0).flatMap((handed) => handoffsOf(handed, signatures[0], origin, argument, context));
|
|
2630
|
+
}
|
|
2631
|
+
if (!isObjectLike(ts, expected)) return [];
|
|
2632
|
+
const value = checker.getApparentType(checker.getTypeAtLocation(argument));
|
|
2633
|
+
return checker.getPropertiesOfType(expected).flatMap((property) => {
|
|
2634
|
+
const signature = memberSignature(property, argument, context);
|
|
2635
|
+
if (!signature) return [];
|
|
2636
|
+
return functionsOfMember(checker.getPropertyOfType(value, property.name), context).flatMap((handed) => handoffsOf(handed, signature, origin, argument, context));
|
|
2637
|
+
});
|
|
2638
|
+
}
|
|
2639
|
+
function callHandoffs(call, context) {
|
|
2640
|
+
const { ts } = context;
|
|
2641
|
+
if (!call.arguments || call.arguments.length === 0 || call.expression.kind === ts.SyntaxKind.ImportKeyword) return [];
|
|
2642
|
+
if (isInsideValidator(ts, call)) return [];
|
|
2643
|
+
const verdict = callTypeVerdict(call, context);
|
|
2644
|
+
if (verdict.kind !== "type-untrusted") return [];
|
|
2645
|
+
return call.arguments.flatMap((argument) => argumentHandoffs(argument, verdict.origin.origin, context));
|
|
2646
|
+
}
|
|
2647
|
+
function implementsHandoffs(declaration, context) {
|
|
2648
|
+
const { ts, checker, policy } = context;
|
|
2649
|
+
const clauses = (declaration.heritageClauses ?? []).filter((clause) => clause.token === ts.SyntaxKind.ImplementsKeyword);
|
|
2650
|
+
if (clauses.length === 0 || isInsideValidator(ts, declaration)) return [];
|
|
2651
|
+
const own = checker.getTypeAtLocation(declaration);
|
|
2652
|
+
const instance = own.getConstructSignatures()[0]?.getReturnType() ?? own;
|
|
2653
|
+
return clauses.flatMap(
|
|
2654
|
+
(clause) => clause.types.flatMap(
|
|
2655
|
+
(implemented) => checker.getPropertiesOfType(checker.getTypeAtLocation(implemented)).flatMap((property) => {
|
|
2656
|
+
const member = property.valueDeclaration ?? property.declarations?.[0];
|
|
2657
|
+
const signature = member ? memberSignature(property, implemented, context) : void 0;
|
|
2658
|
+
if (!member || !signature) return [];
|
|
2659
|
+
const verdict = policy.typeVerdictOf(member);
|
|
2660
|
+
if (verdict.kind !== "type-untrusted") return [];
|
|
2661
|
+
return functionsOfMember(checker.getPropertyOfType(instance, property.name), context).flatMap(
|
|
2662
|
+
(handed) => handoffsOf(handed, signature, verdict.origin.origin, implemented, context)
|
|
2663
|
+
);
|
|
2664
|
+
})
|
|
2665
|
+
)
|
|
2666
|
+
);
|
|
2667
|
+
}
|
|
2668
|
+
function untrustedHandoffsAt(node, context) {
|
|
2669
|
+
const { ts, policy } = context;
|
|
2670
|
+
if (policy.rules.untrustedCallbacks !== "all") return [];
|
|
2671
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) return callHandoffs(node, context);
|
|
2672
|
+
if (ts.isClassDeclaration(node) || ts.isClassExpression(node)) return implementsHandoffs(node, context);
|
|
2673
|
+
return [];
|
|
2674
|
+
}
|
|
2675
|
+
function untrustedHandoffsIn(root, context) {
|
|
2676
|
+
const handoffs = [];
|
|
2677
|
+
const visit = (node) => {
|
|
2678
|
+
handoffs.push(...untrustedHandoffsAt(node, context));
|
|
2679
|
+
context.ts.forEachChild(node, visit);
|
|
2680
|
+
};
|
|
2681
|
+
visit(root);
|
|
2682
|
+
return handoffs;
|
|
2683
|
+
}
|
|
2684
|
+
function untrustedHandoffData(handoff) {
|
|
2685
|
+
return { callback: handoff.callback, origin: handoff.origin, parameter: handoff.parameter, type: handoff.type };
|
|
2686
|
+
}
|
|
2687
|
+
function untrustedHandoffMessage(handoff) {
|
|
2688
|
+
return fillMessage(UNTRUSTED_VALUE_MESSAGES.handoff, untrustedHandoffData(handoff));
|
|
2689
|
+
}
|
|
2690
|
+
function untrustedValueData(value) {
|
|
2691
|
+
return { entry: UNTRUSTED_ENTRY_LABELS[value.entry], origin: value.origin, use: value.use ?? "used", type: value.type };
|
|
2692
|
+
}
|
|
2693
|
+
function untrustedValueMessageId(value) {
|
|
2694
|
+
return value.entry === "generic-return" ? "callerChosen" : "untrusted";
|
|
2695
|
+
}
|
|
2696
|
+
function untrustedValueMessage(value) {
|
|
2697
|
+
return fillMessage(UNTRUSTED_VALUE_MESSAGES[untrustedValueMessageId(value)], untrustedValueData(value));
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
// src/core/check-file.ts
|
|
2701
|
+
var emptyConfigs = /* @__PURE__ */ new Map();
|
|
2702
|
+
function emptyTrustConfig(cwd) {
|
|
2703
|
+
let config = emptyConfigs.get(cwd);
|
|
2704
|
+
if (!config) {
|
|
2705
|
+
config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [], strict: [], tsconfig: [], rules: DEFAULT_RULE_SETTINGS };
|
|
2706
|
+
emptyConfigs.set(cwd, config);
|
|
2707
|
+
}
|
|
2708
|
+
return config;
|
|
2709
|
+
}
|
|
2710
|
+
var policies = /* @__PURE__ */ new WeakMap();
|
|
2711
|
+
function policyFor(ts, checker, config, extraTrust = []) {
|
|
2712
|
+
let byKey = policies.get(checker);
|
|
2713
|
+
if (!byKey) {
|
|
2714
|
+
byKey = /* @__PURE__ */ new Map();
|
|
2715
|
+
policies.set(checker, byKey);
|
|
2716
|
+
}
|
|
2717
|
+
const key = `${config.file}\0${extraTrust.join("\0")}`;
|
|
2718
|
+
const hit = byKey.get(key);
|
|
2719
|
+
if (hit && hit.config === config) return hit.policy;
|
|
2720
|
+
const policy = new TrustPolicy(ts, checker, config, extraTrust);
|
|
2721
|
+
byKey.set(key, { config, policy });
|
|
2722
|
+
return policy;
|
|
2723
|
+
}
|
|
2724
|
+
function positionAt(ts, sourceFile, offset) {
|
|
2725
|
+
const position = ts.getLineAndCharacterOfPosition(sourceFile, offset);
|
|
2726
|
+
return { line: position.line + 1, column: position.character + 1 };
|
|
2727
|
+
}
|
|
2728
|
+
function startOf(ts, sourceFile, node) {
|
|
2729
|
+
return positionAt(ts, sourceFile, node.getStart(sourceFile));
|
|
2730
|
+
}
|
|
2731
|
+
function checkSourceFile(options) {
|
|
2732
|
+
return checkSourceFileWithAccepted(options).findings;
|
|
2733
|
+
}
|
|
2734
|
+
function checkSourceFileWithAccepted(options) {
|
|
2735
|
+
const { ts, sourceFile, config } = options;
|
|
2736
|
+
const checker = options.checker ?? options.program.getTypeChecker();
|
|
2737
|
+
const policy = policyFor(ts, checker, config, options.extraTrust);
|
|
2738
|
+
if (policy.zones.zoneOf(sourceFile.fileName) !== "checked") return { findings: [], accepted: [] };
|
|
2739
|
+
const failureContext = { ts, checker, policy, guardContext: typedGuardContext(ts, checker, policy) };
|
|
2740
|
+
const claimContext = isRuleEnabled(config, TYPE_CLAIM_RULE) ? typeClaimContext(ts, checker, void 0, policy) : null;
|
|
2741
|
+
const valueContext = isRuleEnabled(config, UNTRUSTED_VALUE_RULE) ? untrustedValueContext(ts, checker, policy) : null;
|
|
2742
|
+
const file = policy.zones.relativePath(sourceFile.fileName);
|
|
2743
|
+
const findings = [];
|
|
2744
|
+
const accepted = [];
|
|
2745
|
+
const findingAt = (start, rule, origin, message) => ({ file, rule, origin, ...positionAt(ts, sourceFile, start), message });
|
|
2746
|
+
const reportAt = (start, rule, origin, message) => {
|
|
2747
|
+
findings.push(findingAt(start, rule, origin, message));
|
|
2748
|
+
};
|
|
2749
|
+
const report = (node, rule, origin, message) => reportAt(node.getStart(sourceFile), rule, origin, message);
|
|
2750
|
+
const reportClaim = (claim2) => reportAt(claimSpan(claim2, sourceFile).start, TYPE_CLAIM_RULE, claim2.origin, typeClaimMessage(claim2));
|
|
2751
|
+
if (claimContext) for (const claim2 of directiveClaims(ts, sourceFile)) reportClaim(claim2);
|
|
2752
|
+
for (const found of acceptDirectiveFindings(ts, sourceFile, failureContext)) {
|
|
2753
|
+
reportAt(found.directive.pos, THROW_RULE, DIRECTIVE_ORIGIN, fillMessage(ACCEPT_DIRECTIVE_MESSAGES[found.messageId], found.data));
|
|
2754
|
+
}
|
|
2755
|
+
const visit = (node) => {
|
|
2756
|
+
for (const found of failurePathFindingsAt(node, failureContext)) {
|
|
2757
|
+
const acceptance = acceptanceOf(ts, found.node);
|
|
2758
|
+
if (!acceptance) report(found.node, found.rule, found.origin, found.message);
|
|
2759
|
+
else accepted.push({ finding: findingAt(found.node.getStart(sourceFile), found.rule, found.origin, found.message), text: found.node.getText(sourceFile), acceptance });
|
|
2760
|
+
}
|
|
2761
|
+
if (claimContext) for (const claim2 of typeClaimsAt(node, claimContext)) reportClaim(claim2);
|
|
2762
|
+
const value = valueContext ? untrustedValueAt(node, valueContext) : null;
|
|
2763
|
+
if (value?.outcome === "finding") report(node, UNTRUSTED_VALUE_RULE, value.origin, untrustedValueMessage(value));
|
|
2764
|
+
if (valueContext) {
|
|
2765
|
+
for (const handoff of untrustedHandoffsAt(node, valueContext)) report(handoff.node, UNTRUSTED_VALUE_RULE, handoff.origin, untrustedHandoffMessage(handoff));
|
|
2766
|
+
}
|
|
2767
|
+
ts.forEachChild(node, visit);
|
|
2768
|
+
};
|
|
2769
|
+
visit(sourceFile);
|
|
2770
|
+
if (isRuleEnabled(config, DROPPED_RESULT_RULE)) {
|
|
2771
|
+
for (const dropped of droppedResultsIn(sourceFile, droppedResultContext(ts, checker, policy))) {
|
|
2772
|
+
reportAt(dropped.start, DROPPED_RESULT_RULE, dropped.origin, droppedResultMessage(dropped));
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
if (isRuleEnabled(config, REDUNDANT_GUARD_RULE)) {
|
|
2776
|
+
for (const guard of redundantGuardsIn(sourceFile, failureContext)) {
|
|
2777
|
+
reportAt(guard.start, REDUNDANT_GUARD_RULE, REDUNDANT_GUARD_ORIGIN, redundantGuardMessage(guard));
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
return { findings, accepted };
|
|
2781
|
+
}
|
|
2782
|
+
|
|
2783
|
+
export {
|
|
2784
|
+
alwaysExits,
|
|
2785
|
+
catchProblem,
|
|
2786
|
+
guardOf,
|
|
2787
|
+
droppedResultContext,
|
|
2788
|
+
droppedResultData,
|
|
2789
|
+
droppedResultsIn,
|
|
2790
|
+
entryMatches,
|
|
2791
|
+
TrustPolicy,
|
|
2792
|
+
typedGuardContext,
|
|
2793
|
+
nameBasedGuardContext,
|
|
2794
|
+
throwProblem,
|
|
2795
|
+
untrustedCallProblem,
|
|
2796
|
+
acceptanceOf,
|
|
2797
|
+
acceptDirectiveFindings,
|
|
2798
|
+
redundantGuardData,
|
|
2799
|
+
redundantGuardsIn,
|
|
2800
|
+
claimSpan,
|
|
2801
|
+
typeClaimContext,
|
|
2802
|
+
typeClaimMessage,
|
|
2803
|
+
typeClaimsIn,
|
|
2804
|
+
untrustedValueContext,
|
|
2805
|
+
callTypeVerdict,
|
|
2806
|
+
guardCallOf,
|
|
2807
|
+
untrustedValuesIn,
|
|
2808
|
+
untrustedHandoffsIn,
|
|
2809
|
+
untrustedHandoffData,
|
|
2810
|
+
untrustedValueData,
|
|
2811
|
+
untrustedValueMessageId,
|
|
2812
|
+
untrustedValueMessage,
|
|
2813
|
+
emptyTrustConfig,
|
|
2814
|
+
policyFor,
|
|
2815
|
+
positionAt,
|
|
2816
|
+
startOf,
|
|
2817
|
+
checkSourceFile,
|
|
2818
|
+
checkSourceFileWithAccepted
|
|
2819
|
+
};
|
|
2820
|
+
//# sourceMappingURL=chunk-V72KWVWP.js.map
|