@noego/trust 0.5.1 → 0.6.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 CHANGED
@@ -279,6 +279,157 @@ const loaded = Trust.try(() => JSON.parse(text), () => ({ kind: 'bad_json' }));
279
279
  const fetched = await Trust.tryAsync(() => client.get(url), (cause) => ({ kind: 'http_failed', cause }));
280
280
  ```
281
281
 
282
+ ## Success states
283
+
284
+ > if we can have multiple things, it must be a state, otherwise ok is ok.
285
+
286
+ One kind of success: `Result.ok(value)`. More than one: `Result.state('<state>', value)`.
287
+ The state names the outcome; `ok` still tells success from failure.
288
+
289
+ ### Make and preserve states
290
+
291
+ `Result.state` has three call forms. A value gets a state; a stateless Result gets its Ok
292
+ tagged and its Err passed through unchanged; one argument makes a state with no payload
293
+ (`value` is `undefined`, typed as `void`). An already stated input is a type error.
294
+
295
+ ```ts
296
+ import { Result, Trust, type StatedOk, type StatedResult } from '@noego/trust';
297
+
298
+ const fresh = Result.state('fresh', { id: 7 });
299
+ const tagged = Result.state('fresh', Result.ok({ id: 7 }));
300
+ const failed = Result.state('fresh', Result.err({ kind: 'Missing' }));
301
+ const empty = Result.state('empty');
302
+
303
+ // StatedOk<T, S> is an Ok with a literal state; StatedResult<T, E, S> adds Err<E>.
304
+ type Fresh = StatedOk<{ id: number }, 'fresh'>;
305
+ type Loaded = StatedResult<{ id: number }, { kind: 'Missing' }, 'fresh'>;
306
+ // Different payloads belong in separate members:
307
+ type Choice = Fresh | StatedOk<void, 'empty'>;
308
+ ```
309
+
310
+ Keep state-bearing types when forwarding a result. `Trust.translate` changes failure kinds
311
+ without changing successes or their states. `Trust.decide` preserves existing successes;
312
+ on a stated input, every recovery handler must return `Result.state(...)`, not a bare value.
313
+ Stateless recovery keeps its existing API.
314
+
315
+ ```ts
316
+ function load(id: number) {
317
+ if (id < 0) return Result.err({ kind: 'Missing' });
318
+ return id === 0 ? Result.state('empty') : Result.state('fresh', { id });
319
+ }
320
+
321
+ function recover(id: number) {
322
+ return Trust.decide(load(id), { Missing: () => Result.state('empty') });
323
+ }
324
+ ```
325
+
326
+ ### Check the state before reading the value
327
+
328
+ First deal with failure, then check `r.state === …`, use an exhaustive `switch`, or
329
+ use `Trust.match`. Checking `ok` alone does not decide which success happened.
330
+
331
+ ```ts
332
+ function label(id: number) {
333
+ const r = recover(id);
334
+ if (r.state === 'empty') return 'empty';
335
+ return String(r.value.id);
336
+ }
337
+
338
+ function describe(id: number) {
339
+ const r = recover(id);
340
+ switch (r.state) {
341
+ case 'fresh': return String(r.value.id);
342
+ case 'empty': return 'empty';
343
+ default: { const unreachable: never = r; return unreachable; }
344
+ }
345
+ }
346
+
347
+ function matched(id: number) {
348
+ return Trust.match(recover(id), {
349
+ fresh: value => String(value.id),
350
+ empty: () => 'empty',
351
+ }); // Ok<string>, not a bare string
352
+ }
353
+
354
+ function remapped(id: number) {
355
+ return Trust.match(recover(id), {
356
+ fresh: value => Result.state('present', value),
357
+ empty: () => Result.state('absent'),
358
+ }); // stated output: every handler returns Result.state(...)
359
+ }
360
+ ```
361
+
362
+ Naming a state checks it; reading `.value` once a single state is left checks that one;
363
+ a state that is neither named nor read is reported as `unchecked-state`.
364
+
365
+ `Trust.match` needs a stated result that cannot fail: handle all failures first.
366
+ Its handlers cover every input state, receive that state's payload, and are synchronous.
367
+ Bare handler values produce a plain `Ok`; when every handler returns `Result.state`,
368
+ the output keeps those states. Do not mix stated and bare handler returns.
369
+
370
+ ### Opt in: `trusted-state`
371
+
372
+ In trust.config.json:
373
+
374
+ ```json
375
+ { "rules": { "trusted-state": "on" } }
376
+ ```
377
+
378
+ This is all-or-nothing for the project, not a per-file migration switch. It also turns
379
+ `dropped-result` on. An explicit `"dropped-result": "off"` alongside it (including an
380
+ inherited effective setting) is a config error: remove that setting or turn `trusted-state` off.
381
+
382
+ The findings below use these origins as baseline keys. All are errors except `single-state`.
383
+
384
+ | Origin | When it is reported | How to fix it |
385
+ |---|---|---|
386
+ | `mixed-success` | A success side mixes stateless Ok and states. | Give every success its own state. |
387
+ | `stateless-union` | A stateless Result has several kinds of success. | Split them into states, or make absence an Err kind. |
388
+ | `state-union` | One state's payload holds several types. | Give each outcome its own state. |
389
+ | `single-state` (warning) | A function names only one success state. | Use `Result.ok`; states are for several successes. |
390
+ | `non-literal-state` | A state is not a string literal or union of string literals. | Keep the state names literal. |
391
+ | `unnarrowed-value` | A stated value is read before its state is checked. | Check `state`, switch, or use `Trust.match` first. |
392
+ | `erased-state` | A stated result flows into a stateless Result type. | Preserve `StatedResult` / `StatedOk`, or check and pass plain data. |
393
+ | `unchecked-state` | Possible states are discarded, overwritten, or left unchecked at scope exit. | Check every remaining state, or return the result. |
394
+ | `stored-state` | A stated result is stored where states are not followed. | Check the state and store plain data, not the Result. |
395
+ | `stated-leaves` | A stated result is passed outside checked code. | Check the state and pass plain data. |
396
+ | `returns-ok-result` (`boundary-result`) | A configured boundary returns a Result that cannot fail. | Return plain data, or explicitly exclude that boundary. |
397
+
398
+ ### One type per Ok
399
+
400
+ A union of different types, or a nullable value, as an Ok value is reported, whether
401
+ inline or behind a named alias: `Result<User | Guest, E>`, `Result<User | null, E>`,
402
+ and a named `MaybeUser` mean several possible successes. Nullable lookups often surface
403
+ here first. Split found and absent into states, or make absence a failure.
404
+
405
+ `boolean`, a single enum, and unions of string or number literals are fine: those are
406
+ one value vocabulary, not different payload types. Only the value's **top-level type**
407
+ is examined. Unions inside a payload object are not split into states.
408
+
409
+ ### Boundaries return plain data
410
+
411
+ With the rule on, a configured boundary returns plain data, never a Result — not even
412
+ one that cannot fail. Decide failures, then convert each success to the outside's own
413
+ discriminant. For example, using the loader above:
414
+
415
+ ```ts
416
+ function boundary(id: number) {
417
+ const r = Trust.decide(load(id), { Missing: () => Result.state('empty') });
418
+ switch (r.state) {
419
+ case 'fresh': return { status: 'found', id: r.value.id };
420
+ case 'empty': return { status: 'empty' };
421
+ default: { const unreachable: never = r; return unreachable; }
422
+ }
423
+ }
424
+ ```
425
+
426
+ The rule does not follow unions inside payload objects, fields and module-level
427
+ variables over their lifetime, or results nested inside objects passed outward.
428
+ Storage and direct outward transfers above are checked, but this is not deep object tracking.
429
+
430
+ **Engine status:** This rule is reported by `trust check` / `trust baseline` from engine
431
+ `0.5.1-dev.0` on (protocol 5), which is published by the dev release that follows this merge.
432
+
282
433
  ## Handling a failure: return it or decide it
283
434
 
284
435
  Rules:
@@ -414,6 +565,7 @@ export default [
414
565
  "distrust": ["js:Array.from"],
415
566
  "trust_type": ["zod", { "origin": "node:path", "reason": "returns plain strings" }],
416
567
  "distrust_type": [],
568
+ "rules": { "trusted-state": "off" },
417
569
  "passthrough": ["server/repositories/**"],
418
570
  "ignore": ["**/*.test.ts", "server/testing/**"],
419
571
  "strict": ["server/services/workspace/**", "server/controller/workspace.controller.ts"],
@@ -425,6 +577,9 @@ export default [
425
577
  }
426
578
  ```
427
579
 
580
+ - `rules`: per-rule settings: `type-claim`, `untrusted-value`, `dropped-result`, `trusted-state`,
581
+ `redundant-guard`, `result-lookalike`, and `untrustedCallbacks`. `trusted-state` defaults to `off`;
582
+ see [Success states](#success-states) for its required `dropped-result` setting and engine status.
428
583
  - `extend`: a preset (`js`, `node`, `web`, `default`, `svelte`) or a relative path, or a non-empty array of them
429
584
  (`"extend": ["web", "svelte"]`). Chains are followed. Array entries apply left to right: a later entry
430
585
  overrides an earlier one, and the file itself overrides all of them. For `"extend": ["a", "b"]` the lookup
@@ -89,12 +89,14 @@ type ResultLookalikeSetting = 'off' | 'strict' | 'on';
89
89
  /** Which callback parameters are untrusted-value sources (see the file comment). */
90
90
  type UntrustedCallbacks = 'off' | 'inline' | 'all';
91
91
  /** The rules that are off unless a config turns them on. */
92
- type OptInRule = 'type-claim' | 'untrusted-value' | 'dropped-result' | 'redundant-guard';
92
+ type OptInRule = 'type-claim' | 'untrusted-value' | 'dropped-result' | 'trusted-state' | 'redundant-guard' | 'finally-return';
93
93
  interface TrustRuleSettings {
94
94
  readonly 'type-claim': RuleSwitch;
95
95
  readonly 'untrusted-value': RuleSwitch;
96
96
  readonly 'dropped-result': RuleSwitch;
97
+ readonly 'trusted-state': RuleSwitch;
97
98
  readonly 'redundant-guard': RuleSwitch;
99
+ readonly 'finally-return': RuleSwitch;
98
100
  readonly 'result-lookalike': ResultLookalikeSetting;
99
101
  readonly untrustedCallbacks: UntrustedCallbacks;
100
102
  }
@@ -324,6 +326,21 @@ declare const DROPPED_RESULT_MESSAGES: {
324
326
  readonly overwritten: "`{{subject}}` is assigned again while it can still fail with {{kinds}}, so the failure is dropped. Return it, or handle it with Trust.decide first.";
325
327
  };
326
328
  type DroppedResultOrigin = keyof typeof DROPPED_RESULT_MESSAGES;
329
+ declare const TRUSTED_STATE_RULE = "trusted-state";
330
+ /** Keyed by origin: the baseline key and ESLint messageId. */
331
+ declare const TRUSTED_STATE_MESSAGES: {
332
+ readonly 'unchecked-state': "`{{subject}}` can still be {{states}} here, and that state was never checked. Check it (`{{subject}}.state === '…'`, a `switch`, or `Trust.match`), or return it.";
333
+ readonly 'stored-state': "`{{subject}}` has states ({{states}}) and is stored where states are not followed, so a stored result that is never read is silently dropped. Check the state first and store the plain value.";
334
+ readonly 'stated-leaves': "`{{subject}}` has states ({{states}}) and is passed to `{{callee}}`, which is outside the checked code, so its state would never be checked. Check the state first and pass plain data.";
335
+ readonly 'unnarrowed-value': "`{{subject}}.value` is read while `{{subject}}` can still be {{states}}: check the state first (`{{subject}}.state === '…'`, a `switch`, or `Trust.match`).";
336
+ readonly 'erased-state': "`{{subject}}` has states ({{states}}) but flows into a stateless Result here, so nothing would require the state to be checked. Declare the states in the target type (`StatedResult` / `StatedOk`), or check the state and pass the plain value.";
337
+ readonly "mixed-success": "This success side mixes `Result.ok` with states: once a function has states, every success must be `Result.state('<state>', value)`. Give this outcome its own state.";
338
+ readonly "stateless-union": "This Result has more than one kind of success ({{type}}): if it can be several things, each must be a state. Use `Result.state('<state>', value)` for each outcome, or make an absence an `Err` kind.";
339
+ readonly "state-union": "State '{{state}}' holds more than one type ({{type}}): a state is one outcome, so give each its own state with `Result.state`.";
340
+ readonly "single-state": "This function names only one state ('{{state}}') — use `Result.ok`: states are for functions with more than one kind of success.";
341
+ readonly "non-literal-state": "A success state must be a string literal or a union of string literals, not `{{type}}`: a state that is not a literal cannot be checked.";
342
+ };
343
+ type TrustedStateOrigin = keyof typeof TRUSTED_STATE_MESSAGES;
327
344
  declare const REDUNDANT_GUARD_RULE = "redundant-guard";
328
345
  /** Origin label of every redundant-guard finding (baseline key). */
329
346
  declare const REDUNDANT_GUARD_ORIGIN = "redundant";
@@ -334,18 +351,26 @@ declare const REDUNDANT_GUARD_ORIGIN = "redundant";
334
351
  declare const REDUNDANT_GUARD_MESSAGES: {
335
352
  readonly redundant: "`{{guard}}` guards nothing that can fail: {{calls}}. It invents a failure path callers must unwrap for nothing. Call it directly and return its value; a trusted origin's failure is a programmer error, not a failure path. If the call can fail, remove its origin from \"trust\" in trust.config.json instead.";
336
353
  };
354
+ declare const FINALLY_RETURN_RULE = "finally-return";
355
+ /** Origin label of every finally-return finding (baseline key). */
356
+ declare const FINALLY_RETURN_ORIGIN = "return";
357
+ declare const FINALLY_RETURN_MESSAGES: {
358
+ readonly return: "`return` inside `finally` overwrites any Result (Err or StatedOk) or throw leaving `try` / `catch`. Do not return from `finally`; use `Trust.using(acquire, use, release)` when cleanup returns a Result.";
359
+ };
337
360
  declare const BOUNDARY_RULE = "boundary-result";
338
361
  /**
339
362
  * The messages of `boundary-result` (core/boundaries.ts), keyed by origin: the baseline key, and the ESLint
340
363
  * messageId of `trust/boundary-result`. `{{member}}` is the boundary (`Class.member`, `api.get`, `fn`), `{{item}}`
341
364
  * the `boundaries` item it belongs to (`boundaries[0] in trust.config.json`), `{{kinds}}` the failure kinds its
342
365
  * Result can carry, `{{type}}` `any` or `unknown`, `{{entry}}` an `exclude` name and `{{other}}` a second item.
366
+ * returns-ok-result an error under trusted-state: a Result object crosses the edge even though it cannot fail
343
367
  * returns-result an error: the boundary's return value can fail
344
368
  * unproven-return a warning (an error under strict): the return type is `any` / `unknown`, so nothing shows it is free of a Result
345
369
  * stale-exclude an error, reported against the config file: an `exclude` entry that names no boundary of its item's files
346
370
  * overlapping-items an error at the file's start: two items match the same file, so its boundaries are not checked
347
371
  */
348
372
  declare const BOUNDARY_MESSAGES: {
373
+ readonly 'returns-ok-result': "Boundary \"{{member}}\" returns a Result object: a Result must not cross the edge, even one that cannot fail. Return plain data (read the value, and give several outcomes their own discriminant), or leave it out by adding \"{{member}}\" to \"exclude\" of {{item}}.";
349
374
  readonly 'returns-result': "Boundary \"{{member}}\" returns a Result that can fail with {{kinds}}: a Result must not cross the edge. Decide every kind here (an exhaustive `switch` with a `never` default) and return plain data, or leave it out by adding \"{{member}}\" to \"exclude\" of {{item}}.";
350
375
  readonly 'unproven-return': "Boundary \"{{member}}\" returns `{{type}}`, which may hold a Result: nothing shows a failure does not cross the edge here. Return a type that is not `any` or `unknown`, or leave it out by adding \"{{member}}\" to \"exclude\" of {{item}}.";
351
376
  readonly 'stale-exclude': "Boundary exclude \"{{entry}}\" of {{item}} matches no exported function, class member or object member in its files: it excludes nothing. Remove it, or fix the name (\"Class.member\", \"Class.*\", \".member\" or \"function\").";
@@ -417,4 +442,4 @@ declare function describeBaselineDelta(delta: BaselineDelta<BaselineFinding & {
417
442
  readonly message: string;
418
443
  }>): string[];
419
444
 
420
- export { REDUNDANT_GUARD_RULE as $, updateBaseline as A, type BaselineCounts as B, type TrustRuleSettings as C, type TrustConfig as D, type OriginInfo as E, type Finding as F, type CatchProblem as G, ACCEPT_DIRECTIVE as H, ACCEPT_DIRECTIVE_MESSAGES as I, BOUNDARY_MESSAGES as J, BOUNDARY_RULE as K, type BoundaryGroup as L, type BoundaryOrigin as M, CATCH_ORIGIN as N, OriginResolver as O, DEFAULT_RULE_SETTINGS as P, DIRECTIVE_ORIGIN as Q, DROPPED_RESULT_MESSAGES as R, DROPPED_RESULT_RULE as S, type TypeScript as T, type DroppedResultOrigin as U, type LoadTrustConfigOptions as V, WHOLE_BASELINE as W, type OptInRule as X, REDUNDANT_GUARD_MESSAGES as Y, type ZoneGroup as Z, REDUNDANT_GUARD_ORIGIN as _, type TsconfigMapping as a, type RuleSwitch as a0, THROW_MESSAGES as a1, THROW_RULE as a2, TYPE_CLAIM_KINDS as a3, TYPE_CLAIM_MESSAGES as a4, TYPE_CLAIM_RULE as a5, TrustConfigError as a6, type TrustEntry as a7, type TrustLevel as a8, type TypeClaimOrigin as a9, UNANALYZABLE_ORIGIN as aa, UNTRUSTED_CALL_MESSAGES as ab, UNTRUSTED_CALL_RULE as ac, UNTRUSTED_VALUE_MESSAGES as ad, UNTRUSTED_VALUE_RULE as ae, type UntrustedCallbacks as af, type UntrustedEntry as ag, VALIDATOR_DIRECTIVE as ah, effectiveTrustList as ai, effectiveTypeTrustList as aj, isInsideValidator as ak, isMarkedValidator as al, isRuleEnabled as am, loadTrustConfig as an, normalizeOrigin as ao, type BaselineDelta as b, type BaselineFinding as c, type BaselineScope as d, type TrustDirective as e, type Zone as f, Zones as g, compareToBaseline as h, countFindings as i, describeBaselineDelta as j, directiveDirectlyAbove as k, directiveReason as l, groupMatches as m, isNamedDirective as n, lineDirectivesIn as o, loadTypeScript as p, matchesPatterns as q, nearestPackageName as r, nodeBelow as s, normalizePattern as t, parseBaseline as u, readBaseline as v, realpathOrSelf as w, relativeInside as x, serializeBaseline as y, toPosix as z };
445
+ export { type OptInRule as $, updateBaseline as A, type BaselineCounts as B, type TrustRuleSettings as C, type TrustConfig as D, type OriginInfo as E, type Finding as F, type CatchProblem as G, ACCEPT_DIRECTIVE as H, ACCEPT_DIRECTIVE_MESSAGES as I, BOUNDARY_MESSAGES as J, BOUNDARY_RULE as K, type BoundaryGroup as L, type BoundaryOrigin as M, CATCH_ORIGIN as N, OriginResolver as O, DEFAULT_RULE_SETTINGS as P, DIRECTIVE_ORIGIN as Q, DROPPED_RESULT_MESSAGES as R, DROPPED_RESULT_RULE as S, type TypeScript as T, type DroppedResultOrigin as U, FINALLY_RETURN_MESSAGES as V, WHOLE_BASELINE as W, FINALLY_RETURN_ORIGIN as X, FINALLY_RETURN_RULE as Y, type ZoneGroup as Z, type LoadTrustConfigOptions as _, type TsconfigMapping as a, REDUNDANT_GUARD_MESSAGES as a0, REDUNDANT_GUARD_ORIGIN as a1, REDUNDANT_GUARD_RULE as a2, type RuleSwitch as a3, THROW_MESSAGES as a4, THROW_RULE as a5, TRUSTED_STATE_MESSAGES as a6, TRUSTED_STATE_RULE as a7, TYPE_CLAIM_KINDS as a8, TYPE_CLAIM_MESSAGES as a9, TYPE_CLAIM_RULE as aa, TrustConfigError as ab, type TrustEntry as ac, type TrustLevel as ad, type TrustedStateOrigin as ae, type TypeClaimOrigin as af, UNANALYZABLE_ORIGIN as ag, UNTRUSTED_CALL_MESSAGES as ah, UNTRUSTED_CALL_RULE as ai, UNTRUSTED_VALUE_MESSAGES as aj, UNTRUSTED_VALUE_RULE as ak, type UntrustedCallbacks as al, type UntrustedEntry as am, VALIDATOR_DIRECTIVE as an, effectiveTrustList as ao, effectiveTypeTrustList as ap, isInsideValidator as aq, isMarkedValidator as ar, isRuleEnabled as as, loadTrustConfig as at, normalizeOrigin as au, type BaselineDelta as b, type BaselineFinding as c, type BaselineScope as d, type TrustDirective as e, type Zone as f, Zones as g, compareToBaseline as h, countFindings as i, describeBaselineDelta as j, directiveDirectlyAbove as k, directiveReason as l, groupMatches as m, isNamedDirective as n, lineDirectivesIn as o, loadTypeScript as p, matchesPatterns as q, nearestPackageName as r, nodeBelow as s, normalizePattern as t, parseBaseline as u, readBaseline as v, realpathOrSelf as w, relativeInside as x, serializeBaseline as y, toPosix as z };