@noego/trust 0.5.0-dev.1 → 0.5.0-dev.3

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
@@ -231,6 +231,12 @@ For both forms:
231
231
  - Throwing at the edge is the exception, not the rule: when an API's contract is exceptions, the edge
232
232
  turns the decided failure into one, under `//trust:accept <reason>`.
233
233
 
234
+ The lint holds the edge to this. Name the edge files in trust.config.json (`boundaries`: controllers, a
235
+ job's `main`, the public entry of a library), and `boundary-result` reports every exported function and
236
+ public member there whose return value can still fail, including `Promise<Result<…>>` and `Result[]`
237
+ (see [`boundary-result`](#boundary-result-a-result-does-not-cross-the-edge)). A boundary that is allowed
238
+ to hand a `Result` on (an internal API of the application) is left out by name in the item's `exclude`.
239
+
234
240
  ### Only real failure points return `Result`
235
241
 
236
242
  A `Result` is a promise to the caller that something can go wrong at runtime. Code that cannot fail
@@ -411,6 +417,10 @@ export default [
411
417
  "passthrough": ["server/repositories/**"],
412
418
  "ignore": ["**/*.test.ts", "server/testing/**"],
413
419
  "strict": ["server/services/workspace/**", "server/controller/workspace.controller.ts"],
420
+ "boundaries": [
421
+ { "files": ["server/admin/**/*.controller.ts"], "exclude": ["UserController.get_user"] },
422
+ { "files": ["server/public/**/*.controller.ts"], "exclude": [".health"] }
423
+ ],
414
424
  "tsconfig": [{ "files": "ui/**", "tsconfig": "tsconfig.web.json" }]
415
425
  }
416
426
  ```
@@ -440,7 +450,20 @@ export default [
440
450
  (`callsIgnored`) because ignoring alone silently trusts.
441
451
  - `strict` (`trust check` only): globs of files that are always checked under the strict rules, with or without
442
452
  the `--strict` flag. Use it to hold finished parts of the tree to the strict standard. `!negation` carves files
443
- back out; `ignore` still wins. `trust baseline` and ESLint ignore this key.
453
+ back out; `ignore` still wins. `trust baseline` and ESLint ignore this key (except that `boundary-result` reports
454
+ an unproven boundary return as an error, not a warning, in a file the globs match).
455
+ - `boundaries`: the files at the edge of the program, as a list of items `{ "files": <glob or globs>, "exclude":
456
+ [names] }` (`exclude` optional). Having the key turns the [`boundary-result`](#boundary-result-a-result-does-not-cross-the-edge)
457
+ rule on: every exported function and public member of a matched file is a boundary, and one whose return
458
+ value can fail is reported. An `exclude` name applies to that item's files only: `"UserController.get_user"`
459
+ (that member of every exported class with that name in the item's files), `"UserController.*"` (every public
460
+ member of every exported class or object with that name there, members added later included; never a
461
+ function), `".get_user"` (that member of any exported class or object there), `"get_user"` (an exported
462
+ function). `*` stands only for the whole member part after a class name: `".*"`, `"User*.get"`, `"X.get*"`
463
+ and a bare `"*"` are config errors. A file two items match is an error, and so is an `exclude` name that
464
+ matches nothing in its item's files; split the items (or the configs) to tell same-named classes apart.
465
+ Items of every file in the `extend` chain are kept, each relative to its own directory; there is no `rules`
466
+ switch for this rule.
444
467
  - `tsconfig` (CLI only): an ordered list of `{ "files": <glob or globs>, "tsconfig": <path> }`. The first entry
445
468
  whose globs match a file picks the tsconfig its program is built from; the path is relative to the config
446
469
  file's directory. `--tsconfig` overrides it, and files no entry matches use the nearest `tsconfig.json`. A file
@@ -536,8 +559,8 @@ It needs neither ESLint nor an installed TypeScript package. TypeScript 5.9.3 st
536
559
  are copied and embedded when the engine is built; they are not chosen from the checked project at runtime.
537
560
  The experimental `--rs` and `--go` flags have been removed.
538
561
 
539
- Every rule, including the opt-in `type-claim`, `untrusted-value`, `dropped-result` and `redundant-guard`,
540
- runs in the engine. The TypeScript implementation in `src/core` stays the reference: differential tests
562
+ Every rule, including the opt-in `type-claim`, `untrusted-value`, `dropped-result` and `redundant-guard`, and
563
+ `boundary-result` (on when the config names `boundaries`), runs in the engine. The TypeScript implementation in `src/core` stays the reference: differential tests
541
564
  (`test/native-check.test.ts`, `test/native-opt-in.test.ts`) run the fixtures and the shared rule-case corpus
542
565
  through both and compare whole findings (file, position, rule, message, severity). Two things keep the
543
566
  output independent of the compiler: type text in messages is printed in a canonical member order
@@ -546,9 +569,14 @@ origin is the one reported, on both sides. See [native/RELEASE.md](native/RELEAS
546
569
 
547
570
  The check walks the given files and directories for `.ts`/`.tsx` (skipping `node_modules`, `dist`,
548
571
  `.d.ts`) and skips the config's `ignore` zone. Exit codes are 0 for clean or warnings only,
549
- 1 for trust violations, and 2 when setup, parsing or the engine fails. `--perf` adds three optional
550
- warnings: `perf-delete-property`, `perf-object-as-map`, and `perf-prototype-mutation`. It does not
551
- include a sparse-array rule. Warnings teach the tradeoff and never change the exit code.
572
+ 1 for trust violations, and 2 when setup, parsing or the engine fails. `--perf` adds four optional
573
+ warnings: `perf-delete-from-copy`, `perf-delete-property`, `perf-object-as-map`, and
574
+ `perf-prototype-mutation`. Spread-copy deletes suggest rest destructuring; fixed-key deletes
575
+ explain the potential shape cost even on index-signature types; computed-key deletes suggest
576
+ Map only for long-lived key churn, not objects that must remain plain JSON/API/process payloads.
577
+ Library-declared host objects (such as dataset and Storage), global objects (including const
578
+ aliases and casts), and values typed as `ProcessEnv`/`NodeJS.ProcessEnv` are skipped.
579
+ There is no sparse-array rule. Measure the hot path: warnings are advisory and never change the exit code.
552
580
  `--json` emits one object with `findings` (each has `severity: "error" | "warning"`), setup `errors`,
553
581
  configuration `warnings`, and a `summary` on success.
554
582
 
@@ -997,6 +1025,67 @@ async instance<T>(token: new () => T) {
997
1025
  Fix it by calling directly and returning the value. If the call really can fail, the trust entry is wrong: remove the
998
1026
  origin from `trust`, and the guard becomes required again.
999
1027
 
1028
+ ### `boundary-result`: a Result does not cross the edge
1029
+
1030
+ `Result` is an internal contract; the edge of the program decides every kind that is left and returns plain data
1031
+ (see [The edge decides everything that is left](#the-edge-decides-everything-that-is-left)). `boundary-result`
1032
+ holds the edge to that. It is on as soon as trust.config.json names the edge files under `boundaries`
1033
+ (`trust check`, `trust baseline` and the ESLint rule `trust/boundary-result` read the same key):
1034
+
1035
+ ```json
1036
+ "boundaries": [
1037
+ { "files": ["server/admin/**/*.controller.ts"], "exclude": ["UserController.get_user"] },
1038
+ { "files": ["server/public/**/*.controller.ts"], "exclude": [".health"] },
1039
+ { "files": ["src/index.ts"] }
1040
+ ]
1041
+ ```
1042
+
1043
+ Every exported function and public member of a matched file is a **boundary**: an `export function`, an exported
1044
+ `const` function, every public instance or static method, getter and function-valued property of an exported
1045
+ class (also `export default class`, as controllers are written), the function-valued properties and getters of an
1046
+ exported object, and what a barrel re-exports (`export { a } from './a'`, `export *`), reported at the export
1047
+ statement. Not boundaries: `private`, `protected` and `#private` members, inherited members, type-only exports,
1048
+ and exported values that are not functions. A boundary **can fail** when its awaited return type has an `Err`
1049
+ member from `@noego/trust`, one level into an array or tuple (the `dropped-result` definition), so a
1050
+ `Promise<Result<…>>` method and a `Result[]` return are reported. The origin is the baseline key:
1051
+
1052
+ | Origin | What is reported | Severity |
1053
+ |---|---|---|
1054
+ | `returns-result` | a boundary whose return value can fail, with the kinds it can carry | error |
1055
+ | `unproven-return` | a boundary whose return type is `any` or `unknown`: nothing shows it is free of a `Result` | warning; an error under `--strict` or in a file the `strict` globs match |
1056
+ | `stale-exclude` | an `exclude` name that matches no boundary in its item's files, like a stale `//trust:accept` (reported against the config file, once per run) | error |
1057
+ | `overlapping-items` | a file two items match; its boundaries are not checked until the globs are split | error |
1058
+
1059
+ ```ts
1060
+ // server/admin/user.controller.ts, a boundary file
1061
+ export default class UserController {
1062
+ async get(id: number) {
1063
+ return this.users.find(id);
1064
+ // boundary-result (returns-result): Boundary "UserController.get" returns a Result that can fail with "NotFound"…
1065
+ }
1066
+ }
1067
+ ```
1068
+
1069
+ Fix it by deciding every kind in the boundary (an exhaustive `switch` with a `never` default) and returning plain
1070
+ data. A boundary that is meant to hand its `Result` on, say an internal API another service consumes, is left out by
1071
+ name in the item's `exclude`: `"UserController.get_user"` names that member of every exported class with that
1072
+ declared name in the item's files (a shared class name applies to all of them, on purpose), `"UserController.*"`
1073
+ every public member of every exported class or object with that declared name there (a whole internal API: a
1074
+ method added to the class later is covered too, so the list need not grow with the class), `".get_user"` names
1075
+ that member of any exported class or object there, and `"get_user"` an exported function. A plain name never means
1076
+ a class and `"UserController.*"` never means a function: one entry says one thing. `*` stands only for the whole
1077
+ member part after a class name: `".*"` (every member of everything in the item) is refused when the config loads,
1078
+ as are `"User*.get"`, `"X.get*"` and a bare `"*"`. Names use `.`, as origins and call graphs do (`Store.load`); there
1079
+ is no file-qualified form. To tell two same-named classes apart, put their files in separate items. An `exclude`
1080
+ name applies to its own item only, and `"UserController.*"` is stale, like any other entry, when no exported class
1081
+ or object of that name is in the item's files.
1082
+
1083
+ The stale check needs the whole item: it is decided while checking the first of the item's files, and only when
1084
+ every file the item's globs match on disk is in the program, so `trust check server/admin/one.controller.ts` never
1085
+ calls an entry stale for a file it did not load. `trust explain <file>:<line>` lists every boundary starting on the
1086
+ line, the item it belongs to, the `exclude` name that leaves it out, and what its return value says. `//trust:accept`
1087
+ does not accept a boundary-result finding; `exclude` is the way out.
1088
+
1000
1089
  ### `trust refactor`: the order to refactor in
1001
1090
 
1002
1091
  ```sh
@@ -66,6 +66,8 @@ interface TrustConfig {
66
66
  readonly ignore: readonly ZoneGroup[];
67
67
  /** `strict` globs of the chain: `trust check` also runs the strict rules on files matching them. */
68
68
  readonly strict: readonly ZoneGroup[];
69
+ /** `boundaries` items of the chain, leaf first, in declaration order; empty when no level sets the key (rule off). */
70
+ readonly boundaries: readonly BoundaryGroup[];
69
71
  /** `tsconfig` entries of the chain, leaf first, in declaration order. */
70
72
  readonly tsconfig: readonly TsconfigMapping[];
71
73
  /** Per-rule settings (`rules`), each resolved along the chain; unset keys take DEFAULT_RULE_SETTINGS. */
@@ -100,6 +102,15 @@ interface TsconfigMapping extends ZoneGroup {
100
102
  /** Absolute tsconfig path. Its existence is checked when a file maps to it, not at load. */
101
103
  readonly tsconfig: string;
102
104
  }
105
+ /**
106
+ * One `boundaries` item: files matching `patterns` (zone glob semantics) are boundary files, and the
107
+ * `exclude` names leave members of those files out (`Class.member`, `Class.*`, `.member`, `function`).
108
+ */
109
+ interface BoundaryGroup extends ZoneGroup {
110
+ /** Position in the declaring file's `boundaries` array (for messages). */
111
+ readonly index: number;
112
+ readonly exclude: readonly string[];
113
+ }
103
114
  /**
104
115
  * What to do with a glob that matches no file: `'report'` lists it in `TrustConfig.unmatchedGlobs`
105
116
  * and loads anyway, `true` makes it a load error (TrustConfigError), `false` does not check.
@@ -316,7 +327,28 @@ declare const REDUNDANT_GUARD_ORIGIN = "redundant";
316
327
  declare const REDUNDANT_GUARD_MESSAGES: {
317
328
  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.";
318
329
  };
319
- /** One trust-rule violation. `line`/`column` are 1-based; `file` is relative to the trust root when inside it. */
330
+ declare const BOUNDARY_RULE = "boundary-result";
331
+ /**
332
+ * The messages of `boundary-result` (core/boundaries.ts), keyed by origin: the baseline key, and the ESLint
333
+ * messageId of `trust/boundary-result`. `{{member}}` is the boundary (`Class.member`, `api.get`, `fn`), `{{item}}`
334
+ * the `boundaries` item it belongs to (`boundaries[0] in trust.config.json`), `{{kinds}}` the failure kinds its
335
+ * Result can carry, `{{type}}` `any` or `unknown`, `{{entry}}` an `exclude` name and `{{other}}` a second item.
336
+ * returns-result an error: the boundary's return value can fail
337
+ * unproven-return a warning (an error under strict): the return type is `any` / `unknown`, so nothing shows it is free of a Result
338
+ * stale-exclude an error, reported against the config file: an `exclude` entry that names no boundary of its item's files
339
+ * overlapping-items an error at the file's start: two items match the same file, so its boundaries are not checked
340
+ */
341
+ declare const BOUNDARY_MESSAGES: {
342
+ 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}}.";
343
+ 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}}.";
344
+ 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\").";
345
+ readonly 'overlapping-items': "File \"{{file}}\" is a boundary of both {{item}} and {{other}}: a file belongs to one item. Split the globs (or the configs) so each file matches one item; its boundaries are not checked until then.";
346
+ };
347
+ type BoundaryOrigin = keyof typeof BOUNDARY_MESSAGES;
348
+ /**
349
+ * One trust-rule violation. `line`/`column` are 1-based; `file` is relative to the trust root when inside it.
350
+ * `severity` is set only by a rule that can warn (`boundary-result`'s `unproven-return`); absent means an error.
351
+ */
320
352
  interface Finding {
321
353
  readonly file: string;
322
354
  readonly rule: string;
@@ -324,6 +356,7 @@ interface Finding {
324
356
  readonly line: number;
325
357
  readonly column: number;
326
358
  readonly message: string;
359
+ readonly severity?: 'error' | 'warning';
327
360
  }
328
361
 
329
362
  /** What a baseline counts a finding by. */
@@ -377,4 +410,4 @@ declare function describeBaselineDelta(delta: BaselineDelta<BaselineFinding & {
377
410
  readonly message: string;
378
411
  }>): string[];
379
412
 
380
- export { TYPE_CLAIM_KINDS 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, CATCH_ORIGIN as J, DEFAULT_RULE_SETTINGS as K, DIRECTIVE_ORIGIN as L, DROPPED_RESULT_MESSAGES as M, DROPPED_RESULT_RULE as N, OriginResolver as O, type DroppedResultOrigin as P, type LoadTrustConfigOptions as Q, type OptInRule as R, REDUNDANT_GUARD_MESSAGES as S, type TypeScript as T, REDUNDANT_GUARD_ORIGIN as U, REDUNDANT_GUARD_RULE as V, WHOLE_BASELINE as W, type RuleSwitch as X, THROW_MESSAGES as Y, type ZoneGroup as Z, THROW_RULE as _, type TsconfigMapping as a, TYPE_CLAIM_MESSAGES as a0, TYPE_CLAIM_RULE as a1, TrustConfigError as a2, type TrustEntry as a3, type TrustLevel as a4, type TypeClaimOrigin as a5, UNANALYZABLE_ORIGIN as a6, UNTRUSTED_CALL_MESSAGES as a7, UNTRUSTED_CALL_RULE as a8, UNTRUSTED_VALUE_MESSAGES as a9, UNTRUSTED_VALUE_RULE as aa, type UntrustedCallbacks as ab, type UntrustedEntry as ac, VALIDATOR_DIRECTIVE as ad, effectiveTrustList as ae, effectiveTypeTrustList as af, isInsideValidator as ag, isMarkedValidator as ah, isRuleEnabled as ai, loadTrustConfig as aj, normalizeOrigin as ak, 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 };
413
+ 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 };
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  ACCEPT_DIRECTIVE,
3
3
  ACCEPT_DIRECTIVE_MESSAGES,
4
+ BOUNDARY_MESSAGES,
5
+ BOUNDARY_RULE,
4
6
  CATCH_ORIGIN,
5
7
  DEFAULT_RULE_SETTINGS,
6
8
  DIRECTIVE_ORIGIN,
@@ -28,9 +30,11 @@ import {
28
30
  Zones,
29
31
  directiveDirectlyAbove,
30
32
  directiveProblem,
33
+ filesMatchingGroup,
31
34
  fillMessage,
32
35
  formatFailureKinds,
33
36
  formatMessage,
37
+ groupMatches,
34
38
  isAcceptDirective,
35
39
  isInsideValidator,
36
40
  isMarkedValidator,
@@ -40,7 +44,7 @@ import {
40
44
  realpathOrSelf,
41
45
  svelteFor,
42
46
  trustDirectivesIn
43
- } from "./chunk-UG6D3V4M.js";
47
+ } from "./chunk-PMIYTMMA.js";
44
48
 
45
49
  // src/core/guard.ts
46
50
  function unparen(ts, node) {
@@ -1164,6 +1168,205 @@ function droppedResultsIn(sourceFile, context) {
1164
1168
  return found.sort((a, b) => a.start - b.start);
1165
1169
  }
1166
1170
 
1171
+ // src/core/boundaries.ts
1172
+ function boundaryContext(ts, checker, program, policy, config) {
1173
+ return { ts, checker, program, policy, config, kinds: droppedResultContext(ts, checker, policy) };
1174
+ }
1175
+ function boundaryName(boundary) {
1176
+ return boundary.container === null ? boundary.member : `${boundary.container}.${boundary.member}`;
1177
+ }
1178
+ function excludeMatches(entry, boundary) {
1179
+ const dot = entry.indexOf(".");
1180
+ if (dot < 0) return boundary.container === null && boundary.member === entry;
1181
+ if (boundary.container === null) return false;
1182
+ const container = entry.slice(0, dot);
1183
+ const member = entry.slice(dot + 1);
1184
+ if (member === "*") return container !== "" && container === boundary.container;
1185
+ return boundary.member === member && (container === "" || container === boundary.container);
1186
+ }
1187
+ function itemLabel(item) {
1188
+ const slash = Math.max(item.source.lastIndexOf("/"), item.source.lastIndexOf("\\"));
1189
+ return `boundaries[${item.index}] in ${item.source.slice(slash + 1)}`;
1190
+ }
1191
+ function boundaryMessage(finding) {
1192
+ return fillMessage(BOUNDARY_MESSAGES[finding.origin], finding.data);
1193
+ }
1194
+ function realPath(context, fileName) {
1195
+ return realpathOrSelf(context.policy.zones.virtualPaths.get(fileName) ?? fileName);
1196
+ }
1197
+ function declaredName(ts, node) {
1198
+ const name = node.name;
1199
+ if (!name) return null;
1200
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return { text: name.text, node: name };
1201
+ return null;
1202
+ }
1203
+ function isTypeOnlyExport(ts, declaration) {
1204
+ if (ts.isExportSpecifier(declaration)) return declaration.isTypeOnly || declaration.parent.parent.isTypeOnly;
1205
+ if (ts.isNamespaceExport(declaration)) return declaration.parent.isTypeOnly;
1206
+ return false;
1207
+ }
1208
+ function verdictOfType(context, type) {
1209
+ const { ts, checker } = context;
1210
+ const awaited = checker.getAwaitedType(type) ?? type;
1211
+ if (awaited.flags & ts.TypeFlags.Any) return { kind: "unproven", type: "any" };
1212
+ if (awaited.flags & ts.TypeFlags.Unknown) return { kind: "unproven", type: "unknown" };
1213
+ const kinds = failureKinds(context.kinds, type);
1214
+ return kinds ? { kind: "result", kinds: [...kinds].sort() } : { kind: "plain" };
1215
+ }
1216
+ function verdictOfSignatures(context, signatures) {
1217
+ for (const signature of signatures) {
1218
+ const verdict = verdictOfType(context, context.checker.getReturnTypeOfSignature(signature));
1219
+ if (verdict.kind !== "plain") return verdict;
1220
+ }
1221
+ return { kind: "plain" };
1222
+ }
1223
+ function memberVerdict(context, declaration, type) {
1224
+ if (context.ts.isGetAccessorDeclaration(declaration)) return verdictOfType(context, type);
1225
+ const signatures = type.getCallSignatures();
1226
+ return signatures.length > 0 ? verdictOfSignatures(context, signatures) : null;
1227
+ }
1228
+ function isPublic(ts, declaration) {
1229
+ const name = declaration.name;
1230
+ if (name && ts.isPrivateIdentifier(name)) return false;
1231
+ return (ts.getCombinedModifierFlags(declaration) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) === 0;
1232
+ }
1233
+ function exportStarFor(context, sourceFile, name) {
1234
+ const { ts, checker } = context;
1235
+ for (const statement of sourceFile.statements) {
1236
+ if (!ts.isExportDeclaration(statement) || statement.exportClause || !statement.moduleSpecifier) continue;
1237
+ const module = checker.getSymbolAtLocation(statement.moduleSpecifier);
1238
+ if (module && checker.getExportsOfModule(module).some((exported) => exported.name === name)) return statement;
1239
+ }
1240
+ return null;
1241
+ }
1242
+ function boundariesIn(sourceFile, context) {
1243
+ const { ts, checker, policy } = context;
1244
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
1245
+ if (!moduleSymbol) return [];
1246
+ const found = [];
1247
+ const startOf2 = (declaration, fallback) => {
1248
+ if (!declaration || declaration.getSourceFile() !== sourceFile) return fallback;
1249
+ return (declaredName(ts, declaration)?.node ?? declaration).getStart(sourceFile);
1250
+ };
1251
+ for (const exported of checker.getExportsOfModule(moduleSymbol)) {
1252
+ const alias = (exported.flags & ts.SymbolFlags.Alias) !== 0;
1253
+ const target = alias ? checker.getAliasedSymbol(exported) : exported;
1254
+ const own = (exported.declarations ?? []).find((declaration) => declaration.getSourceFile() === sourceFile);
1255
+ if (own && isTypeOnlyExport(ts, own)) continue;
1256
+ let at;
1257
+ if (own) at = own.getStart(sourceFile);
1258
+ else {
1259
+ const star = exportStarFor(context, sourceFile, exported.name);
1260
+ if (!star || star.isTypeOnly) continue;
1261
+ at = star.getStart(sourceFile);
1262
+ }
1263
+ const declarations = target.declarations ?? [];
1264
+ if (target.flags & ts.SymbolFlags.Class) {
1265
+ const classes = declarations.filter(ts.isClassLike);
1266
+ if (classes.length === 0) continue;
1267
+ const container = declaredName(ts, classes[0])?.text ?? "default";
1268
+ const seen = /* @__PURE__ */ new Set();
1269
+ for (const classLike of classes) {
1270
+ for (const member of classLike.members) {
1271
+ if (!ts.isMethodDeclaration(member) && !ts.isGetAccessorDeclaration(member) && !ts.isPropertyDeclaration(member)) continue;
1272
+ const name = declaredName(ts, member);
1273
+ if (!name || seen.has(name.text) || !isPublic(ts, member)) continue;
1274
+ const symbol = checker.getSymbolAtLocation(name.node);
1275
+ if (!symbol) continue;
1276
+ const verdict = memberVerdict(context, member, checker.getTypeOfSymbol(symbol));
1277
+ if (!verdict) continue;
1278
+ seen.add(name.text);
1279
+ found.push({ container, member: name.text, start: startOf2(member, at), verdict });
1280
+ }
1281
+ }
1282
+ } else if (target.flags & ts.SymbolFlags.Function) {
1283
+ const declaration = declarations.find(ts.isFunctionDeclaration) ?? declarations[0];
1284
+ const member = (declaration && declaredName(ts, declaration)?.text) ?? "default";
1285
+ found.push({ container: null, member, start: startOf2(declaration, at), verdict: verdictOfSignatures(context, checker.getTypeOfSymbol(target).getCallSignatures()) });
1286
+ } else if (target.flags & ts.SymbolFlags.Variable) {
1287
+ const declaration = target.valueDeclaration ?? declarations[0];
1288
+ const type = checker.getTypeOfSymbol(target);
1289
+ const name = (declaration && declaredName(ts, declaration)?.text) ?? exported.name;
1290
+ const signatures = type.getCallSignatures();
1291
+ if (signatures.length > 0) {
1292
+ found.push({ container: null, member: name, start: startOf2(declaration, at), verdict: verdictOfSignatures(context, signatures) });
1293
+ continue;
1294
+ }
1295
+ for (const property of checker.getPropertiesOfType(type)) {
1296
+ const propertyDeclaration = property.valueDeclaration ?? property.declarations?.[0];
1297
+ if (!propertyDeclaration || policy.zones.zoneOf(propertyDeclaration.getSourceFile().fileName) !== "checked" || !isPublic(ts, propertyDeclaration)) continue;
1298
+ const verdict = memberVerdict(context, propertyDeclaration, checker.getTypeOfSymbol(property));
1299
+ if (!verdict) continue;
1300
+ found.push({ container: name, member: property.name, start: startOf2(propertyDeclaration, at), verdict });
1301
+ }
1302
+ }
1303
+ }
1304
+ return found.sort((a, b) => a.start - b.start || (boundaryName(a) < boundaryName(b) ? -1 : boundaryName(a) > boundaryName(b) ? 1 : 0));
1305
+ }
1306
+ var SOURCE_FILE = /\.(?:[cm]?[jt]sx?|svelte)$/;
1307
+ function isSourceFile(path) {
1308
+ return SOURCE_FILE.test(path) && !/\.d\.[cm]?ts$/.test(path);
1309
+ }
1310
+ function itemFiles(item, context) {
1311
+ const { policy } = context;
1312
+ return context.program.getSourceFiles().filter((file) => !file.isDeclarationFile && policy.zones.zoneOf(file.fileName) === "checked" && groupMatches(item, realPath(context, file.fileName))).map((file) => ({ file, path: policy.zones.relativePath(file.fileName) })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((entry) => entry.file);
1313
+ }
1314
+ var completeness = /* @__PURE__ */ new WeakMap();
1315
+ function itemComplete(item, context) {
1316
+ let byItem = completeness.get(context.program);
1317
+ if (!byItem) {
1318
+ byItem = /* @__PURE__ */ new Map();
1319
+ completeness.set(context.program, byItem);
1320
+ }
1321
+ const cached = byItem.get(item);
1322
+ if (cached !== void 0) return cached;
1323
+ const { policy } = context;
1324
+ const loaded = new Set(context.program.getSourceFiles().map((file) => realPath(context, file.fileName)));
1325
+ const complete = filesMatchingGroup(item).filter((path) => isSourceFile(path) && policy.zones.zoneOf(path) !== "ignore").every((path) => loaded.has(realpathOrSelf(path)));
1326
+ byItem.set(item, complete);
1327
+ return complete;
1328
+ }
1329
+ function fileBoundaries(sourceFile, context) {
1330
+ const real = realPath(context, sourceFile.fileName);
1331
+ const items = context.config.boundaries.filter((item2) => groupMatches(item2, real));
1332
+ if (items.length === 0) return { kind: "none" };
1333
+ if (items.length > 1) return { kind: "overlap", items: [items[0], items[1]] };
1334
+ const item = items[0];
1335
+ const files = itemFiles(item, context);
1336
+ const first = files.length > 0 && files[0] === sourceFile && itemComplete(item, context);
1337
+ return { kind: "boundary", item, boundaries: boundariesIn(sourceFile, context), first };
1338
+ }
1339
+ function boundaryFindingsIn(sourceFile, context, strict) {
1340
+ const file = fileBoundaries(sourceFile, context);
1341
+ if (file.kind === "none") return [];
1342
+ const { policy } = context;
1343
+ if (file.kind === "overlap") {
1344
+ const [item2, other] = file.items;
1345
+ return [{ origin: "overlapping-items", start: 0, file: null, severity: "error", data: { file: policy.zones.relativePath(sourceFile.fileName), item: itemLabel(item2), other: itemLabel(other) } }];
1346
+ }
1347
+ const { item } = file;
1348
+ const label = itemLabel(item);
1349
+ const findings = [];
1350
+ if (file.first && item.exclude.length > 0) {
1351
+ const all = itemFiles(item, context).flatMap((other) => other === sourceFile ? file.boundaries : boundariesIn(other, context));
1352
+ for (const entry of item.exclude) {
1353
+ if (!all.some((boundary) => excludeMatches(entry, boundary))) {
1354
+ findings.push({ origin: "stale-exclude", start: 0, file: policy.zones.relativePath(item.source), severity: "error", data: { entry, item: label } });
1355
+ }
1356
+ }
1357
+ }
1358
+ for (const boundary of file.boundaries) {
1359
+ if (boundary.verdict.kind === "plain" || item.exclude.some((entry) => excludeMatches(entry, boundary))) continue;
1360
+ const member = boundaryName(boundary);
1361
+ if (boundary.verdict.kind === "result") {
1362
+ findings.push({ origin: "returns-result", start: boundary.start, file: null, severity: "error", data: { member, kinds: formatFailureKinds(boundary.verdict.kinds, ANY_KIND), item: label } });
1363
+ } else {
1364
+ findings.push({ origin: "unproven-return", start: boundary.start, file: null, severity: strict ? "error" : "warning", data: { member, type: boundary.verdict.type, item: label } });
1365
+ }
1366
+ }
1367
+ return findings;
1368
+ }
1369
+
1167
1370
  // src/core/rules.ts
1168
1371
  var PROMISE_COMBINATORS = /* @__PURE__ */ new Set(["all", "allSettled", "race", "any"]);
1169
1372
  function typedGuardContext(ts, checker, policy) {
@@ -2892,7 +3095,7 @@ var emptyConfigs = /* @__PURE__ */ new Map();
2892
3095
  function emptyTrustConfig(cwd) {
2893
3096
  let config = emptyConfigs.get(cwd);
2894
3097
  if (!config) {
2895
- config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [], strict: [], tsconfig: [], rules: DEFAULT_RULE_SETTINGS, unmatchedGlobs: [] };
3098
+ config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [], strict: [], boundaries: [], tsconfig: [], rules: DEFAULT_RULE_SETTINGS, unmatchedGlobs: [] };
2896
3099
  emptyConfigs.set(cwd, config);
2897
3100
  }
2898
3101
  return config;
@@ -2911,6 +3114,9 @@ function policyFor(ts, checker, config, extraTrust = []) {
2911
3114
  byKey.set(key, { config, policy });
2912
3115
  return policy;
2913
3116
  }
3117
+ function isStrictByConfig(config, fileName) {
3118
+ return config.strict.some((group) => groupMatches(group, realpathOrSelf(fileName)));
3119
+ }
2914
3120
  function positionAt(ts, sourceFile, offset) {
2915
3121
  const position = ts.getLineAndCharacterOfPosition(sourceFile, offset);
2916
3122
  return { line: position.line + 1, column: position.character + 1 };
@@ -2967,6 +3173,13 @@ function checkSourceFileWithAccepted(options) {
2967
3173
  reportAt(guard.start, REDUNDANT_GUARD_RULE, REDUNDANT_GUARD_ORIGIN, redundantGuardMessage(guard));
2968
3174
  }
2969
3175
  }
3176
+ if (config.boundaries.length > 0) {
3177
+ const strict = options.strict ?? isStrictByConfig(config, sourceFile.fileName);
3178
+ for (const found of boundaryFindingsIn(sourceFile, boundaryContext(ts, checker, options.program, policy, config), strict)) {
3179
+ const finding = findingAt(found.start, BOUNDARY_RULE, found.origin, boundaryMessage(found));
3180
+ findings.push({ ...finding, file: found.file ?? finding.file, ...found.severity === "warning" ? { severity: "warning" } : {} });
3181
+ }
3182
+ }
2970
3183
  const svelte = svelteFor(checker);
2971
3184
  const snippetTrusted = policy.lookup("svelte.__renderSnippet", "svelte").trusted && !("distrustedBy" in policy.lookup("svelte.Snippet", "svelte"));
2972
3185
  return { findings: svelte ? findings.flatMap((finding) => {
@@ -2979,9 +3192,16 @@ export {
2979
3192
  alwaysExits,
2980
3193
  catchProblem,
2981
3194
  guardOf,
3195
+ ANY_KIND,
2982
3196
  droppedResultContext,
2983
3197
  droppedResultData,
2984
3198
  droppedResultsIn,
3199
+ boundaryContext,
3200
+ boundaryName,
3201
+ excludeMatches,
3202
+ itemLabel,
3203
+ fileBoundaries,
3204
+ boundaryFindingsIn,
2985
3205
  entryMatches,
2986
3206
  decide,
2987
3207
  TrustPolicy,
@@ -3008,9 +3228,10 @@ export {
3008
3228
  untrustedValueMessage,
3009
3229
  emptyTrustConfig,
3010
3230
  policyFor,
3231
+ isStrictByConfig,
3011
3232
  positionAt,
3012
3233
  startOf,
3013
3234
  checkSourceFile,
3014
3235
  checkSourceFileWithAccepted
3015
3236
  };
3016
- //# sourceMappingURL=chunk-7PY2Q6OX.js.map
3237
+ //# sourceMappingURL=chunk-EPWU2Q4U.js.map