@noego/trust 0.1.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.
@@ -0,0 +1,1084 @@
1
+ // src/eslint/guard.ts
2
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
3
+ var LOOP_OR_SWITCH = /* @__PURE__ */ new Set(["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement", "SwitchStatement"]);
4
+ var CATCH_MESSAGES = {
5
+ rethrow: "`catch` guarding {{target}} must return Result.err(...), not re-throw.",
6
+ notResultErr: "`catch` guarding {{target}} must return Result.err(...) on every return.",
7
+ rawCatchValue: "Result.err(...) guarding {{target}} must not pass the raw caught value; normalize it to a typed error.",
8
+ notAllPaths: "`catch` guarding {{target}} must return Result.err(...) on every path."
9
+ };
10
+ function children(node) {
11
+ const result = [];
12
+ for (const key of Object.keys(node)) {
13
+ if (key === "parent") continue;
14
+ const value = node[key];
15
+ if (Array.isArray(value)) {
16
+ for (const item of value) if (item && typeof item.type === "string") result.push(item);
17
+ } else if (value && typeof value.type === "string") {
18
+ result.push(value);
19
+ }
20
+ }
21
+ return result;
22
+ }
23
+ function collectExits(node, exits) {
24
+ if (FUNCTION_TYPES.has(node.type)) return;
25
+ if (node.type === "ReturnStatement" || node.type === "ThrowStatement") exits.push(node);
26
+ for (const child of children(node)) collectExits(child, exits);
27
+ }
28
+ function containsBreakFor(node, isRoot = true) {
29
+ if (FUNCTION_TYPES.has(node.type)) return false;
30
+ if (!isRoot && LOOP_OR_SWITCH.has(node.type)) return false;
31
+ if (node.type === "BreakStatement" && !node.label) return true;
32
+ return children(node).some((child) => containsBreakFor(child, false));
33
+ }
34
+ function alwaysExits(statement) {
35
+ if (!statement) return false;
36
+ switch (statement.type) {
37
+ case "ReturnStatement":
38
+ case "ThrowStatement":
39
+ return true;
40
+ case "BlockStatement":
41
+ return statement.body.some((child) => alwaysExits(child));
42
+ case "IfStatement":
43
+ return alwaysExits(statement.consequent) && alwaysExits(statement.alternate);
44
+ case "SwitchStatement": {
45
+ const cases = statement.cases;
46
+ if (!cases.some((entry) => entry.test === null)) return false;
47
+ if (containsBreakFor(statement)) return false;
48
+ const last = cases[cases.length - 1];
49
+ return last.consequent.some((child) => alwaysExits(child));
50
+ }
51
+ case "TryStatement": {
52
+ if (alwaysExits(statement.finalizer)) return true;
53
+ const handler = statement.handler;
54
+ return alwaysExits(statement.block) && (!handler || alwaysExits(handler.body));
55
+ }
56
+ case "LabeledStatement":
57
+ return alwaysExits(statement.body);
58
+ default:
59
+ return false;
60
+ }
61
+ }
62
+ function catchProblem(handler, context) {
63
+ const exits = [];
64
+ collectExits(handler.body, exits);
65
+ const param = handler.param;
66
+ const paramName = param?.type === "Identifier" ? param.name : null;
67
+ for (const exit of exits) {
68
+ if (exit.type === "ThrowStatement") return "rethrow";
69
+ const argument = exit.argument;
70
+ if (!argument || !context.isResultErr(argument)) return "notResultErr";
71
+ if (paramName && context.isErrCall(argument)) {
72
+ const [first] = argument.arguments;
73
+ if (first?.type === "Identifier" && first.name === paramName) return "rawCatchValue";
74
+ }
75
+ }
76
+ return alwaysExits(handler.body) ? null : "notAllPaths";
77
+ }
78
+ function guardOf(node, context) {
79
+ let child = node;
80
+ let current = node.parent;
81
+ while (current) {
82
+ if (FUNCTION_TYPES.has(current.type)) {
83
+ const call = current.parent;
84
+ if (call?.type === "CallExpression" && call.arguments[0] === current) {
85
+ const kind = context.trustTryKind(call);
86
+ if (kind) return { status: "guarded", via: kind === "sync" ? "sync-callback" : "async-callback" };
87
+ }
88
+ return { status: "unguarded" };
89
+ }
90
+ if (current.type === "TryStatement" && current.block === child) {
91
+ const handler = current.handler;
92
+ if (handler) {
93
+ const problem = catchProblem(handler, context);
94
+ return problem ? { status: "badCatch", problem } : { status: "guarded", via: "try" };
95
+ }
96
+ }
97
+ child = current;
98
+ current = current.parent;
99
+ }
100
+ return { status: "unguarded" };
101
+ }
102
+ function isNamedErrCall(node) {
103
+ if (node.type !== "CallExpression") return false;
104
+ const callee = node.callee;
105
+ if (callee.type === "Identifier") return callee.name === "err";
106
+ if (callee.type !== "MemberExpression") return false;
107
+ const object = callee.object;
108
+ const property = callee.property;
109
+ return object.type === "Identifier" && object.name === "Result" && property.type === "Identifier" && property.name === "err";
110
+ }
111
+ function namedTryKind(call) {
112
+ const callee = call.callee;
113
+ if (callee.type === "Identifier") {
114
+ if (callee.name === "tryResult") return "sync";
115
+ if (callee.name === "tryResultAsync") return "async";
116
+ return null;
117
+ }
118
+ if (callee.type !== "MemberExpression") return null;
119
+ const object = callee.object;
120
+ const property = callee.property;
121
+ if (object.type !== "Identifier" || object.name !== "Result" || property.type !== "Identifier") return null;
122
+ if (property.name === "try") return "sync";
123
+ if (property.name === "tryAsync") return "async";
124
+ return null;
125
+ }
126
+ var NAME_BASED_GUARD_CONTEXT = {
127
+ isResultErr: isNamedErrCall,
128
+ isErrCall: isNamedErrCall,
129
+ trustTryKind: namedTryKind
130
+ };
131
+
132
+ // src/eslint/presets.ts
133
+ var DEFAULT_PRESET = {
134
+ $comment: "Pure, in-memory JavaScript built-ins and Node APIs that do no I/O and cannot fail on typed input. Deliberately NOT trusted: js:JSON (parse throws), js:URL, js:BigInt, js:structuredClone, js:encodeURI*/decodeURI* (throw URIError), node:fs (except existsSync), node:child_process (except ChildProcess listeners), node:net, node:http(s), node:crypto (except Hash, Hmac, randomUUID), Buffer.from/alloc, process.*, EventEmitter.emit, every npm package.",
135
+ trust: [
136
+ // JavaScript built-ins (TypeScript lib).
137
+ "js:Array",
138
+ "js:ReadonlyArray",
139
+ "js:String",
140
+ "js:Number",
141
+ "js:Boolean",
142
+ "js:Math",
143
+ "js:Object",
144
+ "js:Map",
145
+ "js:ReadonlyMap",
146
+ "js:Set",
147
+ "js:ReadonlySet",
148
+ "js:WeakMap",
149
+ "js:WeakSet",
150
+ "js:Date",
151
+ "js:Error",
152
+ "js:RegExp",
153
+ "js:Promise",
154
+ "js:PromiseLike",
155
+ "js:Symbol",
156
+ "js:Iterator",
157
+ "js:IterableIterator",
158
+ "js:CallableFunction",
159
+ "js:Function",
160
+ "js:AbortController",
161
+ "js:AbortSignal",
162
+ "js:parseInt",
163
+ "js:parseFloat",
164
+ "js:isNaN",
165
+ "js:isFinite",
166
+ "js:TextEncoder",
167
+ "js:URLSearchParams",
168
+ // Node built-in modules.
169
+ // Member-level: existsSync returns false instead of throwing; the rest of node:fs stays untrusted.
170
+ "node:fs.existsSync",
171
+ "node:path",
172
+ "node:timers",
173
+ "node:util",
174
+ "node:events",
175
+ // Member-level, in-memory only. Deliberately NOT trusted: node:crypto.createHash (unknown algorithm),
176
+ // node:crypto.randomBytes (RangeError), ChildProcess.kill / process.kill (signal, permission).
177
+ "node:crypto.randomUUID",
178
+ "node:crypto.Hash",
179
+ "node:crypto.Hmac",
180
+ "node:os.tmpdir",
181
+ "node:os.platform",
182
+ "node:os.arch",
183
+ "node:os.EOL",
184
+ "node:child_process.ChildProcess.on",
185
+ "node:child_process.ChildProcess.once",
186
+ "node:child_process.ChildProcess.unref",
187
+ // Node globals: in-memory Buffer operations. Deliberately NOT trusted: Buffer.from (wrong input
188
+ // type), Buffer.alloc (RangeError), process.cwd (ENOENT when the directory is gone).
189
+ "node:global.Buffer.toString",
190
+ "node:global.Buffer.byteLength",
191
+ "node:global.Buffer.concat",
192
+ "node:global.Buffer.subarray",
193
+ "node:global.Buffer.equals",
194
+ "node:global.Buffer.indexOf",
195
+ "node:global.Buffer.isBuffer",
196
+ // Listener bookkeeping only. Deliberately NOT trusted: EventEmitter.emit (re-throws listener errors,
197
+ // throws on an unhandled 'error' event).
198
+ "node:global.EventEmitter.on",
199
+ "node:global.EventEmitter.off",
200
+ "node:global.EventEmitter.once",
201
+ "node:global.EventEmitter.removeListener",
202
+ "node:global.EventEmitter.listenerCount",
203
+ // Node globals: the timer functions the node:timers module also exports, and their handles.
204
+ "node:global.setTimeout",
205
+ "node:global.clearTimeout",
206
+ "node:global.setInterval",
207
+ "node:global.clearInterval",
208
+ "node:global.setImmediate",
209
+ "node:global.clearImmediate",
210
+ "node:global.Timeout",
211
+ "node:global.Immediate"
212
+ ]
213
+ };
214
+ var PRESETS = {
215
+ default: DEFAULT_PRESET
216
+ };
217
+
218
+ // src/eslint/zones.ts
219
+ import { readdirSync, realpathSync } from "fs";
220
+ import { isAbsolute, join, relative, sep } from "path";
221
+ import { Minimatch } from "minimatch";
222
+ var MINIMATCH_OPTIONS = { dot: true };
223
+ var SKIPPED_DIRECTORIES = /* @__PURE__ */ new Set(["node_modules", ".git"]);
224
+ var matcherCache = /* @__PURE__ */ new Map();
225
+ function matcher(pattern) {
226
+ let cached = matcherCache.get(pattern);
227
+ if (!cached) {
228
+ cached = new Minimatch(pattern, MINIMATCH_OPTIONS);
229
+ matcherCache.set(pattern, cached);
230
+ }
231
+ return cached;
232
+ }
233
+ function toPosix(path) {
234
+ return sep === "/" ? path : path.split(sep).join("/");
235
+ }
236
+ function realpathOrSelf(path) {
237
+ try {
238
+ return realpathSync.native(path);
239
+ } catch {
240
+ return path;
241
+ }
242
+ }
243
+ function normalizePattern(raw) {
244
+ const negated = raw.startsWith("!");
245
+ let body = negated ? raw.slice(1) : raw;
246
+ if (body.startsWith("./")) body = body.slice(2);
247
+ if (body.length === 0) return { error: `empty glob "${raw}"` };
248
+ if (isAbsolute(body) || /^[A-Za-z]:[\\/]/.test(body)) {
249
+ return { error: `glob "${raw}" must be relative to the config file's directory` };
250
+ }
251
+ if (body.startsWith("../")) return { error: `glob "${raw}" must not leave the config file's directory` };
252
+ if (body.endsWith("/")) body = `${body}**`;
253
+ return { pattern: negated ? `!${body}` : body };
254
+ }
255
+ function relativeInside(baseDir, absolutePath) {
256
+ const rel = toPosix(relative(baseDir, absolutePath));
257
+ if (rel === "" || rel.startsWith("../") || rel === ".." || isAbsolute(rel)) return null;
258
+ return rel;
259
+ }
260
+ function matchesPatterns(patterns, rel) {
261
+ let included = false;
262
+ for (const pattern of patterns) {
263
+ if (pattern.startsWith("!")) {
264
+ if (included && matcher(pattern.slice(1)).match(rel)) included = false;
265
+ } else if (!included && matcher(pattern).match(rel)) {
266
+ included = true;
267
+ }
268
+ }
269
+ return included;
270
+ }
271
+ function groupMatches(group, absoluteRealPath) {
272
+ const rel = relativeInside(group.baseDir, absoluteRealPath);
273
+ return rel !== null && matchesPatterns(group.patterns, rel);
274
+ }
275
+ var MAGIC = /[*?[\]{}()!+@]/;
276
+ function staticPrefix(pattern) {
277
+ const parts = pattern.split("/");
278
+ const fixed = [];
279
+ for (let index = 0; index < parts.length - 1; index += 1) {
280
+ if (MAGIC.test(parts[index])) break;
281
+ fixed.push(parts[index]);
282
+ }
283
+ return fixed.join("/");
284
+ }
285
+ function* walkFiles(baseDir, prefix) {
286
+ const start = prefix ? join(baseDir, prefix) : baseDir;
287
+ const stack = [start];
288
+ while (stack.length > 0) {
289
+ const directory = stack.pop();
290
+ let entries;
291
+ try {
292
+ entries = readdirSync(directory, { withFileTypes: true });
293
+ } catch {
294
+ continue;
295
+ }
296
+ for (const entry of entries) {
297
+ const full = join(directory, entry.name);
298
+ if (entry.isDirectory()) {
299
+ if (!SKIPPED_DIRECTORIES.has(entry.name)) stack.push(full);
300
+ } else {
301
+ yield toPosix(relative(baseDir, full));
302
+ }
303
+ }
304
+ }
305
+ }
306
+ function patternMatchesAnyFile(baseDir, pattern) {
307
+ const body = pattern.startsWith("!") ? pattern.slice(1) : pattern;
308
+ const compiled = matcher(body);
309
+ for (const rel of walkFiles(baseDir, staticPrefix(body))) {
310
+ if (compiled.match(rel)) return true;
311
+ }
312
+ return false;
313
+ }
314
+ var Zones = class {
315
+ constructor(rootDir, passthrough, ignore) {
316
+ this.rootDir = rootDir;
317
+ this.passthrough = passthrough;
318
+ this.ignore = ignore;
319
+ }
320
+ rootDir;
321
+ passthrough;
322
+ ignore;
323
+ cache = /* @__PURE__ */ new Map();
324
+ /** Zone of a file. Ignore wins over passthrough; files outside the root or in node_modules are external. */
325
+ zoneOf(fileName) {
326
+ const cached = this.cache.get(fileName);
327
+ if (cached) return cached;
328
+ const zone = this.compute(fileName);
329
+ this.cache.set(fileName, zone);
330
+ return zone;
331
+ }
332
+ /** Project-relative posix path (for `local:` origins and baselines), or the absolute path when outside. */
333
+ relativePath(fileName) {
334
+ const real = realpathOrSelf(fileName);
335
+ return relativeInside(this.rootDir, real) ?? toPosix(real);
336
+ }
337
+ compute(fileName) {
338
+ const real = realpathOrSelf(fileName);
339
+ const rel = relativeInside(this.rootDir, real);
340
+ if (rel === null || rel.split("/").includes("node_modules")) return "external";
341
+ if (this.ignore.some((group) => groupMatches(group, real))) return "ignore";
342
+ if (this.passthrough.some((group) => groupMatches(group, real))) return "passthrough";
343
+ return "checked";
344
+ }
345
+ };
346
+
347
+ // src/eslint/config.ts
348
+ import { existsSync, readFileSync, statSync } from "fs";
349
+ import { dirname, isAbsolute as isAbsolute2, resolve } from "path";
350
+ var TrustConfigError = class extends Error {
351
+ name = "TrustConfigError";
352
+ };
353
+ var FILE_KEYS = /* @__PURE__ */ new Set(["$comment", "extend", "trust", "distrust", "passthrough", "ignore"]);
354
+ var PRESET_KEYS = /* @__PURE__ */ new Set(["$comment", "extend", "trust", "distrust"]);
355
+ var ENTRY_KEYS = /* @__PURE__ */ new Set(["origin", "reason"]);
356
+ function normalizeOrigin(origin) {
357
+ return origin.trim();
358
+ }
359
+ function legacyOriginHint(origin) {
360
+ if (origin.startsWith("builtin:")) return `"${origin}" uses the old "builtin:" prefix; use "js:${origin.slice("builtin:".length)}"`;
361
+ if (origin === "node" || origin.startsWith("node.")) {
362
+ return `"${origin}" uses the old "node." prefix for Node globals; use "node:global${origin.slice("node".length)}"`;
363
+ }
364
+ return null;
365
+ }
366
+ function fail(source, message) {
367
+ throw new TrustConfigError(`trust config ${source}: ${message}`);
368
+ }
369
+ function isRecord(value) {
370
+ return typeof value === "object" && value !== null && !Array.isArray(value);
371
+ }
372
+ function checkedOrigin(source, key, index, origin) {
373
+ const normalized = normalizeOrigin(origin);
374
+ const hint = legacyOriginHint(normalized);
375
+ if (hint) fail(source, `"${key}[${index}]": ${hint}`);
376
+ return normalized;
377
+ }
378
+ function readEntries(source, key, value) {
379
+ if (value === void 0) return [];
380
+ if (!Array.isArray(value)) fail(source, `"${key}" must be an array`);
381
+ return value.map((entry, index) => {
382
+ if (typeof entry === "string") {
383
+ if (!entry.trim()) fail(source, `"${key}[${index}]" must not be empty`);
384
+ return checkedOrigin(source, key, index, entry);
385
+ }
386
+ if (!isRecord(entry)) fail(source, `"${key}[${index}]" must be a string or { origin, reason }`);
387
+ for (const entryKey of Object.keys(entry)) {
388
+ if (!ENTRY_KEYS.has(entryKey)) fail(source, `"${key}[${index}]" has unknown key "${entryKey}"`);
389
+ }
390
+ if (typeof entry.origin !== "string" || !entry.origin.trim()) {
391
+ fail(source, `"${key}[${index}].origin" must be a non-empty string`);
392
+ }
393
+ if (entry.reason !== void 0 && typeof entry.reason !== "string") {
394
+ fail(source, `"${key}[${index}].reason" must be a string`);
395
+ }
396
+ return checkedOrigin(source, key, index, entry.origin);
397
+ });
398
+ }
399
+ function readGlobs(source, key, value) {
400
+ if (value === void 0) return [];
401
+ if (!Array.isArray(value)) fail(source, `"${key}" must be an array of globs`);
402
+ return value.map((entry, index) => {
403
+ if (typeof entry !== "string") fail(source, `"${key}[${index}]" must be a string`);
404
+ const normalized = normalizePattern(entry);
405
+ if ("error" in normalized) fail(source, `"${key}": ${normalized.error}`);
406
+ return normalized.pattern;
407
+ });
408
+ }
409
+ function parseLevel(source, raw, allowedKeys, baseDir) {
410
+ if (!isRecord(raw)) fail(source, "expected an object");
411
+ for (const key of Object.keys(raw)) {
412
+ if (!allowedKeys.has(key)) fail(source, `unknown key "${key}"`);
413
+ }
414
+ if (raw.extend !== void 0 && (typeof raw.extend !== "string" || !raw.extend)) {
415
+ fail(source, '"extend" must be a non-empty string');
416
+ }
417
+ const trust = readEntries(source, "trust", raw.trust);
418
+ const distrust = readEntries(source, "distrust", raw.distrust);
419
+ const both = trust.filter((origin) => distrust.includes(origin));
420
+ if (both.length > 0) fail(source, `"${both[0]}" is both trusted and distrusted`);
421
+ return {
422
+ source,
423
+ baseDir,
424
+ extend: raw.extend,
425
+ trust,
426
+ distrust,
427
+ passthrough: readGlobs(source, "passthrough", raw.passthrough),
428
+ ignore: readGlobs(source, "ignore", raw.ignore)
429
+ };
430
+ }
431
+ function readFileLevel(file) {
432
+ if (!existsSync(file)) throw new TrustConfigError(`trust config not found: ${file}`);
433
+ let raw;
434
+ try {
435
+ raw = JSON.parse(readFileSync(file, "utf8"));
436
+ } catch (error) {
437
+ fail(file, `invalid JSON (${error instanceof Error ? error.message : String(error)})`);
438
+ }
439
+ return parseLevel(file, raw, FILE_KEYS, realpathOrSelf(dirname(file)));
440
+ }
441
+ function readPresetLevel(name) {
442
+ const preset = PRESETS[name];
443
+ if (!preset) throw new TrustConfigError(`unknown preset "${name}"`);
444
+ return parseLevel(`preset:${name}`, preset, PRESET_KEYS, null);
445
+ }
446
+ function nextSource(level) {
447
+ const extend = level.extend;
448
+ if (!extend) return null;
449
+ if (extend.startsWith(".") || isAbsolute2(extend)) {
450
+ if (level.baseDir === null) fail(level.source, `presets may only extend presets, not "${extend}"`);
451
+ return resolve(level.baseDir, extend);
452
+ }
453
+ if (!PRESETS[extend]) fail(level.source, `unknown preset "${extend}"`);
454
+ return `preset:${extend}`;
455
+ }
456
+ function readChain(configFile) {
457
+ const chain = [];
458
+ const visited = [];
459
+ let source = resolve(configFile);
460
+ while (source) {
461
+ if (visited.includes(source)) {
462
+ throw new TrustConfigError(`trust config cycle: ${[...visited, source].join(" -> ")}`);
463
+ }
464
+ visited.push(source);
465
+ const level = source.startsWith("preset:") ? readPresetLevel(source.slice("preset:".length)) : readFileLevel(source);
466
+ chain.push(level);
467
+ source = nextSource(level);
468
+ }
469
+ return chain;
470
+ }
471
+ function zoneGroups(chain, key, validate) {
472
+ const groups = [];
473
+ for (const level of chain) {
474
+ const patterns = level[key];
475
+ if (patterns.length === 0 || level.baseDir === null) continue;
476
+ if (validate) {
477
+ for (const pattern of patterns) {
478
+ if (!patternMatchesAnyFile(level.baseDir, pattern)) {
479
+ fail(level.source, `${key} glob "${pattern}" matches no files under ${level.baseDir}`);
480
+ }
481
+ }
482
+ }
483
+ groups.push({ source: level.source, baseDir: level.baseDir, patterns });
484
+ }
485
+ return groups;
486
+ }
487
+ function loadTrustConfig(configFile, options = {}) {
488
+ const file = resolve(configFile);
489
+ const chain = readChain(file);
490
+ const validate = options.validateGlobs ?? true;
491
+ return {
492
+ file,
493
+ rootDir: realpathOrSelf(dirname(file)),
494
+ levels: chain.map(({ source, trust, distrust }) => ({ source, trust, distrust })),
495
+ passthrough: zoneGroups(chain, "passthrough", validate),
496
+ ignore: zoneGroups(chain, "ignore", validate)
497
+ };
498
+ }
499
+ var cache = /* @__PURE__ */ new Map();
500
+ function loadTrustConfigCached(configFile) {
501
+ const file = resolve(configFile);
502
+ const mtimeMs = existsSync(file) ? statSync(file).mtimeMs : -1;
503
+ const hit = cache.get(file);
504
+ if (hit && hit.mtimeMs === mtimeMs) return hit.config;
505
+ const config = loadTrustConfig(file);
506
+ cache.set(file, { mtimeMs, config });
507
+ return config;
508
+ }
509
+ function effectiveTrustList(config) {
510
+ return [...new Set(config.levels.flatMap((level) => level.trust))];
511
+ }
512
+
513
+ // src/eslint/origin.ts
514
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
515
+ import { dirname as dirname2, join as join2 } from "path";
516
+ var NODE_MODULES = "/node_modules/";
517
+ var TS_LIB_FILE = /\/typescript\/lib\/lib\.[^/]*\.d\.ts$/;
518
+ var TRUST_PACKAGE = "@noego/trust";
519
+ var JS_BASE = "js:";
520
+ var NODE_PREFIX = "node:";
521
+ var NODE_GLOBAL_BASE = "node:global";
522
+ var NODE_TYPES_PACKAGE = "node";
523
+ var NODE_GLOBAL_INTERFACES = {
524
+ Process: "process",
525
+ Require: "require",
526
+ Module: "module",
527
+ Console: "console",
528
+ Global: "global"
529
+ };
530
+ function nodeGlobalPath(members) {
531
+ const path = members[0] === "NodeJS" ? members.slice(1) : [...members];
532
+ if (path.length > 0 && NODE_GLOBAL_INTERFACES[path[0]]) path[0] = NODE_GLOBAL_INTERFACES[path[0]];
533
+ return path;
534
+ }
535
+ var manifestNameCache = /* @__PURE__ */ new Map();
536
+ function readManifestName(directory) {
537
+ const file = join2(directory, "package.json");
538
+ if (!existsSync2(file)) return null;
539
+ try {
540
+ const manifest = JSON.parse(readFileSync2(file, "utf8"));
541
+ if (manifest && typeof manifest === "object" && "name" in manifest && typeof manifest.name === "string") {
542
+ return manifest.name;
543
+ }
544
+ } catch {
545
+ return null;
546
+ }
547
+ return null;
548
+ }
549
+ function nearestPackageName(fileName) {
550
+ const visited = [];
551
+ let directory = dirname2(fileName);
552
+ let result = null;
553
+ for (; ; ) {
554
+ const cached = manifestNameCache.get(directory);
555
+ if (cached !== void 0) {
556
+ result = cached;
557
+ break;
558
+ }
559
+ visited.push(directory);
560
+ const name = readManifestName(directory);
561
+ if (name) {
562
+ result = name;
563
+ break;
564
+ }
565
+ const parent = dirname2(directory);
566
+ if (parent === directory) break;
567
+ directory = parent;
568
+ }
569
+ for (const entry of visited) manifestNameCache.set(entry, result);
570
+ return result;
571
+ }
572
+ function packageOrigin(name) {
573
+ if (!name.startsWith("@types/")) return name;
574
+ const bare = name.slice("@types/".length);
575
+ return bare.includes("__") ? `@${bare.replace("__", "/")}` : bare;
576
+ }
577
+ function packageFromNodeModulesPath(fileName) {
578
+ const index = fileName.lastIndexOf(NODE_MODULES);
579
+ if (index < 0) return null;
580
+ const parts = fileName.slice(index + NODE_MODULES.length).split("/");
581
+ return packageOrigin(parts[0].startsWith("@") ? `${parts[0]}/${parts[1]}` : parts[0]);
582
+ }
583
+ function isTrustPackageFile(fileName) {
584
+ return packageFromNodeModulesPath(toPosix(fileName)) === TRUST_PACKAGE || nearestPackageName(fileName) === TRUST_PACKAGE;
585
+ }
586
+ var OriginResolver = class {
587
+ constructor(ts, zones) {
588
+ this.ts = ts;
589
+ this.zones = zones;
590
+ }
591
+ ts;
592
+ zones;
593
+ originOf(declaration) {
594
+ const fileName = toPosix(declaration.getSourceFile().fileName);
595
+ const members = this.memberPath(declaration);
596
+ const external = (base, path2 = members) => ({
597
+ kind: "external",
598
+ // A namespace base (`js:`) takes its first member directly: `js:JSON.parse`, not `js:.JSON.parse`.
599
+ origin: path2.length > 0 ? `${base}${base.endsWith(":") ? "" : "."}${path2.join(".")}` : base,
600
+ base,
601
+ fileName
602
+ });
603
+ if (TS_LIB_FILE.test(fileName)) return external(JS_BASE);
604
+ const fromNodeModules = packageFromNodeModulesPath(fileName);
605
+ const fromNodeTypes = fromNodeModules === NODE_TYPES_PACKAGE;
606
+ const moduleName = this.ambientModuleName(declaration);
607
+ if (moduleName) return external(fromNodeTypes ? `${NODE_PREFIX}${moduleName}` : moduleName);
608
+ if (fromNodeTypes) return external(NODE_GLOBAL_BASE, nodeGlobalPath(members));
609
+ if (fromNodeModules) return external(fromNodeModules);
610
+ const zone = this.zones.zoneOf(fileName);
611
+ if (zone === "external") {
612
+ const name = nearestPackageName(realpathOrSelf(fileName));
613
+ return external(name ? packageOrigin(name) : `external:${fileName}`);
614
+ }
615
+ const path = this.zones.relativePath(fileName);
616
+ const origin = members.length > 0 ? `local:${path}#${members.join(".")}` : `local:${path}`;
617
+ return { kind: "local", zone, origin, fileName };
618
+ }
619
+ /** Named containers from the module down to (and including) the declaration. */
620
+ memberPath(declaration) {
621
+ const ts = this.ts;
622
+ const names = [];
623
+ for (let node = declaration; node && !ts.isSourceFile(node); node = node.parent) {
624
+ if (ts.isModuleDeclaration(node)) {
625
+ if (ts.isStringLiteral(node.name)) break;
626
+ if (node.flags & ts.NodeFlags.GlobalAugmentation) continue;
627
+ }
628
+ const name = this.containerName(node);
629
+ if (name) names.push(name);
630
+ }
631
+ return names.reverse();
632
+ }
633
+ containerName(node) {
634
+ const ts = this.ts;
635
+ const named = ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node) || ts.isClassExpression(node) || ts.isFunctionDeclaration(node) || ts.isModuleDeclaration(node) || ts.isVariableDeclaration(node) || ts.isMethodSignature(node) || ts.isMethodDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyDeclaration(node) || ts.isPropertyAssignment(node) || ts.isGetAccessorDeclaration(node) || ts.isEnumDeclaration(node);
636
+ if (!named) return null;
637
+ const name = node.name;
638
+ if (!name) return null;
639
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isPrivateIdentifier(name)) {
640
+ return ts.isInterfaceDeclaration(node) ? name.text.replace(/Constructor$/, "") : name.text;
641
+ }
642
+ return null;
643
+ }
644
+ ambientModuleName(declaration) {
645
+ const ts = this.ts;
646
+ for (let node = declaration; node; node = node.parent) {
647
+ if (ts.isModuleDeclaration(node) && node.flags & ts.NodeFlags.GlobalAugmentation) return null;
648
+ if (ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) return node.name.text.replace(/^node:/, "");
649
+ }
650
+ return null;
651
+ }
652
+ };
653
+
654
+ // src/eslint/policy.ts
655
+ function entryMatches(entry, origin, base) {
656
+ if (origin === entry) return true;
657
+ if (!origin.startsWith(entry)) return false;
658
+ const next = origin[entry.length];
659
+ if (base !== void 0 && entry.length < base.length) return next === "/";
660
+ return next === "/" || next === "." || next === "#";
661
+ }
662
+ function bestMatch(entries, origin, base) {
663
+ let best;
664
+ for (const entry of entries) {
665
+ if (entryMatches(entry, origin, base) && (best === void 0 || entry.length > best.length)) best = entry;
666
+ }
667
+ return best;
668
+ }
669
+ var TrustPolicy = class {
670
+ constructor(ts, checker, config, extraTrust = []) {
671
+ this.ts = ts;
672
+ this.checker = checker;
673
+ this.zones = new Zones(config.rootDir, config.passthrough, config.ignore);
674
+ this.origins = new OriginResolver(ts, this.zones);
675
+ this.levels = extraTrust.length > 0 ? [{ source: "rule options", trust: extraTrust, distrust: [] }, ...config.levels] : config.levels;
676
+ }
677
+ ts;
678
+ checker;
679
+ zones;
680
+ origins;
681
+ levels;
682
+ /**
683
+ * Walks leaf → root; the first level with a matching entry decides. Within a level the most specific
684
+ * entry wins (`distrust @noego/wood` + `trust @noego/wood.TraceProvider` trusts only the tracer);
685
+ * on equal specificity distrust wins.
686
+ */
687
+ lookup(origin, base) {
688
+ for (const level of this.levels) {
689
+ const distrusted = bestMatch(level.distrust, origin, base);
690
+ const trusted = bestMatch(level.trust, origin, base);
691
+ if (trusted && (!distrusted || trusted.length > distrusted.length)) {
692
+ return { trusted: true, by: { source: level.source, entry: trusted } };
693
+ }
694
+ if (distrusted) return { trusted: false, distrustedBy: { source: level.source, entry: distrusted } };
695
+ }
696
+ return { trusted: false };
697
+ }
698
+ classify(node) {
699
+ const resolved = this.calleeDeclaration(node);
700
+ if (!resolved) return { kind: "unresolved" };
701
+ const origin = this.origins.originOf(resolved.declaration);
702
+ if (origin.kind === "local" && origin.zone === "checked") return { kind: "first-party", origin };
703
+ if (origin.kind === "local" && origin.zone === "ignore") return { kind: "calls-ignored", origin };
704
+ const decision = this.lookup(origin.origin, origin.kind === "external" ? origin.base : void 0);
705
+ if (!decision.trusted && decision.distrustedBy) return { kind: "untrusted", origin, distrustedBy: decision.distrustedBy };
706
+ if (resolved.signature && this.returnsResult(resolved.signature)) return { kind: "returns-result", origin };
707
+ if (decision.trusted) return { kind: "trusted", origin, by: decision.by };
708
+ return { kind: "untrusted", origin };
709
+ }
710
+ calleeDeclaration(node) {
711
+ const ts = this.ts;
712
+ const signature = this.checker.getResolvedSignature(node);
713
+ const fromSignature = signature?.declaration && !ts.isJSDocSignature(signature.declaration) ? signature.declaration : void 0;
714
+ const anonymous = !fromSignature || ts.isCallSignatureDeclaration(fromSignature) || ts.isConstructSignatureDeclaration(fromSignature) || ts.isFunctionTypeNode(fromSignature);
715
+ if (fromSignature && !anonymous) return { declaration: fromSignature, signature };
716
+ let symbol = this.checker.getSymbolAtLocation(node.expression);
717
+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = this.checker.getAliasedSymbol(symbol);
718
+ const fromSymbol = symbol?.declarations?.[0];
719
+ const sameFile = fromSymbol && fromSignature && fromSymbol.getSourceFile() === fromSignature.getSourceFile();
720
+ const declaration = !fromSignature || sameFile ? fromSymbol : fromSignature;
721
+ return declaration ? { declaration, signature } : null;
722
+ }
723
+ /** Declared return type is Result / Promise<Result> from @noego/trust (every union member is Ok or Err). */
724
+ returnsResult(signature) {
725
+ const returnType = this.checker.getReturnTypeOfSignature(signature);
726
+ const awaited = this.checker.getAwaitedType(returnType) ?? returnType;
727
+ return this.isResultType(awaited);
728
+ }
729
+ isResultType(type) {
730
+ const members = type.isUnion() ? type.types : [type];
731
+ return members.length > 0 && members.every((member) => this.resultVariant(member) !== null);
732
+ }
733
+ /** True when every member of the type is an `Err` from @noego/trust. */
734
+ isErrType(type) {
735
+ const members = type.isUnion() ? type.types : [type];
736
+ return members.length > 0 && members.every((member) => this.resultVariant(member) === "err");
737
+ }
738
+ /** 'ok' | 'err' when the type is @noego/trust's Ok/Err (by the declaration of its `ok` property). */
739
+ resultVariant(type) {
740
+ const property = type.getProperty("ok");
741
+ const declaration = property?.valueDeclaration ?? property?.declarations?.[0];
742
+ if (!property || !declaration || !isTrustPackageFile(declaration.getSourceFile().fileName)) return null;
743
+ const discriminant = this.checker.typeToString(this.checker.getTypeOfSymbol(property));
744
+ if (discriminant === "true") return "ok";
745
+ if (discriminant === "false") return "err";
746
+ return null;
747
+ }
748
+ /** Name of the @noego/trust function a call resolves to (`err`, `tryResult`, …), else null. */
749
+ trustFunctionName(node) {
750
+ const resolved = this.calleeDeclaration(node);
751
+ if (!resolved || !isTrustPackageFile(resolved.declaration.getSourceFile().fileName)) return null;
752
+ const name = resolved.declaration.name;
753
+ return name && this.ts.isIdentifier(name) ? name.text : null;
754
+ }
755
+ };
756
+
757
+ // src/eslint/rule-setup.ts
758
+ import { resolve as resolve2 } from "path";
759
+
760
+ // src/eslint/typescript.ts
761
+ import { createRequire } from "module";
762
+ import { join as join3 } from "path";
763
+ var cache2 = /* @__PURE__ */ new Map();
764
+ function loadTypeScript(cwd) {
765
+ const cached = cache2.get(cwd);
766
+ if (cached) return cached;
767
+ let ts;
768
+ try {
769
+ ts = createRequire(join3(cwd, "__noego_trust__.cjs"))("typescript");
770
+ } catch {
771
+ ts = createRequire(import.meta.url)("typescript");
772
+ }
773
+ cache2.set(cwd, ts);
774
+ return ts;
775
+ }
776
+
777
+ // src/eslint/rule-setup.ts
778
+ var OPTIONS_SCHEMA = [
779
+ {
780
+ type: "object",
781
+ properties: {
782
+ configFile: { type: "string" },
783
+ trust: { type: "array", items: { type: "string" } }
784
+ },
785
+ additionalProperties: false
786
+ }
787
+ ];
788
+ var emptyConfigs = /* @__PURE__ */ new Map();
789
+ function emptyConfig(cwd) {
790
+ let config = emptyConfigs.get(cwd);
791
+ if (!config) {
792
+ config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [] };
793
+ emptyConfigs.set(cwd, config);
794
+ }
795
+ return config;
796
+ }
797
+ var policies = /* @__PURE__ */ new WeakMap();
798
+ function policyFor(cwd, checker, config, extraTrust) {
799
+ let byKey = policies.get(checker);
800
+ if (!byKey) {
801
+ byKey = /* @__PURE__ */ new Map();
802
+ policies.set(checker, byKey);
803
+ }
804
+ const key = `${config.file}\0${extraTrust.join("\0")}`;
805
+ const hit = byKey.get(key);
806
+ if (hit && hit.config === config) return hit.policy;
807
+ const policy = new TrustPolicy(loadTypeScript(cwd), checker, config, extraTrust);
808
+ byKey.set(key, { config, policy });
809
+ return policy;
810
+ }
811
+ function setupRule(context) {
812
+ const options = context.options[0] ?? {};
813
+ const config = options.configFile ? loadTrustConfigCached(resolve2(context.cwd, options.configFile)) : emptyConfig(context.cwd);
814
+ const services = context.sourceCode.parserServices;
815
+ const program = services?.program ?? null;
816
+ const map = services?.esTreeNodeToTSNodeMap;
817
+ if (!program || !map) {
818
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
819
+ return { zone: zones.zoneOf(context.filename), policy: null, guardContext: NAME_BASED_GUARD_CONTEXT, tsNode: null, checker: null };
820
+ }
821
+ const checker = program.getTypeChecker();
822
+ const policy = policyFor(context.cwd, checker, config, (options.trust ?? []).map(normalizeOrigin));
823
+ const tsNode = (node) => map.get(node);
824
+ const guardContext = {
825
+ isResultErr: (expression) => policy.isErrType(checker.getTypeAtLocation(tsNode(expression))),
826
+ isErrCall: (expression) => expression.type === "CallExpression" && policy.trustFunctionName(tsNode(expression)) === "err",
827
+ trustTryKind: (call) => {
828
+ const name = policy.trustFunctionName(tsNode(call));
829
+ if (name === "tryResult") return "sync";
830
+ if (name === "tryResultAsync") return "async";
831
+ return null;
832
+ }
833
+ };
834
+ return { zone: policy.zones.zoneOf(context.filename), policy, guardContext, tsNode, checker };
835
+ }
836
+
837
+ // src/eslint/rules/untrusted-call-must-return-result.ts
838
+ var PROMISE_COMBINATORS = /* @__PURE__ */ new Set(["all", "allSettled", "race", "any"]);
839
+ function withOrigin(template) {
840
+ return template.replace("{{target}}", 'the call into "{{origin}}"');
841
+ }
842
+ var UNTRUSTED_CALL_MESSAGES = {
843
+ unguarded: 'Call into untrusted "{{origin}}" must be inside a `try` (same function) whose `catch` returns Result.err(...), or inside Result.try/tryAsync. If "{{origin}}" cannot fail, trust it in trust.config.json.',
844
+ notAwaited: 'Async call into untrusted "{{origin}}" must be awaited inside the guard, or its rejection escapes the catch.',
845
+ callsIgnored: 'Call into "{{origin}}" is trusted only because its file is ignored. List that file under "passthrough" instead of "ignore" so calls into it must be handled.',
846
+ rethrow: withOrigin(CATCH_MESSAGES.rethrow),
847
+ notResultErr: withOrigin(CATCH_MESSAGES.notResultErr),
848
+ rawCatchValue: withOrigin(CATCH_MESSAGES.rawCatchValue),
849
+ notAllPaths: withOrigin(CATCH_MESSAGES.notAllPaths)
850
+ };
851
+ function chainTop(node) {
852
+ let current = node;
853
+ for (; ; ) {
854
+ const member = current.parent;
855
+ const call = member?.parent;
856
+ if (member?.type === "MemberExpression" && member.object === current && call?.type === "CallExpression" && call.callee === member) {
857
+ current = call;
858
+ } else {
859
+ return current;
860
+ }
861
+ }
862
+ }
863
+ function isPromiseCombinator(call) {
864
+ if (call?.type !== "CallExpression") return false;
865
+ const callee = call.callee;
866
+ if (callee.type !== "MemberExpression") return false;
867
+ const object = callee.object;
868
+ const property = callee.property;
869
+ return object.type === "Identifier" && object.name === "Promise" && property.type === "Identifier" && PROMISE_COMBINATORS.has(property.name);
870
+ }
871
+ function isConsumed(expression, guard) {
872
+ const top = chainTop(expression);
873
+ const parent = top.parent;
874
+ if (!parent) return false;
875
+ if (parent.type === "AwaitExpression") return true;
876
+ if (parent.type === "ArrayExpression" && isPromiseCombinator(parent.parent)) return isConsumed(parent.parent, guard);
877
+ if (guard.status === "guarded" && guard.via === "async-callback") {
878
+ if (parent.type === "ReturnStatement") return true;
879
+ if (parent.type === "ArrowFunctionExpression" && parent.body === top) return true;
880
+ }
881
+ return false;
882
+ }
883
+ var rule = {
884
+ meta: {
885
+ type: "problem",
886
+ docs: { description: "Require calls into untrusted code to be handled locally and returned as Result.err." },
887
+ schema: OPTIONS_SCHEMA,
888
+ messages: UNTRUSTED_CALL_MESSAGES
889
+ },
890
+ create(context) {
891
+ const setup = setupRule(context);
892
+ if (!setup.policy || !setup.tsNode || !setup.checker) {
893
+ throw new Error("untrusted-call-must-return-result requires typed linting (parserOptions.projectService or project).");
894
+ }
895
+ if (setup.zone !== "checked") return {};
896
+ const { policy, tsNode, checker, guardContext } = setup;
897
+ function check(esNode) {
898
+ const node = esNode;
899
+ const target = tsNode(node);
900
+ const verdict = policy.classify(target);
901
+ if (verdict.kind === "calls-ignored") {
902
+ context.report({ node: esNode, messageId: "callsIgnored", data: { origin: verdict.origin.origin } });
903
+ return;
904
+ }
905
+ if (verdict.kind !== "untrusted") return;
906
+ const origin = verdict.origin.origin;
907
+ const guard = guardOf(node, guardContext);
908
+ if (guard.status === "unguarded") {
909
+ context.report({ node: esNode, messageId: "unguarded", data: { origin } });
910
+ } else if (guard.status === "badCatch") {
911
+ context.report({ node: esNode, messageId: guard.problem, data: { origin } });
912
+ } else if (checker.getTypeAtLocation(target).getProperty("then") && !isConsumed(node, guard)) {
913
+ context.report({ node: esNode, messageId: "notAwaited", data: { origin } });
914
+ }
915
+ }
916
+ return { CallExpression: check, NewExpression: check };
917
+ }
918
+ };
919
+ var untrusted_call_must_return_result_default = rule;
920
+
921
+ // src/eslint/baseline.ts
922
+ var UNTRUSTED_CALL_RULE = "untrusted-call-must-return-result";
923
+ var THROW_RULE = "throw-must-return-result";
924
+ var THROW_ORIGIN = "throw";
925
+ function escapeRegExp(text) {
926
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
927
+ }
928
+ function templateRegExp(template) {
929
+ let groupUsed = false;
930
+ const source = template.split("{{origin}}").map(escapeRegExp).reduce((acc, part) => {
931
+ if (acc === null) return part;
932
+ const placeholder = groupUsed ? ".+?" : "(.+?)";
933
+ groupUsed = true;
934
+ return `${acc}${placeholder}${part}`;
935
+ }, null);
936
+ return new RegExp(`^${source}$`);
937
+ }
938
+ var UNTRUSTED_PATTERNS = new Map(Object.entries(UNTRUSTED_CALL_MESSAGES).map(([id, text]) => [id, templateRegExp(text)]));
939
+ var BASELINED_PROMISE_RULES = /* @__PURE__ */ new Set([
940
+ "@typescript-eslint/no-floating-promises",
941
+ "@typescript-eslint/no-misused-promises"
942
+ ]);
943
+ function originFromMessage(rule2, messageId, message) {
944
+ if (rule2 === THROW_RULE) return THROW_ORIGIN;
945
+ if (BASELINED_PROMISE_RULES.has(rule2)) return messageId ?? "promise";
946
+ const pattern = messageId ? UNTRUSTED_PATTERNS.get(messageId) : void 0;
947
+ return pattern?.exec(message)?.[1] ?? `unknown:${messageId ?? "message"}`;
948
+ }
949
+ function ruleNameOf(ruleId) {
950
+ if (!ruleId) return null;
951
+ if (BASELINED_PROMISE_RULES.has(ruleId)) return ruleId;
952
+ const name = ruleId.slice(ruleId.lastIndexOf("/") + 1);
953
+ return name === UNTRUSTED_CALL_RULE || name === THROW_RULE ? name : null;
954
+ }
955
+ function findingsFromResults(results, rootDir) {
956
+ const root = realpathOrSelf(rootDir);
957
+ const findings = [];
958
+ for (const result of results) {
959
+ const real = realpathOrSelf(result.filePath);
960
+ const file = relativeInside(root, real) ?? toPosix(real);
961
+ for (const message of result.messages) {
962
+ const rule2 = ruleNameOf(message.ruleId);
963
+ if (!rule2) continue;
964
+ findings.push({
965
+ file,
966
+ rule: rule2,
967
+ origin: originFromMessage(rule2, message.messageId, message.message),
968
+ line: message.line,
969
+ column: message.column,
970
+ message: message.message
971
+ });
972
+ }
973
+ }
974
+ return findings;
975
+ }
976
+ function fatalMessages(results) {
977
+ return results.flatMap(
978
+ (result) => result.messages.filter((message) => message.fatal).map((message) => `${result.filePath}:${message.line}:${message.column} ${message.message}`)
979
+ );
980
+ }
981
+ function countFindings(findings) {
982
+ const counts = {};
983
+ for (const finding of findings) {
984
+ const byRule = counts[finding.file] ??= {};
985
+ const byOrigin = byRule[finding.rule] ??= {};
986
+ byOrigin[finding.origin] = (byOrigin[finding.origin] ?? 0) + 1;
987
+ }
988
+ return counts;
989
+ }
990
+ function compareToBaseline(findings, baseline) {
991
+ const groups = /* @__PURE__ */ new Map();
992
+ for (const finding of findings) {
993
+ const key = JSON.stringify([finding.file, finding.rule, finding.origin]);
994
+ const list = groups.get(key) ?? [];
995
+ list.push(finding);
996
+ groups.set(key, list);
997
+ }
998
+ const added = [];
999
+ for (const list of groups.values()) {
1000
+ const { file, rule: rule2, origin } = list[0];
1001
+ const allowed = baseline[file]?.[rule2]?.[origin] ?? 0;
1002
+ if (list.length > allowed) added.push({ file, rule: rule2, origin, allowed, found: list.length, findings: list });
1003
+ }
1004
+ const stale = [];
1005
+ for (const [file, byRule] of Object.entries(baseline)) {
1006
+ for (const [rule2, byOrigin] of Object.entries(byRule)) {
1007
+ for (const [origin, allowed] of Object.entries(byOrigin)) {
1008
+ const found = groups.get(JSON.stringify([file, rule2, origin]))?.length ?? 0;
1009
+ if (found < allowed) stale.push({ file, rule: rule2, origin, allowed, found, findings: [] });
1010
+ }
1011
+ }
1012
+ }
1013
+ return { added, stale };
1014
+ }
1015
+ function sortObject(record, map) {
1016
+ return Object.fromEntries(
1017
+ Object.keys(record).sort().map((key) => [key, map(record[key])])
1018
+ );
1019
+ }
1020
+ function serializeBaseline(counts) {
1021
+ const violations = sortObject(counts, (byRule) => sortObject(byRule, (byOrigin) => sortObject(byOrigin, (count) => count)));
1022
+ const document = {
1023
+ $comment: "Generated by `trust baseline --update`. Existing @noego/trust violations, counted per file + rule + origin. CI fails when a count grows. Shrink it by fixing calls and re-running --update; never hand-raise a count.",
1024
+ version: 1,
1025
+ violations
1026
+ };
1027
+ return `${JSON.stringify(document, null, 2)}
1028
+ `;
1029
+ }
1030
+ function isRecord2(value) {
1031
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1032
+ }
1033
+ function parseBaseline(text, source) {
1034
+ const document = JSON.parse(text);
1035
+ if (!isRecord2(document) || document.version !== 1 || !isRecord2(document.violations)) {
1036
+ throw new Error(`${source}: expected { "version": 1, "violations": { \u2026 } }`);
1037
+ }
1038
+ const counts = {};
1039
+ for (const [file, byRule] of Object.entries(document.violations)) {
1040
+ if (!isRecord2(byRule)) throw new Error(`${source}: violations["${file}"] must be an object`);
1041
+ for (const [rule2, byOrigin] of Object.entries(byRule)) {
1042
+ if (!isRecord2(byOrigin)) throw new Error(`${source}: violations["${file}"]["${rule2}"] must be an object`);
1043
+ for (const [origin, count] of Object.entries(byOrigin)) {
1044
+ if (typeof count !== "number" || !Number.isInteger(count) || count < 0) {
1045
+ throw new Error(`${source}: count for ${file} ${rule2} ${origin} must be a non-negative integer`);
1046
+ }
1047
+ ((counts[file] ??= {})[rule2] ??= {})[origin] = count;
1048
+ }
1049
+ }
1050
+ }
1051
+ return counts;
1052
+ }
1053
+
1054
+ export {
1055
+ CATCH_MESSAGES,
1056
+ alwaysExits,
1057
+ catchProblem,
1058
+ guardOf,
1059
+ PRESETS,
1060
+ realpathOrSelf,
1061
+ Zones,
1062
+ TrustConfigError,
1063
+ normalizeOrigin,
1064
+ loadTrustConfig,
1065
+ effectiveTrustList,
1066
+ OriginResolver,
1067
+ entryMatches,
1068
+ TrustPolicy,
1069
+ loadTypeScript,
1070
+ OPTIONS_SCHEMA,
1071
+ setupRule,
1072
+ UNTRUSTED_CALL_MESSAGES,
1073
+ untrusted_call_must_return_result_default,
1074
+ UNTRUSTED_CALL_RULE,
1075
+ THROW_RULE,
1076
+ originFromMessage,
1077
+ findingsFromResults,
1078
+ fatalMessages,
1079
+ countFindings,
1080
+ compareToBaseline,
1081
+ serializeBaseline,
1082
+ parseBaseline
1083
+ };
1084
+ //# sourceMappingURL=chunk-2KNNLUSN.js.map