@evobug_com/safe-ts-skill 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/install.mjs +31 -7
- package/package.json +1 -1
- package/safe-ts-migrate/SKILL.md +80 -13
- package/safe-ts-migrate/references/architecture.md +10 -3
- package/safe-ts-migrate/references/census.md +31 -9
- package/safe-ts-migrate/references/escape-hatches.md +19 -9
- package/safe-ts-migrate/references/final-pass.md +7 -5
- package/safe-ts-migrate/references/fix-the-design.md +87 -0
- package/safe-ts-migrate/references/order-and-gates.md +9 -4
- package/safe-ts-migrate/references/patterns-core.md +1240 -85
- package/safe-ts-migrate/references/patterns-react.md +52 -16
- package/safe-ts-migrate/references/patterns-vue.md +98 -21
- package/safe-ts-migrate/references/review-checklist.md +7 -0
- package/safe-ts-migrate/references/templates.md +46 -21
- package/safe-ts-migrate/references/tool-gaps.md +284 -14
- package/safe-ts-migrate/scripts/census.mjs +343 -144
|
@@ -35,22 +35,35 @@ The guide pages linked from each entry say more; read them when an entry doesn't
|
|
|
35
35
|
- [A hand-written type guard](#a-hand-written-type-guard)
|
|
36
36
|
- [An index read](#an-index-read)
|
|
37
37
|
- [An optional key](#an-optional-key)
|
|
38
|
+
- [A method in an interface](#a-method-in-an-interface)
|
|
39
|
+
- [A failure behind an interface](#a-failure-behind-an-interface)
|
|
40
|
+
- [A list spread into Math.max or push](#a-list-spread-into-mathmax-or-push)
|
|
41
|
+
- [A "not found" answer used as a value](#a-not-found-answer-used-as-a-value)
|
|
42
|
+
- [A promise used as its value](#a-promise-used-as-its-value)
|
|
43
|
+
- [A value used after it was used up](#a-value-used-after-it-was-used-up)
|
|
44
|
+
- [Text given to a sink](#text-given-to-a-sink)
|
|
45
|
+
- [A constructor that calls an overridable method](#a-constructor-that-calls-an-overridable-method)
|
|
38
46
|
- [A table keyed by server data](#a-table-keyed-by-server-data)
|
|
39
47
|
- [A server value from a list that can grow](#a-server-value-from-a-list-that-can-grow)
|
|
40
48
|
- [Base64](#base64)
|
|
49
|
+
- [A built-in that throws on data](#a-built-in-that-throws-on-data)
|
|
41
50
|
- [A trusted boundary](#a-trusted-boundary)
|
|
42
51
|
- [Strict code with legacy callers that pass null](#strict-code-with-legacy-callers-that-pass-null)
|
|
43
52
|
- [Command-line arguments](#command-line-arguments)
|
|
44
53
|
- [IndexedDB](#indexeddb)
|
|
45
54
|
- [A bug inside a Result-returning call](#a-bug-inside-a-result-returning-call)
|
|
46
55
|
- [panic on a loading state](#panic-on-a-loading-state)
|
|
56
|
+
- [A method handed over by name](#a-method-handed-over-by-name)
|
|
57
|
+
- [A parameter the function changes](#a-parameter-the-function-changes)
|
|
47
58
|
- [Casts in tests](#casts-in-tests)
|
|
59
|
+
- [A function result the checker cannot read](#a-function-result-the-checker-cannot-read)
|
|
48
60
|
|
|
49
61
|
## A function that throws
|
|
50
62
|
|
|
51
|
-
A caller can't see that `findName` throws, so it doesn't handle it. Return the error
|
|
52
|
-
`safe-ts migrate throw-to-result <dir>` does
|
|
53
|
-
(guide: Adopting SAFE-TS, "Migrating with
|
|
63
|
+
A caller can't see that `findName` throws, so it doesn't handle it. Return the error, named as
|
|
64
|
+
an `Enum` of the kinds the caller handles. `safe-ts migrate throw-to-result <dir>` does the first
|
|
65
|
+
step for the functions it can convert safely (guide: Adopting SAFE-TS, "Migrating with
|
|
66
|
+
codemods"): it keeps the thrown class (`err(new NotFound(...))`). Name the kinds after it.
|
|
54
67
|
|
|
55
68
|
```ts bad no-throw
|
|
56
69
|
export class NotFound extends Error {}
|
|
@@ -65,15 +78,17 @@ export function findName(id: string): string {
|
|
|
65
78
|
```
|
|
66
79
|
|
|
67
80
|
```ts good
|
|
81
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
68
82
|
import { err, type Result } from "@evobug_com/safe-ts-std/result";
|
|
69
83
|
|
|
70
|
-
export
|
|
84
|
+
export type LookupError = Enum<{ NotFound: { id: string } }>;
|
|
85
|
+
export const LookupError = constructors<LookupError>();
|
|
71
86
|
|
|
72
87
|
const names = new Map([["1", "Ada"]]);
|
|
73
88
|
|
|
74
|
-
export function findName(id: string): Result<string,
|
|
89
|
+
export function findName(id: string): Result<string, LookupError> {
|
|
75
90
|
const name = names.get(id);
|
|
76
|
-
if (name === undefined) return err(
|
|
91
|
+
if (name === undefined) return err(LookupError.NotFound({ id }));
|
|
77
92
|
return name;
|
|
78
93
|
}
|
|
79
94
|
```
|
|
@@ -88,20 +103,25 @@ Errors, "When the whole request should stop"). `throw new Error(...)` is never t
|
|
|
88
103
|
and the build turns it into that `if`. When the error type changes on the way up, give `q` the
|
|
89
104
|
mapping, or use `mapErr` outside `q` (guide: Errors, "Pass an error up with q(...)"). With the
|
|
90
105
|
idiomatic layer on, `prefer-q` reports the `if (isErr(x)) return x` (its quick fix writes the
|
|
91
|
-
`q`
|
|
106
|
+
`q`; `safe-ts fix prefer-q src/` applies it everywhere, as a diff to review first), and
|
|
107
|
+
`prefer-map-err` the error re-wrapped by hand. Not in files a Vite config imports: they run
|
|
108
|
+
without the transform, so the `if` stays there.
|
|
92
109
|
|
|
93
110
|
```ts bad prefer-map-err prefer-q
|
|
111
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
94
112
|
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
95
113
|
|
|
96
114
|
type Upload = { readonly size: number };
|
|
97
|
-
type
|
|
115
|
+
type CheckError = Enum<{ TooLarge: { max: number } }>;
|
|
116
|
+
export type UploadError = Enum<{ Invalid: { problem: CheckError }; StoreFull: {} }>;
|
|
117
|
+
export const UploadError = constructors<UploadError>();
|
|
98
118
|
|
|
99
|
-
declare function checkUpload(size: number): Result<Upload,
|
|
119
|
+
declare function checkUpload(size: number): Result<Upload, CheckError>;
|
|
100
120
|
declare function storeUpload(upload: Upload): Result<string, UploadError>;
|
|
101
121
|
|
|
102
122
|
export function startUpload(size: number): Result<string, UploadError> {
|
|
103
123
|
const upload = checkUpload(size);
|
|
104
|
-
if (isErr(upload)) return err({
|
|
124
|
+
if (isErr(upload)) return err(UploadError.Invalid({ problem: upload.error }));
|
|
105
125
|
const id = storeUpload(upload);
|
|
106
126
|
if (isErr(id)) return id;
|
|
107
127
|
return id;
|
|
@@ -109,15 +129,18 @@ export function startUpload(size: number): Result<string, UploadError> {
|
|
|
109
129
|
```
|
|
110
130
|
|
|
111
131
|
```ts good
|
|
132
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
112
133
|
import { q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
113
134
|
|
|
114
135
|
type Upload = { readonly size: number };
|
|
115
|
-
type
|
|
136
|
+
type CheckError = Enum<{ TooLarge: { max: number } }>;
|
|
137
|
+
export type UploadError = Enum<{ Invalid: { problem: CheckError }; StoreFull: {} }>;
|
|
138
|
+
export const UploadError = constructors<UploadError>();
|
|
116
139
|
|
|
117
|
-
declare function checkUpload(size: number): Result<Upload,
|
|
140
|
+
declare function checkUpload(size: number): Result<Upload, CheckError>;
|
|
118
141
|
declare function storeUpload(upload: Upload): Result<string, UploadError>;
|
|
119
142
|
|
|
120
|
-
const invalid = (
|
|
143
|
+
const invalid = (problem: CheckError): UploadError => UploadError.Invalid({ problem });
|
|
121
144
|
|
|
122
145
|
export function startUpload(size: number): Result<string, UploadError> {
|
|
123
146
|
const upload = q(checkUpload(size), invalid);
|
|
@@ -127,22 +150,26 @@ export function startUpload(size: number): Result<string, UploadError> {
|
|
|
127
150
|
```
|
|
128
151
|
|
|
129
152
|
`q(...)` is a statement of its own (`const x = q(...)`, `x = q(...)`, `q(...);`,
|
|
130
|
-
`return q(...)`), in a function that returns a `Result`.
|
|
153
|
+
`return q(...)`), in a function that returns a `Result`. The error it passes on must be one the
|
|
154
|
+
function declares: `q(parse(text))` with `parse` returning `Result<number, "bad-number">`, in a
|
|
155
|
+
function declaring `Result<number, "other">`, returns an error no caller's `match` expects, and
|
|
156
|
+
`tsc` can't see it (`q` gives it `T`). `q-undeclared-error` (an error) reports it where both
|
|
157
|
+
sides are written; declare the error, or map it with `q(result, (error): Declared => ...)`. It needs the build transform: the
|
|
131
158
|
Vite plugin, or `node --import @evobug_com/safe-ts-transform/register` for code Node runs.
|
|
132
159
|
|
|
133
160
|
## Requests return a Result
|
|
134
161
|
|
|
135
|
-
A raw `fetch` can wait forever, rejects on a network failure, and `response.json()` gives
|
|
136
|
-
|
|
137
|
-
a
|
|
162
|
+
A raw `fetch` can wait forever, rejects on a network failure, and `response.json()` gives a
|
|
163
|
+
value nobody checked (`unknown` with std's strict-lib, `any` without it), which a cast then
|
|
164
|
+
believes. A request function owns all three: a time limit and the caller's signal, the failure
|
|
165
|
+
as a typed error, and the body checked against the type.
|
|
138
166
|
|
|
139
|
-
```ts bad fetch-signal unhandled-failure
|
|
167
|
+
```ts bad fetch-signal unhandled-failure no-unchecked-cast
|
|
140
168
|
export type User = { readonly id: number; readonly name: string };
|
|
141
169
|
|
|
142
170
|
export async function fetchUser(id: number): Promise<User> {
|
|
143
171
|
const response = await fetch(`/api/users/${id}`);
|
|
144
|
-
|
|
145
|
-
return user;
|
|
172
|
+
return (await response.json()) as User;
|
|
146
173
|
}
|
|
147
174
|
```
|
|
148
175
|
|
|
@@ -198,10 +225,14 @@ the functions it calls return `Result`s, the `try` has nothing left to catch, an
|
|
|
198
225
|
the callee changes, at every caller. The checker helps: `must-use-result` follows a `Result`
|
|
199
226
|
through store members (Pinia setup and options stores), returned objects and factories, and
|
|
200
227
|
reports one that is dropped, `.catch(() => {})` included; with the idiomatic layer on,
|
|
201
|
-
`catch-on-result` reports a `.catch` or a `try` around nothing but calls that return a `Result
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
228
|
+
`catch-on-result` reports a `.catch` or a `try` around nothing but calls that return a `Result`
|
|
229
|
+
(not a `try` whose callee also throws a tracked `PropagateError` that this `catch` takes: that
|
|
230
|
+
`try` is a boundary).
|
|
231
|
+
It follows a method through a field or a property declared with its class
|
|
232
|
+
(`this.repo.save()`, `deps.repo.save()`) and through a function declared to return the class
|
|
233
|
+
(`makeRepo().save()`), but can't see one reached through a value typed with an interface or a
|
|
234
|
+
union, a `ref` or a `Map` (rule page `must-use-result`, "What the rule can't see"): search for
|
|
235
|
+
each changed function's name too.
|
|
205
236
|
|
|
206
237
|
```ts bad
|
|
207
238
|
declare function saveDraft(text: string): Promise<void>;
|
|
@@ -217,27 +248,36 @@ export async function onSave(text: string, show: (message: string) => void): Pro
|
|
|
217
248
|
```
|
|
218
249
|
|
|
219
250
|
```ts good
|
|
251
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
220
252
|
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
221
253
|
|
|
222
|
-
type SaveError = {
|
|
254
|
+
type SaveError = Enum<{ Offline: {}; Conflict: { by: string } }>;
|
|
223
255
|
|
|
224
256
|
declare function saveDraft(text: string): Promise<Result<void, SaveError>>;
|
|
225
257
|
|
|
226
258
|
export async function onSave(text: string, show: (message: string) => void): Promise<void> {
|
|
227
259
|
const saved = await saveDraft(text);
|
|
228
|
-
|
|
260
|
+
if (!isErr(saved)) return show("Saved");
|
|
261
|
+
show(
|
|
262
|
+
match(saved.error, {
|
|
263
|
+
Offline: () => "Offline: the draft stays on this device",
|
|
264
|
+
Conflict: ({ by }) => `${by} changed it in the meantime`,
|
|
265
|
+
}),
|
|
266
|
+
);
|
|
229
267
|
}
|
|
230
268
|
```
|
|
231
269
|
|
|
232
270
|
The `try` left behind once `saveDraft` returns a `Result`:
|
|
233
271
|
|
|
234
272
|
```ts bad catch-on-result
|
|
273
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
235
274
|
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
236
275
|
|
|
237
|
-
type SaveError = {
|
|
276
|
+
type SaveError = Enum<{ Empty: {} }>;
|
|
277
|
+
const SaveError = constructors<SaveError>();
|
|
238
278
|
|
|
239
279
|
async function saveDraft(text: string): Promise<Result<void, SaveError>> {
|
|
240
|
-
return text === "" ? err(
|
|
280
|
+
return text === "" ? err(SaveError.Empty()) : undefined;
|
|
241
281
|
}
|
|
242
282
|
|
|
243
283
|
export async function onSave(text: string): Promise<string> {
|
|
@@ -247,7 +287,7 @@ export async function onSave(text: string): Promise<string> {
|
|
|
247
287
|
} catch {
|
|
248
288
|
return "Could not save";
|
|
249
289
|
}
|
|
250
|
-
return isErr(saved) ?
|
|
290
|
+
return isErr(saved) ? match(saved.error, { Empty: () => "Nothing to save" }) : "Saved";
|
|
251
291
|
}
|
|
252
292
|
```
|
|
253
293
|
|
|
@@ -300,7 +340,10 @@ for "maybe missing", `Result<void, E>` for a command that can fail, an `Enum` va
|
|
|
300
340
|
"none" carries meaning of its own. With the idiomatic layer on, `sentinel-error` reports the
|
|
301
341
|
`''`-for-no-error case, and `strict-truthiness` the `if (block)` that reads it: a test of a
|
|
302
342
|
string or number for truth hides `""` and `0` along with `undefined`. Compare with what is
|
|
303
|
-
meant (`!== undefined`, `> 0`).
|
|
343
|
+
meant (`!== undefined`, `> 0`). Where the value may be `undefined` (an `Option`, `x?:`, `a?.b`),
|
|
344
|
+
the replacement decides both: `x !== undefined && x !== ""` keeps the meaning, `x !== undefined`
|
|
345
|
+
lets `""` through, and `x !== ""` alone is true for `undefined` (`compare-misses-undefined`, an
|
|
346
|
+
error).
|
|
304
347
|
|
|
305
348
|
```ts bad sentinel-error strict-truthiness
|
|
306
349
|
type Wallet = { readonly balance: number };
|
|
@@ -316,21 +359,29 @@ export function buyTitle(wallet: Wallet, price: number): string {
|
|
|
316
359
|
```
|
|
317
360
|
|
|
318
361
|
```ts good
|
|
362
|
+
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
319
363
|
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
320
364
|
|
|
321
365
|
type Wallet = { readonly balance: number };
|
|
322
366
|
|
|
323
|
-
export
|
|
324
|
-
|
|
367
|
+
export type BuyBlock = Enum<{ TooExpensive: { missing: number } }>;
|
|
368
|
+
export const BuyBlock = constructors<BuyBlock>();
|
|
369
|
+
|
|
370
|
+
export function buyBlock(wallet: Wallet, price: number): Option<BuyBlock> {
|
|
371
|
+
return price > wallet.balance ? BuyBlock.TooExpensive({ missing: price - wallet.balance }) : undefined;
|
|
325
372
|
}
|
|
326
373
|
|
|
327
374
|
export function buyTitle(wallet: Wallet, price: number): string {
|
|
328
|
-
|
|
329
|
-
|
|
375
|
+
return match(buyBlock(wallet, price), {
|
|
376
|
+
TooExpensive: ({ missing }) => `Can't buy: ${missing} EUR short`,
|
|
377
|
+
undefined: () => "Buy",
|
|
378
|
+
});
|
|
330
379
|
}
|
|
331
380
|
```
|
|
332
381
|
|
|
333
|
-
The `-1` of `indexOf` is the same trap, and the checker is
|
|
382
|
+
The `-1` of `indexOf` is the same trap. Compared, as here, it is right and the checker is
|
|
383
|
+
silent; used as a position (`splice`, `slice`, an index) before the comparison it is reported
|
|
384
|
+
([below](#a-not-found-answer-used-as-a-value)). Either way an `Option` says it in the type:
|
|
334
385
|
|
|
335
386
|
```ts bad
|
|
336
387
|
const SIZES = ["small", "medium", "large"] as const;
|
|
@@ -366,11 +417,16 @@ that describes the `''` from the project's conventions.
|
|
|
366
417
|
## A closed set of states
|
|
367
418
|
|
|
368
419
|
A value that is one of a few kinds, handled with `if`/`else if` on strings, compiles when a
|
|
369
|
-
kind is added and every chain misses it
|
|
370
|
-
|
|
371
|
-
`
|
|
372
|
-
|
|
373
|
-
|
|
420
|
+
kind is added and every chain misses it: the new kind takes the last `else`.
|
|
421
|
+
`exhaustive-dispatch` reports a chain that tests two kinds or more and leaves some to that
|
|
422
|
+
`else` (on an `Enum`'s tag, a union of literals, or the constants of a code object), and
|
|
423
|
+
`exhaustive-switch` a `switch` on one without `default: unreachable(x)`. An `Enum` with `match`
|
|
424
|
+
stops compiling instead. Each variant carries only its own data. For a union already
|
|
425
|
+
discriminated by a `type` field, `safe-ts migrate union-to-enum <Type> <dir>` converts it with
|
|
426
|
+
its producers and consumers: checks become `is`, a `switch` whose every case returns becomes
|
|
427
|
+
`match`.
|
|
428
|
+
|
|
429
|
+
```ts bad exhaustive-dispatch
|
|
374
430
|
export type Payment = {
|
|
375
431
|
readonly kind: "card" | "transfer" | "cash";
|
|
376
432
|
readonly last4?: string;
|
|
@@ -403,8 +459,69 @@ export function paymentLabel(payment: Payment): string {
|
|
|
403
459
|
}
|
|
404
460
|
```
|
|
405
461
|
|
|
406
|
-
Plain names with no data (`"asc" | "desc"`) can stay a union of strings
|
|
407
|
-
|
|
462
|
+
Plain names with no data (`"asc" | "desc"`) can stay a union of strings, handled with
|
|
463
|
+
`match(order, { asc: ..., desc: ... })` like an enum; the `Enum` pays off when the kinds carry
|
|
464
|
+
different data. A union or a code object of numbers (`Object.freeze({ WALK: 0, RUN: 1 })`, a `codesOf(...)` table) that stays
|
|
465
|
+
one is handled in a `switch` ending in `default: return unreachable(x)`, or read from a table
|
|
466
|
+
typed by the set (`Record<Phase, number>`), which TypeScript checks for every member. Type the
|
|
467
|
+
field as the set (`phase: Phase`, with `type Phase = (typeof Phase)[keyof typeof Phase]`), not
|
|
468
|
+
`number`.
|
|
469
|
+
|
|
470
|
+
```ts good
|
|
471
|
+
import { unreachable } from "@evobug_com/safe-ts-std/enum";
|
|
472
|
+
|
|
473
|
+
export const Phase = Object.freeze({ WALK: 0, RUN: 1, TEND: 2 });
|
|
474
|
+
export type Phase = (typeof Phase)[keyof typeof Phase];
|
|
475
|
+
|
|
476
|
+
const CARRY: Readonly<Record<Phase, number>> = { [Phase.WALK]: 10, [Phase.RUN]: 5, [Phase.TEND]: 0 };
|
|
477
|
+
|
|
478
|
+
export function carryMax(phase: Phase): number {
|
|
479
|
+
return CARRY[phase];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function phaseName(phase: Phase): string {
|
|
483
|
+
switch (phase) {
|
|
484
|
+
case Phase.WALK:
|
|
485
|
+
return "walk";
|
|
486
|
+
case Phase.RUN:
|
|
487
|
+
return "run";
|
|
488
|
+
case Phase.TEND:
|
|
489
|
+
return "tend";
|
|
490
|
+
default:
|
|
491
|
+
return unreachable(phase);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
A plain `string` compared with many words (a command, a mode read from the URL) is a set that
|
|
497
|
+
exists only as those tests, and its other lists (a help text, a menu) drift. Parse it once at
|
|
498
|
+
the boundary into a union, with a table that maps the words (aliases included) to the members,
|
|
499
|
+
and `match` on the union. `string-dispatch` (idiomatic) reports the comparisons; a function
|
|
500
|
+
declared to return the closed type is the parser and isn't reported.
|
|
501
|
+
|
|
502
|
+
Three other tests leave a new member to chance, and the fix is always to name the members once:
|
|
503
|
+
|
|
504
|
+
- `u.phase === Phase.INSIDE && u.job !== Job.FLEE` guarding work is work for "every job but
|
|
505
|
+
`FLEE`", and a job added later takes it (`negative-member-guard`). Test a named set instead.
|
|
506
|
+
An early `return;` / `continue` for the excluded member is fine.
|
|
507
|
+
- `afterJob >= Job.MOVE && afterJob <= Job.IGNITE` picks members by code, and a code table's new
|
|
508
|
+
names are appended past the range (`code-range-compare`). Name the members; where the order is
|
|
509
|
+
the meaning (stages, levels), put `@ordered` in the doc comment of the table's `const`.
|
|
510
|
+
- The same value tested against overlapping sets in several functions (a check, a reader, a
|
|
511
|
+
writer) is copies of one set that drift (`inline-member-set`, from `safe-ts check`). Export one
|
|
512
|
+
set and use it in all of them.
|
|
513
|
+
|
|
514
|
+
```ts good
|
|
515
|
+
export const Job = Object.freeze({ NONE: 0, MOVE: 1, DEPOSIT: 2, FLEE: 3, MINE: 4, WORSHIP: 5 });
|
|
516
|
+
export type Job = (typeof Job)[keyof typeof Job];
|
|
517
|
+
|
|
518
|
+
/** Jobs a unit away from them keeps: the checks, the save writer and the reader use this set. */
|
|
519
|
+
export const KEPT_JOBS: ReadonlySet<Job> = new Set([Job.MOVE, Job.DEPOSIT, Job.MINE]);
|
|
520
|
+
|
|
521
|
+
export function keptResume(afterJob: Job): boolean {
|
|
522
|
+
return KEPT_JOBS.has(afterJob);
|
|
523
|
+
}
|
|
524
|
+
```
|
|
408
525
|
|
|
409
526
|
## A set of boolean flags
|
|
410
527
|
|
|
@@ -428,6 +545,7 @@ export function dialogTitle(dialog: Dialog): string {
|
|
|
428
545
|
|
|
429
546
|
```ts good
|
|
430
547
|
import { constructors, type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
548
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
431
549
|
|
|
432
550
|
export type Dialog = Enum<{
|
|
433
551
|
Closed: {};
|
|
@@ -437,9 +555,9 @@ export type Dialog = Enum<{
|
|
|
437
555
|
}>;
|
|
438
556
|
export const Dialog = constructors<Dialog>();
|
|
439
557
|
|
|
440
|
-
export function dialogTitle(dialog: Dialog): string {
|
|
558
|
+
export function dialogTitle(dialog: Dialog): Option<string> {
|
|
441
559
|
return match(dialog, {
|
|
442
|
-
Closed: () =>
|
|
560
|
+
Closed: () => undefined,
|
|
443
561
|
Editing: () => "Edit",
|
|
444
562
|
Saving: () => "Saving…",
|
|
445
563
|
Failed: ({ reason }) => `Failed: ${reason}`,
|
|
@@ -455,7 +573,9 @@ by `useTask`: see the trio entry of the framework catalogue.
|
|
|
455
573
|
Both `x.tag === "Ready"` and `is(x, ...)` / `variant(...)` / `match` compile and narrow. The
|
|
456
574
|
SAFE-TS style is the second, and with the idiomatic layer on, `prefer-is-over-tag` reports the
|
|
457
575
|
raw tag (`x.tag === "..."`, `x.tag !== "..."`, `switch (x.tag)`) in code and in Vue templates,
|
|
458
|
-
with a quick fix to `is(x, "Ready")
|
|
576
|
+
with a quick fix to `is(x, "Ready")`, or `is(x, Status.Ready)` where the enum's constructors
|
|
577
|
+
are in scope (`safe-ts fix prefer-is-over-tag src/` for all of them; with the prelude on it
|
|
578
|
+
adds no import). Write the style in the project's conventions:
|
|
459
579
|
|
|
460
580
|
- `match(value, { ... })` when every variant needs its own decision: a variant added later
|
|
461
581
|
makes it stop compiling.
|
|
@@ -488,7 +608,11 @@ export function publishedAt(status: Status): string {
|
|
|
488
608
|
```
|
|
489
609
|
|
|
490
610
|
The build turns `is` and `variant` on a plain variable into the same tag check, so the style
|
|
491
|
-
costs nothing at runtime (guide: Enums and match).
|
|
611
|
+
costs nothing at runtime (guide: Enums and match). Name the variant by its constructor when the
|
|
612
|
+
enum has one: `is(x, "Published")` is the same test, and `prefer-constructor-tag` (idiomatic)
|
|
613
|
+
reports it with a quick fix to `Status.Published`, so a rename follows every use. An enum
|
|
614
|
+
without constructors keeps the string form. Keep tags strings: an interned string tag reads as
|
|
615
|
+
fast as a number (guide: Performance myths).
|
|
492
616
|
|
|
493
617
|
## A union told apart by keys
|
|
494
618
|
|
|
@@ -582,6 +706,12 @@ export function clearDueDate(issue: Issue): string {
|
|
|
582
706
|
## JSON and storage
|
|
583
707
|
|
|
584
708
|
`JSON.parse(text) as T` believes the text. `parseJson<T>` checks it and returns a `Result`.
|
|
709
|
+
`unsafe(() => JSON.parse(text))` gives `unknown` (std turns a function's `any` into `unknown`),
|
|
710
|
+
and with std's strict-lib in tsconfig.json `"types"` so does `JSON.parse` itself: either way
|
|
711
|
+
the value goes through `validate<T>` before use. A message event is the same:
|
|
712
|
+
`MessageEvent<unknown>`, never a bare `MessageEvent`, whose `data` is `any`, nor
|
|
713
|
+
`MessageEvent<Job>`, which claims what was posted (`no-hidden-any`). A worker thread's
|
|
714
|
+
`workerData` and `"message"` value are the same: `validate<T>` them where they come in.
|
|
585
715
|
With the browser pack, `getItem(localStorage, key)` returns an `Option<string>` and
|
|
586
716
|
`setItem(...)` a `Result` (a full storage is a value to check).
|
|
587
717
|
|
|
@@ -600,19 +730,23 @@ export function saveDraft(draft: Draft): void {
|
|
|
600
730
|
|
|
601
731
|
```ts good
|
|
602
732
|
import { getItem, setItem } from "@evobug_com/safe-ts-feature-browser/storage";
|
|
733
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
603
734
|
import { type JsonResult, parseJson } from "@evobug_com/safe-ts-std/json";
|
|
604
|
-
import type
|
|
735
|
+
import { mapErr, type Option, type Result } from "@evobug_com/safe-ts-std/result";
|
|
605
736
|
|
|
606
737
|
type Draft = { readonly title: string; readonly body: string };
|
|
607
738
|
|
|
739
|
+
export type SaveError = Enum<{ StorageFull: {} }>;
|
|
740
|
+
export const SaveError = constructors<SaveError>();
|
|
741
|
+
|
|
608
742
|
/** No saved draft is `undefined`; a saved one that doesn't fit `Draft` is an error. */
|
|
609
743
|
export function loadDraft(): JsonResult<Option<Draft>> {
|
|
610
744
|
const text = getItem(localStorage, "draft");
|
|
611
745
|
return text === undefined ? undefined : parseJson<Draft>(text);
|
|
612
746
|
}
|
|
613
747
|
|
|
614
|
-
export function saveDraft(draft: Draft): Result<void,
|
|
615
|
-
return setItem(localStorage, "draft", JSON.stringify(draft));
|
|
748
|
+
export function saveDraft(draft: Draft): Result<void, SaveError> {
|
|
749
|
+
return mapErr(setItem(localStorage, "draft", JSON.stringify(draft)), () => SaveError.StorageFull());
|
|
616
750
|
}
|
|
617
751
|
```
|
|
618
752
|
|
|
@@ -644,7 +778,7 @@ of them is a new `as`.
|
|
|
644
778
|
```ts bad no-unchecked-cast
|
|
645
779
|
type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
|
|
646
780
|
|
|
647
|
-
export function readSettings(message: MessageEvent): Settings {
|
|
781
|
+
export function readSettings(message: MessageEvent<unknown>): Settings {
|
|
648
782
|
return message.data as Settings;
|
|
649
783
|
}
|
|
650
784
|
```
|
|
@@ -654,7 +788,7 @@ import { type JsonResult, validate } from "@evobug_com/safe-ts-std/json";
|
|
|
654
788
|
|
|
655
789
|
type Settings = { readonly theme: "light" | "dark"; readonly fontSize: number };
|
|
656
790
|
|
|
657
|
-
export function readSettings(message: MessageEvent): JsonResult<Settings> {
|
|
791
|
+
export function readSettings(message: MessageEvent<unknown>): JsonResult<Settings> {
|
|
658
792
|
return validate<Settings>(message.data);
|
|
659
793
|
}
|
|
660
794
|
```
|
|
@@ -666,12 +800,12 @@ global ones from a declaration file. Not package types, global types from `@type
|
|
|
666
800
|
|
|
667
801
|
## A hand-written type guard
|
|
668
802
|
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
803
|
+
`value is T`, `asserts value is T` and an overload over a looser implementation are casts:
|
|
804
|
+
TypeScript never checks the body against them (`return true` compiles), so `no-type-predicate`
|
|
805
|
+
and `no-overload` report them, as errors. For data of unknown shape, use `validate<T>`, which
|
|
806
|
+
tests every field:
|
|
673
807
|
|
|
674
|
-
```ts bad
|
|
808
|
+
```ts bad no-type-predicate
|
|
675
809
|
type User = { readonly id: number; readonly name: string; readonly email: string };
|
|
676
810
|
|
|
677
811
|
export function isUser(value: unknown): value is User {
|
|
@@ -689,9 +823,25 @@ export function readUser(value: unknown): JsonResult<User> {
|
|
|
689
823
|
}
|
|
690
824
|
```
|
|
691
825
|
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
826
|
+
Everything else, by what the guard did:
|
|
827
|
+
|
|
828
|
+
- **Its body is one test TypeScript narrows by** (`typeof`, `instanceof`, `Array.isArray`,
|
|
829
|
+
`x !== undefined`, `!!x`, a discriminant, `is(x, Variant)`, `isSome(x)`): drop `: x is T`
|
|
830
|
+
(`safe-ts fix no-type-predicate --fix "Let TypeScript infer"`). TypeScript infers the same
|
|
831
|
+
predicate and checks it. When that stops the code compiling, the claim was more than the
|
|
832
|
+
test: fix what the error points at, not the inference.
|
|
833
|
+
- **A filter**: `.filter(isSome)`, `.filter((e) => is(e, "Moved"))`; a second condition goes in a
|
|
834
|
+
second `.filter` once the first narrowed.
|
|
835
|
+
- **One of a list** (`KINDS.some((k) => k === name)`): `KINDS.find((k) => k === name)`, an
|
|
836
|
+
`Option<Kind>`; a table's key: `getOwn(TABLE, name)`.
|
|
837
|
+
- **`Record<string, unknown>`**: std's `isJsonObject` / `isJsonPlainObject`.
|
|
838
|
+
- **An assertion**: return the check's `Result`, or `if (!test) panic("...")` at the use site.
|
|
839
|
+
`asserts ok` whose body is exactly `if (!ok) throw ...` / `panic(...)` is allowed.
|
|
840
|
+
- **A method on a library's object** (`"activateVao" in proto`), a result type the body can't
|
|
841
|
+
build: `trust<T>(value)` next to the test, with the reason (see "A trusted boundary").
|
|
842
|
+
- **Overloads** whose results differ: one function per signature, or one signature returning
|
|
843
|
+
an `Enum`. Overloads with the implementation's own result, each parameter one member of its
|
|
844
|
+
union, are allowed.
|
|
695
845
|
|
|
696
846
|
## An index read
|
|
697
847
|
|
|
@@ -745,7 +895,7 @@ export function confirm(title: string, onAccept: Option<() => void>, onCancel: O
|
|
|
745
895
|
- `stable-shape` accepts one such spread in any literal, and two where the type the literal is
|
|
746
896
|
written for declares both keys optional. With three or more (eight shapes), and for objects
|
|
747
897
|
read in a hot loop, declare the fields `Option<T>` and always write them, `x: undefined`
|
|
748
|
-
included. The same for a Vue component's optional props a template always passes
|
|
898
|
+
included; assigning them after the literal (`o.x = v`) makes as many shapes. The same for a Vue component's optional props a template always passes
|
|
749
899
|
(`:x="maybe"`): declare them `x?: Option<T>`.
|
|
750
900
|
- To drop keys from an existing object, `omit(settings, "theme")` (`@evobug_com/safe-ts-std/dict`),
|
|
751
901
|
not `delete` or `{ ...settings, theme: undefined }`.
|
|
@@ -764,6 +914,671 @@ export function order(id: string, delivery: Delivery): Order {
|
|
|
764
914
|
Decide the form for the component library's optional props in the foundation step, once
|
|
765
915
|
([order-and-gates.md](order-and-gates.md)).
|
|
766
916
|
|
|
917
|
+
With the idiomatic rules on, `no-optional-field` reports `key?:` in the project's own types
|
|
918
|
+
(not JSON types, props, a library's options or declarations): a value whose type doesn't list
|
|
919
|
+
the key is assignable there, holding whatever it had. Declare the field `key: Option<T>` and
|
|
920
|
+
write the key where the object is made (`key: undefined` when there is none). `?:` stays for
|
|
921
|
+
the shapes above, like `Callbacks` when `openDialog` is a library's.
|
|
922
|
+
|
|
923
|
+
## A method in an interface
|
|
924
|
+
|
|
925
|
+
`handle(animal: Animal): string` in an interface or type literal is checked in both directions,
|
|
926
|
+
so an implementation that only takes a `Dog` is accepted (`no-method-signature`). Write the
|
|
927
|
+
member as a property; `safe-ts fix no-method-signature <dirs> --write` rewrites them all, and
|
|
928
|
+
`tsc` then shows each assignment that relied on the bivariance.
|
|
929
|
+
|
|
930
|
+
```ts bad no-method-signature
|
|
931
|
+
type Animal = { readonly kind: string };
|
|
932
|
+
|
|
933
|
+
export interface Handler {
|
|
934
|
+
handle(animal: Animal): string;
|
|
935
|
+
}
|
|
936
|
+
```
|
|
937
|
+
|
|
938
|
+
```ts good
|
|
939
|
+
type Animal = { readonly kind: string };
|
|
940
|
+
|
|
941
|
+
export interface Handler {
|
|
942
|
+
readonly handle: (animal: Animal) => string;
|
|
943
|
+
}
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
## An override that asks for more
|
|
947
|
+
|
|
948
|
+
A class's own methods are compared both ways too: `override admit(dog: Dog)` over
|
|
949
|
+
`admit(animal: Animal)` compiles, and a call through the base class hands it any animal
|
|
950
|
+
(`override-parameter`). Take the base's parameter type and check inside, or declare the member
|
|
951
|
+
on the base as a function-typed property (`readonly admit = (animal: Animal): string => ...`),
|
|
952
|
+
which TypeScript checks in every override.
|
|
953
|
+
|
|
954
|
+
```ts bad override-parameter
|
|
955
|
+
type Animal = { readonly kind: string };
|
|
956
|
+
type Dog = { readonly kind: string; readonly bark: () => string };
|
|
957
|
+
|
|
958
|
+
export class Shelter {
|
|
959
|
+
admit(animal: Animal): string {
|
|
960
|
+
return animal.kind;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
export class Kennel extends Shelter {
|
|
965
|
+
override admit(dog: Dog): string {
|
|
966
|
+
return dog.bark();
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
```
|
|
970
|
+
|
|
971
|
+
```ts good
|
|
972
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
973
|
+
|
|
974
|
+
type Animal = { readonly kind: string; readonly bark: Option<() => string> };
|
|
975
|
+
|
|
976
|
+
export class Shelter {
|
|
977
|
+
admit(animal: Animal): string {
|
|
978
|
+
return animal.kind;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
export class Kennel extends Shelter {
|
|
983
|
+
override admit(animal: Animal): string {
|
|
984
|
+
return animal.bark === undefined ? "only dogs here" : animal.bark();
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
```
|
|
988
|
+
|
|
989
|
+
## A failure behind an interface
|
|
990
|
+
|
|
991
|
+
A call through an interface, an abstract method or a stored callback runs whatever was put
|
|
992
|
+
there, so the checker can't follow it: the type must say what it can fail with
|
|
993
|
+
(`failure-contract`). A function type that says nothing can't fail, so an implementation that
|
|
994
|
+
throws a `PropagateError` is reported where it is put in. Decide where the failure belongs:
|
|
995
|
+
handle it inside the implementation (the slot stays one that can't fail), or declare it on the
|
|
996
|
+
slot with `Throws<R, E>` and handle it at the callers, which the checker then holds to it. For
|
|
997
|
+
an `async` member, `Promise<Throws<T, E>>`; for a callback kept in a field or a list,
|
|
998
|
+
`Throwing<Args, R, E>`.
|
|
999
|
+
|
|
1000
|
+
```ts bad failure-contract
|
|
1001
|
+
import { PropagateError } from "@evobug_com/safe-ts-std/result";
|
|
1002
|
+
|
|
1003
|
+
export class Offline extends PropagateError {}
|
|
1004
|
+
|
|
1005
|
+
export interface Feed {
|
|
1006
|
+
readonly latest: () => string;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
export const remoteFeed: Feed = {
|
|
1010
|
+
latest: () => {
|
|
1011
|
+
throw new Offline("no network");
|
|
1012
|
+
},
|
|
1013
|
+
};
|
|
1014
|
+
```
|
|
1015
|
+
|
|
1016
|
+
```ts good
|
|
1017
|
+
import { PropagateError, type Throws } from "@evobug_com/safe-ts-std/result";
|
|
1018
|
+
|
|
1019
|
+
export class Offline extends PropagateError {}
|
|
1020
|
+
|
|
1021
|
+
export interface Feed {
|
|
1022
|
+
readonly latest: () => Throws<string, Offline>;
|
|
1023
|
+
}
|
|
1024
|
+
|
|
1025
|
+
export const remoteFeed: Feed = {
|
|
1026
|
+
latest: () => {
|
|
1027
|
+
throw new Offline("no network");
|
|
1028
|
+
},
|
|
1029
|
+
};
|
|
1030
|
+
```
|
|
1031
|
+
|
|
1032
|
+
On an existing codebase, `safe-ts check` lists each implementation that fails under a slot
|
|
1033
|
+
that declares nothing: one finding per member, so the census shows which interfaces need a
|
|
1034
|
+
declaration. Declaring it moves the finding to the callers that don't handle it.
|
|
1035
|
+
|
|
1036
|
+
## A method the language calls for you
|
|
1037
|
+
|
|
1038
|
+
`toString`, `valueOf`, `toJSON`, `[Symbol.iterator]`, `then`, `[Symbol.dispose]` run without a
|
|
1039
|
+
call naming them (a template, `a < b`, `JSON.stringify`, `for...of`, `await`, `using`), so a
|
|
1040
|
+
`PropagateError` they let out reaches nobody who was told (`implicit-propagation`). Keep them
|
|
1041
|
+
total and put what can fail in a method the caller names; an iteration that may fail becomes a
|
|
1042
|
+
generator method (`for (const row of table.rows())`), which is followed where it is stepped.
|
|
1043
|
+
|
|
1044
|
+
```ts bad implicit-propagation
|
|
1045
|
+
import { PropagateError } from "@evobug_com/safe-ts-std/result";
|
|
1046
|
+
|
|
1047
|
+
class Unpriced extends PropagateError {}
|
|
1048
|
+
|
|
1049
|
+
export class Price {
|
|
1050
|
+
readonly cents: number;
|
|
1051
|
+
constructor(cents: number) {
|
|
1052
|
+
this.cents = cents;
|
|
1053
|
+
}
|
|
1054
|
+
toString(): string {
|
|
1055
|
+
if (this.cents < 0) throw new Unpriced("negative");
|
|
1056
|
+
return `${this.cents / 100} EUR`;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
```ts good
|
|
1062
|
+
import { err, isErr, type Result } from "@evobug_com/safe-ts-std/result";
|
|
1063
|
+
|
|
1064
|
+
export class Price {
|
|
1065
|
+
readonly cents: number;
|
|
1066
|
+
constructor(cents: number) {
|
|
1067
|
+
this.cents = cents;
|
|
1068
|
+
}
|
|
1069
|
+
format(): Result<string, "negative"> {
|
|
1070
|
+
return this.cents < 0 ? err("negative") : `${this.cents / 100} EUR`;
|
|
1071
|
+
}
|
|
1072
|
+
toString(): string {
|
|
1073
|
+
const text = this.format();
|
|
1074
|
+
return isErr(text) ? "(no price)" : text;
|
|
1075
|
+
}
|
|
1076
|
+
}
|
|
1077
|
+
```
|
|
1078
|
+
|
|
1079
|
+
## A list spread into Math.max or push
|
|
1080
|
+
|
|
1081
|
+
`Math.max(...values)` and `target.push(...extra)` pass every element as an argument: a
|
|
1082
|
+
`RangeError` past about 100,000 elements, and `Math.max()` of nothing is `-Infinity`
|
|
1083
|
+
(`unbounded-spread`). Use `maxOf` / `minOf` (`Option<number>`), a loop for `push`, and a new
|
|
1084
|
+
array (`[...a, ...b]`, which has no limit) for `unshift` and `splice`.
|
|
1085
|
+
|
|
1086
|
+
```ts bad unbounded-spread
|
|
1087
|
+
export function highest(scores: readonly number[]): number {
|
|
1088
|
+
return Math.max(...scores);
|
|
1089
|
+
}
|
|
1090
|
+
```
|
|
1091
|
+
|
|
1092
|
+
```ts good
|
|
1093
|
+
import { maxOf } from "@evobug_com/safe-ts-std/array";
|
|
1094
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1095
|
+
|
|
1096
|
+
export function highest(scores: readonly number[]): Option<number> {
|
|
1097
|
+
return maxOf(scores);
|
|
1098
|
+
}
|
|
1099
|
+
```
|
|
1100
|
+
|
|
1101
|
+
## A "not found" answer used as a value
|
|
1102
|
+
|
|
1103
|
+
Some built-ins answer "there is none" with a value of their own type, and the code goes on
|
|
1104
|
+
with a wrong one instead of failing: `-1` from `indexOf`, `findIndex` and `search`
|
|
1105
|
+
(`not-found-index`: `splice(-1, 1)` removes the last element), `NaN` from `Date.parse` and
|
|
1106
|
+
from a `new Date(text)` that didn't parse (`number-parse-nan`, as for `Number(text)`), `NaN`
|
|
1107
|
+
from a division by the length of a `filter` that kept nothing (`divide-by-length`), and holes from a write past
|
|
1108
|
+
an array's end, which read as `undefined` under a `number[]` type (`sparse-array-write`). All
|
|
1109
|
+
but the last are warnings. The fix is the check the value needs, before the use, or a type
|
|
1110
|
+
that says "none": `indexIn` (an `Option` index), `Option<number>` for a mean of nothing,
|
|
1111
|
+
a `Map` for a table with gaps.
|
|
1112
|
+
|
|
1113
|
+
```ts bad not-found-index divide-by-length number-parse-nan sparse-array-write
|
|
1114
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1115
|
+
|
|
1116
|
+
export function removeTag(tags: Mut<string[]>, tag: string): void {
|
|
1117
|
+
tags.splice(tags.indexOf(tag), 1);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
export function meanPassTime(runs: readonly { ok: boolean; ms: number }[]): number {
|
|
1121
|
+
const passed = runs.filter((run) => run.ok);
|
|
1122
|
+
return passed.reduce((sum, run) => sum + run.ms, 0) / passed.length;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
export function age(birthday: string, now: Date): number {
|
|
1126
|
+
return now.getFullYear() - new Date(birthday).getFullYear();
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
export function namesByCode(codes: readonly number[]): readonly string[] {
|
|
1130
|
+
const names: string[] = [];
|
|
1131
|
+
for (const code of codes) names[code] = `#${code}`;
|
|
1132
|
+
return names;
|
|
1133
|
+
}
|
|
1134
|
+
```
|
|
1135
|
+
|
|
1136
|
+
```ts good
|
|
1137
|
+
import { indexIn } from "@evobug_com/safe-ts-std/array";
|
|
1138
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1139
|
+
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1140
|
+
|
|
1141
|
+
export function removeTag(tags: Mut<string[]>, tag: string): boolean {
|
|
1142
|
+
const at = indexIn(tags, tag);
|
|
1143
|
+
if (at === undefined) return false;
|
|
1144
|
+
tags.splice(at, 1);
|
|
1145
|
+
return true;
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
export function meanPassTime(runs: readonly { ok: boolean; ms: number }[]): Option<number> {
|
|
1149
|
+
const passed = runs.filter((run) => run.ok);
|
|
1150
|
+
if (passed.length === 0) return undefined;
|
|
1151
|
+
return passed.reduce((sum, run) => sum + run.ms, 0) / passed.length;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
export function age(birthday: string, now: Date): Option<number> {
|
|
1155
|
+
const born = new Date(birthday);
|
|
1156
|
+
if (Number.isNaN(born.getTime())) return undefined;
|
|
1157
|
+
return now.getFullYear() - born.getFullYear();
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
export function namesByCode(codes: readonly number[]): ReadonlyMap<number, string> {
|
|
1161
|
+
const names = new Map<number, string>();
|
|
1162
|
+
for (const code of codes) names.set(code, `#${code}`);
|
|
1163
|
+
return names;
|
|
1164
|
+
}
|
|
1165
|
+
```
|
|
1166
|
+
|
|
1167
|
+
The idioms that are right because of the `-1` aren't reported:
|
|
1168
|
+
`path.slice(path.lastIndexOf("/") + 1)` (everything after the last slash, or all of it) and
|
|
1169
|
+
`list.splice(list.findLastIndex(...) + 1, 0, item)` (insert after, or at the start). Most of
|
|
1170
|
+
what an existing codebase gets is `list.splice(list.indexOf(x), 1)` where `x` is known to be in
|
|
1171
|
+
the list for a reason the checker can't see: keep the check anyway (`if (at !== -1)`), since a
|
|
1172
|
+
second removal of the same `x` takes another element.
|
|
1173
|
+
|
|
1174
|
+
|
|
1175
|
+
## A regex with the `g` flag tested again
|
|
1176
|
+
|
|
1177
|
+
`test` and `exec` on a regex with `g` (or `y`) start where its last match ended
|
|
1178
|
+
(`lastIndex`): a field regex tested in a method, a local one tested in a loop over other
|
|
1179
|
+
strings or in a callback, answers `true`, `false`, `true` for strings that all match
|
|
1180
|
+
(`regex-last-index`). `g` is for walking the matches of one string; to test, drop it. To walk
|
|
1181
|
+
matches, `text.matchAll(re)`, which doesn't use `lastIndex`.
|
|
1182
|
+
|
|
1183
|
+
```ts good
|
|
1184
|
+
export function numbered(lines: readonly string[]): number {
|
|
1185
|
+
const digits = /\d+/;
|
|
1186
|
+
return lines.filter((line) => digits.test(line)).length;
|
|
1187
|
+
}
|
|
1188
|
+
```
|
|
1189
|
+
|
|
1190
|
+
## An answer nobody reads
|
|
1191
|
+
|
|
1192
|
+
A call whose only point is its answer, as a statement of its own, drops all it did:
|
|
1193
|
+
`name.trim();` leaves `name` untrimmed, `list.concat(more);` and `scores.toSorted(...)` make
|
|
1194
|
+
copies nobody keeps, a function of the program that changes nothing outside itself answers into
|
|
1195
|
+
the void (`unused-answer`, an error). Keep the answer, or assign it where it was meant to go. A
|
|
1196
|
+
member that does something and answers how much of it happened is the same rule:
|
|
1197
|
+
`encoder.encodeInto(text, out)` writes what fits and says so in `{ read, written }`,
|
|
1198
|
+
`readSync(fd, buffer)` says how many bytes it read. Read the answer and act on it.
|
|
1199
|
+
|
|
1200
|
+
```ts bad unused-answer
|
|
1201
|
+
export function clean(name: string): string {
|
|
1202
|
+
name.trim();
|
|
1203
|
+
return name;
|
|
1204
|
+
}
|
|
1205
|
+
```
|
|
1206
|
+
|
|
1207
|
+
```ts good
|
|
1208
|
+
export function clean(name: string): string {
|
|
1209
|
+
return name.trim();
|
|
1210
|
+
}
|
|
1211
|
+
```
|
|
1212
|
+
|
|
1213
|
+
An argument named after another parameter of the function than the one it lands in
|
|
1214
|
+
(`misplaced-argument`, a warning) is the sign of a parameter inserted in front, or two arguments
|
|
1215
|
+
swapped: `corner(x, y)` after `corner(size, x, y)` gained `size`. Pass each argument where its
|
|
1216
|
+
parameter is; a function of several values of one type is safer with an object
|
|
1217
|
+
(`area({ width, height })`).
|
|
1218
|
+
|
|
1219
|
+
## A promise used as its value
|
|
1220
|
+
|
|
1221
|
+
A promise read where its value is meant answers wrong without failing: `isErr(load())` is
|
|
1222
|
+
always `false` (to TypeScript a `Promise<Result<T, E>>` is a `Result`, whose value is the
|
|
1223
|
+
promise), `` `${count()}` `` is `[object Promise]`, `ids.filter(async ...)` keeps every id.
|
|
1224
|
+
std's types refuse the first (`tsc` says *this is a promise: `await` it, then pass the value*);
|
|
1225
|
+
`promise-as-value` reports the rest. The fix is the `await`, inside an `async` function; for a
|
|
1226
|
+
callback a built-in reads right away, decide each item where its answer is known, in a
|
|
1227
|
+
`for...of` with `await`. A dropped call that can't reject is `floating-promise` (a warning):
|
|
1228
|
+
`await` it where what follows needs it, or write `void` where it runs on its own on purpose.
|
|
1229
|
+
|
|
1230
|
+
```ts bad promise-as-value floating-promise
|
|
1231
|
+
async function allowed(id: string): Promise<boolean> {
|
|
1232
|
+
return id.startsWith("u-");
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
async function audit(ids: readonly string[]): Promise<void> {
|
|
1236
|
+
console.log(ids.length);
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
export function visible(ids: readonly string[]): string[] {
|
|
1240
|
+
const kept = ids.filter(async (id) => await allowed(id));
|
|
1241
|
+
audit(kept);
|
|
1242
|
+
return kept;
|
|
1243
|
+
}
|
|
1244
|
+
```
|
|
1245
|
+
|
|
1246
|
+
```ts good
|
|
1247
|
+
async function allowed(id: string): Promise<boolean> {
|
|
1248
|
+
return id.startsWith("u-");
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
async function audit(ids: readonly string[]): Promise<void> {
|
|
1252
|
+
console.log(ids.length);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
export async function visible(ids: readonly string[]): Promise<string[]> {
|
|
1256
|
+
const kept: string[] = [];
|
|
1257
|
+
for (const id of ids) if (await allowed(id)) kept.push(id);
|
|
1258
|
+
// The audit runs on its own: nothing below needs it done.
|
|
1259
|
+
void audit(kept);
|
|
1260
|
+
return kept;
|
|
1261
|
+
}
|
|
1262
|
+
```
|
|
1263
|
+
|
|
1264
|
+
## A value used after it was used up
|
|
1265
|
+
|
|
1266
|
+
Some operations use a value up, and the types don't say so: after `buf.transfer()` (or a
|
|
1267
|
+
transfer list: `worker.postMessage(buf, [buf])`) the buffer is detached, a generator or a
|
|
1268
|
+
`list.values()` iterator runs once, a body is read once, a stream locked by `getReader()` can't
|
|
1269
|
+
be read another way, a closed socket sends nothing (`use-after-consume`, an error). The fix is
|
|
1270
|
+
in the order or in a copy: read what you need before the transfer, collect an iterator once
|
|
1271
|
+
(`[...it]`) or make a new one, keep what the body gave, transfer a copy (`buf.slice(0)`).
|
|
1272
|
+
|
|
1273
|
+
```ts bad use-after-consume
|
|
1274
|
+
function* ids(): Generator<string> {
|
|
1275
|
+
yield "a";
|
|
1276
|
+
yield "b";
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
export function twice(): string {
|
|
1280
|
+
const all = ids();
|
|
1281
|
+
const first = [...all].join(",");
|
|
1282
|
+
return `${first} / ${[...all].join(",")}`;
|
|
1283
|
+
}
|
|
1284
|
+
```
|
|
1285
|
+
|
|
1286
|
+
```ts good
|
|
1287
|
+
function* ids(): Generator<string> {
|
|
1288
|
+
yield "a";
|
|
1289
|
+
yield "b";
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
export function twice(): string {
|
|
1293
|
+
const all = [...ids()];
|
|
1294
|
+
return `${all.join(",")} / ${all.join(",")}`;
|
|
1295
|
+
}
|
|
1296
|
+
```
|
|
1297
|
+
|
|
1298
|
+
A `Result` kept in a local is the same kind of mistake when nothing looks at it on some path:
|
|
1299
|
+
`const r = save(x); console.log(r); return true;` drops the error (`must-use-result`). Check it
|
|
1300
|
+
where it is made, or return it.
|
|
1301
|
+
|
|
1302
|
+
## Text given to a sink
|
|
1303
|
+
|
|
1304
|
+
`innerHTML`, `href`, `new Function`, `exec`, `readFile`, `new RegExp`, `db.exec` do what the text
|
|
1305
|
+
says: parse it as markup, follow it (`javascript:` runs), run it, hand it to a shell, open the path
|
|
1306
|
+
it spells, compile it, run it as SQL (`markup-sink`, `url-sink`, `code-sink`, `command-sink`,
|
|
1307
|
+
`path-sink`, `pattern-sink`, `sql-sink`). Each takes a constant the source shows, or its brand
|
|
1308
|
+
from the constructor that checks it: `escapeHtml(text)` or a `defineSanitizer` sanitizer (`Html`),
|
|
1309
|
+
`safeHref(url)` (`SafeUrl`), `pathUnder(root, name)` (`SafePath`), `escapeRegExp(text)`
|
|
1310
|
+
(`RegexSource`). Code, shell commands and SQL have no constructor: write the code, run the program
|
|
1311
|
+
without a shell with the data as arguments, bind the data to placeholders. A helper that takes a
|
|
1312
|
+
`string` and gives it to a sink is reported in the helper: type its parameter with the brand, and
|
|
1313
|
+
its callers make one. `path-sink` reports only in code a request, a socket's data or a message
|
|
1314
|
+
reaches (a handler the runtime calls with outside data, and what it calls), and only from
|
|
1315
|
+
`safe-ts check`: a build script's paths are its operator's.
|
|
1316
|
+
|
|
1317
|
+
```ts bad markup-sink
|
|
1318
|
+
export function showName(name: string): void {
|
|
1319
|
+
const el = document.createElement("b");
|
|
1320
|
+
el.innerHTML = name;
|
|
1321
|
+
document.body.append(el);
|
|
1322
|
+
}
|
|
1323
|
+
```
|
|
1324
|
+
|
|
1325
|
+
```ts good
|
|
1326
|
+
export function showName(name: string): void {
|
|
1327
|
+
const el = document.createElement("b");
|
|
1328
|
+
el.textContent = name;
|
|
1329
|
+
document.body.append(el);
|
|
1330
|
+
}
|
|
1331
|
+
```
|
|
1332
|
+
|
|
1333
|
+
```ts
|
|
1334
|
+
// path-sink, from `safe-ts check`: a request reaches it
|
|
1335
|
+
import { createServer } from "node:http";
|
|
1336
|
+
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
|
|
1337
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
1338
|
+
|
|
1339
|
+
async function avatar(dir: string, user: string): Promise<string> {
|
|
1340
|
+
const text = await readFile(`${dir}/${user}.svg`, "utf8");
|
|
1341
|
+
return isErr(text) ? "" : text;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
export const server = createServer((req, res) => {
|
|
1345
|
+
avatar(process.cwd(), req.url ?? "").then(
|
|
1346
|
+
(svg) => res.end(svg),
|
|
1347
|
+
() => res.end(),
|
|
1348
|
+
);
|
|
1349
|
+
});
|
|
1350
|
+
```
|
|
1351
|
+
|
|
1352
|
+
```ts good
|
|
1353
|
+
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
|
|
1354
|
+
import { join } from "node:path";
|
|
1355
|
+
import { pathUnder } from "@evobug_com/safe-ts-std/path";
|
|
1356
|
+
import { isErr } from "@evobug_com/safe-ts-std/result";
|
|
1357
|
+
|
|
1358
|
+
const AVATARS = join(import.meta.dirname, "avatars");
|
|
1359
|
+
|
|
1360
|
+
export async function avatar(user: string): Promise<string> {
|
|
1361
|
+
const file = pathUnder(AVATARS, `${user}.svg`);
|
|
1362
|
+
if (isErr(file)) return "";
|
|
1363
|
+
const text = await readFile(file, "utf8");
|
|
1364
|
+
return isErr(text) ? "" : text;
|
|
1365
|
+
}
|
|
1366
|
+
```
|
|
1367
|
+
|
|
1368
|
+
A value the project vouches for that std has no brand for (an SQL fragment, an id a parser made)
|
|
1369
|
+
is a brand of its own: `Brand<"Sql">`, `brandConstructor("Sql", make)`, `brandSinks("Sql",
|
|
1370
|
+
["pg Pool#query"])` (docs: proof types, brands of your own).
|
|
1371
|
+
|
|
1372
|
+
## State across an await
|
|
1373
|
+
|
|
1374
|
+
Between two `await`s nothing else runs; across one, anything can. Shared state (a field of
|
|
1375
|
+
`this`, module state, a local an `async` callback captures) read before an `await` is stale after
|
|
1376
|
+
it: writing back what was made from it loses a concurrent change, and acting on a check made
|
|
1377
|
+
before it lets two callers both pass (`stale-across-await`, a warning). Read after the `await`;
|
|
1378
|
+
claim the work before the first one (an in-flight promise in a map, a flag set right after its
|
|
1379
|
+
test). A `Mut` parameter is the caller's loan to this call alone: two at once are `aliased-mut`'s.
|
|
1380
|
+
|
|
1381
|
+
```ts bad stale-across-await
|
|
1382
|
+
async function price(id: string): Promise<number> {
|
|
1383
|
+
await Promise.resolve();
|
|
1384
|
+
return id.length;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
export class Cart {
|
|
1388
|
+
total = 0;
|
|
1389
|
+
async add(id: string): Promise<void> {
|
|
1390
|
+
this.total += await price(id);
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
```
|
|
1394
|
+
|
|
1395
|
+
```ts good
|
|
1396
|
+
async function price(id: string): Promise<number> {
|
|
1397
|
+
await Promise.resolve();
|
|
1398
|
+
return id.length;
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
export class Cart {
|
|
1402
|
+
total = 0;
|
|
1403
|
+
async add(id: string): Promise<void> {
|
|
1404
|
+
const amount = await price(id);
|
|
1405
|
+
this.total += amount;
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
```
|
|
1409
|
+
|
|
1410
|
+
## What happened during an await
|
|
1411
|
+
|
|
1412
|
+
The world moves on during an `await`. An event that happens once (`close` on a socket or stream,
|
|
1413
|
+
`abort` on a signal, a page's `load`) may come while the function waits: a listener added after
|
|
1414
|
+
the `await` never runs (`late-listener`, an error). Add it before the first `await`, or test what
|
|
1415
|
+
says it happened (`conn.closed`, `signal.aborted`, `document.readyState`) after waiting. A
|
|
1416
|
+
`useTask` / `latest` run may be superseded while it waits: what it writes itself after the
|
|
1417
|
+
`await` lands after the newer run's (`superseded-task-write`, an error). Return the value for the
|
|
1418
|
+
task to hold, or test `signal.aborted` after the `await`, or hand the signal to the awaited call.
|
|
1419
|
+
|
|
1420
|
+
```ts bad late-listener
|
|
1421
|
+
import type { Socket } from "node:net";
|
|
1422
|
+
|
|
1423
|
+
declare function firstPage(): Promise<string>;
|
|
1424
|
+
|
|
1425
|
+
export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
|
|
1426
|
+
conn.write(await firstPage());
|
|
1427
|
+
conn.once("close", unsubscribe);
|
|
1428
|
+
}
|
|
1429
|
+
```
|
|
1430
|
+
|
|
1431
|
+
```ts good
|
|
1432
|
+
import type { Socket } from "node:net";
|
|
1433
|
+
|
|
1434
|
+
declare function firstPage(): Promise<string>;
|
|
1435
|
+
|
|
1436
|
+
export async function stream(conn: Socket, unsubscribe: () => void): Promise<void> {
|
|
1437
|
+
conn.once("close", unsubscribe);
|
|
1438
|
+
conn.write(await firstPage());
|
|
1439
|
+
}
|
|
1440
|
+
```
|
|
1441
|
+
|
|
1442
|
+
```ts bad superseded-task-write
|
|
1443
|
+
import { useTask } from "@evobug_com/safe-ts-vue/task";
|
|
1444
|
+
import { ref } from "vue";
|
|
1445
|
+
|
|
1446
|
+
declare function readFile(name: string): Promise<string>;
|
|
1447
|
+
|
|
1448
|
+
export function useViewer() {
|
|
1449
|
+
const open = ref("");
|
|
1450
|
+
const pick = useTask(async (_signal, name: string): Promise<void> => {
|
|
1451
|
+
open.value = await readFile(name);
|
|
1452
|
+
});
|
|
1453
|
+
return { open, pick };
|
|
1454
|
+
}
|
|
1455
|
+
```
|
|
1456
|
+
|
|
1457
|
+
```ts good
|
|
1458
|
+
import { useTask } from "@evobug_com/safe-ts-vue/task";
|
|
1459
|
+
|
|
1460
|
+
declare function readFile(name: string, init?: { signal?: AbortSignal }): Promise<string>;
|
|
1461
|
+
|
|
1462
|
+
export function useViewer() {
|
|
1463
|
+
return useTask((signal, name: string) => readFile(name, { signal }));
|
|
1464
|
+
}
|
|
1465
|
+
```
|
|
1466
|
+
|
|
1467
|
+
## A promise that never settles, a resource kept
|
|
1468
|
+
|
|
1469
|
+
A `new Promise` whose executor has a path that neither resolves nor rejects it hangs whoever
|
|
1470
|
+
awaits it (`promise-never-settles`, an error): settle it on every path, in the `catch` too, or hand
|
|
1471
|
+
`resolve` to a timer or a listener that will. A resource acquired in a function (a file handle,
|
|
1472
|
+
an interval, a server, an observer) and released on one path only stays held on the others, the
|
|
1473
|
+
path where an `await` rejects, a call throws (even one a caller catches) or `q(...)` returns the
|
|
1474
|
+
error included (`unreleased-resource`, a
|
|
1475
|
+
warning): release it in a `finally`, or `await using` it where it is disposable.
|
|
1476
|
+
|
|
1477
|
+
```ts bad unreleased-resource
|
|
1478
|
+
export function poll(tick: () => void, done: () => boolean): void {
|
|
1479
|
+
const id = setInterval(tick, 100);
|
|
1480
|
+
if (done()) return;
|
|
1481
|
+
tick();
|
|
1482
|
+
clearInterval(id);
|
|
1483
|
+
}
|
|
1484
|
+
```
|
|
1485
|
+
|
|
1486
|
+
```ts good
|
|
1487
|
+
export function poll(tick: () => void, done: () => boolean): void {
|
|
1488
|
+
const id = setInterval(tick, 100);
|
|
1489
|
+
try {
|
|
1490
|
+
if (done()) return;
|
|
1491
|
+
tick();
|
|
1492
|
+
} finally {
|
|
1493
|
+
clearInterval(id);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
```
|
|
1497
|
+
|
|
1498
|
+
## A change left behind, a test already decided
|
|
1499
|
+
|
|
1500
|
+
A change and the change that undoes it (a flag set and cleared, a count up and down, an entry
|
|
1501
|
+
added and removed) with a way out between them that skips the undo leaves the flag on for good
|
|
1502
|
+
(`unbalanced-update`, a warning): an `await` that rejects, a call that throws, a `return`, a
|
|
1503
|
+
`q(...)` that returns the error. Undo it in a `finally`; in a component, `useTask` holds the busy state itself. A test of a
|
|
1504
|
+
place the function just gave a literal (`stop(mut(worker)); if (worker.task !== undefined)`) is
|
|
1505
|
+
decided before it runs (`decided-test`, an error): read what it is about before the change.
|
|
1506
|
+
|
|
1507
|
+
```ts bad unbalanced-update
|
|
1508
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1509
|
+
|
|
1510
|
+
interface Room {
|
|
1511
|
+
users: number;
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
function enter(room: Mut<Room>): void {
|
|
1515
|
+
room.users += 1;
|
|
1516
|
+
}
|
|
1517
|
+
|
|
1518
|
+
function leave(room: Mut<Room>): void {
|
|
1519
|
+
room.users -= 1;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
export function visit(room: Mut<Room>, calledOff: boolean): string {
|
|
1523
|
+
enter(mut(room));
|
|
1524
|
+
if (calledOff) return "called off";
|
|
1525
|
+
leave(mut(room));
|
|
1526
|
+
return "done";
|
|
1527
|
+
}
|
|
1528
|
+
```
|
|
1529
|
+
|
|
1530
|
+
```ts good
|
|
1531
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1532
|
+
|
|
1533
|
+
interface Room {
|
|
1534
|
+
users: number;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
function enter(room: Mut<Room>): void {
|
|
1538
|
+
room.users += 1;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
function leave(room: Mut<Room>): void {
|
|
1542
|
+
room.users -= 1;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
export function visit(room: Mut<Room>, calledOff: boolean): string {
|
|
1546
|
+
enter(mut(room));
|
|
1547
|
+
try {
|
|
1548
|
+
if (calledOff) return "called off";
|
|
1549
|
+
return "done";
|
|
1550
|
+
} finally {
|
|
1551
|
+
leave(mut(room));
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
```
|
|
1555
|
+
|
|
1556
|
+
## A constructor that calls an overridable method
|
|
1557
|
+
|
|
1558
|
+
A base constructor (or an instance field's initializer) that calls `this.describe()`, which a
|
|
1559
|
+
subclass overrides, runs the override before the subclass's fields are set
|
|
1560
|
+
(`constructor-calls-override`, from `safe-ts check`). Pass the value in (`super(label)`),
|
|
1561
|
+
compute it in a static factory after `new`, or make the method `private`. `class ... extends`
|
|
1562
|
+
itself is fine.
|
|
1563
|
+
|
|
1564
|
+
```ts good
|
|
1565
|
+
export class Base {
|
|
1566
|
+
readonly label: string;
|
|
1567
|
+
constructor(label: string) {
|
|
1568
|
+
this.label = label;
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
export class Named extends Base {
|
|
1573
|
+
constructor(private readonly name: string) {
|
|
1574
|
+
super(name.toUpperCase());
|
|
1575
|
+
}
|
|
1576
|
+
greeting(): string {
|
|
1577
|
+
return `${this.label} (${this.name})`;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
```
|
|
1581
|
+
|
|
767
1582
|
## A table keyed by server data
|
|
768
1583
|
|
|
769
1584
|
`LABELS[state]` with `state` from the server reads `undefined` for a value this build doesn't
|
|
@@ -870,13 +1685,47 @@ as Latin-1) before switching, and say so in the hand-off report
|
|
|
870
1685
|
([behaviour.md](behaviour.md)). Don't wrap `btoa` in `unsafe(...)` to keep the old output
|
|
871
1686
|
unless the architecture document lists it.
|
|
872
1687
|
|
|
1688
|
+
## A built-in that throws on data
|
|
1689
|
+
|
|
1690
|
+
`unhandled-failure` reports the language's built-ins that throw for a value their types allow
|
|
1691
|
+
([builtins.md in the docs](https://safe-ts.evobug-pages.com/guide/builtins)): `reduce` without an
|
|
1692
|
+
initial value on a list that may be empty, `toISOString` of a date parsed from text, and
|
|
1693
|
+
`toFixed`, `toString(radix)`, `repeat`, `String.fromCodePoint`, `new Array(n)`, `BigInt(n)`, a
|
|
1694
|
+
locale or time zone given to `Intl`, when the argument comes from data (a parameter, a field,
|
|
1695
|
+
parsed text); bigint `/` by a divisor that may be `0n`. Write the form that can't fail; don't
|
|
1696
|
+
wrap these in `unsafe(...)` to quiet them:
|
|
1697
|
+
|
|
1698
|
+
- `reduce`: pass the initial value the reduction starts from (`0` for a sum), or check
|
|
1699
|
+
`list.length > 0` first where an empty list means something else.
|
|
1700
|
+
- a date from text: keep it in a `const` and check `Number.isNaN(date.getTime())` first; return
|
|
1701
|
+
an error from the function, as the input was wrong.
|
|
1702
|
+
- an argument from a caller: check the range first (`if (digits < 0 || digits > 100) ...`), or
|
|
1703
|
+
clamp it (`Math.min(100, Math.max(0, digits))`); to pad text use `padStart` / `padEnd`, not
|
|
1704
|
+
`repeat`.
|
|
1705
|
+
- a locale or time zone from settings: make the formatter once, in `unsafe(...)`, where the
|
|
1706
|
+
value enters the program, and pass the formatter on.
|
|
1707
|
+
- a bigint divisor: check `d === 0n` first.
|
|
1708
|
+
|
|
1709
|
+
```ts bad unhandled-failure
|
|
1710
|
+
export function column(text: string, width: number, digits: number, n: number): string {
|
|
1711
|
+
return " ".repeat(width - text.length) + text + n.toFixed(digits);
|
|
1712
|
+
}
|
|
1713
|
+
```
|
|
1714
|
+
|
|
1715
|
+
```ts good
|
|
1716
|
+
export function column(text: string, width: number, digits: number, n: number): string {
|
|
1717
|
+
const shown = digits >= 0 && digits <= 20 ? n.toFixed(digits) : n.toFixed(2);
|
|
1718
|
+
return text.padStart(width) + shown;
|
|
1719
|
+
}
|
|
1720
|
+
```
|
|
1721
|
+
|
|
873
1722
|
## A trusted boundary
|
|
874
1723
|
|
|
875
1724
|
A value no check fits, or not worth one, that another part of the same program made (a
|
|
876
1725
|
worker of the same build that posts only one message type): `trust<T>(value)` from
|
|
877
1726
|
`@evobug_com/safe-ts-std/result`. It does nothing at runtime, is searchable, and `safe-ts check`
|
|
878
1727
|
counts it in its escape-hatches line, so it replaces the `as T` and the overload or guard that
|
|
879
|
-
hid one. Data from outside the program (the network, storage, a file) is validated instead.
|
|
1728
|
+
hid one (`no-overload`, `no-type-predicate`). Data from outside the program (the network, storage, a file) is validated instead.
|
|
880
1729
|
|
|
881
1730
|
```ts bad no-unchecked-cast
|
|
882
1731
|
type Progress = { readonly done: number; readonly total: number };
|
|
@@ -942,10 +1791,16 @@ export function portText(): string {
|
|
|
942
1791
|
|
|
943
1792
|
```ts good
|
|
944
1793
|
import { parseArgs } from "@evobug_com/safe-ts-feature-node/util";
|
|
1794
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
945
1795
|
import { q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
946
1796
|
|
|
947
|
-
export
|
|
948
|
-
|
|
1797
|
+
export type ArgsError = Enum<{ BadArgs: { message: string } }>;
|
|
1798
|
+
export const ArgsError = constructors<ArgsError>();
|
|
1799
|
+
|
|
1800
|
+
const badArgs = (error: Error): ArgsError => ArgsError.BadArgs({ message: error.message });
|
|
1801
|
+
|
|
1802
|
+
export function portText(): Result<string, ArgsError> {
|
|
1803
|
+
const parsed = q(parseArgs({ options: { port: { type: "string" } } }), badArgs);
|
|
949
1804
|
return parsed.values.port ?? "8080";
|
|
950
1805
|
}
|
|
951
1806
|
```
|
|
@@ -957,32 +1812,39 @@ throws in some calls and reports in callbacks in others. The browser pack's
|
|
|
957
1812
|
`@evobug_com/safe-ts-feature-browser/indexeddb` settles each request as a `Promise<Result>` (or a
|
|
958
1813
|
`Result` for the calls that only throw), with typed errors: `open`, `createObjectStore` (in
|
|
959
1814
|
`upgrade`), `transaction`, `objectStore`, `get` (with a validator), `getGuarded`, `put`,
|
|
960
|
-
`deleteKey`, `clear`, `commit`.
|
|
961
|
-
|
|
1815
|
+
`deleteKey`, `clear`, `commit`. Name the error the callers see as an `Enum` of the kinds the UI
|
|
1816
|
+
handles. Here that is one kind, `Storage`, whose line `describeError` writes from whichever
|
|
1817
|
+
pack error it was.
|
|
962
1818
|
|
|
963
1819
|
```ts good
|
|
964
1820
|
import { commit, createObjectStore, get, objectStore, open, put, transaction } from "@evobug_com/safe-ts-feature-browser/indexeddb";
|
|
965
1821
|
import { validate } from "@evobug_com/safe-ts-std/json";
|
|
1822
|
+
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
|
|
966
1823
|
import { describeError, type Option, q, type Result } from "@evobug_com/safe-ts-std/result";
|
|
967
1824
|
|
|
968
1825
|
type Draft = { readonly id: string; readonly text: string };
|
|
969
1826
|
|
|
970
|
-
|
|
1827
|
+
export type DraftError = Enum<{ Storage: { reason: string } }>;
|
|
1828
|
+
export const DraftError = constructors<DraftError>();
|
|
1829
|
+
|
|
1830
|
+
const storage = (error: unknown): DraftError => DraftError.Storage({ reason: describeError(error) });
|
|
1831
|
+
|
|
1832
|
+
const openDrafts = (): Promise<Result<IDBDatabase, unknown>> =>
|
|
971
1833
|
open(indexedDB, "app", { version: 1, upgrade: (database) => createObjectStore(database, "drafts", { keyPath: "id" }) });
|
|
972
1834
|
|
|
973
|
-
export async function saveDraft(draft: Draft): Promise<Result<void,
|
|
974
|
-
const db = q(await openDrafts(),
|
|
975
|
-
const tx = q(transaction(db, "drafts", "readwrite"),
|
|
976
|
-
const store = q(objectStore(tx, "drafts"),
|
|
977
|
-
q(await put(store, draft),
|
|
978
|
-
return q(await commit(tx),
|
|
1835
|
+
export async function saveDraft(draft: Draft): Promise<Result<void, DraftError>> {
|
|
1836
|
+
const db = q(await openDrafts(), storage);
|
|
1837
|
+
const tx = q(transaction(db, "drafts", "readwrite"), storage);
|
|
1838
|
+
const store = q(objectStore(tx, "drafts"), storage);
|
|
1839
|
+
q(await put(store, draft), storage);
|
|
1840
|
+
return q(await commit(tx), storage);
|
|
979
1841
|
}
|
|
980
1842
|
|
|
981
|
-
export async function loadDraft(id: string): Promise<Result<Option<Draft>,
|
|
982
|
-
const db = q(await openDrafts(),
|
|
983
|
-
const tx = q(transaction(db, "drafts"),
|
|
984
|
-
const store = q(objectStore(tx, "drafts"),
|
|
985
|
-
return q(await get(store, id, (value) => validate<Draft>(value)),
|
|
1843
|
+
export async function loadDraft(id: string): Promise<Result<Option<Draft>, DraftError>> {
|
|
1844
|
+
const db = q(await openDrafts(), storage);
|
|
1845
|
+
const tx = q(transaction(db, "drafts"), storage);
|
|
1846
|
+
const store = q(objectStore(tx, "drafts"), storage);
|
|
1847
|
+
return q(await get(store, id, (value) => validate<Draft>(value)), storage);
|
|
986
1848
|
}
|
|
987
1849
|
```
|
|
988
1850
|
|
|
@@ -997,16 +1859,22 @@ to the user as an ordinary failure. Pass `Panic`: the throw becomes a `Panic` (n
|
|
|
997
1859
|
and the returned `Err` keeps its type (guide: Errors, "When you call code that throws").
|
|
998
1860
|
|
|
999
1861
|
```ts good
|
|
1862
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
1000
1863
|
import { isErr, isPanic, Panic, type Result, unsafeAsync } from "@evobug_com/safe-ts-std/result";
|
|
1001
1864
|
|
|
1002
|
-
|
|
1865
|
+
type SendError = Enum<{ Refused: {}; Offline: {} }>;
|
|
1866
|
+
|
|
1867
|
+
declare function send(message: string): Promise<Result<void, SendError>>;
|
|
1003
1868
|
|
|
1004
1869
|
export async function deliver(message: string): Promise<string> {
|
|
1005
|
-
// A throw from send() is a bug: kept apart from the
|
|
1870
|
+
// A throw from send() is a bug: kept apart from the errors it returns.
|
|
1006
1871
|
const sent = await unsafeAsync(() => send(message), Panic);
|
|
1007
|
-
if (isPanic(sent))
|
|
1008
|
-
|
|
1009
|
-
|
|
1872
|
+
if (isPanic(sent)) {
|
|
1873
|
+
console.error("bug in send", sent.reason);
|
|
1874
|
+
return "Not delivered";
|
|
1875
|
+
}
|
|
1876
|
+
if (!isErr(sent)) return "Delivered";
|
|
1877
|
+
return match(sent.error, { Refused: () => "The server refused it", Offline: () => "Offline: try again later" });
|
|
1010
1878
|
}
|
|
1011
1879
|
```
|
|
1012
1880
|
|
|
@@ -1035,15 +1903,160 @@ export function userName(session: Session): string {
|
|
|
1035
1903
|
```
|
|
1036
1904
|
|
|
1037
1905
|
```ts good
|
|
1906
|
+
import type { AsyncState } from "@evobug_com/safe-ts-std/async-state";
|
|
1907
|
+
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
|
|
1038
1908
|
import type { Option } from "@evobug_com/safe-ts-std/result";
|
|
1039
1909
|
|
|
1040
|
-
type
|
|
1910
|
+
type User = { readonly name: string };
|
|
1911
|
+
type LoadError = Enum<{ Offline: {}; Status: { status: number } }>;
|
|
1912
|
+
type Session = { readonly user: AsyncState<Option<User>, LoadError> };
|
|
1913
|
+
|
|
1914
|
+
export function userLine(session: Session): string {
|
|
1915
|
+
return match(session.user, {
|
|
1916
|
+
Ready: ({ value }) => value?.name ?? "Signed out",
|
|
1917
|
+
Failed: () => "Couldn't load your account",
|
|
1918
|
+
_: () => "Loading…",
|
|
1919
|
+
});
|
|
1920
|
+
}
|
|
1921
|
+
```
|
|
1922
|
+
|
|
1923
|
+
## A method handed over by name
|
|
1041
1924
|
|
|
1042
|
-
|
|
1043
|
-
|
|
1925
|
+
`queueMicrotask(this.flush)`, `items.forEach(this.add)`, `const { flush } = buffer` and
|
|
1926
|
+
`onClick={this.save}` hand over the method without its object: when it runs, `this` is
|
|
1927
|
+
`undefined` and the first `this.x` throws `TypeError`. TypeScript accepts it; `unbound-method`
|
|
1928
|
+
reports it for a method that uses `this`. Write an arrow that calls the method on its object
|
|
1929
|
+
where it is handed over, or make it an arrow-function field when it is always handed over (a
|
|
1930
|
+
listener). The quick fix binds it (`this.flush.bind(this)`), which also works.
|
|
1931
|
+
|
|
1932
|
+
```ts bad unbound-method
|
|
1933
|
+
export class Buffer {
|
|
1934
|
+
private readonly lines: string[] = [];
|
|
1935
|
+
flush(): void {
|
|
1936
|
+
this.lines.length = 0;
|
|
1937
|
+
}
|
|
1938
|
+
later(): void {
|
|
1939
|
+
queueMicrotask(this.flush);
|
|
1940
|
+
}
|
|
1044
1941
|
}
|
|
1045
1942
|
```
|
|
1046
1943
|
|
|
1944
|
+
```ts good
|
|
1945
|
+
export class Buffer {
|
|
1946
|
+
private readonly lines: string[] = [];
|
|
1947
|
+
flush(): void {
|
|
1948
|
+
this.lines.length = 0;
|
|
1949
|
+
}
|
|
1950
|
+
later(): void {
|
|
1951
|
+
queueMicrotask(() => this.flush());
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
```
|
|
1955
|
+
|
|
1956
|
+
## A parameter the function changes
|
|
1957
|
+
|
|
1958
|
+
A function that changes what it is given declares the parameter `Mut<T>`, and every caller
|
|
1959
|
+
lends the value with `mut(value)`, like Rust's `&mut value`; everything else only reads its
|
|
1960
|
+
parameters (`no-param-mutation`). TypeScript refuses a value passed to a `Mut` parameter without
|
|
1961
|
+
`mut(...)` and checks `Mut` in both directions: a `Dog[]` isn't a `Mut<Animal[]>`, and a function
|
|
1962
|
+
taking `Mut<T>` doesn't fit a callback slot of type `(value: T) => void`. `missing-mut` reports a
|
|
1963
|
+
call without the loan (its fix writes it), `aliased-mut` a call that lends `x` and also gets `x`
|
|
1964
|
+
or a part of it.
|
|
1965
|
+
|
|
1966
|
+
```ts bad missing-mut no-tsc
|
|
1967
|
+
import type { Mut } from "@evobug_com/safe-ts-std/mut";
|
|
1968
|
+
|
|
1969
|
+
type Cart = { items: string[] };
|
|
1970
|
+
|
|
1971
|
+
function addItem(cart: Mut<Cart>, item: string): void {
|
|
1972
|
+
cart.items.push(item);
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
export function restock(cart: Mut<Cart>, items: readonly string[]): void {
|
|
1976
|
+
for (const item of items) addItem(cart, item);
|
|
1977
|
+
}
|
|
1978
|
+
```
|
|
1979
|
+
|
|
1980
|
+
```ts good
|
|
1981
|
+
import { type Mut, mut } from "@evobug_com/safe-ts-std/mut";
|
|
1982
|
+
|
|
1983
|
+
type Cart = { items: string[] };
|
|
1984
|
+
|
|
1985
|
+
function addItem(cart: Mut<Cart>, item: string): void {
|
|
1986
|
+
cart.items.push(item);
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
export function restock(cart: Mut<Cart>, items: readonly string[]): void {
|
|
1990
|
+
for (const item of items) addItem(mut(cart), item);
|
|
1991
|
+
}
|
|
1992
|
+
```
|
|
1993
|
+
|
|
1994
|
+
An optional value stays optional (`mut(maybe)` for an `Option<Mut<T>>` parameter); a fresh
|
|
1995
|
+
literal gets the parameter's type first (`const out: number[] = []`, then `mut(out)`); a list
|
|
1996
|
+
whose elements are changed is `readonly Mut<T>[]`, lent with `mutEach(items)` (no copy; the
|
|
1997
|
+
transform erases it, as it erases `mut(x)`).
|
|
1998
|
+
Don't give `mut` a type argument except for a fresh literal (`mut<Cost>({ ... })`):
|
|
1999
|
+
`mut<Animal[]>(dogs)` is a cast (`no-unchecked-cast`). A value with more properties than the
|
|
2000
|
+
parameter names is lent as it is (a subclass, a `Tree` for `Mut<Entity>`); one whose writable
|
|
2001
|
+
property is narrower is refused, rightly. A member is lent where its union is asked
|
|
2002
|
+
(`Mut<number[]>` as `Mut<number[] | Int32Array>`). Don't make a function generic to get past a refusal: TypeScript lets a
|
|
2003
|
+
generic body write the bound's type into `T`'s narrower property. A union narrowed to one member
|
|
2004
|
+
(`is`, `match`, a tag test) is passed on where that member's `Mut` is asked.
|
|
2005
|
+
|
|
2006
|
+
What is reached through a borrowed value is borrowed too, and `no-param-mutation` says so:
|
|
2007
|
+
|
|
2008
|
+
- **A method of your own class that changes its object** (`c.bump()`, `deps.limiter.take()`):
|
|
2009
|
+
the function takes the object `Mut<Counter>` (also a deps bag whose service it changes:
|
|
2010
|
+
`Mut<Deps>`), and its callers lend it; or it calls the method on what it owns. A getter that
|
|
2011
|
+
changes its object (`mutating-getter`) becomes a method; a memo it fills goes in a
|
|
2012
|
+
`/** @cache */` field. A method lends its own object as `mut<Counter>(this)`.
|
|
2013
|
+
- **A part handed out** (`const inner = peek(o); inner.value = 1`): return `Readonly<Inner>` /
|
|
2014
|
+
`readonly T[]` where callers only read, a copy where they change their own, or take and
|
|
2015
|
+
return `Mut` (`function peekMut(o: Mut<Outer>): Mut<Inner> { return mut(o.inner) }`).
|
|
2016
|
+
- **A borrowed value a class keeps and changes later** (`add(item: Item) { this.items.push(item) }`,
|
|
2017
|
+
then `item.value = 0` in another method; a constructor's `private readonly deps: Deps` whose
|
|
2018
|
+
`deps.metrics.logins++` runs later): declare that parameter `Mut<...>`, so callers write
|
|
2019
|
+
`mut(item)` / `new Service(mut(deps))`; or keep a copy.
|
|
2020
|
+
- **Two loans alive at once** (`aliased-mut`): `await Promise.all([f(mut(x)), g(mut(x))])`,
|
|
2021
|
+
`xs.map(async () => f(mut(x)))` and a loop that pushes `f(mut(x))` into a list become a
|
|
2022
|
+
`for...of` with `await` in it, or one object per call; a promise kept in a `const` is awaited
|
|
2023
|
+
before the object is lent again (quick fix *Await `p` first*) or written by its owner. A
|
|
2024
|
+
listener or a method that starts `f(mut(this.state))` and returns takes turns: chain it
|
|
2025
|
+
(`this.tail = this.tail.then(() => f(mut(this.state)))`) or keep the call in flight and return
|
|
2026
|
+
it to a second caller. A function that starts `f(mut(param))` without awaiting it returns the
|
|
2027
|
+
promise (declared `Promise<...>`) or awaits it, on every way out: what may throw goes before the
|
|
2028
|
+
lend, or the promise is awaited in a `finally` (an exception between the lend and the `await`, a
|
|
2029
|
+
member of the `Promise.all` that rejects first, leaves the call running). Only callees that write the loan after an
|
|
2030
|
+
`await` count (a write of their own answer too: the older answer may land on the newer).
|
|
2031
|
+
- **A `readonly` value given a writable place** (`readonly-dropped`: `const rw: Loose = frozen`,
|
|
2032
|
+
`const PALETTE: Palette = Object.freeze({ ... })` with `Palette`'s fields writable, a `return` of a
|
|
2033
|
+
`Readonly<T>` where `T` is declared): write `readonly` on the place too (`Readonly<Palette>`, the
|
|
2034
|
+
interface's fields `readonly`), or give it a copy it may change (`{ ...frozen }`).
|
|
2035
|
+
- **A shallow copy changed through a field** (`const copy = { ...order }; copy.meta.tag = "x"`,
|
|
2036
|
+
`[...order.lines, extra]` then an element changed, `Object.assign({}, order)`, a rest
|
|
2037
|
+
`const { id, ...rest } = order`, a helper's `return { ...o }`): the copy's own slots are the
|
|
2038
|
+
function's, what they hold is the caller's. Copy that part too (`{ ...order, meta: { ...order.meta
|
|
2039
|
+
} }`, `order.lines.map((l) => ({ ...l }))`), give the field a new value first (`copy.meta = {
|
|
2040
|
+
... }` as a statement right after the copy), or `structuredClone(order)`; don't write
|
|
2041
|
+
`mut({ ...order })` to lend a copy whose fields hold objects.
|
|
2042
|
+
- **A `Sub[]` bound to a writable `Base[]`** (`covariant-alias`): write `readonly Base[]` on the
|
|
2043
|
+
wider side (`ReadonlyMap`, `readonly` fields of your generic type), or bind a copy.
|
|
2044
|
+
- **A handler lent as one that needs more** (`covariant-alias`: `{ onEvent: (a: Animal) => string }`
|
|
2045
|
+
lent as `Mut<{ onEvent: (d: Dog) => string }>`): write the property `readonly` in the type the
|
|
2046
|
+
callee takes (it calls the handler, it doesn't replace it), or give both types the same
|
|
2047
|
+
parameter and result.
|
|
2048
|
+
- **An object a borrowed list holds, changed** (`for (const u of units) u.x = 1`, `find`, `get`, an
|
|
2049
|
+
element of a `filter`ed copy): the function takes `readonly Mut<Unit>[]` (or
|
|
2050
|
+
`ReadonlyMap<K, Mut<V>>`), its callers lend each (`mutEach(units)`); a new list it
|
|
2051
|
+
builds (`filter`, `slice`) is its own to push to.
|
|
2052
|
+
- **A write through a union to a property its members type differently** (`union-tag-write`,
|
|
2053
|
+
`unit.kind = "archer"` on a `Mason | Archer`): put a new object of that member where it is
|
|
2054
|
+
held, or narrow first.
|
|
2055
|
+
|
|
2056
|
+
The fixes ripple once: a function that now takes `Mut<X>` makes its callers lend `x`, and a
|
|
2057
|
+
caller that only borrowed `x` itself gets the same finding. Run `safe-ts migrate mut --write`
|
|
2058
|
+
after declaring, to write the loans.
|
|
2059
|
+
|
|
1047
2060
|
## Casts in tests
|
|
1048
2061
|
|
|
1049
2062
|
`as unknown as Service` and `as never` in tests say a value has a type without anything to
|
|
@@ -1072,3 +2085,145 @@ test("the greeting uses the customer's name", () => {
|
|
|
1072
2085
|
assert.equal(greeting(fixture<Invoice>({ customer: { name: "Ada" } })), "Dear Ada");
|
|
1073
2086
|
});
|
|
1074
2087
|
```
|
|
2088
|
+
|
|
2089
|
+
## A test that cannot fail
|
|
2090
|
+
|
|
2091
|
+
A test passes when nothing in it fails, so one that checks nothing passes whatever the code
|
|
2092
|
+
does. Reported in test files, as errors: a path to the test's end with no assertion
|
|
2093
|
+
(`test-without-assertion`: none at all, one only inside a branch or after an early `return`, or
|
|
2094
|
+
all of them in a `catch`), an assertion whose outcome is fixed (`assertion-cannot-fail`:
|
|
2095
|
+
`expect(r).toBe(r)`, constants only, `expect(x)` with no matcher, `toBeDefined()` on a value that
|
|
2096
|
+
is always there, the test's own mock), one that runs after the test ended (`deferred-assertion`:
|
|
2097
|
+
a timer, a listener, a `.then` nobody awaits) and one a `catch` swallows
|
|
2098
|
+
(`swallowed-assertion`); `.only` (`focused-test`, an error too); and, as warnings, a skip with
|
|
2099
|
+
no reason (`skipped-test`), two tests of one name (`duplicate-test-name`) and an empty `describe`
|
|
2100
|
+
(`empty-test-suite`). Don't fix one by adding an assertion that restates what the test just
|
|
2101
|
+
computed: assert what the result must be. A test that only checks that the code doesn't throw
|
|
2102
|
+
says so: `assert.doesNotThrow(() => f())`, `await assert.doesNotReject(p)`,
|
|
2103
|
+
`expect(() => f()).not.toThrow()`. A throw is checked with `assert.throws` / `.toThrow()`, not
|
|
2104
|
+
with a `try` / `catch`.
|
|
2105
|
+
|
|
2106
|
+
```ts bad test-without-assertion
|
|
2107
|
+
import { test } from "node:test";
|
|
2108
|
+
|
|
2109
|
+
function total(prices: readonly number[]): number {
|
|
2110
|
+
return prices.reduce((sum, price) => sum + price, 0);
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
test("total adds the prices", () => {
|
|
2114
|
+
total([3, 4]);
|
|
2115
|
+
});
|
|
2116
|
+
```
|
|
2117
|
+
|
|
2118
|
+
```ts good
|
|
2119
|
+
import assert from "node:assert/strict";
|
|
2120
|
+
import { test } from "node:test";
|
|
2121
|
+
|
|
2122
|
+
function total(prices: readonly number[]): number {
|
|
2123
|
+
return prices.reduce((sum, price) => sum + price, 0);
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
test("total adds the prices", () => {
|
|
2127
|
+
assert.equal(total([3, 4]), 7);
|
|
2128
|
+
});
|
|
2129
|
+
```
|
|
2130
|
+
|
|
2131
|
+
A helper the test calls counts when it asserts on every path (also one imported from another
|
|
2132
|
+
file); an unknown function counts only when its name says it checks (`assertValid`,
|
|
2133
|
+
`expectNoErrors`). Every skipped test is counted among the escape hatches (`skippedTests` in the
|
|
2134
|
+
baseline), with a reason or not.
|
|
2135
|
+
|
|
2136
|
+
## A function result the checker cannot read
|
|
2137
|
+
|
|
2138
|
+
The rules that judge a value by its type read the declared return type, or, without one, what
|
|
2139
|
+
each `return` plainly is (a literal, `.length`, arithmetic, a call of a function whose result
|
|
2140
|
+
is known, `err(...)`, a declared local, a class's method, a Vue `ref`). A result made
|
|
2141
|
+
otherwise (`await`, a package's call) is unknown, and those rules say nothing about it. With
|
|
2142
|
+
the idiomatic rules on, `undeclared-return-type` lists each such
|
|
2143
|
+
function; declare what it returns. `safe-ts fix undeclared-return-type <dirs>` writes
|
|
2144
|
+
the type where every `return` names one. Leave a single test undeclared (`return typeof x ===
|
|
2145
|
+
"string"`): TypeScript infers the predicate from it only without a return type.
|
|
2146
|
+
|
|
2147
|
+
```ts good
|
|
2148
|
+
class Cart {
|
|
2149
|
+
constructor(readonly items: readonly string[]) {}
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
export function openCart(items: readonly string[]): Cart {
|
|
2153
|
+
return new Cart(items);
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
export function isText(value: unknown) {
|
|
2157
|
+
return typeof value === "string";
|
|
2158
|
+
}
|
|
2159
|
+
```
|
|
2160
|
+
|
|
2161
|
+
## Code nothing reaches
|
|
2162
|
+
|
|
2163
|
+
An agent that writes a new function leaves the old one. Delete what nothing reaches instead of
|
|
2164
|
+
keeping it "in case": `unused-code` (idiomatic, `safe-ts check` only) reports an export no file
|
|
2165
|
+
of the program imports (and that no entry, package `exports`, `import()`, worker or config file
|
|
2166
|
+
offers outside), and what only such code uses; `unused-private` (idiomatic) a private member
|
|
2167
|
+
nothing in its class uses, or a field written and never read; `unreachable-code` code after a
|
|
2168
|
+
call that never returns, and a fallback after every member of a closed type is handled.
|
|
2169
|
+
`safe-ts fix unused-code <dirs>` deletes what nothing refers to at all; run it again for what
|
|
2170
|
+
that left. A fallback that "can't happen" is `unreachable(x)`: TypeScript checks it, and a
|
|
2171
|
+
member added later fails to compile there.
|
|
2172
|
+
|
|
2173
|
+
```ts good
|
|
2174
|
+
import { unreachable } from "@evobug_com/safe-ts-std/enum";
|
|
2175
|
+
|
|
2176
|
+
type Kind = "a" | "b";
|
|
2177
|
+
|
|
2178
|
+
export function label(kind: Kind): string {
|
|
2179
|
+
if (kind === "a") return "A";
|
|
2180
|
+
if (kind === "b") return "B";
|
|
2181
|
+
return unreachable(kind);
|
|
2182
|
+
}
|
|
2183
|
+
```
|
|
2184
|
+
|
|
2185
|
+
```ts bad unreachable-code
|
|
2186
|
+
type Kind = "a" | "b";
|
|
2187
|
+
|
|
2188
|
+
export function label(kind: Kind): string {
|
|
2189
|
+
if (kind === "a") return "A";
|
|
2190
|
+
if (kind === "b") return "B";
|
|
2191
|
+
return "?";
|
|
2192
|
+
}
|
|
2193
|
+
```
|
|
2194
|
+
|
|
2195
|
+
```ts bad unused-private
|
|
2196
|
+
export class Counter {
|
|
2197
|
+
private count = 0;
|
|
2198
|
+
private last = 0;
|
|
2199
|
+
bump(): number {
|
|
2200
|
+
this.count += 1;
|
|
2201
|
+
this.last = this.count;
|
|
2202
|
+
return this.count;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
```
|
|
2206
|
+
|
|
2207
|
+
## Event names at both ends
|
|
2208
|
+
|
|
2209
|
+
An event's name is a string at both ends: rename or mistype one and nothing fails, the
|
|
2210
|
+
listener just never runs. Write the name once (an exported `const`, used by the emit and the
|
|
2211
|
+
listener), and give the listener's event its type on the DOM (`(event: MouseEvent) => ...`):
|
|
2212
|
+
TypeScript then refuses a name the element's event map doesn't have. `unknown-event` reports a
|
|
2213
|
+
DOM listener for an event its class never dispatches (`"clik"`), `unmatched-event` a listener
|
|
2214
|
+
nothing emits for and an emit nobody listens for on the same emitter, naming the near miss at
|
|
2215
|
+
both sites (both `safe-ts check` only).
|
|
2216
|
+
|
|
2217
|
+
```ts
|
|
2218
|
+
import { EventEmitter } from "node:events";
|
|
2219
|
+
|
|
2220
|
+
export const UserCreated = "user:created";
|
|
2221
|
+
export type Events = { [UserCreated]: [id: string] };
|
|
2222
|
+
|
|
2223
|
+
export class Users {
|
|
2224
|
+
readonly events = new EventEmitter<Events>();
|
|
2225
|
+
create(id: string): void {
|
|
2226
|
+
this.events.emit(UserCreated, id);
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
```
|