@noego/trust 0.3.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 +954 -30
- 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 +1141 -64
- 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 +74 -168
- package/dist/eslint/index.js +320 -32
- package/dist/eslint/index.js.map +1 -1
- package/dist/index.cjs +4 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -15
- package/dist/index.d.ts +42 -15
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +7 -4
- package/dist/chunk-APNT6ZSM.js +0 -2168
- package/dist/chunk-APNT6ZSM.js.map +0 -1
package/README.md
CHANGED
|
@@ -2,70 +2,392 @@
|
|
|
2
2
|
|
|
3
3
|
Make the failure path explicit. Everything is untrusted by default: every call into untrusted code,
|
|
4
4
|
and every `throw`, must be handled locally by a `try` whose `catch` returns `Result.err(...)` (or by
|
|
5
|
-
`
|
|
5
|
+
`Trust.try` / `Trust.tryAsync`). The goal is prevention. When something on the trust list causes a
|
|
6
6
|
bug, remove it from the list, and the lint flags every call to it.
|
|
7
7
|
|
|
8
|
-
##
|
|
8
|
+
## Concepts
|
|
9
|
+
|
|
10
|
+
The rest of this README is reference. This section is the model that holds it together; read it
|
|
11
|
+
first.
|
|
12
|
+
|
|
13
|
+
### What `ok` means
|
|
14
|
+
|
|
15
|
+
`ok: true` means **the program is ok with the value**: it holds something it knows how to use. It
|
|
16
|
+
does **not** mean "no error happened".
|
|
17
|
+
|
|
18
|
+
`ok: false` means **not decided yet**: something failed, and no code has said what that failure
|
|
19
|
+
means where it now stands.
|
|
20
|
+
|
|
21
|
+
So an error can be `ok: true`. "User 7 not found", turned by a decision into a guest user, or into
|
|
22
|
+
`{ status: 'not_found', id: 7 }` for a screen to render, is a value the program is ok with. The
|
|
23
|
+
failure did not vanish; it was given a meaning. That act — turning `ok: false` into `ok: true` by
|
|
24
|
+
naming what each failure means — is called **deciding**. There are two forms, each with its own job:
|
|
25
|
+
|
|
26
|
+
- **`Trust.decide` decides a subset.** The kinds this code understands become `ok`; every other kind
|
|
27
|
+
stays a failure in the type and is passed up. Below the boundary this is almost always
|
|
28
|
+
*recovery*: the cache is down, read the database instead.
|
|
29
|
+
- **An exhaustive `switch` decides everything.** At a boundary where no failure may leave — an API
|
|
30
|
+
response, an IPC reply, a CLI exit — `switch (r.error.kind)` gives every kind a `case`, and a
|
|
31
|
+
`never` default makes the compiler prove none is missing.
|
|
9
32
|
|
|
10
|
-
|
|
33
|
+
Which one, and where, is settled by one question: [can this layer still answer what it was
|
|
34
|
+
asked?](#when-to-decide-and-when-to-pass-up)
|
|
35
|
+
|
|
36
|
+
### A failure has a lifecycle
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
throw raw exception from code outside the trust list not a value yet
|
|
40
|
+
Trust.try becomes Err<{ kind: 'NotFound', id }> ok: false — a fact, named
|
|
41
|
+
return r passed up, unchanged, through every layer that ok: false — still undecided
|
|
42
|
+
cannot say what it means
|
|
43
|
+
Trust.translate optionally renamed for the layer above ok: false — a different fact
|
|
44
|
+
Trust.decide some kinds given a meaning (a fallback, a default) ok: true — for those kinds
|
|
45
|
+
the rest stay failures and keep moving up ok: false for the rest
|
|
46
|
+
switch at the edge, every kind left given a meaning ok: true — all decided
|
|
47
|
+
edge the decided value leaves as plain data no Result at all
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Each step has one visible form in the code:
|
|
51
|
+
|
|
52
|
+
| Step | Tool | What it says |
|
|
53
|
+
|---|---|---|
|
|
54
|
+
| A throw becomes a failure | `Trust.try` / `Trust.tryAsync` | "this outside call can fail, and here is the name of how" |
|
|
55
|
+
| A failure moves up | `if (!r.ok) return r;` | "I don't know what this means here" |
|
|
56
|
+
| A failure changes kind | `Trust.translate` | "below, this is `NotFound`; to my caller it is `Missing`" |
|
|
57
|
+
| Some failures stop | `Trust.decide` | "these kinds mean this here; the others are not mine to decide" |
|
|
58
|
+
| Every failure stops, at the edge | exhaustive `switch (r.error.kind)` with a `never` default | "here is what each one means to whoever receives this" |
|
|
59
|
+
|
|
60
|
+
Nothing else may catch, swallow or re-encode a failure: not a `try`, not `?? null`, not
|
|
61
|
+
`return false`, not `{ kind: 'failed' }`. Each of those stops a failure without saying what it
|
|
62
|
+
meant, so the reason is lost. The lint enforces this when `dropped-result` is on (see
|
|
63
|
+
[`dropped-result`](#dropped-result-every-failure-is-passed-up-or-handled)). It does not check what an
|
|
64
|
+
edge returns: a `Result` returned out through the edge counts as passed up, so "no `Result` crosses
|
|
65
|
+
the edge" is held in review.
|
|
66
|
+
|
|
67
|
+
### Three roles
|
|
68
|
+
|
|
69
|
+
Code that holds a `Result` plays one of three roles:
|
|
70
|
+
|
|
71
|
+
- **Reporter.** Talks to the outside world (a database, a file, a socket) and reports what happened as
|
|
72
|
+
facts: a row, or a named failure with its context (`{ kind: 'NotFound', id }`). It never decides.
|
|
73
|
+
- **Translator.** Passes failures up untouched and adds its own when a fact means failure *for it*
|
|
74
|
+
(a lost compare-and-set race is a fact to the reporter and a failure to the code that needed to
|
|
75
|
+
win it). It never collapses several kinds into one: collapsing is deciding.
|
|
76
|
+
- **Decider.** Knows what a failure means where it stands and decides it. Any layer may decide a kind
|
|
77
|
+
it can recover from with `Trust.decide` (the cache failed → read the database); what it cannot
|
|
78
|
+
recover from it passes up. The edge is the decider of last resort and decides everything that is
|
|
79
|
+
left with an exhaustive `switch`.
|
|
80
|
+
|
|
81
|
+
### When to decide, and when to pass up
|
|
82
|
+
|
|
83
|
+
A failure is decided by the first layer that can **still answer the question it was asked**. Every
|
|
84
|
+
other layer passes it up. Two questions settle almost every case:
|
|
85
|
+
|
|
86
|
+
1. **After I handle this, does my caller still get what it asked for?**
|
|
87
|
+
Yes → decide it here. No → pass it up.
|
|
88
|
+
2. **Is there anyone above me to pass it to?**
|
|
89
|
+
No → this is a boundary: decide every kind, with the `switch`.
|
|
90
|
+
|
|
91
|
+
**Decide when the failure does not change your answer.** The cache is unavailable → read the
|
|
92
|
+
database. The primary host times out → try the replica. The config file is missing → use the
|
|
93
|
+
defaults. The caller asked for a profile and gets a profile; the failure changed *how* the answer
|
|
94
|
+
was produced, not *what* it is. This is recovery, and it is the normal reason a layer below the
|
|
95
|
+
boundary decides. The recovering layer is the decider, so it is the one that logs the cause (once).
|
|
96
|
+
|
|
97
|
+
**Pass up when the failure changes the answer.** The profile does not exist. No fallback produces
|
|
98
|
+
one, and what "no profile" means — a 404, "create one", "skip this row", "show a placeholder" —
|
|
99
|
+
depends on who asked. The service does not know that; the caller might; the boundary must. A layer
|
|
100
|
+
that turns this into `null`, `false` or a default has not decided, it has guessed on the caller's
|
|
101
|
+
behalf.
|
|
11
102
|
|
|
12
103
|
```ts
|
|
13
|
-
|
|
104
|
+
// A service: recovers from the cache, passes the database's failures up.
|
|
105
|
+
async function profile(id: number) {
|
|
106
|
+
const cached = Trust.decide(await cache.get(id), {
|
|
107
|
+
CacheUnavailable: (f) => {
|
|
108
|
+
log.warn('profile cache unavailable, reading database', { id, cause: f.cause }); // decided here, logged here
|
|
109
|
+
return null;
|
|
110
|
+
},
|
|
111
|
+
CacheMiss: () => null,
|
|
112
|
+
});
|
|
113
|
+
if (cached.value) return Result.ok(cached.value);
|
|
114
|
+
return db.profiles.get(id); // Err<NotFound> | Err<QueryFailed>: not this layer's to decide
|
|
115
|
+
}
|
|
14
116
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
117
|
+
// The boundary: nobody is left to ask, so every kind becomes an answer.
|
|
118
|
+
async function handleGetProfile(req: Request) {
|
|
119
|
+
const found = await profiles.profile(req.params.id);
|
|
120
|
+
if (!found.ok) {
|
|
121
|
+
switch (found.error.kind) {
|
|
122
|
+
case 'NotFound': return reply(404, { error: 'profile not found', id: found.error.id });
|
|
123
|
+
case 'QueryFailed':
|
|
124
|
+
log.error('profile read failed', { cause: found.error.cause });
|
|
125
|
+
return reply(503, { error: 'try again later' });
|
|
126
|
+
default: {
|
|
127
|
+
const unhandled: never = found.error;
|
|
128
|
+
return unhandled;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
20
131
|
}
|
|
132
|
+
return reply(200, found.value);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The only grey area is a method whose contract already includes absence: "the latest message, *if
|
|
137
|
+
any*" answers `null` to not-found because `null` is what the caller asked for. "Message 42" does
|
|
138
|
+
not. Read the method's question, not the failure's name.
|
|
139
|
+
|
|
140
|
+
**At the boundary, decide everything.** An HTTP or IPC reply, a CLI exit code, a UI event handler,
|
|
141
|
+
a scheduled job with no caller: there is no one left to pass a failure to. The boundary says what
|
|
142
|
+
every kind means — a status, a message, a retry, a log line and nothing — and returns plain data.
|
|
143
|
+
Returning a `Result` from a boundary is not a decision; it is hoping someone else will make one, and
|
|
144
|
+
no one is there. The exhaustive `switch` with the `never` default is the form, because it is the
|
|
145
|
+
only one that makes "every kind" a compile-time fact.
|
|
146
|
+
|
|
147
|
+
### The `ok` path: keep the `Result` until the boundary
|
|
148
|
+
|
|
149
|
+
The same rule fixes what the success path looks like. Taking the value out of a `Result` for good —
|
|
150
|
+
returning `Profile` where you held `Result<Profile, …>` — is legitimate only where every failure has
|
|
151
|
+
been decided, and that is the boundary. Everywhere else, **return the `Result`, ok or not.**
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
// A service that needs the value to continue reads it, and still returns a Result.
|
|
155
|
+
async greeting(id: number) {
|
|
156
|
+
const profile = await this.profiles.get(id);
|
|
157
|
+
if (!profile.ok) return profile; // failures pass up first
|
|
158
|
+
return Result.ok(`Hello, ${profile.value.name}`); // the value, used, re-wrapped
|
|
21
159
|
}
|
|
160
|
+
```
|
|
22
161
|
|
|
23
|
-
|
|
24
|
-
|
|
162
|
+
- Reading `r.value` after `if (!r.ok) return r;` is fine: the failure has already left. What is not
|
|
163
|
+
fine is the function's *return type* dropping the `Result`.
|
|
164
|
+
- `return r` when the value is exactly what your caller asked for (it carries the value and the
|
|
165
|
+
failures together); `Result.ok(newValue)` when this function changes the value.
|
|
166
|
+
- A function that returns a plain value from a `Result` has decided every failure, so it is a
|
|
167
|
+
boundary. If it is a service, a helper, a repository composer — not a boundary — it has invented
|
|
168
|
+
one in the middle of the program: its callers get a value that may be a guess (an empty profile,
|
|
169
|
+
a default name) with no way to tell, and the kinds the lint was following stop dead there. Most
|
|
170
|
+
of a program is below the boundary, so most of a program returns `Result`.
|
|
171
|
+
- A boundary is defined by "there is no one above me to return to", not by the layer's name. A
|
|
172
|
+
controller usually; but a scheduled job, an event listener, a queue consumer, a `main` are
|
|
173
|
+
boundaries inside the application too. Each decides everything and returns plain data (or
|
|
174
|
+
nothing); everything beneath them returns `Result`.
|
|
175
|
+
|
|
176
|
+
### The edge decides everything that is left
|
|
177
|
+
|
|
178
|
+
Every program has an **edge**: the place where values leave it — an HTTP handler, an IPC controller,
|
|
179
|
+
a CLI's `main`, a public library function. `Result` is an internal contract; it does not cross the
|
|
180
|
+
edge. The edge is the last decider: it handles **every** kind still possible and returns plain data.
|
|
181
|
+
|
|
182
|
+
The edge decides with an exhaustive `switch`. Narrow with `if (!r.ok)`, give every kind a `case`, and
|
|
183
|
+
end with a `default` that assigns the failure to `never`. An API response handler, for example:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
const found = await accounts.get(id);
|
|
187
|
+
if (!found.ok) {
|
|
188
|
+
switch (found.error.kind) {
|
|
189
|
+
case 'NotFound':
|
|
190
|
+
return { status: 'not_found' as const, id: found.error.id }; // found.error narrowed to NotFound
|
|
191
|
+
case 'ConnectionFailed':
|
|
192
|
+
log.error('account read failed', { cause: found.error.cause }); // logged once, by the decider
|
|
193
|
+
return { status: 'unavailable' as const };
|
|
194
|
+
default: {
|
|
195
|
+
const unhandled: never = found.error; // a new kind below stops this compiling
|
|
196
|
+
return unhandled;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return found.value; // plain data: the account, or one of the two statuses
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
- The `never` default is what makes the switch exhaustive: it compiles only while every kind has a
|
|
204
|
+
`case`. It is required, and it holds only the `never` check — a fallback value, a log or a throw
|
|
205
|
+
there would absorb a kind nobody decided.
|
|
206
|
+
- Every `case` ends in `return` with a value: no fall-through between kinds (unless the project
|
|
207
|
+
enables `noFallthroughCasesInSwitch`, the compiler does not catch a forgotten `return`), and no
|
|
208
|
+
empty `case`. Kinds that mean the same thing may stack their labels (`case 'A': case 'B': return …`).
|
|
209
|
+
- `dropped-result` follows the switch: each `case 'Kind':` handles that kind, and a kind no `case`
|
|
210
|
+
names is still reported. It does not check that the `default` is present or that a `case` returns
|
|
211
|
+
a non-void value; those are held in review.
|
|
212
|
+
|
|
213
|
+
`Trust.decide` is not the edge's tool. Its job is a **subset**: below the edge, a layer that can
|
|
214
|
+
recover from some kinds decides those and passes the rest on (the `profile` service above). What
|
|
215
|
+
`decide` leaves is a new value with fewer kinds, followed the same way: passed up, decided by another
|
|
216
|
+
`decide`, or decided in full by the edge's `switch`. A `decide` that happens to name every kind does
|
|
217
|
+
compile to a plain `Ok`, but at an edge write the `switch`: it says "this is where every failure
|
|
218
|
+
ends".
|
|
219
|
+
|
|
220
|
+
For both forms:
|
|
221
|
+
|
|
222
|
+
- A handler (a `case` or a `decide` handler) returns what the failure means to the receiver, never
|
|
223
|
+
`Result.err(...)`. A handler that returns an `Err` has decided nothing; it hands the receiver an
|
|
224
|
+
`ok: false` it cannot act on. `decide` rejects a handler that returns `undefined` / `void`; for a
|
|
225
|
+
`case`, review does.
|
|
226
|
+
- The success value and the handlers' values come out of the edge as one union. Only a failure's
|
|
227
|
+
`kind` is required to be a literal; what a handler returns is ordinary data. If the receiver needs
|
|
228
|
+
to tell outcomes apart by type, give the handlers' values a field it can narrow on — note that
|
|
229
|
+
handler return values are not kept literal (`status: 'not_found'` infers as `string`), so write
|
|
230
|
+
`as const` where a literal type matters.
|
|
231
|
+
- Throwing at the edge is the exception, not the rule: when an API's contract is exceptions, the edge
|
|
232
|
+
turns the decided failure into one, under `//trust:accept <reason>`.
|
|
233
|
+
|
|
234
|
+
### Only real failure points return `Result`
|
|
235
|
+
|
|
236
|
+
A `Result` is a promise to the caller that something can go wrong at runtime. Code that cannot fail
|
|
237
|
+
returns its value:
|
|
238
|
+
|
|
239
|
+
- An origin on the `trust` list cannot fail by definition. Resolving an instance from a DI container,
|
|
240
|
+
logging, a pure computation: call it and use the value. Wrapping it in `Trust.try` invents a failure
|
|
241
|
+
that never happens, and every caller must unwrap it for nothing (`redundant-guard` reports it).
|
|
242
|
+
- Programmer errors at startup (a missing registration, a misconfigured container) are not failures a
|
|
243
|
+
caller can handle. They fail loudly on first run; they are not `Result`s.
|
|
244
|
+
- What remains — I/O, a database, parsing data from outside, a child process — returns `Result`.
|
|
245
|
+
|
|
246
|
+
If a trusted origin turns out to fail in practice, take it off the `trust` list: the lint then
|
|
247
|
+
requires the guard at every call, and the failure enters the lifecycle above.
|
|
248
|
+
|
|
249
|
+
### Kinds are the vocabulary
|
|
250
|
+
|
|
251
|
+
- A failure is a plain object with a literal `kind` and the context the decider will need
|
|
252
|
+
(`{ kind: 'NotFound', id }`, not `{ kind: 'NotFound' }`, and never a bare string or `Error`).
|
|
253
|
+
- Return types stay inferred, so the set of kinds flows from the reporter to the edge with no
|
|
254
|
+
hand-written union to drift. Change a kind below and every decider that named it goes red.
|
|
255
|
+
- Name a kind for what happened (`account_not_found`, `write_failed`), not for what to do about it.
|
|
256
|
+
What to do is the decider's job.
|
|
257
|
+
|
|
258
|
+
## Runtime: `@noego/trust`
|
|
259
|
+
|
|
260
|
+
Zero imports, safe in any bundle. Two namespaces:
|
|
261
|
+
|
|
262
|
+
| | |
|
|
263
|
+
|---|---|
|
|
264
|
+
| `Result.ok(value)` / `Result.err(failure)` | make a result |
|
|
265
|
+
| `Trust.try(fn, onError)` / `Trust.tryAsync(fn, onError)` | the only boundary that may catch a throw |
|
|
266
|
+
| `Trust.decide(r, handlers)` | decides a subset of kinds into `ok`; the kinds it does not name stay failures. At the edge, every kind is decided with an exhaustive `switch` instead (see [The edge decides everything that is left](#the-edge-decides-everything-that-is-left)) |
|
|
267
|
+
| `Trust.translate(r, mappers)` | the only place a failure may change kind |
|
|
268
|
+
|
|
269
|
+
```ts
|
|
270
|
+
import { Result, Trust } from '@noego/trust';
|
|
271
|
+
|
|
272
|
+
const loaded = Trust.try(() => JSON.parse(text), () => ({ kind: 'bad_json' }));
|
|
273
|
+
const fetched = await Trust.tryAsync(() => client.get(url), (cause) => ({ kind: 'http_failed', cause }));
|
|
25
274
|
```
|
|
26
275
|
|
|
27
276
|
## Handling a failure: return it or decide it
|
|
28
277
|
|
|
29
278
|
Rules:
|
|
30
279
|
|
|
31
|
-
1. A failure is an object with a literal `kind`: `{ kind: 'NotFound', id }`.
|
|
32
|
-
|
|
33
|
-
|
|
280
|
+
1. A failure is an object with a literal `kind`: `{ kind: 'NotFound', id }`. Write it as a plain object literal; the
|
|
281
|
+
kind stays literal without `as const`.
|
|
282
|
+
2. On failure either `return r` (pass it up) or decide it: `Trust.decide` for the kinds this code
|
|
283
|
+
understands (the rest stay failures), or, at the edge, an exhaustive `switch (r.error.kind)` ending in a
|
|
284
|
+
`never` default for every kind. Nothing else may stop a failure.
|
|
285
|
+
3. A `case` or `decide` handler returns a value (never `undefined`/`void`); that value says what replaced the failure.
|
|
34
286
|
4. Leave fallible functions' return types inferred so the failure kinds flow to the caller.
|
|
35
|
-
5. A thrown error from outside code becomes a named failure in `
|
|
287
|
+
5. A thrown error from outside code becomes a named failure in `Trust.try` / `Trust.tryAsync`. No other `try` is needed.
|
|
36
288
|
|
|
37
289
|
```ts
|
|
38
|
-
import { Result } from '@noego/trust';
|
|
290
|
+
import { Result, Trust } from '@noego/trust';
|
|
39
291
|
|
|
40
292
|
async function lookup(id: number) {
|
|
41
|
-
const found = await
|
|
293
|
+
const found = await Trust.tryAsync(
|
|
42
294
|
() => db.find(id),
|
|
43
295
|
(cause) => ({ kind: 'ConnectionFailed', cause }),
|
|
44
296
|
);
|
|
45
297
|
if (!found.ok) return found;
|
|
46
298
|
return found.value ? Result.ok(found.value) : Result.err({ kind: 'NotFound', id });
|
|
47
299
|
}
|
|
300
|
+
// inferred: Ok<Row> | Err<{ kind: 'ConnectionFailed'; cause: unknown }> | Err<{ kind: 'NotFound'; id: number }>
|
|
48
301
|
|
|
49
302
|
const r = await lookup(7);
|
|
50
303
|
// NotFound becomes a guest value; ConnectionFailed stays a failure in the type.
|
|
51
|
-
const user =
|
|
304
|
+
const user = Trust.decide(r, { NotFound: () => GUEST });
|
|
52
305
|
if (!user.ok) return user; // Err<{ kind: 'ConnectionFailed'; ... }>
|
|
53
306
|
```
|
|
54
307
|
|
|
55
|
-
`
|
|
308
|
+
`Trust.translate(r, { NotFound: (f) => ({ kind: 'Missing', id: f.id }) })` turns one failure into another.
|
|
56
309
|
Handlers and mappers are synchronous: async handlers are not supported.
|
|
57
310
|
|
|
311
|
+
A single declared failure whose `kind` is a union (`{ kind: 'missing' | 'locked'; path: string }`) is treated as one
|
|
312
|
+
failure per kind, so each handler narrows to its own kind.
|
|
313
|
+
|
|
314
|
+
### New in 0.5.0
|
|
315
|
+
|
|
316
|
+
Upgrading from 0.4.0 changes no finding: the two new rules are **off** until a project turns them on, so
|
|
317
|
+
`trust check`, `trust baseline` and the ESLint `typedConfig` report exactly what 0.4.0 reported.
|
|
318
|
+
|
|
319
|
+
- **`type-claim`** reports every place a type is claimed instead of proven: a narrowing `as`, `x!`, `any` in a
|
|
320
|
+
typed position, a written type predicate, a caller-chosen generic return
|
|
321
|
+
(see [`type-claim`](#type-claim-types-that-are-claimed-not-proven)).
|
|
322
|
+
- **`untrusted-value`** makes type trust opt-in: a value whose type was declared by an origin that is not
|
|
323
|
+
type-trusted (a call's return, a callback parameter the outside fills, a property or global it declares) may
|
|
324
|
+
only be validated, kept as `unknown`, or tested by a built-in check
|
|
325
|
+
(see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)).
|
|
326
|
+
- **`trust_type` / `distrust_type`**: a second pair of origin lists in trust.config.json, separate from
|
|
327
|
+
`trust` / `distrust`, saying which origins declare types that are true at runtime (`"trust_type": ["zod",
|
|
328
|
+
"node:path"]`). They inherit through `extend` and resolve like `trust` / `distrust`.
|
|
329
|
+
- **`//trust:validator_function`**: a comment that marks a function as a validator. Passing an untrusted value
|
|
330
|
+
to it is allowed, what it returns is trusted, and claims inside it are not reported
|
|
331
|
+
(see [Validators](#validators-trustvalidator_function)).
|
|
332
|
+
- **`//trust:accept <reason>`**: a comment directly above a statement that accepts its throw, untrusted call or
|
|
333
|
+
promise finding, with the reason why (see [Accepted failure paths](#accepted-failure-paths-trustaccept-reason)).
|
|
334
|
+
- **`trust refactor`** prints the order to fix files in: waves of files whose imports are already done, leaves
|
|
335
|
+
first, with circular-import groups kept together (see [`trust refactor`](#trust-refactor-the-order-to-refactor-in)).
|
|
336
|
+
|
|
337
|
+
Turn the new rules on per project with `rules` in trust.config.json:
|
|
338
|
+
|
|
339
|
+
```json
|
|
340
|
+
{
|
|
341
|
+
"extend": "default",
|
|
342
|
+
"rules": { "type-claim": "on", "untrusted-value": "on", "untrustedCallbacks": "inline" }
|
|
343
|
+
}
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
- `"type-claim"` / `"untrusted-value"` / `"dropped-result"`: `"on"` or `"off"` (default `"off"`). `dropped-result`
|
|
347
|
+
(see [`dropped-result`](#dropped-result-every-failure-is-passed-up-or-handled)) reports every place a `Result` that
|
|
348
|
+
can still fail is dropped instead of returned or handled. `redundant-guard`
|
|
349
|
+
(see [`redundant-guard`](#redundant-guard-a-guard-around-code-that-cannot-fail)) reports a guard around code that
|
|
350
|
+
cannot fail. Both use `"on"` / `"off"` like the others.
|
|
351
|
+
- `"untrustedCallbacks"`: which callback parameters `untrusted-value` treats as untrusted: `"inline"` (default: a
|
|
352
|
+
parameter of a function written inline where an origin that is not type-trusted calls it, e.g.
|
|
353
|
+
`ws.on('message', (data) => …)`), `"off"` (none), or `"all"` (`"inline"`, plus every function handed to such
|
|
354
|
+
an origin some other way, judged at the hand-off: see
|
|
355
|
+
[Callbacks not written inline](#callbacks-not-written-inline-untrustedcallbacks-all)).
|
|
356
|
+
- Each key inherits through `extend` on its own, like the other keys: the nearest file that sets it wins. A
|
|
357
|
+
shared base config can turn a rule on for every project that extends it, and one project can still turn it off.
|
|
358
|
+
|
|
359
|
+
The CLI (`trust check`, `trust baseline`, `trust explain`, `trust refactor`) and the ESLint rules read the same
|
|
360
|
+
settings, so they always agree. `typedConfig` still registers `trust/type-claim` and `trust/untrusted-value`;
|
|
361
|
+
they report nothing while the config leaves them off. `trust explain` says when a rule is off instead of listing
|
|
362
|
+
its claims or values. After you turn a rule on, run `trust baseline --update` to record what it finds today.
|
|
363
|
+
|
|
364
|
+
### Breaking in 0.4.0
|
|
365
|
+
|
|
366
|
+
`Result` is now only `{ ok, err }`. `try`, `tryAsync`, `decide` and `translate` moved to `Trust`:
|
|
367
|
+
`Result.try` → `Trust.try`, `Result.tryAsync` → `Trust.tryAsync`, `Result.decide` → `Trust.decide`,
|
|
368
|
+
`Result.translate` → `Trust.translate`. The underlying functions (`ok`, `err`, `tryResult`, `tryResultAsync`,
|
|
369
|
+
`decide`, `translate`) stay exported for declaration identity; write the namespace form in application code.
|
|
370
|
+
|
|
58
371
|
### Breaking in 0.3.0
|
|
59
372
|
|
|
60
373
|
An inline `err({ kind: ... })` now keeps its literal kind, so a callback returning several different failures no longer collapses to `{ kind: string }`. Give the receiving function a union type, or let it infer the callback's whole return type.
|
|
61
374
|
|
|
62
375
|
## Lint: `@noego/trust/eslint`
|
|
63
376
|
|
|
64
|
-
Rules (typed linting required for `untrusted-call-must-return-result`):
|
|
377
|
+
Rules (typed linting required for `untrusted-call-must-return-result`, `type-claim` and `untrusted-value`):
|
|
65
378
|
|
|
66
379
|
- `trust/untrusted-call-must-return-result`: calls/`new` into untrusted origins must be guarded.
|
|
67
380
|
Messages: `unguarded`, `notAwaited`, `callsIgnored`, `rethrow`, `notResultErr`, `rawCatchValue`, `notAllPaths`.
|
|
68
381
|
- `trust/throw-must-return-result`: every `throw` must be guarded.
|
|
382
|
+
- `trust/type-claim`: every place a type is claimed instead of proven (see [`type-claim`](#type-claim-types-that-are-claimed-not-proven)).
|
|
383
|
+
Messages are the claim kinds: `claim:as`, `claim:non-null`, `claim:any`, `claim:predicate`, `claim:generic-return`,
|
|
384
|
+
`unanalyzable`, and `directive` (a `//trust:` comment that marks nothing). `typedConfig` enables it with the other two.
|
|
385
|
+
- `trust/untrusted-value`: every use of a value whose type was declared by an origin that is not type-trusted
|
|
386
|
+
(see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)). Messages: `untrusted`, and `callerChosen` for a
|
|
387
|
+
return type the call picked itself. `typedConfig` enables it too.
|
|
388
|
+
|
|
389
|
+
The plugin is a thin adapter: it maps ESLint's nodes to TypeScript nodes and runs the same rule code as
|
|
390
|
+
`trust check`, so `eslint` and `typescript-eslint` are optional peers needed only for the plugin.
|
|
69
391
|
|
|
70
392
|
```js
|
|
71
393
|
// eslint.config.js
|
|
@@ -84,33 +406,65 @@ export default [
|
|
|
84
406
|
"extend": "default",
|
|
85
407
|
"trust": ["zod", { "origin": "@noego/ioc", "reason": "DI container, no I/O" }],
|
|
86
408
|
"distrust": ["js:Array.from"],
|
|
409
|
+
"trust_type": ["zod", { "origin": "node:path", "reason": "returns plain strings" }],
|
|
410
|
+
"distrust_type": [],
|
|
87
411
|
"passthrough": ["server/repositories/**"],
|
|
88
|
-
"ignore": ["**/*.test.ts", "server/testing/**"]
|
|
412
|
+
"ignore": ["**/*.test.ts", "server/testing/**"],
|
|
413
|
+
"strict": ["server/services/workspace/**", "server/controller/workspace.controller.ts"],
|
|
414
|
+
"tsconfig": [{ "files": "ui/**", "tsconfig": "tsconfig.web.json" }]
|
|
89
415
|
}
|
|
90
416
|
```
|
|
91
417
|
|
|
92
|
-
- `extend`: a preset (`js`, `node`, `web`, `default`) or a relative path
|
|
418
|
+
- `extend`: a preset (`js`, `node`, `web`, `default`, `svelte`) or a relative path, or a non-empty array of them
|
|
419
|
+
(`"extend": ["web", "svelte"]`). Chains are followed. Array entries apply left to right: a later entry
|
|
420
|
+
overrides an earlier one, and the file itself overrides all of them. For `"extend": ["a", "b"]` the lookup
|
|
421
|
+
order is this file, then `b`'s chain, then `a`'s chain; a level both reach (`js`) is looked at once, at its
|
|
422
|
+
first position in that order. Settings with a single value (each `rules` key) come from the nearest level
|
|
423
|
+
that sets them, so `b` beats `a`. An empty array, an entry that is not a non-empty string, the same entry
|
|
424
|
+
twice, an unknown preset and a cycle through any entry are load errors naming the file. Presets may extend
|
|
425
|
+
an array of presets, never a file.
|
|
93
426
|
- `trust` / `distrust`: origins. An entry covers the origin itself, its subpaths (`node:fs` covers
|
|
94
427
|
`node:fs/promises`), and its members (`js:JSON` covers `js:JSON.parse`). Lookup walks from this file toward the
|
|
95
428
|
root preset; the first level whose `distrust` matches makes it untrusted, so `distrust` removes inherited trust.
|
|
429
|
+
- `trust_type` / `distrust_type`: a second, separate pair of lists with the same origin syntax, entry shapes
|
|
430
|
+
(`"origin"` or `{ "origin", "reason" }`), `extend` chain and lookup. `trust` says a call into the origin cannot
|
|
431
|
+
fail; `trust_type` says the types the origin declares are true at runtime. Neither implies the other:
|
|
432
|
+
`fs.readFileSync` can throw but its `string` is true; a typed IPC payload cannot throw but its type may be
|
|
433
|
+
false. An origin not on the type-trust list gives untrusted values (see
|
|
434
|
+
[`untrusted-value`](#untrusted-value-type-trust-is-opt-in)). Within one file an origin may not be on both
|
|
435
|
+
`trust_type` and `distrust_type`; it may be on `trust` and `distrust_type`. First-party code in checked files and
|
|
436
|
+
`@noego/trust` itself need no entry. The earlier names `typeTrust` / `typeDistrust` are rejected with an error
|
|
437
|
+
naming the replacement.
|
|
96
438
|
- `passthrough`: files not checked inside; calls *into* them from checked code are untrusted (`local:<path>#<member>`).
|
|
97
439
|
- `ignore`: files not checked inside and trusted from outside; calls into them from checked code are reported
|
|
98
440
|
(`callsIgnored`) because ignoring alone silently trusts.
|
|
441
|
+
- `strict` (`trust check` only): globs of files that are always checked under the strict rules, with or without
|
|
442
|
+
the `--strict` flag. Use it to hold finished parts of the tree to the strict standard. `!negation` carves files
|
|
443
|
+
back out; `ignore` still wins. `trust baseline` and ESLint ignore this key.
|
|
444
|
+
- `tsconfig` (CLI only): an ordered list of `{ "files": <glob or globs>, "tsconfig": <path> }`. The first entry
|
|
445
|
+
whose globs match a file picks the tsconfig its program is built from; the path is relative to the config
|
|
446
|
+
file's directory. `--tsconfig` overrides it, and files no entry matches use the nearest `tsconfig.json`. A file
|
|
447
|
+
that maps to a missing tsconfig stops the run (exit 2) with the entry named. ESLint ignores this key.
|
|
99
448
|
- Globs use ESLint flat-config semantics (minimatch, `dot: true`, `!negation`, last match wins), relative to the
|
|
100
449
|
config file's directory, matched on realpaths. A glob matching no file is a load error.
|
|
101
450
|
|
|
102
451
|
A call is also trusted when its declared return type is `Result` / `Promise<Result>` from `@noego/trust`,
|
|
103
|
-
unless its origin is explicitly distrusted. `Result.err`, `
|
|
452
|
+
unless its origin is explicitly distrusted. `Result.err`, `Trust.try` and `Trust.tryAsync` are recognised
|
|
104
453
|
by declaration, not by name.
|
|
105
454
|
|
|
106
455
|
### Presets
|
|
107
456
|
|
|
108
|
-
| Preset | Extends | Trusts |
|
|
109
|
-
|
|
110
|
-
| `js` | | Pure JavaScript built-ins that cannot fail on typed input (`js:Array`, `js:Map`, `js:Math`, …), the same in every runtime. |
|
|
111
|
-
| `node` | `js` | Node built-in APIs, audited member by member against the Node v24 source (v26 recorded). |
|
|
112
|
-
| `web` | `js` | Nothing beyond `js` yet: browser globals have not been audited. |
|
|
113
|
-
| `default` | `node` | Alias of `node`. |
|
|
457
|
+
| Preset | Extends | Trusts (cannot fail) | Type-trusts |
|
|
458
|
+
|---|---|---|---|
|
|
459
|
+
| `js` | | Pure JavaScript built-ins that cannot fail on typed input (`js:Array`, `js:Map`, `js:Math`, …), the same in every runtime. | The language built-ins whose declared types hold whenever their inputs have theirs (`js:Array`, `js:String`, `js:Map`, `js:Promise`, `js:Math`, …). |
|
|
460
|
+
| `node` | `js` | Node built-in APIs, audited member by member against the Node v24 source (v26 recorded). | Nothing beyond `js` yet. |
|
|
461
|
+
| `web` | `js` | Nothing beyond `js` yet: browser globals have not been audited. | Nothing beyond `js` yet. |
|
|
462
|
+
| `default` | `node` | Alias of `node`. | Alias of `node`. |
|
|
463
|
+
| `svelte` | | Svelte 5 runes (`svelte.$state`, `svelte.$derived`, `svelte.$effect`, `svelte.$props`, `svelte.$bindable`, `svelte.$inspect`, each with its sub-runes), `svelte.tick`, `svelte/store`, and `SvelteMap` / `SvelteSet` / `SvelteDate` / `createSubscriber` of `svelte/reactivity` (not `SvelteURL` / `SvelteURLSearchParams`: their constructors throw). | The runes that return what they are given: `$state`, `$state.raw`, `$derived`, `$derived.by`. Not `$state.snapshot` (a clone, typed by approximation) and not `$props` (declared `any`). |
|
|
464
|
+
|
|
465
|
+
`svelte` extends nothing: it is an add-on for a runtime preset, `"extend": ["web", "svelte"]` or
|
|
466
|
+
`["default", "svelte"]`. Runes are global functions in svelte's types, so their origins are `svelte.<rune>`
|
|
467
|
+
(`svelte.$state`, `svelte.$state.raw`).
|
|
114
468
|
|
|
115
469
|
The `node` list trusts a call only if arguments that satisfy its TypeScript types cannot make it throw or fail
|
|
116
470
|
asynchronously (rejected promise, error-first callback, an `'error'` event caused by the call). Doing I/O or
|
|
@@ -120,6 +474,15 @@ not, and neither do engine resource limits. Whole-module or whole-class entries
|
|
|
120
474
|
was trusted, with explicit `distrust` entries for any member that can fail under a trusted class. The evidence
|
|
121
475
|
for every entry is in `research/node-api/`.
|
|
122
476
|
|
|
477
|
+
Type trust is a separate audit, and so far only the `js` preset (and `svelte`, for its runes) has one: built-ins that carry their types from
|
|
478
|
+
what they are given (an array of users maps over users) or return what the specification says. It leaves out
|
|
479
|
+
`js:JSON` (`parse` returns `any`; `stringify` is declared `string` but returns `undefined` for `undefined`, a
|
|
480
|
+
function or a symbol), the `groups` of a regular-expression match, and every DOM / web API except the timer
|
|
481
|
+
handles of `js:setTimeout` / `js:setInterval` (`js:fetch`, `js:Response`, `js:MessageEvent`, `js:Location`, …):
|
|
482
|
+
what those hold comes from outside. Node APIs are not type-trusted by any preset; add the ones a project relies
|
|
483
|
+
on to its own `trust_type` (`node:path`, `node:fs`, …). A config with no `extend` type-trusts nothing, not even
|
|
484
|
+
`js:Array`.
|
|
485
|
+
|
|
123
486
|
A project with several runtimes gives each area its own trust config:
|
|
124
487
|
|
|
125
488
|
```js
|
|
@@ -151,7 +514,568 @@ The old `builtin:` and `node.` prefixes are rejected at load time with the repla
|
|
|
151
514
|
## CLI: `trust`
|
|
152
515
|
|
|
153
516
|
```sh
|
|
154
|
-
trust explain server/services/foo.ts:42[:7] # origin + verdict for each call on that line
|
|
517
|
+
trust explain server/services/foo.ts:42[:7] # origin + throw-trust and type-trust verdict for each call on that line,
|
|
518
|
+
# why a type claim there is one, and where an untrusted value comes from
|
|
155
519
|
trust baseline server --update # write trust-baseline.json (file + rule + origin -> count)
|
|
156
520
|
trust baseline server # exit 1 when any count grows
|
|
521
|
+
trust baseline server --tsconfig tsconfig.json # one tsconfig for all files, as in trust check
|
|
522
|
+
trust check server # no baseline, no ESLint: exit 1 on any trust finding
|
|
523
|
+
trust check ui --tsconfig tsconfig.web.json # one tsconfig for all files instead of the mapped / nearest one
|
|
524
|
+
trust check server --strict # also fail on written return types
|
|
525
|
+
trust check ui --config /tmp/trust.json --root . # a config outside the project; its paths resolve against --root
|
|
526
|
+
trust refactor server # the order to fix the files with findings in: waves, leaves first
|
|
527
|
+
trust refactor server ui --json # the same plan as JSON: { "waves": [["a.ts", ["b.ts", "c.ts"]], ["d.ts"]], ... }
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
`trust check` needs no ESLint: it runs both trust rules, the promise rules, `type-claim` and `untrusted-value`
|
|
531
|
+
(all described below) with TypeScript alone (only `typescript` must be installed). It walks the given files and directories
|
|
532
|
+
for `.ts`/`.tsx` (skipping `node_modules`, `dist`, `.d.ts`),
|
|
533
|
+
skips files in the config's `ignore` zone, and reports with no baseline: every finding is a violation (exit 0 clean,
|
|
534
|
+
1 findings, 2 could not run: TypeScript not found, unreadable tsconfig, or a file that does not parse or load).
|
|
535
|
+
Findings, positions and messages are the same as the ESLint rules'. Each file is type-checked with `--tsconfig`
|
|
536
|
+
when given, else the tsconfig of the first matching `tsconfig` entry in the trust config, else the nearest
|
|
537
|
+
`tsconfig.json` above it (one program per tsconfig, rooted at the checked files plus the tsconfig's `.d.ts`
|
|
538
|
+
files). Map files whose ESLint tsconfig is not the nearest one (e.g. `ui/**` linted with `tsconfig.web.json`)
|
|
539
|
+
in the config, and `trust check server ui` needs no flags. `trust explain` resolves its file the same way.
|
|
540
|
+
`--root <dir>` (all three commands) resolves the config's globs, `tsconfig` paths and baseline keys against
|
|
541
|
+
`<dir>` instead of the config file's directory. `trust refactor` takes `--tsconfig` and `--root` the same way.
|
|
542
|
+
|
|
543
|
+
`trust baseline` runs on TypeScript alone too (no ESLint, no env flag): it finds files exactly as `trust check`
|
|
544
|
+
does, takes `--tsconfig <path>` the same way, and compares the core's findings with `trust-baseline.json`.
|
|
545
|
+
With paths (`trust baseline ui`), the run speaks only for the files it checked: only their entries are reported
|
|
546
|
+
as having fewer findings, and `--update` rewrites only their entries, keeping every other file's entries as they
|
|
547
|
+
are. Files skipped as ignored and files outside the paths never count. With no paths the run covers the whole
|
|
548
|
+
tree: every entry without its findings counts, and `--update` writes only the current findings (this is how
|
|
549
|
+
entries of deleted files go away).
|
|
550
|
+
|
|
551
|
+
Besides the two trust rules it counts two promise rules:
|
|
552
|
+
|
|
553
|
+
- `floating-promise` (origin `unhandled`): a promise expression statement that is not awaited, assigned, or
|
|
554
|
+
handled with `.catch(...)` / `.then(onFulfilled, onRejected)`. Prefix it with `void` to run it on purpose
|
|
555
|
+
without waiting.
|
|
556
|
+
- `misused-promise`: a promise used as a condition (`condition`: `if`, `while`, ternary, `!`, `&&`/`||`/`??`), or
|
|
557
|
+
an async callback passed where a void-returning function is expected (`void-callback`, e.g. `forEach`,
|
|
558
|
+
`setTimeout`).
|
|
559
|
+
|
|
560
|
+
Baseline entries under the old `@typescript-eslint/no-floating-promises` / `@typescript-eslint/no-misused-promises`
|
|
561
|
+
ids become stale (nothing reports those ids anymore); one `trust baseline --update` clears them and records the new
|
|
562
|
+
rule ids.
|
|
563
|
+
|
|
564
|
+
### `type-claim`: types that are claimed, not proven
|
|
565
|
+
|
|
566
|
+
The trust rules make every failure explicit; `type-claim` does the same for types. It reports every place where
|
|
567
|
+
a type is asserted instead of inferred or checked, so the list can be baselined and only shrink. `trust check`,
|
|
568
|
+
`trust baseline` and the ESLint plugin (`trust/type-claim`) run the same rule code. Each finding's origin is the
|
|
569
|
+
kind of claim, so the baseline groups them per file and kind:
|
|
570
|
+
|
|
571
|
+
| origin | what is reported | not reported |
|
|
572
|
+
|---|---|---|
|
|
573
|
+
| `claim:as` | `x as T` / `<T>x` when the type of `x` is not assignable to `T` (`unknown as User`, `string \| undefined` as `string`, a downcast) | a widening assertion (`admin as User`, `x as unknown`), `as const`, `satisfies` |
|
|
574
|
+
| `claim:non-null` | `x!` | `x ?? fallback`, a check that narrows |
|
|
575
|
+
| `claim:any` | a written `any` (also `as any`); a value of type `any` assigned, passed or returned where another type is expected; a member of an `any` value used, or the value called | `any` kept in an unannotated variable, or handed to `unknown` |
|
|
576
|
+
| `claim:predicate` | a written type predicate or assertion signature (`x is T`, `asserts x is T`, `asserts x`): the compiler does not check the body against it | a predicate the compiler infers from the body (no annotation) |
|
|
577
|
+
| `claim:generic-return` | a call whose type parameter appears only in the return type, so the caller picks the result type: `parse<User>(text)`, `const u: User = parse(text)`, `db.query<Row>(sql)`. Reported whatever the callee's origin, unless a `trust_type` entry of your own config covers it (see [`untrusted-value`](#untrusted-value-type-trust-is-opt-in)) | nothing chosen (the type parameter stays `unknown`, or the declaration's own default/constraint); a type parameter that also types a parameter; `new Map<K, V>()`; a callee whose own body proves the type for every choice (it has a body and no claim in it: `function none<T>(): T[] { return []; }`, a failure constructor returning `Result<T, E>`) |
|
|
578
|
+
| `unanalyzable` | a node the analyzer cannot type: a value or type that does not resolve (missing import, unknown name), a generic call whose declaration cannot be read, a TypeScript too old to answer (assignability needs 5.4). Never a silent pass | |
|
|
579
|
+
|
|
580
|
+
A member chain on an `any` value is one finding (at its first link), and `x as any` is one finding (at the
|
|
581
|
+
keyword) however the result is used. A cast from `any` (`JSON.parse(text) as User`) is `claim:any`, not
|
|
582
|
+
`claim:as`: `any` is assignable to everything, so the claim is the `any`. A declaration without a body (a
|
|
583
|
+
`.d.ts`, an overload or interface signature) proves nothing, so a caller-chosen generic declared that way is
|
|
584
|
+
a `claim:generic-return` unless your own config type-trusts its origin.
|
|
585
|
+
|
|
586
|
+
The only place a claim is allowed is inside a validator, a function marked `//trust:validator_function` (see
|
|
587
|
+
[Validators](#validators-trustvalidator_function)). Adopt the rule like the others: `trust baseline --update`
|
|
588
|
+
records today's claims, and from then on only new ones fail. `trust explain <file>:<line>` prints the kind and
|
|
589
|
+
the reason:
|
|
590
|
+
|
|
591
|
+
```text
|
|
592
|
+
server/users.ts:73 (zone: checked)
|
|
593
|
+
|
|
594
|
+
73:10 value as T
|
|
595
|
+
claim: claim:as (rule type-claim)
|
|
596
|
+
why: Type assertion claims "unknown" is "T", but "unknown" is not assignable to "T": nothing proves it. Narrow or validate the value instead.
|
|
597
|
+
```
|
|
598
|
+
|
|
599
|
+
Not covered: `.svelte` files, and TypeScript's own unsound corners (method bivariance, array covariance).
|
|
600
|
+
|
|
601
|
+
#### Validators: `//trust:validator_function`
|
|
602
|
+
|
|
603
|
+
A claim is allowed in one place: a **validator**, a function that checks an `unknown` value and returns it
|
|
604
|
+
typed. Mark it with the directive on the line directly above its declaration:
|
|
605
|
+
|
|
606
|
+
```ts
|
|
607
|
+
import { Result } from '@noego/trust';
|
|
608
|
+
|
|
609
|
+
//trust:validator_function
|
|
610
|
+
export function parseUser(input: unknown) {
|
|
611
|
+
if (typeof input !== 'object' || input === null || typeof (input as { name?: unknown }).name !== 'string') {
|
|
612
|
+
return Result.err({ kind: 'invalid', issues: ['name must be a string'] });
|
|
613
|
+
}
|
|
614
|
+
return Result.ok(input as User);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const parsed = parseUser(payload); // payload: unknown
|
|
618
|
+
if (!parsed.ok) return parsed; // Err<{ kind: 'invalid'; issues: string[] }>
|
|
619
|
+
parsed.value; // User
|
|
620
|
+
```
|
|
621
|
+
|
|
622
|
+
From there on that function is not questioned:
|
|
623
|
+
|
|
624
|
+
- No claim inside it is a finding: `as`, `!`, `any`, a written type predicate and a caller-chosen generic are
|
|
625
|
+
allowed in its signature, its body and the functions nested in it. Remove the directive and every one of
|
|
626
|
+
them is a finding again.
|
|
627
|
+
- Its return type is trusted at every call site: a generic validator (`validate<T>(input: unknown)`) is not a
|
|
628
|
+
`claim:generic-return` for its callers.
|
|
629
|
+
- Passing an untrusted value into it is the sanctioned exit from `unknown`. A validator returns `Result`, so a
|
|
630
|
+
failed validation is an ordinary failure kind (`{ kind: 'invalid', issues }`) that callers return or decide
|
|
631
|
+
like any other; a validator never throws.
|
|
632
|
+
|
|
633
|
+
The directive is recognised on a function declaration, a method (class or object literal), and an arrow or
|
|
634
|
+
function expression assigned to a `const`, exported or not (a space after `//` is fine). It must be the last
|
|
635
|
+
comment on the line directly above the declaration's first token: after any JSDoc, with no blank line between.
|
|
636
|
+
Every other `//trust:` comment, except `//trust:accept` (see
|
|
637
|
+
[Accepted failure paths](#accepted-failure-paths-trustaccept-reason)), is a finding (`type-claim`, origin `directive`): a misspelling
|
|
638
|
+
(`//trust:validator`), extra words after it, a block comment, or a directive above a blank line, a `let`, a
|
|
639
|
+
class, a class property, at the end of a block or a file, or alone inside an empty body, class, object, array,
|
|
640
|
+
type literal or parameter list. A typo cannot silently leave a function unmarked or mark the wrong thing.
|
|
641
|
+
|
|
642
|
+
The directive is a human decision, like a trust-list entry: trust does not inspect what a marked function does,
|
|
643
|
+
and a wrong validator means wrong trust. The recommended way to write one is to link the schema to the type,
|
|
644
|
+
so the compiler keeps them in agreement. With [AJV](https://ajv.js.org/), `JSONSchemaType<T>` rejects a schema
|
|
645
|
+
that does not match `T` (trust has no dependency on AJV and does not check schemas; this is the pattern):
|
|
646
|
+
|
|
647
|
+
```ts
|
|
648
|
+
import Ajv, { type JSONSchemaType } from 'ajv';
|
|
649
|
+
import { Result } from '@noego/trust';
|
|
650
|
+
|
|
651
|
+
interface User {
|
|
652
|
+
name: string;
|
|
653
|
+
age?: number;
|
|
654
|
+
role: 'admin' | 'member';
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// Does not compile when a property of User is missing, misnamed or mistyped here.
|
|
658
|
+
const userSchema: JSONSchemaType<User> = {
|
|
659
|
+
type: 'object',
|
|
660
|
+
properties: {
|
|
661
|
+
name: { type: 'string' },
|
|
662
|
+
age: { type: 'integer', nullable: true },
|
|
663
|
+
role: { type: 'string', enum: ['admin', 'member'] },
|
|
664
|
+
},
|
|
665
|
+
required: ['name', 'role'],
|
|
666
|
+
additionalProperties: false,
|
|
667
|
+
};
|
|
668
|
+
const isUser = new Ajv().compile(userSchema);
|
|
669
|
+
|
|
670
|
+
//trust:validator_function
|
|
671
|
+
export function parseUser(input: unknown) {
|
|
672
|
+
if (!isUser(input)) return Result.err({ kind: 'invalid', issues: isUser.errors ?? [] });
|
|
673
|
+
return Result.ok(input);
|
|
674
|
+
}
|
|
675
|
+
```
|
|
676
|
+
|
|
677
|
+
`JSONSchemaType<T>` patterns: an optional property (`age?: number`) is `nullable: true` and left out of
|
|
678
|
+
`required`; `T | null` is `{ type: ..., nullable: true }`; a union of object shapes is `oneOf` / `anyOf` with
|
|
679
|
+
each member written out; a `Date` or a class instance has no JSON form, so validate the wire shape (an ISO
|
|
680
|
+
string) and convert after the check.
|
|
681
|
+
|
|
682
|
+
#### Accepted failure paths: `//trust:accept <reason>`
|
|
683
|
+
|
|
684
|
+
Some failures are meant to escape: the one public edge where internal `Result` failures become the exceptions
|
|
685
|
+
an API promises, or a fallback that is the design. Accept such a failure path with the directive on the line
|
|
686
|
+
directly above **the statement**, the `throw` itself or the statement holding the call, never above its
|
|
687
|
+
function:
|
|
688
|
+
|
|
689
|
+
```ts
|
|
690
|
+
export function raise(failure: Failure): never {
|
|
691
|
+
//trust:accept public API contract: callers get these error classes
|
|
692
|
+
throw toError(failure);
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
try {
|
|
696
|
+
//trust:accept runtimes without async_hooks fall back to synchronous propagation
|
|
697
|
+
const hooks =
|
|
698
|
+
process.getBuiltinModule?.('node:async_hooks') ??
|
|
699
|
+
require('node:async_hooks');
|
|
700
|
+
// ...
|
|
701
|
+
} catch {
|
|
702
|
+
// fallback
|
|
703
|
+
}
|
|
704
|
+
```
|
|
705
|
+
|
|
706
|
+
- It accepts the findings of `throw-must-return-result`, `untrusted-call-must-return-result`,
|
|
707
|
+
`floating-promise` and `misused-promise` that belong to that statement, and nothing else. A finding belongs
|
|
708
|
+
to the innermost statement around it in the same function: a statement nested in a block of the accepted one
|
|
709
|
+
(an `if` or loop body) is one of its own, and so is everything inside a function or class written in it
|
|
710
|
+
(`const f = () => risky();` accepts nothing). Never the enclosing function, never a sibling statement.
|
|
711
|
+
- Never a type claim: validators are the only way out there.
|
|
712
|
+
- The reason is required: it is the human decision, like a trust-list entry. Nothing checks it.
|
|
713
|
+
- Placement is as strict as the validator directive's: the last comment on the line directly above the
|
|
714
|
+
statement's first token, no blank line between. The statement holds expressions of its own: an expression,
|
|
715
|
+
`const`/`let`/`var`, `return`, `throw`, `if`, a loop, `switch`, `export default`. A function, class or other
|
|
716
|
+
declaration, a block or a `try` is not one.
|
|
717
|
+
|
|
718
|
+
An accept that accepts nothing is a finding (`throw-must-return-result`, origin `directive`), whether or not
|
|
719
|
+
`type-claim` is on: no reason, a block comment, above a blank line, above a declaration or anything that is not
|
|
720
|
+
such a statement, or above a statement with nothing to accept (stale). A misspelling (`//trust:acept`) is no
|
|
721
|
+
accept: it accepts nothing, the finding below it stays, and `type-claim` (when on) reports the comment like any
|
|
722
|
+
unknown directive. `trust check`, `trust baseline`, `trust explain` and the ESLint rules decide it with the same
|
|
723
|
+
code; without type information the ESLint rule cannot tell a stale accept and does not report it.
|
|
724
|
+
`trust explain` lists each accepted finding on the line with its reason:
|
|
725
|
+
|
|
726
|
+
```text
|
|
727
|
+
91:5 throw toError(failure);
|
|
728
|
+
accepted: throw-must-return-result (throw) by //trust:accept on line 90
|
|
729
|
+
reason: public API contract: callers get these error classes
|
|
730
|
+
finding: `throw` must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Trust.try/tryAsync.
|
|
731
|
+
```
|
|
732
|
+
|
|
733
|
+
`--strict` adds `no-written-return-type`: a function, method, arrow or getter with a body must not spell out its
|
|
734
|
+
return type; the inferred type is the truth. Bodiless signatures,
|
|
735
|
+
type predicates (`x is Foo`) and assertion signatures (`asserts x`) are exempt. The flag makes every checked
|
|
736
|
+
file strict for that run; the config's `strict` globs make matching files strict on every `trust check` run
|
|
737
|
+
(the summary then says `(N strict by config)`). The `ignore` list is the only way to exempt a file.
|
|
738
|
+
|
|
739
|
+
### `untrusted-value`: type trust is opt-in
|
|
740
|
+
|
|
741
|
+
`type-claim` reports the claims written in checked code. `untrusted-value` covers the ones that arrive from
|
|
742
|
+
outside: a value is only as true as the type someone declared for it, and a DB row generic, a typed IPC
|
|
743
|
+
payload, `postMessage` data or a library `.d.ts` can all be wrong at runtime. So nothing external is
|
|
744
|
+
type-trusted unless a `trust_type` entry says so (see [trust.config.json](#trustconfigjson)), and a value from
|
|
745
|
+
anywhere else is treated like `unknown` until a validator has seen it.
|
|
746
|
+
|
|
747
|
+
A value is untrusted when the type it has was declared by an origin that is not on the type-trust list. It
|
|
748
|
+
enters checked code in one of these ways (the *entry*, shown by `trust explain`):
|
|
749
|
+
|
|
750
|
+
| entry | what | example |
|
|
751
|
+
|---|---|---|
|
|
752
|
+
| `return` | the result of a call / `new` into such an origin | `readConfig()`, `await fetchRow()` |
|
|
753
|
+
| `parameter` | a parameter of a callback whose signature such an origin declares: the outside calls it, and an annotation on the parameter is your claim | `ws.on('message', (data) => …)`, `ipcMain.handle((event, payload: Foo) => …)` |
|
|
754
|
+
| `read` | a property or global such an origin declares | `process.env.PORT`, `event.data`, `location.hash` |
|
|
755
|
+
| `generic-return` | the result of a call that picked its own return type, **even from a first-party origin or one only a built-in preset type-trusts** | `db.query<User>(sql)` |
|
|
756
|
+
| `catch` | a `catch` variable | `catch (error)` |
|
|
757
|
+
| `guard` | a value narrowed by a type guard or assertion function (`x is T`, `asserts x is T`, `asserts x`) whose signature such an origin declares: the narrowed type is that origin's claim, even when the value was declared `unknown` | `if (validateUser(input)) input.name` with `validateUser = ajv.compile(schema)`, `assertUser(input)` |
|
|
758
|
+
|
|
759
|
+
A `guard` names the origin that declares the **signature** the call resolves to, not the name it is called
|
|
760
|
+
through: `const validateUser = ajv.compile(schema)` is your name for AJV's `ValidateFunction<User>`, so the
|
|
761
|
+
origin is `ajv.ValidateFunction`, and `"trust_type": ["ajv"]` (or that member path) trusts what it narrows.
|
|
762
|
+
The guard counts where it holds: the branch of an `if` / `?:` / `&&` / `||` / loop its result decides, the code
|
|
763
|
+
after an `if` whose other branch exits (`if (!validateUser(input)) return;`), and the code after an assertion
|
|
764
|
+
call. Not a source: a guard your checked code declares (its written `x is T` is already a `claim:predicate`), a
|
|
765
|
+
validator, a guard declared by `@noego/trust`, and the built-in checks below.
|
|
766
|
+
|
|
767
|
+
It stays untrusted through `await`, `!`, parentheses, an assertion, `?:`, `??` / `||` / `&&`, and a `const` /
|
|
768
|
+
`let` with no written type. An untrusted value may only be:
|
|
769
|
+
|
|
770
|
+
- passed to a validator (a function marked [`//trust:validator_function`](#validators-trustvalidator_function));
|
|
771
|
+
- kept as `unknown`: stored, assigned, passed or returned where `unknown` is expected (`any` too; `type-claim`
|
|
772
|
+
reports that one);
|
|
773
|
+
- tested by a built-in check: `typeof`, `in`, `instanceof`, `Array.isArray`, `===` / `!==`, truthiness;
|
|
774
|
+
- thrown, discarded, or kept in a variable with no written type (it is still untrusted there).
|
|
775
|
+
|
|
776
|
+
Any other use is a finding that names the origin: passing or storing it where a type is expected, returning it
|
|
777
|
+
from a function that does not return `unknown`, reading a member, computing with it, iterating or spreading it.
|
|
778
|
+
|
|
779
|
+
```ts
|
|
780
|
+
const row = fetchRow(); // untrusted (returned by "pg-lib.fetchRow"), nothing reported yet
|
|
781
|
+
save(row); // finding: passed where "Row" is expected
|
|
782
|
+
const kept: unknown = fetchRow(); // fine: kept as unknown
|
|
783
|
+
const parsed = parseRow(fetchRow()); // fine: parseRow is a validator
|
|
784
|
+
ipcMain.handle('save', (event, payload: Order) => payload.id); // finding: read through its member "id"
|
|
785
|
+
const port: unknown = process.env.PORT; // fine
|
|
786
|
+
if (typeof port === 'string') listen(Number(port)); // fine: the compiler narrowed `unknown`
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
Members: who declares the member decides what reading it is.
|
|
790
|
+
|
|
791
|
+
- A member declared by an origin that is not type-trusted (`event.data`, `row.name` of the package's own
|
|
792
|
+
`Row`), or by nothing at all (an index signature: `process.env.PORT`), is a **read**: no finding, and the
|
|
793
|
+
member is the untrusted value, judged where it is used in turn.
|
|
794
|
+
- A member declared by checked code or by a type-trusted origin (`payload.id` of your own `Order`,
|
|
795
|
+
`text.length`) would come out looking trusted, so reading it from an untrusted value is the finding.
|
|
796
|
+
- A global or an imported constant (`process`, `JSON`, `location`) is a name, not a value that was handed
|
|
797
|
+
over: what is read from it is judged by the member's own declaration (`JSON.stringify` is fine with only
|
|
798
|
+
`js:JSON.stringify` type-trusted).
|
|
799
|
+
|
|
800
|
+
Narrowing happens on `unknown`. The compiler narrows a typed value against its declared type, and that type is
|
|
801
|
+
the unproven claim, so `typeof row.name === 'string'` is allowed but unlocks nothing; keep the value as
|
|
802
|
+
`unknown` and the compiler's own narrowing is the proof (a library's type guard is not: what it narrows is a
|
|
803
|
+
`guard` value). Nothing is reported for a value whose type claims
|
|
804
|
+
nothing: `unknown`, `any` (`type-claim` reports its uses), `void` / `undefined` / `null` / `never`, and functions
|
|
805
|
+
(a function is judged where it is called). That is why a `catch` variable never produces a finding here: it is
|
|
806
|
+
`unknown`, so the compiler already holds it. Uses inside a validator are not reported.
|
|
807
|
+
|
|
808
|
+
A caller-chosen generic return is reported twice on purpose: `type-claim` reports the call
|
|
809
|
+
(`claim:generic-return`), and `untrusted-value` reports each use of what it returned. A validator, or choosing
|
|
810
|
+
`unknown`, removes both. So does a `trust_type` entry **in your own config files** that covers the callee, at
|
|
811
|
+
member level or above: `"trust_type": ["@noego/ioc.Container.get"]` (or `["@noego/ioc"]`) says the container
|
|
812
|
+
returns whatever `T` the caller names, so `container.get<Foo>('x')` is neither a claim nor an untrusted value,
|
|
813
|
+
and a `distrust_type` entry that wins along the chain takes it back. Entries that come from the built-in presets
|
|
814
|
+
(`js`, `node`, `web`, `web_strict`, `svelte`) never unlock a caller-chosen return: a broad preset entry such as
|
|
815
|
+
`js:Array` must not silently bless `Array<User>(n)`; name the origin in your own config if you mean it. This
|
|
816
|
+
works for checked code too: a first-party generic is a claim unless your config names its `local:` origin
|
|
817
|
+
(`"trust_type": ["local:ui/actions/resolve_in_renderer_scope.ts#resolveSyncInScope"]`, the path relative to
|
|
818
|
+
the project root, i.e. the leaf config's directory).
|
|
819
|
+
|
|
820
|
+
Findings baseline per file + rule + origin, like every other rule, so `trust baseline --update` records today's
|
|
821
|
+
uses and only new ones fail. `trust explain <file>:<line>` prints the type-trust verdict of every call next to
|
|
822
|
+
its throw-trust verdict, and every untrusted value on the line with what became of it:
|
|
823
|
+
|
|
824
|
+
```text
|
|
825
|
+
server/orders.ts:17 (zone: checked)
|
|
826
|
+
|
|
827
|
+
17:11 fetchRow()
|
|
828
|
+
origin: pg-lib.fetchRow
|
|
829
|
+
verdict: UNTRUSTED (no trust entry matches)
|
|
830
|
+
hint: guard it, or trust "pg-lib.fetchRow" (or a prefix of it) in trust.config.json
|
|
831
|
+
types: UNTRUSTED (no trust_type entry matches)
|
|
832
|
+
validate what it returns, or add "pg-lib.fetchRow" (or a prefix of it) to "trust_type" in trust.config.json
|
|
833
|
+
declared: /repo/node_modules/pg-lib/index.d.ts:13
|
|
834
|
+
|
|
835
|
+
17:11 fetchRow()
|
|
836
|
+
value: untrusted "Row", returned by "pg-lib.fetchRow" (rule untrusted-value)
|
|
837
|
+
use: Untrusted value returned by "pg-lib.fetchRow" is passed where "Row" is expected: its type "Row" is declared, not proven. …
|
|
838
|
+
```
|
|
839
|
+
|
|
840
|
+
The `types:` line is one of: `trusted` (first-party code, `@noego/trust` itself, or a validator),
|
|
841
|
+
`type-trusted by "<entry>" in <config level>`, `UNTRUSTED (no trust_type entry matches)`,
|
|
842
|
+
`UNTRUSTED (type-distrusted by "<entry>" in <config level>)`, or `UNTRUSTED (the call picks its own return type …)`.
|
|
843
|
+
|
|
844
|
+
A call to a type guard or assertion function also gets `guard:` lines: what it narrows, the predicate, the
|
|
845
|
+
origin of its signature, and whether that origin is type-trusted:
|
|
846
|
+
|
|
847
|
+
```text
|
|
848
|
+
10:7 validateUser(input)
|
|
849
|
+
…
|
|
850
|
+
guard: narrows "input" (data is User), declared by "ajv.ValidateFunction"
|
|
851
|
+
UNTRUSTED (no trust_type entry matches): the narrowed value is untrusted (rule untrusted-value)
|
|
852
|
+
validate the value instead, or add "ajv.ValidateFunction" (or a prefix of it) to "trust_type" in trust.config.json
|
|
853
|
+
```
|
|
854
|
+
|
|
855
|
+
#### Callbacks not written inline (`"untrustedCallbacks": "all"`)
|
|
856
|
+
|
|
857
|
+
With the default `"inline"`, a callback is linked to the origin that calls it only when it is written inline at
|
|
858
|
+
the call. A function written any other way adopts the library's declared type silently:
|
|
859
|
+
`function handle(data: Mine) { … }; ws.on('message', handle)` reports nothing. Set
|
|
860
|
+
`"rules": { "untrustedCallbacks": "all" }` to judge every function you hand to an origin that is not
|
|
861
|
+
type-trusted, at the hand-off:
|
|
862
|
+
|
|
863
|
+
- At every call / `new` into such an origin, each argument whose expected type has call signatures (a callback)
|
|
864
|
+
or methods (a handler object, a class instance) is resolved to the functions it hands over: a named function,
|
|
865
|
+
a `const` function, `this.method`, `fn.bind(...)` (bound arguments skipped), the methods and properties of an
|
|
866
|
+
object literal (or of a `const` holding one), and the methods and function fields of a class instance.
|
|
867
|
+
- A class that `implements` an interface such an origin declares is judged at its `implements` clause, each
|
|
868
|
+
implementing method against the interface member.
|
|
869
|
+
- Each parameter the origin fills whose type claims something (anything but `unknown` / `any`; an unconstrained
|
|
870
|
+
type parameter counts as `unknown`) is a finding at the hand-off, naming the origin:
|
|
871
|
+
|
|
872
|
+
```text
|
|
873
|
+
"handle" receives data from "ws.WebSocket.on" but declares its parameter "data" as "Mine", which nothing
|
|
874
|
+
proves. Declare the parameter `unknown` and validate it, or, if "ws.WebSocket.on" declares true types, add it
|
|
875
|
+
to "trust_type" in trust.config.json.
|
|
157
876
|
```
|
|
877
|
+
|
|
878
|
+
The function itself is not tainted: first-party code may call `handle` with a value it has checked, and those
|
|
879
|
+
calls are not reported. The way out is configuration only: a `trust_type` entry for the method that calls it
|
|
880
|
+
(`"ws.WebSocket.on"`, `"evil-lib.on"`) clears every hand-off to it (and the inline case too, when the callback's
|
|
881
|
+
signature is written in that method's declaration, as in `on(event, handler: (data: Payload) => void)`); for `implements`, the
|
|
882
|
+
entry is the interface member (`"evil-lib.Handler.onData"`) or the interface. An inline arrow or function
|
|
883
|
+
expression is unchanged: its parameters stay untrusted values judged where they are used, exactly as under
|
|
884
|
+
`"inline"`. Nothing is reported inside a validator, and a validator handed over is not questioned. `"inline"` and
|
|
885
|
+
`"off"` report none of these findings; turning `"all"` on adds only them, so run `trust baseline --update` after.
|
|
886
|
+
|
|
887
|
+
Not covered: values that reach a field or a collection through code that is not checked, and a function handed
|
|
888
|
+
over through a parameter or a mutable variable (`let`), whose value is not known where it is handed over.
|
|
889
|
+
|
|
890
|
+
### `dropped-result`: every failure is passed up or handled
|
|
891
|
+
|
|
892
|
+
The trust rules turn every throw into a `Result`; `dropped-result` makes sure no `Result` that can still fail is
|
|
893
|
+
then lost. It is opt-in: `"rules": { "dropped-result": "on" }` in trust.config.json (`trust check`, `trust baseline`
|
|
894
|
+
and the ESLint rule `trust/dropped-result` read the same switch).
|
|
895
|
+
|
|
896
|
+
A value can fail when its type has an `Err` member (awaited, and one level into an array or tuple, so
|
|
897
|
+
`Promise.all([...])` counts). Each such value is followed through the function that holds it, path by path, and must
|
|
898
|
+
end in one of two ways:
|
|
899
|
+
|
|
900
|
+
- **passed up**: returned (`return r`, `if (!r.ok) return r;`, an arrow function's expression body), or flowing into
|
|
901
|
+
a call whose own value can fail (`Promise.all`, a wrapper returning it). On a path where a value is known to be an
|
|
902
|
+
`Err`, returning any value that can fail passes it up (`if (!r.ok) return Result.err({ kind: 'LoadFailed' })`), and
|
|
903
|
+
the first failure returned covers the values not checked yet on that path.
|
|
904
|
+
- **carried out**: the returned value takes the failure along, whatever its type: `return this.failed(r.error)`,
|
|
905
|
+
`return reply(r)`, `return { error: r.error }`, or a call's `Result` returned inside the response
|
|
906
|
+
(`return this.reply('status', await svc.status())`). This is how a controller hands its failures to the
|
|
907
|
+
framework. Reading only `r.ok` / `r.value` carries nothing, and neither does a call that returns nothing.
|
|
908
|
+
- **handled**: `Trust.decide` / `Trust.translate` (what they leave is a new value, followed the same way), a branch
|
|
909
|
+
that names the kind (`r.error.kind === 'NotFound'`, `case 'NotFound':`), or handed to a parameter whose declared
|
|
910
|
+
type is a `Result` (that function is checked in turn, its parameter followed like a variable).
|
|
911
|
+
In a `switch (r.error.kind)`, each `case` narrows to its kind and a `default` receives only the kinds no
|
|
912
|
+
`case` names; with every kind named, the `default` has nothing left, which is the exhaustive form
|
|
913
|
+
(see [The edge decides everything that is left](#the-edge-decides-everything-that-is-left)).
|
|
914
|
+
|
|
915
|
+
Everything else is reported with the kinds still possible there. The origin is the baseline key:
|
|
916
|
+
|
|
917
|
+
| Origin | What dropped the failure |
|
|
918
|
+
|---|---|
|
|
919
|
+
| `discarded` | a call's `Result` nobody keeps: an expression statement, `void`, `f().ok` |
|
|
920
|
+
| `argument` | a call's `Result` passed where no `Result` is expected (`console.log(f())`) |
|
|
921
|
+
| `stored` | a call's `Result` put where failures are not followed (an object property, a field) |
|
|
922
|
+
| `callback` | a function returning a `Result` handed to a callee that takes no `Result` back (`forEach`, an event listener) |
|
|
923
|
+
| `return` | a `return` that neither passes a variable up nor follows a check that handled it (`if (!r.ok) return null`) |
|
|
924
|
+
| `end` | a variable that can still fail when it goes out of scope: the end of its function or block (falling off the end of an `if` / `else if` chain that misses a kind), a `break` / `continue` |
|
|
925
|
+
| `overwritten` | a variable assigned again while it can still fail |
|
|
926
|
+
|
|
927
|
+
```ts
|
|
928
|
+
const r = find(); // Result<number, { kind: 'NotFound' } | { kind: 'Locked' }>
|
|
929
|
+
if (r.ok) return Result.ok(r.value);
|
|
930
|
+
else if (r.error.kind === 'NotFound') return Result.ok(0);
|
|
931
|
+
// dropped-result (end): `r` can still fail with "Locked" when it goes out of scope here
|
|
932
|
+
```
|
|
933
|
+
|
|
934
|
+
A kind that is not a string literal (`{ kind: string }`) can never be named away: such a value is passed up or
|
|
935
|
+
decided. Variables are followed in the function that declares them; a module-level variable is not followed, and a
|
|
936
|
+
closure reading a variable of an outer function does not handle it. Control flow is followed through if / else,
|
|
937
|
+
switch, loops (one pass), try / catch / finally, labels, break and continue; conditions narrow on `r.ok` (with `!`,
|
|
938
|
+
`&&`, `||`, `=== true` / `false`) and on `r.error.kind` compared with a string literal. `//trust:accept` does not
|
|
939
|
+
accept a dropped-result finding.
|
|
940
|
+
|
|
941
|
+
### `redundant-guard`: a guard around code that cannot fail
|
|
942
|
+
|
|
943
|
+
The other half of the same contract: a guard (`Trust.try` / `Trust.tryAsync`, or a `try` whose `catch` returns
|
|
944
|
+
`Result.err`) turns a throw into a named failure, so around code that cannot throw it invents a failure path. Every
|
|
945
|
+
caller then holds a `Result` whose `Err` never happens, and a caller that forgets to unwrap it uses the `Result` as
|
|
946
|
+
the value. Opt-in: `"rules": { "redundant-guard": "on" }`.
|
|
947
|
+
|
|
948
|
+
The guarded code can fail when it holds, outside nested functions: a call or `new` whose origin is untrusted,
|
|
949
|
+
unresolved or in an ignored file; a call into first-party code not declared to return a `Result` (it may still
|
|
950
|
+
throw); a `throw`; a dynamic `import()`; an `await` (or `for await`) of something that is not a call. Calls into
|
|
951
|
+
trusted origins and to functions declared to return a `Result` cannot fail. A guard around only those is reported at
|
|
952
|
+
the guard (origin `redundant`):
|
|
953
|
+
|
|
954
|
+
```ts
|
|
955
|
+
// trust.config.json trusts @noego/ioc: resolution failures are programmer errors at boot
|
|
956
|
+
async instance<T>(token: new () => T) {
|
|
957
|
+
return Trust.tryAsync(() => this.scope.instance(token), (cause) => ({ kind: 'resolution_failed', cause }));
|
|
958
|
+
// redundant-guard: `Trust.tryAsync` guards nothing that can fail: every call inside is trusted ("@noego/ioc…")
|
|
959
|
+
}
|
|
960
|
+
```
|
|
961
|
+
|
|
962
|
+
Fix it by calling directly and returning the value. If the call really can fail, the trust entry is wrong: remove the
|
|
963
|
+
origin from `trust`, and the guard becomes required again.
|
|
964
|
+
|
|
965
|
+
### `trust refactor`: the order to refactor in
|
|
966
|
+
|
|
967
|
+
```sh
|
|
968
|
+
trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--baseline <path>] [--config <path>] [--tsconfig <path>] [--root <dir>]
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
A file's inferred failure and return types change when the files it imports change, so fixing findings top-down
|
|
972
|
+
means doing work twice. `trust refactor` prints the order that avoids it. It builds the static import graph of
|
|
973
|
+
the files `trust baseline` would check (same file walk, same programs and `tsconfig` mapping, `ignore` zone
|
|
974
|
+
skipped; the current directory when no path is given) and prints a plan:
|
|
975
|
+
|
|
976
|
+
```json
|
|
977
|
+
{ "waves": [["a.ts", "b.ts", ["c.ts", "d.ts"]], ["e.ts"]] }
|
|
978
|
+
```
|
|
979
|
+
|
|
980
|
+
- A **wave** is a list of work items that can be done in parallel. A wave starts when the wave before it is
|
|
981
|
+
done: everything a file imports is in an earlier wave, so the first wave is the leaves.
|
|
982
|
+
- A **string** is one file. An **array** is a circular-import group: files that import each other, directly or
|
|
983
|
+
through other files, and so must be refactored together.
|
|
984
|
+
- Only files with findings are in the plan. A file with no findings is left out, but the order it carries is
|
|
985
|
+
kept: if `top.ts` imports `clean.ts` and `clean.ts` imports `leaf.ts`, `top.ts` still comes after `leaf.ts`.
|
|
986
|
+
In a circular group only the files with findings are listed; a group with one such file is a plain string.
|
|
987
|
+
|
|
988
|
+
The findings come from `trust-baseline.json` in the project root (or `--baseline <path>`, which must exist): a
|
|
989
|
+
file is work when the baseline has a count above zero for it. With no baseline file the command runs a fresh
|
|
990
|
+
check (the rules `trust baseline` counts) and uses the files that have findings. The last line of the text
|
|
991
|
+
output says which one was used.
|
|
992
|
+
|
|
993
|
+
How imports become edges:
|
|
994
|
+
|
|
995
|
+
- A named or default import, and a named re-export, points at the file that declares the name. An import through
|
|
996
|
+
a barrel (`export { a } from './a'`) depends on `a.ts`, not on the barrel, so barrels do not create cycles.
|
|
997
|
+
- `import * as`, `export *`, `import x = require(...)`, `import './x'` and `import('./x')` point at the module file.
|
|
998
|
+
- Type-only imports count (inferred types flow through them). `--value-only` leaves out the ones written as
|
|
999
|
+
type-only: `import type`, `export type`, `{ type X }`, and `import('./x').T` in a type.
|
|
1000
|
+
- Only the files of the run are in the graph: an import of a file outside the paths, in the `ignore` zone, or in
|
|
1001
|
+
`node_modules` is not an edge.
|
|
1002
|
+
|
|
1003
|
+
What the graph cannot see is reported, not guessed:
|
|
1004
|
+
|
|
1005
|
+
- `import(expression)` with a computed specifier is listed under `warnings` (file, line, column, and the
|
|
1006
|
+
expression's text). Order the files it loads by hand.
|
|
1007
|
+
- A file that no program can load, or that does not parse, stops the run (exit 2), as in `trust baseline`.
|
|
1008
|
+
|
|
1009
|
+
`--json` prints one document: `waves` as above, plus `cycles` (every circular group, largest first, with `size`,
|
|
1010
|
+
all its `files`, the `tasks` among them, `tooLarge` and `closingEdges`), `warnings`, and a `summary` (files and
|
|
1011
|
+
import edges in the graph, files with findings, work items, ignored files, where the findings came from).
|
|
1012
|
+
The text output prints the same plan as `Wave 1 of N`, `Wave 2 of N`, …, then the circular groups, the computed
|
|
1013
|
+
imports and a one-line summary. Exit code 0 means a plan was printed; 2 means the command could not run
|
|
1014
|
+
(TypeScript not found, unreadable tsconfig or baseline, a missing path, or a file that does not load).
|
|
1015
|
+
|
|
1016
|
+
#### Circular groups: what closes them
|
|
1017
|
+
|
|
1018
|
+
Every circular group lists its **closing edges**: a small set of imports without which the group has no cycle.
|
|
1019
|
+
|
|
1020
|
+
```json
|
|
1021
|
+
{ "from": "view.ts", "to": "model.ts", "names": ["LIMIT", "Model"] }
|
|
1022
|
+
```
|
|
1023
|
+
|
|
1024
|
+
reads "`view.ts` imports `LIMIT` and `Model` from `model.ts`" (`*` is the module as a whole). Removing these
|
|
1025
|
+
imports is optional structural cleanup: it ends the circle for good. A common case is a types file that imports
|
|
1026
|
+
an implementation. The set is chosen to be cheap to cut (an import of names that cannot change, such as an
|
|
1027
|
+
interface, costs less than an import of a function); it is small, but not always the smallest possible.
|
|
1028
|
+
|
|
1029
|
+
#### Circular groups that are too large
|
|
1030
|
+
|
|
1031
|
+
A circular group with more than 8 files (`--max-group <n>` changes the limit) is `tooLarge`: too large for one
|
|
1032
|
+
unit of work. The command shrinks it in three steps. Groups at or under the limit are left as they are, and a
|
|
1033
|
+
unit above the limit is never emitted without saying so.
|
|
1034
|
+
|
|
1035
|
+
**1. Imports that cannot carry a change are dropped.** An import orders two files only when what it imports can
|
|
1036
|
+
change because of the refactor:
|
|
1037
|
+
|
|
1038
|
+
| Imported | Can it change? |
|
|
1039
|
+
| --- | --- |
|
|
1040
|
+
| A function, method, accessor or constructor with a body | Yes. Its inferred types follow what it calls. A written return type that is not a `Result` is rewritten when the function fails |
|
|
1041
|
+
| A function whose written return type is a `Result` (or a promise of one) | No. It is a frozen contract |
|
|
1042
|
+
| A variable or property with an inferred type | Yes, unless its value is a literal (`10`, `'x'`, `[1, 2] as const`, an object of literals) |
|
|
1043
|
+
| A class | Yes, when a member or its base class can |
|
|
1044
|
+
| An interface, a type alias, a written type annotation, a signature without a body | Only when it mentions something that can: `typeof load`, a class |
|
|
1045
|
+
| An enum, anything in a `.d.ts` file, an import that binds no name (`import './x'`) | No |
|
|
1046
|
+
| A whole module (`import * as`, `export *`, `import('./x')`) | Yes, when one of its exports can |
|
|
1047
|
+
| Anything else | Yes. The import is kept when in doubt |
|
|
1048
|
+
|
|
1049
|
+
The group is planned again without the imports that cannot carry a change. `waves` then holds what is left of it:
|
|
1050
|
+
smaller groups and single files, each in its own place. The group's entry in `cycles` gets
|
|
1051
|
+
`split: { droppedEdges, keptEdges, groups }`, where `groups` are the circular groups still inside it (empty when
|
|
1052
|
+
it fell apart). Only imports inside a too-large group are dropped; every other import orders its files as before.
|
|
1053
|
+
This step looks at what is imported, not at how the import is written: `import { Model }` of an interface is
|
|
1054
|
+
dropped, `import type { Store }` of a class with methods is kept.
|
|
1055
|
+
|
|
1056
|
+
**2. A group that is still too large gets an internal order.** It stays one work item (an array in `waves`), and
|
|
1057
|
+
its entry under `split.groups` has `tooLarge: true` and an `order`: the declarations with findings, in waves,
|
|
1058
|
+
callees first.
|
|
1059
|
+
|
|
1060
|
+
```json
|
|
1061
|
+
{ "order": [["c.ts#load"], ["d.ts#save"], ["c.ts#report"]], "recursion": [] }
|
|
1062
|
+
```
|
|
1063
|
+
|
|
1064
|
+
Files that import each other in a circle usually do not call each other in a circle, so the order comes from the
|
|
1065
|
+
calls between declarations (each call is resolved the way `trust explain` resolves it). A declaration is named
|
|
1066
|
+
`file#name`: `c.ts#load`, `c.ts#Store.load` for a class member, `c.ts#Tools.run` inside a namespace,
|
|
1067
|
+
`c.ts#default` for an unnamed default export, and `c.ts#(top level)` for statements outside any declaration.
|
|
1068
|
+
Code nested in a declaration (a callback, an inner function) belongs to it. A declaration is work when a fresh
|
|
1069
|
+
check finds a finding in it and its file has findings; the other declarations only carry the order. A call
|
|
1070
|
+
counts when its callee can change by the table above, so a call through an interface member or to a function with
|
|
1071
|
+
a frozen contract orders nothing. Only calls are followed: a function passed as a value is not.
|
|
1072
|
+
|
|
1073
|
+
**3. Mutual recursion is reported.** Declarations that call each other in a circle have no order. They are one
|
|
1074
|
+
array in `order`, and `recursion` lists each such circle with its `declarations`, the `files` they are in, the
|
|
1075
|
+
calls that close it (`closingEdges`, with `callSites`), and `freeze`. There are two ways out:
|
|
1076
|
+
|
|
1077
|
+
- **Freeze a contract.** Write the return type of one callee as a `Result` by hand. Changes stop travelling
|
|
1078
|
+
through it, and the rest gets an order. `freeze` names the callee of a closing call with the fewest call sites
|
|
1079
|
+
in the group's files.
|
|
1080
|
+
- **Iterate to a fixed point.** Refactor the declarations of the circle in passes until their inferred failure
|
|
1081
|
+
types stop changing. Inferred failure sets only grow, so this ends.
|