@noego/trust 0.4.0 → 0.5.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +962 -14
  2. package/dist/baseline-Bkav9mS0.d.ts +380 -0
  3. package/dist/chunk-7PY2Q6OX.js +3016 -0
  4. package/dist/chunk-7PY2Q6OX.js.map +1 -0
  5. package/dist/chunk-UG6D3V4M.js +6990 -0
  6. package/dist/chunk-UG6D3V4M.js.map +1 -0
  7. package/dist/chunk-XXLWC5DB.js +112 -0
  8. package/dist/chunk-XXLWC5DB.js.map +1 -0
  9. package/dist/cli/index.js +1391 -65
  10. package/dist/cli/index.js.map +1 -1
  11. package/dist/cli/wasm-worker.js +257 -0
  12. package/dist/cli/wasm-worker.js.map +1 -0
  13. package/dist/core/index.d.ts +129 -0
  14. package/dist/core/index.js +115 -0
  15. package/dist/core/index.js.map +1 -0
  16. package/dist/eslint/index.d.ts +77 -167
  17. package/dist/eslint/index.js +320 -32
  18. package/dist/eslint/index.js.map +1 -1
  19. package/dist/licenses/@jridgewell__resolve-uri/LICENSE +19 -0
  20. package/dist/licenses/@jridgewell__sourcemap-codec/LICENSE +19 -0
  21. package/dist/licenses/@jridgewell__trace-mapping/LICENSE +19 -0
  22. package/dist/licenses/JS-DEPENDENCIES.json +83 -0
  23. package/dist/licenses/balanced-match/LICENSE.md +23 -0
  24. package/dist/licenses/brace-expansion/LICENSE +23 -0
  25. package/dist/licenses/dedent-js/LICENSE +19 -0
  26. package/dist/licenses/minimatch/LICENSE.md +55 -0
  27. package/dist/licenses/scule/LICENSE +21 -0
  28. package/dist/licenses/svelte2tsx/LICENSE +21 -0
  29. package/dist/native/licenses/CARGO-DEPENDENCIES.json +479 -0
  30. package/dist/native/licenses/LICENSE-trust.txt +15 -0
  31. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-0BSD +12 -0
  32. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-APACHE +201 -0
  33. package/dist/native/licenses/cargo/adler2-2.0.1/LICENSE-MIT +23 -0
  34. package/dist/native/licenses/cargo/aho-corasick-1.1.5/COPYING +3 -0
  35. package/dist/native/licenses/cargo/aho-corasick-1.1.5/LICENSE-MIT +21 -0
  36. package/dist/native/licenses/cargo/autocfg-1.5.1/LICENSE-APACHE +201 -0
  37. package/dist/native/licenses/cargo/autocfg-1.5.1/LICENSE-MIT +25 -0
  38. package/dist/native/licenses/cargo/bitflags-1.3.2/LICENSE-APACHE +201 -0
  39. package/dist/native/licenses/cargo/bitflags-1.3.2/LICENSE-MIT +25 -0
  40. package/dist/native/licenses/cargo/bstr-1.13.1/COPYING +8 -0
  41. package/dist/native/licenses/cargo/bstr-1.13.1/LICENSE-APACHE +201 -0
  42. package/dist/native/licenses/cargo/bstr-1.13.1/LICENSE-MIT +21 -0
  43. package/dist/native/licenses/cargo/bumpalo-3.20.3/LICENSE-APACHE +201 -0
  44. package/dist/native/licenses/cargo/bumpalo-3.20.3/LICENSE-MIT +25 -0
  45. package/dist/native/licenses/cargo/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  46. package/dist/native/licenses/cargo/cfg-if-1.0.5/LICENSE-MIT +25 -0
  47. package/dist/native/licenses/cargo/crc32fast-1.5.2/LICENSE-APACHE +202 -0
  48. package/dist/native/licenses/cargo/crc32fast-1.5.2/LICENSE-MIT +21 -0
  49. package/dist/native/licenses/cargo/defmt-1.1.1/LICENSE-APACHE +201 -0
  50. package/dist/native/licenses/cargo/defmt-1.1.1/LICENSE-MIT +25 -0
  51. package/dist/native/licenses/cargo/defmt-macros-1.1.1/LICENSE-APACHE +201 -0
  52. package/dist/native/licenses/cargo/defmt-macros-1.1.1/LICENSE-MIT +25 -0
  53. package/dist/native/licenses/cargo/equivalent-1.0.2/LICENSE-APACHE +201 -0
  54. package/dist/native/licenses/cargo/equivalent-1.0.2/LICENSE-MIT +25 -0
  55. package/dist/native/licenses/cargo/flate2-1.1.10/LICENSE-APACHE +201 -0
  56. package/dist/native/licenses/cargo/flate2-1.1.10/LICENSE-MIT +25 -0
  57. package/dist/native/licenses/cargo/globset-0.4.20/COPYING +3 -0
  58. package/dist/native/licenses/cargo/globset-0.4.20/LICENSE-MIT +21 -0
  59. package/dist/native/licenses/cargo/hashbrown-0.17.1/LICENSE-APACHE +201 -0
  60. package/dist/native/licenses/cargo/hashbrown-0.17.1/LICENSE-MIT +25 -0
  61. package/dist/native/licenses/cargo/indexmap-2.14.0/LICENSE-APACHE +201 -0
  62. package/dist/native/licenses/cargo/indexmap-2.14.0/LICENSE-MIT +25 -0
  63. package/dist/native/licenses/cargo/itoa-1.0.18/LICENSE-APACHE +176 -0
  64. package/dist/native/licenses/cargo/itoa-1.0.18/LICENSE-MIT +23 -0
  65. package/dist/native/licenses/cargo/jiff-0.2.37/COPYING +3 -0
  66. package/dist/native/licenses/cargo/jiff-0.2.37/LICENSE-MIT +21 -0
  67. package/dist/native/licenses/cargo/jiff-core-0.1.1/COPYING +3 -0
  68. package/dist/native/licenses/cargo/jiff-core-0.1.1/LICENSE-MIT +21 -0
  69. package/dist/native/licenses/cargo/jiff-tzdb-0.1.9/COPYING +3 -0
  70. package/dist/native/licenses/cargo/jiff-tzdb-0.1.9/LICENSE-MIT +21 -0
  71. package/dist/native/licenses/cargo/jiff-tzdb-platform-0.1.3/COPYING +3 -0
  72. package/dist/native/licenses/cargo/jiff-tzdb-platform-0.1.3/LICENSE-MIT +21 -0
  73. package/dist/native/licenses/cargo/log-0.4.34/LICENSE-APACHE +201 -0
  74. package/dist/native/licenses/cargo/log-0.4.34/LICENSE-MIT +25 -0
  75. package/dist/native/licenses/cargo/lzma-rust2-0.21.0/LICENSE +201 -0
  76. package/dist/native/licenses/cargo/memchr-2.8.2/COPYING +3 -0
  77. package/dist/native/licenses/cargo/memchr-2.8.2/LICENSE-MIT +21 -0
  78. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE +25 -0
  79. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-APACHE.md +177 -0
  80. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-MIT.md +24 -0
  81. package/dist/native/licenses/cargo/miniz_oxide-0.9.1/LICENSE-ZLIB.md +14 -0
  82. package/dist/native/licenses/cargo/num-bigint-0.4.6/LICENSE-APACHE +201 -0
  83. package/dist/native/licenses/cargo/num-bigint-0.4.6/LICENSE-MIT +25 -0
  84. package/dist/native/licenses/cargo/num-integer-0.1.47/LICENSE-APACHE +201 -0
  85. package/dist/native/licenses/cargo/num-integer-0.1.47/LICENSE-MIT +25 -0
  86. package/dist/native/licenses/cargo/num-traits-0.2.19/LICENSE-APACHE +201 -0
  87. package/dist/native/licenses/cargo/num-traits-0.2.19/LICENSE-MIT +25 -0
  88. package/dist/native/licenses/cargo/proc-macro2-1.0.107/LICENSE-APACHE +176 -0
  89. package/dist/native/licenses/cargo/proc-macro2-1.0.107/LICENSE-MIT +23 -0
  90. package/dist/native/licenses/cargo/quote-1.0.47/LICENSE-APACHE +176 -0
  91. package/dist/native/licenses/cargo/quote-1.0.47/LICENSE-MIT +23 -0
  92. package/dist/native/licenses/cargo/regex-automata-0.4.18/LICENSE-APACHE +201 -0
  93. package/dist/native/licenses/cargo/regex-automata-0.4.18/LICENSE-MIT +25 -0
  94. package/dist/native/licenses/cargo/regex-syntax-0.8.11/LICENSE-APACHE +201 -0
  95. package/dist/native/licenses/cargo/regex-syntax-0.8.11/LICENSE-MIT +25 -0
  96. package/dist/native/licenses/cargo/rustc-hash-2.1.2/LICENSE-APACHE +176 -0
  97. package/dist/native/licenses/cargo/rustc-hash-2.1.2/LICENSE-MIT +23 -0
  98. package/dist/native/licenses/cargo/ryu-js-1.0.2/LICENSE-APACHE +176 -0
  99. package/dist/native/licenses/cargo/ryu-js-1.0.2/LICENSE-BOOST +23 -0
  100. package/dist/native/licenses/cargo/serde-1.0.229/LICENSE-APACHE +176 -0
  101. package/dist/native/licenses/cargo/serde-1.0.229/LICENSE-MIT +23 -0
  102. package/dist/native/licenses/cargo/serde_core-1.0.229/LICENSE-APACHE +176 -0
  103. package/dist/native/licenses/cargo/serde_core-1.0.229/LICENSE-MIT +23 -0
  104. package/dist/native/licenses/cargo/serde_derive-1.0.229/LICENSE-APACHE +176 -0
  105. package/dist/native/licenses/cargo/serde_derive-1.0.229/LICENSE-MIT +23 -0
  106. package/dist/native/licenses/cargo/serde_json-1.0.152/LICENSE-APACHE +176 -0
  107. package/dist/native/licenses/cargo/serde_json-1.0.152/LICENSE-MIT +23 -0
  108. package/dist/native/licenses/cargo/simd-adler32-0.3.10/LICENSE.md +21 -0
  109. package/dist/native/licenses/cargo/smallvec-1.15.1/LICENSE-APACHE +201 -0
  110. package/dist/native/licenses/cargo/smallvec-1.15.1/LICENSE-MIT +25 -0
  111. package/dist/native/licenses/cargo/syn-2.0.119/LICENSE-APACHE +176 -0
  112. package/dist/native/licenses/cargo/syn-2.0.119/LICENSE-MIT +23 -0
  113. package/dist/native/licenses/cargo/syn-3.0.7/LICENSE-APACHE +176 -0
  114. package/dist/native/licenses/cargo/syn-3.0.7/LICENSE-MIT +23 -0
  115. package/dist/native/licenses/cargo/thiserror-2.0.21/LICENSE-APACHE +176 -0
  116. package/dist/native/licenses/cargo/thiserror-2.0.21/LICENSE-MIT +23 -0
  117. package/dist/native/licenses/cargo/thiserror-impl-2.0.21/LICENSE-APACHE +176 -0
  118. package/dist/native/licenses/cargo/thiserror-impl-2.0.21/LICENSE-MIT +23 -0
  119. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-APACHE +176 -0
  120. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-MIT +23 -0
  121. package/dist/native/licenses/cargo/unicode-ident-1.0.26/LICENSE-UNICODE +39 -0
  122. package/dist/native/licenses/cargo/xxhash-rust-0.8.15/LICENSE +23 -0
  123. package/dist/native/licenses/cargo/zlib-rs-0.6.8/LICENSE +19 -0
  124. package/dist/native/licenses/cargo/zmij-1.0.23/LICENSE-MIT +23 -0
  125. package/dist/native/licenses/ts-rust/LICENSE +21 -0
  126. package/dist/native/licenses/ts-rust/NOTICE.md +53 -0
  127. package/dist/native/licenses/ts-rust/licenses/Go-LICENSE.txt +27 -0
  128. package/dist/native/licenses/ts-rust/licenses/TypeScript-LICENSE.txt +55 -0
  129. package/dist/native/licenses/ts-rust/licenses/TypeScript-NOTICE.txt +405 -0
  130. package/dist/native/licenses/ts-rust/licenses/Unicode-LICENSE.txt +39 -0
  131. package/dist/native/licenses/ts-rust/licenses/vscode-languageserver-node-LICENSE.txt +18 -0
  132. package/dist/native/licenses/typescript/LICENSE.txt +55 -0
  133. package/dist/native/licenses/typescript/ThirdPartyNoticeText.txt +193 -0
  134. package/dist/native/licenses/typescript/manifest.json +105 -0
  135. package/dist/native/trust_native_wasm.wasm +0 -0
  136. package/dist/svelte2tsx/index.cjs +7064 -0
  137. package/dist/svelte2tsx/svelte-jsx-v4.d.ts +230 -0
  138. package/dist/svelte2tsx/svelte-jsx.d.ts +1492 -0
  139. package/dist/svelte2tsx/svelte-shims-v4.d.ts +290 -0
  140. package/dist/svelte2tsx/svelte-shims.d.ts +305 -0
  141. package/package.json +31 -8
  142. package/dist/chunk-YJYGTNJD.js +0 -2168
  143. package/dist/chunk-YJYGTNJD.js.map +0 -1
package/dist/cli/index.js CHANGED
@@ -1,104 +1,475 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  TrustPolicy,
4
+ callTypeVerdict,
5
+ checkSourceFile,
6
+ checkSourceFileWithAccepted,
7
+ claimSpan,
8
+ decide,
9
+ emptyTrustConfig,
10
+ guardCallOf,
11
+ policyFor,
12
+ positionAt,
13
+ startOf,
14
+ typeClaimContext,
15
+ typeClaimMessage,
16
+ typeClaimsIn,
17
+ untrustedValueContext,
18
+ untrustedValueMessage,
19
+ untrustedValuesIn
20
+ } from "../chunk-7PY2Q6OX.js";
21
+ import {
22
+ compareFindings,
23
+ forEachSourceFile,
24
+ formatFinding,
25
+ formatWalkFailure,
26
+ logUnmatchedGlobs,
27
+ logWalkFailure,
28
+ relativeTo,
29
+ resolveFiles
30
+ } from "../chunk-XXLWC5DB.js";
31
+ import {
32
+ DROPPED_RESULT_RULE,
33
+ SvelteFileError,
34
+ SvelteInputs,
35
+ TYPE_CLAIM_RULE,
36
+ UNTRUSTED_ENTRY_LABELS,
37
+ UNTRUSTED_VALUE_RULE,
38
+ WHOLE_BASELINE,
39
+ Zones,
4
40
  compareToBaseline,
5
- countFindings,
6
- fatalMessages,
7
- findingsFromResults,
41
+ createPrograms,
42
+ describeBaselineDelta,
43
+ groupByTsconfig,
44
+ groupMatches,
45
+ isRuleEnabled,
8
46
  loadTrustConfig,
9
47
  loadTypeScript,
10
- parseBaseline,
48
+ prepareSvelte,
49
+ readBaseline,
11
50
  realpathOrSelf,
12
- serializeBaseline
13
- } from "../chunk-YJYGTNJD.js";
51
+ serializeBaseline,
52
+ sourceFileOf,
53
+ svelteFor,
54
+ svelteForSource,
55
+ updateBaseline
56
+ } from "../chunk-UG6D3V4M.js";
14
57
 
15
58
  // src/cli/baseline-command.ts
16
- import { existsSync, readFileSync, writeFileSync } from "fs";
17
- import { createRequire } from "module";
59
+ import { existsSync, writeFileSync } from "fs";
18
60
  import { join, resolve } from "path";
19
- function loadESLint(cwd) {
20
- const require2 = createRequire(join(cwd, "__noego_trust__.cjs"));
21
- return require2("eslint").ESLint;
22
- }
23
- function describeDelta(delta) {
24
- const header = `${delta.file} ${delta.rule} ${delta.origin}: ${delta.found} found, ${delta.allowed} baselined`;
25
- return [header, ...delta.findings.map((finding) => ` ${delta.file}:${finding.line}:${finding.column} ${finding.message}`)];
26
- }
27
61
  async function runBaselineCommand(options) {
28
- const config = loadTrustConfig(resolve(options.cwd, options.configFile));
62
+ const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
63
+ if ("missing" in resolved) {
64
+ options.log(`trust baseline: no such file or directory: ${resolved.missing}`);
65
+ return 2;
66
+ }
67
+ const configPath = resolve(options.cwd, options.configFile);
68
+ const rootDir = options.root === void 0 ? void 0 : resolve(options.cwd, options.root);
69
+ const config = existsSync(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
70
+ logUnmatchedGlobs(options.log, "baseline", config);
29
71
  const baselineFile = resolve(options.cwd, options.baselineFile ?? join(config.rootDir, "trust-baseline.json"));
30
- const ESLint = loadESLint(options.cwd);
31
- const eslint = new ESLint({ cwd: options.cwd, ...options.eslintOptions });
32
- const results = await eslint.lintFiles(options.paths.length > 0 ? [...options.paths] : ["."]);
33
- const fatal = fatalMessages(results);
34
- if (fatal.length > 0) {
35
- options.log(`ESLint reported ${fatal.length} fatal error(s); fix them before using the baseline:`);
36
- for (const line of fatal.slice(0, 50)) options.log(` ${line}`);
72
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
73
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
74
+ const scope = options.paths.length === 0 ? WHOLE_BASELINE : { kind: "files", files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };
75
+ const findings = [];
76
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
77
+ const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile }) => {
78
+ findings.push(...checkSourceFile({ ts, program, config, sourceFile }));
79
+ });
80
+ if (walk.status !== "ok") {
81
+ logWalkFailure(options.log, "baseline", walk);
82
+ return 2;
83
+ }
84
+ const baseline = options.update && scope.kind === "all" ? { counts: {} } : readBaseline(baselineFile);
85
+ if ("error" in baseline) {
86
+ options.log(`trust baseline: could not read the baseline: ${baseline.error}`);
37
87
  return 2;
38
88
  }
39
- const findings = findingsFromResults(results, config.rootDir);
40
89
  if (options.update) {
41
- writeFileSync(baselineFile, serializeBaseline(countFindings(findings)));
42
- options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${results.length} linted file(s).`);
90
+ const updated = updateBaseline(baseline.counts, findings, scope);
91
+ writeFileSync(baselineFile, serializeBaseline(updated.counts));
92
+ const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : "";
93
+ options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);
43
94
  return 0;
44
95
  }
45
- const baseline = existsSync(baselineFile) ? parseBaseline(readFileSync(baselineFile, "utf8"), baselineFile) : {};
46
- const { added, stale } = compareToBaseline(findings, baseline);
96
+ const { added, stale } = compareToBaseline(findings, baseline.counts, scope);
47
97
  if (stale.length > 0) {
48
98
  options.log(`${stale.length} baseline entr${stale.length === 1 ? "y has" : "ies have"} fewer findings now; run with --update to shrink the baseline.`);
49
99
  }
50
100
  if (added.length === 0) {
51
- options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${results.length} file(s)).`);
101
+ options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);
52
102
  return 0;
53
103
  }
54
104
  const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);
55
105
  options.log(`${count} new @noego/trust violation(s) not in ${baselineFile}:`);
56
- for (const delta of added) for (const line of describeDelta(delta)) options.log(` ${line}`);
106
+ for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);
57
107
  options.log("Guard each call (try/catch returning Result.err, or Trust.try), or trust its origin in trust.config.json.");
58
- options.log("`trust explain <file>:<line>` shows which origin a call resolves to.");
108
+ const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);
109
+ if (hasTypeClaims) options.log("Prove each claimed type (narrow or validate the value) instead of asserting it.");
110
+ const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);
111
+ if (hasUntrustedValues) {
112
+ options.log('Validate each untrusted value (or keep it as `unknown` and narrow it), or add its origin to "trust_type" in trust.config.json.');
113
+ }
114
+ if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {
115
+ options.log("Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.");
116
+ }
117
+ const alsoShows = `${hasTypeClaims ? ", and why a line is a type claim" : ""}${hasUntrustedValues ? ", and where an untrusted value comes from" : ""}`;
118
+ options.log(`\`trust explain <file>:<line>\` shows which origin a call resolves to${alsoShows}.`);
59
119
  return 1;
60
120
  }
61
121
 
62
- // src/cli/explain.ts
63
- import { dirname, resolve as resolve2 } from "path";
64
- function compilerOptions(ts, tsconfig) {
65
- if (!tsconfig) return { allowJs: true, strict: true };
66
- const parsed = ts.getParsedCommandLineOfConfigFile(tsconfig, {}, {
67
- ...ts.sys,
68
- onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
69
- throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"));
122
+ // src/cli/check-command.ts
123
+ import { existsSync as existsSync2 } from "fs";
124
+ import { resolve as resolve4 } from "path";
125
+
126
+ // src/cli/native-check.ts
127
+ import { readFileSync as readFileSync2 } from "fs";
128
+ import { resolve as resolve3 } from "path";
129
+ import { spawnSync } from "child_process";
130
+ import { Worker } from "worker_threads";
131
+
132
+ // src/cli/native-engine.ts
133
+ import { accessSync, constants, readFileSync, statSync } from "fs";
134
+ import { createRequire } from "module";
135
+ import { dirname, join as join2, resolve as resolve2 } from "path";
136
+ import { fileURLToPath } from "url";
137
+ function nativePlatformPackage(platform, arch, libc = null) {
138
+ if (platform === "darwin" && (arch === "arm64" || arch === "x64")) return `@noego/trust-darwin-${arch}`;
139
+ if (platform === "linux" && libc === "glibc" && (arch === "arm64" || arch === "x64")) return `@noego/trust-linux-${arch}-gnu`;
140
+ if (platform === "win32" && arch === "x64") return "@noego/trust-win32-x64-msvc";
141
+ return null;
142
+ }
143
+ var NATIVE_MINIMUM_GLIBC = "2.35";
144
+ function supportsNativeGlibc(version) {
145
+ if (!version || !/^\d+\.\d+(?:\.\d+)?$/.test(version)) return false;
146
+ const [major, minor] = version.split(".").map(Number);
147
+ const [minimumMajor, minimumMinor] = NATIVE_MINIMUM_GLIBC.split(".").map(Number);
148
+ return major > minimumMajor || major === minimumMajor && minor >= minimumMinor;
149
+ }
150
+ function runtimeLinux(platform) {
151
+ if (platform !== "linux") return { libc: null, version: null };
152
+ try {
153
+ const report = process.report?.getReport();
154
+ if (typeof report !== "object" || report === null) return { libc: null, version: null };
155
+ const header = report.header;
156
+ const version = header?.glibcVersionRuntime ?? null;
157
+ return { libc: version ? "glibc" : "musl", version };
158
+ } catch {
159
+ return { libc: null, version: null };
160
+ }
161
+ }
162
+ var requireFromHere = createRequire(import.meta.url);
163
+ function packageRoots() {
164
+ const here = dirname(fileURLToPath(import.meta.url));
165
+ const roots = [resolve2(here, "..", "..")];
166
+ try {
167
+ roots.unshift(dirname(requireFromHere.resolve("@noego/trust/package.json")));
168
+ } catch {
169
+ }
170
+ return [...new Set(roots)];
171
+ }
172
+ function isFile(path, executable = false, platform = process.platform) {
173
+ try {
174
+ if (!statSync(path).isFile()) return false;
175
+ accessSync(path, executable && platform !== "win32" ? constants.X_OK : constants.R_OK);
176
+ return true;
177
+ } catch {
178
+ return false;
179
+ }
180
+ }
181
+ function packageVersion(roots, name) {
182
+ for (const root of roots) {
183
+ try {
184
+ const manifest = JSON.parse(readFileSync(join2(root, "package.json"), "utf8"));
185
+ const version = manifest.optionalDependencies?.[name];
186
+ if (manifest.name === "@noego/trust" && typeof version === "string" && /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) return version;
187
+ } catch {
70
188
  }
189
+ }
190
+ return null;
191
+ }
192
+ function nativeBinary(options = {}) {
193
+ const env = options.env ?? process.env;
194
+ if (env.TRUST_NATIVE_BIN) return env.TRUST_NATIVE_BIN;
195
+ const roots = options.roots ?? packageRoots();
196
+ const platform = options.platform ?? process.platform;
197
+ const linux = runtimeLinux(platform);
198
+ const libc = options.libc === void 0 ? linux.libc : options.libc;
199
+ const glibcVersion = options.glibcVersion === void 0 ? linux.version : options.glibcVersion;
200
+ const supported = platform !== "linux" || libc === "glibc" && supportsNativeGlibc(glibcVersion);
201
+ const name = supported ? nativePlatformPackage(platform, options.arch ?? process.arch, libc) : null;
202
+ const version = name ? packageVersion(roots, name) : null;
203
+ const executable = platform === "win32" ? "trust-native.exe" : "trust-native";
204
+ if (name && version) {
205
+ try {
206
+ const manifestPath = (options.resolvePackage ?? requireFromHere.resolve)(`${name}/package.json`);
207
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
208
+ const candidate = join2(dirname(manifestPath), "bin", executable);
209
+ if (manifest.name === name && manifest.version === version && isFile(candidate, true, platform)) return candidate;
210
+ } catch {
211
+ }
212
+ }
213
+ return roots.map((root) => join2(root, "native", "target", "release", executable)).find((candidate) => isFile(candidate, true, platform)) ?? null;
214
+ }
215
+ function nativeWasm(options = {}) {
216
+ const env = options.env ?? process.env;
217
+ if (env.TRUST_NATIVE_WASM) return env.TRUST_NATIVE_WASM;
218
+ const candidates = (options.roots ?? packageRoots()).flatMap((root) => [
219
+ join2(root, "dist", "native", "trust_native_wasm.wasm"),
220
+ join2(root, "native", "target", "wasm32-wasip1", "wasm", "trust_native_wasm.wasm"),
221
+ join2(root, "native", "target", "wasm32-wasip1", "release", "trust_native_wasm.wasm")
222
+ ]);
223
+ return candidates.find((candidate) => isFile(candidate)) ?? null;
224
+ }
225
+ function nativeEngine(options = {}) {
226
+ const forced = (options.env ?? process.env).TRUST_NATIVE_ENGINE;
227
+ if (forced !== "wasm") {
228
+ const path2 = nativeBinary(options);
229
+ if (path2) return { kind: "binary", path: path2 };
230
+ if (forced === "binary") return null;
231
+ }
232
+ const path = nativeWasm(options);
233
+ return path ? { kind: "wasm", path } : null;
234
+ }
235
+
236
+ // src/cli/native-check.ts
237
+ var NATIVE_PROTOCOL_VERSION = 3;
238
+ var WASM_STACK_SIZE_MB = 256;
239
+ var OPT_IN_RULES = [];
240
+ function runBinary(binary, request, cwd) {
241
+ const result = spawnSync(binary, [], { cwd, input: request, encoding: "utf8", maxBuffer: 1024 * 1024 * 1024 });
242
+ if (result.error) return { status: -1, output: `trust-native could not run: ${result.error.message}`, stderr: "" };
243
+ if (result.status !== 0) {
244
+ return { status: result.status ?? -1, output: `trust-native exited with ${result.status ?? result.signal}: ${result.stderr.trim().split("\n").slice(0, 5).join("\n")}`, stderr: result.stderr };
245
+ }
246
+ return { status: 0, output: result.stdout, stderr: result.stderr };
247
+ }
248
+ function runWasm(wasmPath, request) {
249
+ return new Promise((resolvePromise) => {
250
+ const worker = new Worker(new URL("./wasm-worker.js", import.meta.url), {
251
+ workerData: { wasmPath, request },
252
+ resourceLimits: { stackSizeMb: WASM_STACK_SIZE_MB }
253
+ });
254
+ let result;
255
+ worker.on("message", (message) => {
256
+ result = message.status === 0 ? message : { status: message.status, output: `trust-native (wasm) failed with ${message.status}: ${message.output.trim().split("\n").slice(0, 5).join("\n")}`, stderr: message.stderr };
257
+ });
258
+ worker.on("error", (error) => {
259
+ result ??= { status: -1, output: `trust-native (wasm) crashed: ${error.message}`, stderr: "" };
260
+ });
261
+ worker.on("exit", (code) => {
262
+ resolvePromise(result ?? { status: -1, output: `trust-native (wasm) worker ended without a result (exit ${code})`, stderr: "" });
263
+ });
264
+ });
265
+ }
266
+ function validResponse(value) {
267
+ if (!value || typeof value !== "object") return false;
268
+ const response = value;
269
+ if (response.version !== NATIVE_PROTOCOL_VERSION || !Array.isArray(response.findings) || !Array.isArray(response.errors)) return false;
270
+ if (response.setupError !== null && typeof response.setupError !== "string") return false;
271
+ if (!response.errors.every((error) => typeof error === "string")) return false;
272
+ if (!response.findings.every((finding) => finding && typeof finding === "object" && ["file", "rule", "message"].every((key) => typeof finding[key] === "string") && Number.isInteger(finding.line) && finding.line > 0 && Number.isInteger(finding.column) && finding.column > 0 && (finding.severity === "error" || finding.severity === "warning"))) return false;
273
+ const stats = response.stats;
274
+ return !!stats && ["loadSeconds", "checkSeconds", "checkedFiles"].every((key) => typeof stats[key] === "number" && Number.isFinite(stats[key]) && stats[key] >= 0);
275
+ }
276
+ async function checkNative(options) {
277
+ const { config } = options;
278
+ if (options.files.length === 0) return { findings: [], walk: { status: "ok" } };
279
+ for (const rule of OPT_IN_RULES) {
280
+ if (isRuleEnabled(config, rule)) {
281
+ return { findings: [], walk: { status: "setup-failed", message: `the native engine does not support the "${rule}" rule yet; this release cannot check this configuration safely` } };
282
+ }
283
+ }
284
+ const engine = nativeEngine();
285
+ if (!engine) {
286
+ return {
287
+ findings: [],
288
+ walk: {
289
+ status: "setup-failed",
290
+ message: "the trust-native engine is missing: reinstall @noego/trust (it includes a Wasm fallback), unset TRUST_NATIVE_ENGINE if it forces an unavailable binary, or set TRUST_NATIVE_BIN / TRUST_NATIVE_WASM; for a checkout, build the engine in native/"
291
+ }
292
+ };
293
+ }
294
+ let svelte;
295
+ let extraRoots;
296
+ try {
297
+ const needed = options.files.some((file) => file.endsWith(".svelte") || readFileSync2(file, "utf8").includes(".svelte"));
298
+ if (!needed) {
299
+ svelte = new SvelteInputs();
300
+ extraRoots = {};
301
+ } else {
302
+ const ts = loadTypeScript(options.cwd);
303
+ svelte = prepareSvelte(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);
304
+ const grouping = groupByTsconfig(ts, options.cwd, options.files, options.programs.tsconfig, options.programs.mappings);
305
+ if (grouping.kind !== "grouped") return { findings: [], walk: { status: "setup-failed", message: grouping.message } };
306
+ extraRoots = Object.fromEntries([...grouping.groups].map(([owner, files]) => [owner ?? "", svelte.extraRoots(files)]));
307
+ }
308
+ } catch (error) {
309
+ return { findings: [], walk: error instanceof SvelteFileError ? { status: "file-errors", errors: [error.message] } : { status: "setup-failed", message: error instanceof Error ? error.message : String(error) } };
310
+ }
311
+ const request = JSON.stringify({
312
+ version: NATIVE_PROTOCOL_VERSION,
313
+ cwd: options.cwd,
314
+ rootDir: config.rootDir,
315
+ files: options.files.map((file) => svelte.generated(file)),
316
+ virtualFiles: Object.fromEntries(svelte.virtual),
317
+ virtualPaths: Object.fromEntries(svelte.paths),
318
+ extraRoots,
319
+ programs: options.programs,
320
+ perf: options.perf ?? false,
321
+ rules: { typeClaim: isRuleEnabled(config, "type-claim"), untrustedValue: isRuleEnabled(config, "untrusted-value"), untrustedCallbacks: config.rules.untrustedCallbacks, droppedResult: isRuleEnabled(config, "dropped-result"), redundantGuard: isRuleEnabled(config, "redundant-guard") },
322
+ config: {
323
+ levels: config.levels.map((level) => ({ source: level.source, trust: level.trust, distrust: level.distrust, typeTrust: level.typeTrust, typeDistrust: level.typeDistrust })),
324
+ passthrough: config.passthrough.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns })),
325
+ ignore: config.ignore.map((group) => ({ source: group.source, baseDir: group.baseDir, patterns: group.patterns }))
326
+ },
327
+ strictFiles: options.strictFiles.map((file) => svelte.generated(file))
71
328
  });
72
- return parsed?.options ?? {};
329
+ const started = Date.now();
330
+ const result = engine.kind === "binary" ? runBinary(engine.path, request, options.cwd) : await runWasm(engine.path, request);
331
+ if (result.status !== 0) {
332
+ return { findings: [], walk: { status: "setup-failed", message: result.output } };
333
+ }
334
+ let response;
335
+ try {
336
+ const value = JSON.parse(result.output);
337
+ if (!validResponse(value)) throw new Error("Invalid engine response");
338
+ response = value;
339
+ } catch {
340
+ return { findings: [], walk: { status: "setup-failed", message: `trust-native (${engine.kind}) returned malformed output` } };
341
+ }
342
+ if (process.env.TRUST_NATIVE_DEBUG) {
343
+ options.log(
344
+ `trust native: ${engine.kind} engine checked ${response.stats.checkedFiles} file(s): load ${response.stats.loadSeconds.toFixed(1)}s, rules ${response.stats.checkSeconds.toFixed(1)}s, round trip ${((Date.now() - started) / 1e3).toFixed(1)}s`
345
+ );
346
+ if (result.stderr.trim()) options.log(result.stderr.trim());
347
+ }
348
+ if (response.setupError !== null) return { findings: [], walk: { status: "setup-failed", message: response.setupError } };
349
+ if (response.errors.length > 0) return { findings: [], walk: { status: "file-errors", errors: response.errors.map((error) => svelte.error(error)) } };
350
+ const snippetTrusted = decide(config.levels, (level) => level, "svelte.__renderSnippet", "svelte").trusted && !("distrustedBy" in decide(config.levels, (level) => level, "svelte.Snippet", "svelte"));
351
+ const findings = response.findings.flatMap((finding) => {
352
+ const file = resolve3(config.rootDir, finding.file);
353
+ const mapped = svelte.finding(file, finding, snippetTrusted);
354
+ return mapped ? [{ ...mapped, file: svelte.paths.has(file) ? relativeTo(config.rootDir, svelte.original(file)) : finding.file }] : [];
355
+ });
356
+ return { findings, walk: { status: "ok" } };
357
+ }
358
+
359
+ // src/cli/check-command.ts
360
+ async function runCheckCommand(options) {
361
+ const fail = (errors) => {
362
+ if (options.json) options.log(JSON.stringify({ findings: [], errors, warnings: [] }));
363
+ else for (const error of errors) options.log(error);
364
+ return 2;
365
+ };
366
+ if (options.paths.length === 0) return fail(["trust check needs at least one path: trust check <paths...> [--strict] [--perf] [--json]"]);
367
+ try {
368
+ const resolved = resolveFiles(options.cwd, options.paths);
369
+ if ("missing" in resolved) return fail([`trust check: no such file or directory: ${resolved.missing}`]);
370
+ const configPath = resolve4(options.cwd, options.configFile);
371
+ const rootDir = options.root === void 0 ? void 0 : resolve4(options.cwd, options.root);
372
+ const config = existsSync2(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
373
+ const warnings = config.unmatchedGlobs.map((line) => `trust check: warning: ${line}`);
374
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
375
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
376
+ const skipped = resolved.files.length - files.length;
377
+ const strictByConfig = files.filter((file) => config.strict.some((group) => groupMatches(group, realpathOrSelf(file))));
378
+ const result = await checkNative({
379
+ cwd: options.cwd,
380
+ files,
381
+ config,
382
+ programs: { tsconfig: options.tsconfig, mappings: config.tsconfig },
383
+ strictFiles: options.strict ? files : strictByConfig,
384
+ perf: options.perf,
385
+ // Keep --json a single parseable document, even with debugging enabled.
386
+ log: (line) => {
387
+ if (!options.json) options.log(line);
388
+ }
389
+ });
390
+ if (result.walk.status !== "ok") return fail(formatWalkFailure("trust check", result.walk));
391
+ const findings = result.findings.sort(compareFindings).map((finding) => ({ ...finding, severity: finding.severity ?? "error" }));
392
+ const errors = findings.filter((finding) => finding.severity === "error").length;
393
+ const advice = findings.length - errors;
394
+ if (options.json) {
395
+ options.log(JSON.stringify({ findings, errors: [], warnings, summary: { errors, warnings: advice, checkedFiles: files.length, skippedFiles: skipped } }));
396
+ } else {
397
+ for (const warning of warnings) options.log(warning);
398
+ for (const finding of findings) options.log(formatFinding(finding));
399
+ const notes = [];
400
+ if (options.strict) notes.push("strict");
401
+ else if (strictByConfig.length) notes.push(`${strictByConfig.length} strict by config`);
402
+ if (options.perf) notes.push("perf");
403
+ const counts = options.perf ? `${errors} error(s), ${advice} warning(s)` : `${findings.length} finding(s)`;
404
+ options.log(`${counts} in ${files.length} checked file(s), ${skipped} ignored file(s) skipped${notes.length ? ` (${notes.join(", ")})` : ""}.`);
405
+ }
406
+ return errors > 0 ? 1 : 0;
407
+ } catch (error) {
408
+ return fail([`trust check: ${error instanceof Error ? error.message : String(error)}`]);
409
+ }
410
+ }
411
+
412
+ // src/cli/explain.ts
413
+ import { resolve as resolve5 } from "path";
414
+ function clipText(raw) {
415
+ const text = raw.replace(/\s+/g, " ");
416
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
73
417
  }
74
418
  function declaredAt(ts, policy, node) {
75
419
  const resolved = policy.calleeDeclaration(node);
76
420
  if (!resolved) return null;
77
421
  const source = resolved.declaration.getSourceFile();
78
422
  const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));
79
- return `${source.fileName}:${line + 1}`;
423
+ const inputs = svelteForSource(source);
424
+ const original = inputs?.position(source.fileName, startOf(ts, source, resolved.declaration));
425
+ return `${inputs?.original(source.fileName) ?? source.fileName}:${original?.line ?? line + 1}`;
80
426
  }
427
+ function explainGuard(call, source, context) {
428
+ const guard = guardCallOf(call, context);
429
+ return guard ? { predicate: guard.predicate, narrows: clipText(guard.argument.getText(source)), asserts: guard.asserts, verdict: guard.verdict } : null;
430
+ }
431
+ var NOT_REPORTED = {
432
+ allowed: "not reported: it is passed to a validator, kept as `unknown`, tested by a built-in check, or kept in a variable with no written type",
433
+ "no-claim": "not reported: its type claims nothing (`unknown`, `any`, an empty type or a function)",
434
+ validator: "not reported: it is inside a validator"
435
+ };
81
436
  function explain(options) {
82
437
  const ts = loadTypeScript(options.cwd);
83
- const file = resolve2(options.cwd, options.file);
84
- const tsconfig = options.tsconfig ? resolve2(options.cwd, options.tsconfig) : ts.findConfigFile(dirname(file), ts.sys.fileExists);
85
- const program = ts.createProgram({ rootNames: [file], options: { ...compilerOptions(ts, tsconfig), noEmit: true } });
86
- const source = program.getSourceFile(file) ?? program.getSourceFile(realpathOrSelf(file));
438
+ const file = resolve5(options.cwd, options.file);
439
+ const rootDir = options.root === void 0 ? void 0 : resolve5(options.cwd, options.root);
440
+ const config = loadTrustConfig(resolve5(options.cwd, options.configFile), { rootDir });
441
+ const creation = createPrograms(ts, options.cwd, [file], options.tsconfig, config.tsconfig);
442
+ if (creation.kind !== "created") return creation;
443
+ const [{ program }] = creation.groups;
444
+ const source = sourceFileOf(program, file);
87
445
  if (!source) throw new Error(`could not load ${file} into a TypeScript program`);
88
446
  const checker = program.getTypeChecker();
89
- const policy = new TrustPolicy(ts, checker, loadTrustConfig(resolve2(options.cwd, options.configFile)));
447
+ const policy = new TrustPolicy(ts, checker, config);
448
+ const valueContext = untrustedValueContext(ts, checker, policy);
449
+ const generatedLines = svelteFor(checker)?.generatedLines(source.fileName, options.line);
450
+ const here = (position) => {
451
+ if (generatedLines && !generatedLines.has(position.line)) return null;
452
+ const mapped = svelteFor(checker)?.position(source.fileName, position);
453
+ if (mapped === null) return null;
454
+ position = mapped ?? position;
455
+ const onLine = position.line === options.line;
456
+ return onLine && (options.column === void 0 || position.column === options.column) ? position : null;
457
+ };
90
458
  const calls = [];
91
459
  const visit = (node) => {
92
460
  if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
93
- const position = ts.getLineAndCharacterOfPosition(source, node.getStart(source));
94
- const onLine = position.line + 1 === options.line;
95
- if (onLine && (options.column === void 0 || position.character + 1 === options.column)) {
96
- const text = node.getText(source).replace(/\s+/g, " ");
461
+ const position = here(startOf(ts, source, node));
462
+ if (position) {
97
463
  calls.push({
98
- line: position.line + 1,
99
- column: position.character + 1,
100
- text: text.length > 80 ? `${text.slice(0, 77)}...` : text,
101
- verdict: policy.classify(node),
464
+ ...position,
465
+ text: clipText(node.getText(source)),
466
+ verdict: (() => {
467
+ const verdict = policy.classify(node);
468
+ const wrapper = policy.lookup("svelte.__renderSnippet", "svelte");
469
+ return verdict.kind === "untrusted" && !verdict.distrustedBy && verdict.origin.origin === "svelte.Snippet" && svelteFor(checker)?.snippetCall(source.fileName, node.getStart(source)) && wrapper.trusted ? { kind: "trusted", origin: verdict.origin, by: wrapper.by } : verdict;
470
+ })(),
471
+ typeTrust: callTypeVerdict(node, valueContext),
472
+ guard: ts.isCallExpression(node) ? explainGuard(node, source, valueContext) : null,
102
473
  declaredAt: declaredAt(ts, policy, node)
103
474
  });
104
475
  }
@@ -106,7 +477,35 @@ function explain(options) {
106
477
  ts.forEachChild(node, visit);
107
478
  };
108
479
  visit(source);
109
- return { file, zone: policy.zones.zoneOf(file), calls };
480
+ const claimsOn = isRuleEnabled(config, TYPE_CLAIM_RULE);
481
+ const valuesOn = isRuleEnabled(config, UNTRUSTED_VALUE_RULE);
482
+ const explained = [TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE];
483
+ const off = explained.filter((rule) => !isRuleEnabled(config, rule));
484
+ const claims = (claimsOn ? typeClaimsIn(source, typeClaimContext(ts, checker, void 0, policy)) : []).flatMap((claim) => {
485
+ const span = claimSpan(claim, source);
486
+ const position = here(positionAt(ts, source, span.start));
487
+ return position ? [{ ...position, text: clipText(source.text.slice(span.start, span.end)), origin: claim.origin, why: typeClaimMessage(claim) }] : [];
488
+ });
489
+ const found = valuesOn ? untrustedValuesIn(source, valueContext) : [];
490
+ const valueNodes = new Set(found.map((value) => value.node));
491
+ const isReadThrough = (node) => (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node && valueNodes.has(node.parent);
492
+ const isCall = (node) => ts.isCallExpression(node) || ts.isNewExpression(node);
493
+ const values = found.flatMap((value) => {
494
+ const position = here(startOf(ts, source, value.node));
495
+ if (!position || isReadThrough(value.node) || value.outcome === "no-claim" && isCall(value.node)) return [];
496
+ const why = value.outcome === "finding" ? untrustedValueMessage(value) : NOT_REPORTED[value.outcome];
497
+ return [{ ...position, text: clipText(value.node.getText(source)), entry: value.entry, origin: value.origin, type: value.type, outcome: value.outcome, why }];
498
+ });
499
+ const accepted = checkSourceFileWithAccepted({ ts, program, checker, config, sourceFile: source }).accepted.flatMap((entry) => {
500
+ const { finding, acceptance } = entry;
501
+ const position = here({ line: finding.line, column: finding.column });
502
+ if (!position) return [];
503
+ const directivePosition = positionAt(ts, source, acceptance.directive.pos);
504
+ const directiveLine = svelteFor(checker)?.position(source.fileName, directivePosition)?.line ?? directivePosition.line;
505
+ return [{ ...position, text: clipText(entry.text), rule: finding.rule, origin: finding.origin, why: finding.message, reason: acceptance.reason, directiveLine }];
506
+ });
507
+ const unique = (items) => [...new Map(items.map((item) => [JSON.stringify(item), item])).values()];
508
+ return { kind: "explained", explanation: { file, zone: policy.zones.zoneOf(file), calls: unique(calls), claims: unique(claims), values: unique(values), accepted: unique(accepted), off } };
110
509
  }
111
510
  function describe(verdict) {
112
511
  switch (verdict.kind) {
@@ -131,25 +530,914 @@ function describe(verdict) {
131
530
  ];
132
531
  }
133
532
  }
533
+ function describeTypeTrust(verdict) {
534
+ switch (verdict.kind) {
535
+ case "unresolved":
536
+ return [];
537
+ case "first-party":
538
+ return ["types: trusted (first-party code in a checked file is checked itself)"];
539
+ case "trust-package":
540
+ return ["types: trusted (declared by @noego/trust)"];
541
+ case "validator":
542
+ return ["types: trusted (the callee is a validator: //trust:validator_function)"];
543
+ case "type-trusted":
544
+ return [`types: type-trusted by "${verdict.by.entry}" in ${verdict.by.source}`];
545
+ case "caller-chosen-generic":
546
+ return [
547
+ "types: UNTRUSTED (the call picks its own return type: a type parameter found only in the return position, which no type trust proves)",
548
+ " validate the returned value"
549
+ ];
550
+ case "type-untrusted":
551
+ return [
552
+ verdict.distrustedBy ? `types: UNTRUSTED (type-distrusted by "${verdict.distrustedBy.entry}" in ${verdict.distrustedBy.source})` : "types: UNTRUSTED (no trust_type entry matches)",
553
+ ` validate what it returns, or add "${verdict.origin.origin}" (or a prefix of it) to "trust_type" in trust.config.json`
554
+ ];
555
+ }
556
+ }
557
+ function describeGuard(guard) {
558
+ const head = `guard: ${guard.asserts ? "asserts" : "narrows"} "${guard.narrows}" (${guard.predicate}), declared by "${guard.verdict.origin.origin}"`;
559
+ switch (guard.verdict.kind) {
560
+ case "first-party":
561
+ return [head, " not an untrusted value: first-party code in a checked file (its written predicate is a type claim, rule type-claim)"];
562
+ case "trust-package":
563
+ return [head, " trusted (declared by @noego/trust)"];
564
+ case "validator":
565
+ return [head, " trusted (the guard is a validator: //trust:validator_function)"];
566
+ case "built-in":
567
+ return [head, " trusted (a built-in check)"];
568
+ case "type-trusted":
569
+ return [head, ` type-trusted by "${guard.verdict.by.entry}" in ${guard.verdict.by.source}`];
570
+ case "type-untrusted":
571
+ return [
572
+ head,
573
+ guard.verdict.distrustedBy ? ` UNTRUSTED (type-distrusted by "${guard.verdict.distrustedBy.entry}" in ${guard.verdict.distrustedBy.source}): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})` : ` UNTRUSTED (no trust_type entry matches): the narrowed value is untrusted (rule ${UNTRUSTED_VALUE_RULE})`,
574
+ ` validate the value instead, or add "${guard.verdict.origin.origin}" (or a prefix of it) to "trust_type" in trust.config.json`
575
+ ];
576
+ }
577
+ }
134
578
  function formatExplanation(explanation) {
135
579
  const lines = [`${explanation.file} (zone: ${explanation.zone})`];
136
- if (explanation.zone !== "checked") lines.push("note: calls in this file are not checked (only checked-zone files are linted)");
137
- if (explanation.calls.length === 0) lines.push("no call or `new` expression starts at that location");
580
+ if (explanation.zone !== "checked") {
581
+ lines.push("note: calls, type claims and untrusted values in this file are not checked (only checked-zone files are linted)");
582
+ }
583
+ for (const rule of explanation.off) {
584
+ lines.push(`note: ${rule} is off in this config, so it is not explained; turn it on with "rules": { "${rule}": "on" } in trust.config.json`);
585
+ }
586
+ if (explanation.calls.length === 0 && explanation.claims.length === 0 && explanation.values.length === 0 && explanation.accepted.length === 0) {
587
+ lines.push("no call, `new` expression, type claim or untrusted value starts at that location");
588
+ }
589
+ for (const accepted of explanation.accepted) {
590
+ lines.push("", `${accepted.line}:${accepted.column} ${accepted.text}`);
591
+ lines.push(` accepted: ${accepted.rule} (${accepted.origin}) by //trust:accept on line ${accepted.directiveLine}`);
592
+ lines.push(` reason: ${accepted.reason}`);
593
+ lines.push(` finding: ${accepted.why}`);
594
+ }
138
595
  for (const call of explanation.calls) {
139
596
  lines.push("", `${call.line}:${call.column} ${call.text}`);
140
597
  for (const detail of describe(call.verdict)) lines.push(` ${detail}`);
598
+ for (const detail of describeTypeTrust(call.typeTrust)) lines.push(` ${detail}`);
599
+ if (call.guard) for (const detail of describeGuard(call.guard)) lines.push(` ${detail}`);
141
600
  if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);
142
601
  }
602
+ for (const claim of explanation.claims) {
603
+ lines.push("", `${claim.line}:${claim.column} ${claim.text}`);
604
+ lines.push(` claim: ${claim.origin} (rule ${TYPE_CLAIM_RULE})`);
605
+ lines.push(` why: ${claim.why}`);
606
+ }
607
+ for (const value of explanation.values) {
608
+ lines.push("", `${value.line}:${value.column} ${value.text}`);
609
+ lines.push(` value: untrusted "${value.type}", ${UNTRUSTED_ENTRY_LABELS[value.entry]} "${value.origin}" (rule ${UNTRUSTED_VALUE_RULE})`);
610
+ lines.push(` use: ${value.why}`);
611
+ }
143
612
  return lines.join("\n");
144
613
  }
145
614
 
615
+ // src/cli/refactor-command.ts
616
+ import { existsSync as existsSync3 } from "fs";
617
+ import { join as join3, resolve as resolve6 } from "path";
618
+
619
+ // src/core/call-graph.ts
620
+ var TOP_LEVEL = "(top level)";
621
+ function memberName(ts, member) {
622
+ if (ts.isConstructorDeclaration(member)) return "constructor";
623
+ const name = member.name;
624
+ if (!name) return void 0;
625
+ return ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : void 0;
626
+ }
627
+ function nameIn(ts, chain, index, prefix) {
628
+ const statement = chain[index];
629
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) return null;
630
+ if (ts.isFunctionDeclaration(statement)) return prefix + (statement.name?.text ?? "default");
631
+ if (ts.isClassDeclaration(statement)) {
632
+ const owner = prefix + (statement.name?.text ?? "default");
633
+ const member = chain.at(index + 1);
634
+ const name = member && ts.isClassElement(member) ? memberName(ts, member) : void 0;
635
+ return name === void 0 ? owner : `${owner}.${name}`;
636
+ }
637
+ if (ts.isVariableStatement(statement)) {
638
+ const declaration = chain.at(index + 2);
639
+ return prefix + (declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) ? declaration.name.text : TOP_LEVEL);
640
+ }
641
+ if (ts.isModuleDeclaration(statement)) {
642
+ const inner = `${prefix}${statement.name.text}.`;
643
+ const body = chain.at(index + 1);
644
+ if (body && ts.isModuleDeclaration(body)) return nameIn(ts, chain, index + 1, inner);
645
+ if (body && ts.isModuleBlock(body) && chain.length > index + 2) return nameIn(ts, chain, index + 2, inner);
646
+ return prefix + statement.name.text;
647
+ }
648
+ if (ts.isExportAssignment(statement)) return `${prefix}default`;
649
+ return prefix + TOP_LEVEL;
650
+ }
651
+ function declarationOf(ts, node) {
652
+ const chain = [];
653
+ for (let current = node; !ts.isSourceFile(current); current = current.parent) chain.push(current);
654
+ if (chain.length === 0) return null;
655
+ chain.reverse();
656
+ const virtual = svelteForSource(node.getSourceFile());
657
+ const render = virtual && chain.findIndex((part) => ts.isFunctionDeclaration(part) && part.name?.text === "$$render");
658
+ const index = typeof render === "number" && render >= 0 ? render + 2 : 0;
659
+ return index < chain.length ? nameIn(ts, chain, index, "") : TOP_LEVEL;
660
+ }
661
+ function declarationAt(ts, sourceFile, line, column) {
662
+ const generated = svelteForSource(sourceFile)?.generatedPositions(sourceFile.fileName, { line, column })[0];
663
+ const position = ts.getPositionOfLineAndCharacter(sourceFile, (generated?.line ?? line) - 1, (generated?.column ?? column) - 1);
664
+ let node = sourceFile;
665
+ for (; ; ) {
666
+ const child = ts.forEachChild(node, (candidate) => candidate.getStart(sourceFile) <= position && position < candidate.end ? candidate : void 0);
667
+ if (!child) break;
668
+ node = child;
669
+ }
670
+ return declarationOf(ts, node) ?? TOP_LEVEL;
671
+ }
672
+ function collectCalls(ts, policy, change, sourceFile) {
673
+ const calls = [];
674
+ const visit = (node) => {
675
+ if (ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword || ts.isNewExpression(node)) {
676
+ const from = declarationOf(ts, node);
677
+ const callee = from === null ? null : policy.calleeDeclaration(node);
678
+ if (from !== null && callee && change.declarationCanChange(callee.declaration)) {
679
+ const to = declarationOf(ts, callee.declaration);
680
+ if (to !== null) calls.push({ from, targetFile: callee.declaration.getSourceFile().fileName, to });
681
+ }
682
+ }
683
+ ts.forEachChild(node, visit);
684
+ };
685
+ visit(sourceFile);
686
+ return calls;
687
+ }
688
+
689
+ // src/core/change.ts
690
+ var ChangeOracle = class {
691
+ constructor(ts, checker, policy) {
692
+ this.ts = ts;
693
+ this.checker = checker;
694
+ this.policy = policy;
695
+ }
696
+ ts;
697
+ checker;
698
+ policy;
699
+ known = /* @__PURE__ */ new Map();
700
+ /** Declarations being judged right now: meeting one again (a type that mentions itself) assumes "cannot change". */
701
+ open = /* @__PURE__ */ new Set();
702
+ assumptions = 0;
703
+ /** Can what the symbol names change? Follows an import to what it imports; a symbol nothing declares can. */
704
+ symbolCanChange(symbol) {
705
+ if (!symbol) return true;
706
+ const target = symbol.flags & this.ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
707
+ const declarations = target.declarations ?? [];
708
+ return declarations.length === 0 || declarations.some((declaration) => this.declarationCanChange(declaration));
709
+ }
710
+ declarationCanChange(declaration) {
711
+ const known = this.known.get(declaration);
712
+ if (known !== void 0) return known;
713
+ if (this.open.has(declaration)) {
714
+ this.assumptions += 1;
715
+ return false;
716
+ }
717
+ this.open.add(declaration);
718
+ const before = this.assumptions;
719
+ const result = this.judge(declaration);
720
+ this.open.delete(declaration);
721
+ if (result || this.assumptions === before || this.open.size === 0) this.known.set(declaration, result);
722
+ return result;
723
+ }
724
+ judge(node) {
725
+ const ts = this.ts;
726
+ if (node.getSourceFile().isDeclarationFile) return false;
727
+ if (ts.isSourceFile(node)) return this.exportsCanChange(node);
728
+ if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return this.mentionsChange(node);
729
+ if (ts.isEnumDeclaration(node) || ts.isEnumMember(node) || ts.isTypeParameterDeclaration(node)) return false;
730
+ if (ts.isFunctionLike(node)) {
731
+ const body = node.body;
732
+ return body ? !this.frozen(node) : this.mentionsChange(node);
733
+ }
734
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) {
735
+ if (node.type) return this.mentionsChange(node.type);
736
+ if (ts.isPropertySignature(node)) return false;
737
+ return node.initializer ? this.expressionCanChange(node.initializer) : true;
738
+ }
739
+ if (ts.isPropertyAssignment(node)) return this.expressionCanChange(node.initializer);
740
+ if (ts.isExportAssignment(node)) return this.expressionCanChange(node.expression);
741
+ if (ts.isClassLike(node)) {
742
+ const base = (node.heritageClauses ?? []).filter((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);
743
+ return base.some((clause) => this.mentionsChange(clause)) || node.members.some((member) => this.memberCanChange(member));
744
+ }
745
+ return true;
746
+ }
747
+ memberCanChange(member) {
748
+ const ts = this.ts;
749
+ if (ts.isClassStaticBlockDeclaration(member) || ts.isSemicolonClassElement(member)) return false;
750
+ return this.declarationCanChange(member);
751
+ }
752
+ exportsCanChange(sourceFile) {
753
+ const module = this.checker.getSymbolAtLocation(sourceFile);
754
+ if (!module) return false;
755
+ return this.checker.getExportsOfModule(module).some((exported) => this.symbolCanChange(exported));
756
+ }
757
+ /** A written return type that is a Result (or a promise of one) and mentions nothing that can change. */
758
+ frozen(node) {
759
+ if (!node.type) return false;
760
+ const written = this.checker.getTypeFromTypeNode(node.type);
761
+ const awaited = this.checker.getAwaitedType(written) ?? written;
762
+ return this.policy.isResultType(awaited) && !this.mentionsChange(node.type);
763
+ }
764
+ /** The type of a value without a written type: fixed for a literal, open for a call, a name or anything computed. */
765
+ expressionCanChange(expression) {
766
+ const ts = this.ts;
767
+ if (ts.isParenthesizedExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) {
768
+ return this.expressionCanChange(expression.expression);
769
+ }
770
+ if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {
771
+ return ts.isConstTypeReference(expression.type) ? this.expressionCanChange(expression.expression) : this.mentionsChange(expression.type);
772
+ }
773
+ if (ts.isLiteralExpression(expression) || ts.isTemplateExpression(expression)) return false;
774
+ const kind = expression.kind;
775
+ if (kind === ts.SyntaxKind.TrueKeyword || kind === ts.SyntaxKind.FalseKeyword || kind === ts.SyntaxKind.NullKeyword) return false;
776
+ if (ts.isPrefixUnaryExpression(expression)) return this.expressionCanChange(expression.operand);
777
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression) || ts.isClassExpression(expression)) return this.declarationCanChange(expression);
778
+ if (ts.isArrayLiteralExpression(expression)) {
779
+ return expression.elements.some((element) => ts.isSpreadElement(element) || this.expressionCanChange(element));
780
+ }
781
+ if (ts.isObjectLiteralExpression(expression)) return expression.properties.some((property) => this.declarationCanChange(property));
782
+ return true;
783
+ }
784
+ /** Does a written type (or a declaration made of written types) name something that can change? */
785
+ mentionsChange(node) {
786
+ const ts = this.ts;
787
+ const visit = (child) => {
788
+ if (ts.isTypeReferenceNode(child) && this.symbolCanChange(this.named(child.typeName))) return true;
789
+ if (ts.isTypeQueryNode(child) && this.symbolCanChange(this.named(child.exprName))) return true;
790
+ if (ts.isExpressionWithTypeArguments(child)) {
791
+ const expression = child.expression;
792
+ if (this.symbolCanChange(this.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(expression) ? expression.name : expression))) return true;
793
+ }
794
+ if (ts.isImportTypeNode(child)) {
795
+ const name = child.qualifier ?? (ts.isLiteralTypeNode(child.argument) ? child.argument.literal : void 0);
796
+ if (!name || this.symbolCanChange(ts.isStringLiteral(name) ? this.checker.getSymbolAtLocation(name) : this.named(name))) return true;
797
+ }
798
+ return ts.forEachChild(child, visit) ?? false;
799
+ };
800
+ return visit(node);
801
+ }
802
+ named(name) {
803
+ return this.checker.getSymbolAtLocation(this.ts.isQualifiedName(name) ? name.right : name);
804
+ }
805
+ };
806
+ var oracles = /* @__PURE__ */ new WeakMap();
807
+ function changeOracleFor(ts, checker, policy) {
808
+ let oracle = oracles.get(policy);
809
+ if (!oracle) {
810
+ oracle = new ChangeOracle(ts, checker, policy);
811
+ oracles.set(policy, oracle);
812
+ }
813
+ return oracle;
814
+ }
815
+
816
+ // src/core/import-graph.ts
817
+ var WHOLE_MODULE = "*";
818
+ var resolutionCaches = /* @__PURE__ */ new WeakMap();
819
+ function resolutionCache(ts, program) {
820
+ let cache = resolutionCaches.get(program);
821
+ if (!cache) {
822
+ cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (name) => name, program.getCompilerOptions());
823
+ resolutionCaches.set(program, cache);
824
+ }
825
+ return cache;
826
+ }
827
+ function declarationFiles(symbol) {
828
+ return [...new Set((symbol?.declarations ?? []).map((declaration) => declaration.getSourceFile().fileName))];
829
+ }
830
+ function collectImports(ts, program, sourceFile, change) {
831
+ const checker = program.getTypeChecker();
832
+ const edges = [];
833
+ const computed = [];
834
+ const add = (imported, name, typeOnly) => {
835
+ for (const target of imported.files) edges.push({ target, typeOnly, name, carriesChange: imported.carriesChange });
836
+ };
837
+ const moduleFiles = (specifier) => {
838
+ const declared = declarationFiles(checker.getSymbolAtLocation(specifier));
839
+ if (declared.length > 0 || !ts.isStringLiteralLike(specifier)) return declared;
840
+ const resolved = ts.resolveModuleName(specifier.text, sourceFile.fileName, program.getCompilerOptions(), ts.sys, resolutionCache(ts, program));
841
+ return resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : [];
842
+ };
843
+ const wholeModule = (specifier) => {
844
+ return { files: moduleFiles(specifier), carriesChange: change ? change.symbolCanChange(checker.getSymbolAtLocation(specifier)) : true };
845
+ };
846
+ const loadedOnly = (specifier) => {
847
+ return { files: moduleFiles(specifier), carriesChange: change === void 0 };
848
+ };
849
+ const declaring = (name, specifier) => {
850
+ const symbol = checker.getSymbolAtLocation(name);
851
+ const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
852
+ const declared = declarationFiles(target);
853
+ if (declared.length === 0) return { files: moduleFiles(specifier), carriesChange: true };
854
+ return { files: declared, carriesChange: change ? change.symbolCanChange(target) : true };
855
+ };
856
+ const visitImport = (node) => {
857
+ const clause = node.importClause;
858
+ if (!clause) {
859
+ add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, false);
860
+ return;
861
+ }
862
+ if (clause.name) add(declaring(clause.name, node.moduleSpecifier), "default", clause.isTypeOnly);
863
+ const bindings = clause.namedBindings;
864
+ if (!bindings) return;
865
+ if (ts.isNamespaceImport(bindings)) {
866
+ add(wholeModule(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);
867
+ return;
868
+ }
869
+ if (bindings.elements.length === 0) add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);
870
+ for (const element of bindings.elements) {
871
+ add(declaring(element.name, node.moduleSpecifier), (element.propertyName ?? element.name).text, clause.isTypeOnly || element.isTypeOnly);
872
+ }
873
+ };
874
+ const visitExport = (node, specifier) => {
875
+ const clause = node.exportClause;
876
+ if (!clause || !ts.isNamedExports(clause)) {
877
+ add(wholeModule(specifier), WHOLE_MODULE, node.isTypeOnly);
878
+ return;
879
+ }
880
+ if (clause.elements.length === 0) add(loadedOnly(specifier), WHOLE_MODULE, node.isTypeOnly);
881
+ for (const element of clause.elements) {
882
+ add(declaring(element.name, specifier), (element.propertyName ?? element.name).text, node.isTypeOnly || element.isTypeOnly);
883
+ }
884
+ };
885
+ const visitImportType = (node) => {
886
+ if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) return;
887
+ const specifier = node.argument.literal;
888
+ let name = node.qualifier;
889
+ while (name && ts.isQualifiedName(name)) name = name.left;
890
+ if (name) add(declaring(name, specifier), name.text, true);
891
+ else add(wholeModule(specifier), WHOLE_MODULE, true);
892
+ };
893
+ const visitDynamicImport = (node) => {
894
+ const specifier = node.arguments.at(0);
895
+ if (!specifier) return;
896
+ if (ts.isStringLiteralLike(specifier)) add(wholeModule(specifier), WHOLE_MODULE, false);
897
+ else computed.push({ ...startOf(ts, sourceFile, specifier), specifier: specifier.getText(sourceFile) });
898
+ };
899
+ const visit = (node) => {
900
+ if (ts.isImportDeclaration(node)) visitImport(node);
901
+ else if (ts.isExportDeclaration(node) && node.moduleSpecifier) visitExport(node, node.moduleSpecifier);
902
+ else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
903
+ add(wholeModule(node.moduleReference.expression), WHOLE_MODULE, node.isTypeOnly);
904
+ } else if (ts.isImportTypeNode(node)) visitImportType(node);
905
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) visitDynamicImport(node);
906
+ ts.forEachChild(node, visit);
907
+ };
908
+ visit(sourceFile);
909
+ return { edges, computed };
910
+ }
911
+
912
+ // src/core/refactor-plan.ts
913
+ function indexGraph(files, dependencies) {
914
+ const sorted = [...new Set(files)].sort();
915
+ const indexOf = new Map(sorted.map((file, index) => [file, index]));
916
+ const imports = sorted.map((file, index) => {
917
+ const targets = /* @__PURE__ */ new Set();
918
+ for (const dependency of dependencies.get(file) ?? []) {
919
+ const target = indexOf.get(dependency);
920
+ if (target !== void 0 && target !== index) targets.add(target);
921
+ }
922
+ return [...targets].sort((a, b) => a - b);
923
+ });
924
+ return { files: sorted, imports };
925
+ }
926
+ function components(graph) {
927
+ const count = graph.files.length;
928
+ const order = new Array(count).fill(-1);
929
+ const low = new Array(count).fill(0);
930
+ const onStack = new Array(count).fill(false);
931
+ const stack = [];
932
+ const found = [];
933
+ let next = 0;
934
+ for (let root = 0; root < count; root += 1) {
935
+ if (order[root] !== -1) continue;
936
+ const frames = [];
937
+ const open = (file) => {
938
+ order[file] = next;
939
+ low[file] = next;
940
+ next += 1;
941
+ stack.push(file);
942
+ onStack[file] = true;
943
+ frames.push({ file, followed: 0 });
944
+ };
945
+ open(root);
946
+ while (frames.length > 0) {
947
+ const frame = frames[frames.length - 1];
948
+ const targets = graph.imports[frame.file];
949
+ if (frame.followed < targets.length) {
950
+ const target = targets[frame.followed];
951
+ frame.followed += 1;
952
+ if (order[target] === -1) open(target);
953
+ else if (onStack[target]) low[frame.file] = Math.min(low[frame.file], order[target]);
954
+ continue;
955
+ }
956
+ frames.pop();
957
+ if (frames.length > 0) {
958
+ const parent = frames[frames.length - 1].file;
959
+ low[parent] = Math.min(low[parent], low[frame.file]);
960
+ }
961
+ if (low[frame.file] !== order[frame.file]) continue;
962
+ const component = [];
963
+ for (; ; ) {
964
+ const member = stack.pop();
965
+ onStack[member] = false;
966
+ component.push(member);
967
+ if (member === frame.file) break;
968
+ }
969
+ found.push(component.sort((a, b) => a - b));
970
+ }
971
+ }
972
+ return found;
973
+ }
974
+ function firstFile(item) {
975
+ return typeof item === "string" ? item : item[0];
976
+ }
977
+ function byName(a, b) {
978
+ return a < b ? -1 : a > b ? 1 : 0;
979
+ }
980
+ function reaches(edges, from, to) {
981
+ const seen = /* @__PURE__ */ new Set([from]);
982
+ const queue = [from];
983
+ while (queue.length > 0) {
984
+ const file = queue.pop();
985
+ if (file === to) return true;
986
+ for (const target of edges.get(file) ?? []) {
987
+ if (seen.has(target)) continue;
988
+ seen.add(target);
989
+ queue.push(target);
990
+ }
991
+ }
992
+ return false;
993
+ }
994
+ function closingEdgesOf(graph, members, cost) {
995
+ if (members.length < 2) return [];
996
+ const inside = new Set(members);
997
+ const out = new Map(members.map((member) => [member, []]));
998
+ const into = new Map(members.map((member) => [member, []]));
999
+ const degree = new Map(members.map((member) => [member, { out: 0, in: 0, outCost: 0, inCost: 0 }]));
1000
+ const degreeOf = (member) => {
1001
+ return degree.get(member);
1002
+ };
1003
+ for (const member of members) {
1004
+ for (const target of graph.imports[member]) {
1005
+ if (!inside.has(target)) continue;
1006
+ out.get(member).push(target);
1007
+ into.get(target).push(member);
1008
+ const edgeCost = cost(member, target);
1009
+ degreeOf(member).out += 1;
1010
+ degreeOf(member).outCost += edgeCost;
1011
+ degreeOf(target).in += 1;
1012
+ degreeOf(target).inCost += edgeCost;
1013
+ }
1014
+ }
1015
+ const left = new Set(members);
1016
+ const first = [];
1017
+ const last = [];
1018
+ const gap = (member) => degreeOf(member).outCost - degreeOf(member).inCost;
1019
+ while (left.size > 0) {
1020
+ let sink;
1021
+ let source;
1022
+ let widest;
1023
+ for (const member of left) {
1024
+ if (degreeOf(member).out === 0) {
1025
+ sink = member;
1026
+ break;
1027
+ }
1028
+ if (source !== void 0) continue;
1029
+ if (degreeOf(member).in === 0) source = member;
1030
+ else if (widest === void 0 || gap(member) > gap(widest)) widest = member;
1031
+ }
1032
+ const picked = sink ?? source ?? widest;
1033
+ if (sink !== void 0) last.push(picked);
1034
+ else first.push(picked);
1035
+ left.delete(picked);
1036
+ for (const target of out.get(picked)) {
1037
+ degreeOf(target).in -= 1;
1038
+ degreeOf(target).inCost -= cost(picked, target);
1039
+ }
1040
+ for (const importer of into.get(picked)) {
1041
+ degreeOf(importer).out -= 1;
1042
+ degreeOf(importer).outCost -= cost(importer, picked);
1043
+ }
1044
+ }
1045
+ const position = new Map([...first, ...last.reverse()].map((member, index) => [member, index]));
1046
+ const kept = new Map(members.map((member) => [member, /* @__PURE__ */ new Set()]));
1047
+ const candidates = [];
1048
+ for (const member of members) {
1049
+ for (const target of out.get(member)) {
1050
+ if (position.get(member) > position.get(target)) candidates.push([member, target]);
1051
+ else kept.get(member).add(target);
1052
+ }
1053
+ }
1054
+ candidates.sort((a, b) => cost(b[0], b[1]) - cost(a[0], a[1]) || a[0] - b[0] || a[1] - b[1]);
1055
+ const closing = [];
1056
+ for (const [from, to] of candidates) {
1057
+ if (reaches(kept, to, from)) closing.push([from, to]);
1058
+ else kept.get(from).add(to);
1059
+ }
1060
+ return closing.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
1061
+ }
1062
+ function planGraph(graph, input) {
1063
+ const units = components(graph);
1064
+ const unitOf = new Array(graph.files.length).fill(0);
1065
+ units.forEach((members, unit) => {
1066
+ for (const member of members) unitOf[member] = unit;
1067
+ });
1068
+ const weight = input.weight;
1069
+ const cost = weight ? (from, to) => weight(graph.files[from], graph.files[to]) : () => 1;
1070
+ const depth = [];
1071
+ const waves = [];
1072
+ const cycles = [];
1073
+ const work = units.map((members) => members.map((member) => graph.files[member]).filter((file) => input.tasks.has(file)));
1074
+ units.forEach((members, unit) => {
1075
+ let below = 0;
1076
+ for (const member of members) {
1077
+ for (const target of graph.imports[member]) {
1078
+ const imported = unitOf[target];
1079
+ if (imported !== unit) below = Math.max(below, depth[imported] + (work[imported].length > 0 ? 1 : 0));
1080
+ }
1081
+ }
1082
+ depth[unit] = below;
1083
+ const tasks = work[unit];
1084
+ if (members.length > 1) {
1085
+ const files = members.map((member) => graph.files[member]);
1086
+ const closingEdges = closingEdgesOf(graph, members, cost).map(([from, to]) => ({ from: graph.files[from], to: graph.files[to] }));
1087
+ cycles.push({ size: files.length, files, tasks, tooLarge: files.length > input.maxGroupSize, closingEdges });
1088
+ }
1089
+ if (tasks.length === 0) return;
1090
+ while (waves.length <= below) waves.push([]);
1091
+ waves[below].push(tasks.length === 1 ? tasks[0] : tasks);
1092
+ });
1093
+ for (const wave of waves) wave.sort((a, b) => byName(firstFile(a), firstFile(b)));
1094
+ cycles.sort((a, b) => b.size - a.size || byName(a.files[0], b.files[0]));
1095
+ return { waves, cycles };
1096
+ }
1097
+ function planRefactor(input) {
1098
+ const graph = indexGraph(input.files, input.dependencies);
1099
+ const full = planGraph(graph, input);
1100
+ const carriesChange = input.carriesChange;
1101
+ if (!carriesChange || !full.cycles.some((cycle) => cycle.tooLarge)) return full;
1102
+ const groupOf = /* @__PURE__ */ new Map();
1103
+ full.cycles.forEach((cycle, index) => {
1104
+ if (cycle.tooLarge) for (const file of cycle.files) groupOf.set(file, index);
1105
+ });
1106
+ const dropped = /* @__PURE__ */ new Map();
1107
+ const kept = /* @__PURE__ */ new Map();
1108
+ const imports = graph.imports.map((targets, file) => {
1109
+ const group = groupOf.get(graph.files[file]);
1110
+ if (group === void 0) return targets;
1111
+ return targets.filter((target) => {
1112
+ if (groupOf.get(graph.files[target]) !== group) return true;
1113
+ const carries = carriesChange(graph.files[file], graph.files[target]);
1114
+ const counts = carries ? kept : dropped;
1115
+ counts.set(group, (counts.get(group) ?? 0) + 1);
1116
+ return carries;
1117
+ });
1118
+ });
1119
+ const pruned = planGraph({ files: graph.files, imports }, input);
1120
+ const cycles = full.cycles.map((cycle, index) => {
1121
+ if (!cycle.tooLarge) return cycle;
1122
+ const groups = pruned.cycles.filter((left) => groupOf.get(left.files[0]) === index);
1123
+ return { ...cycle, split: { droppedEdges: dropped.get(index) ?? 0, keptEdges: kept.get(index) ?? 0, groups } };
1124
+ });
1125
+ return { waves: pruned.waves, cycles };
1126
+ }
1127
+
1128
+ // src/cli/refactor-command.ts
1129
+ var DEFAULT_MAX_GROUP_SIZE = 8;
1130
+ var CHANGING_NAME_COST = 10;
1131
+ function hasFindings(byRule) {
1132
+ return Object.values(byRule).some((byOrigin) => Object.values(byOrigin).some((count) => count > 0));
1133
+ }
1134
+ function byName2(a, b) {
1135
+ return a < b ? -1 : a > b ? 1 : 0;
1136
+ }
1137
+ function internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) {
1138
+ const inGroup = new Set(group.files);
1139
+ const taskFiles = new Set(group.tasks);
1140
+ const calls = /* @__PURE__ */ new Map();
1141
+ const declarations = /* @__PURE__ */ new Set();
1142
+ const withFindings = /* @__PURE__ */ new Set();
1143
+ for (const file of group.files) {
1144
+ const entry = loaded.get(file);
1145
+ if (!entry) continue;
1146
+ const { ts, program, sourceFile } = entry;
1147
+ const checker = program.getTypeChecker();
1148
+ const policy = policyFor(ts, checker, config);
1149
+ for (const call of collectCalls(ts, policy, changeOracleFor(ts, checker, policy), sourceFile)) {
1150
+ const targetFile = keyOfTarget(policy.zones.virtualPaths.get(call.targetFile) ?? call.targetFile);
1151
+ if (targetFile === void 0 || !inGroup.has(targetFile)) continue;
1152
+ const from = `${file}#${call.from}`;
1153
+ const to = `${targetFile}#${call.to}`;
1154
+ if (from === to) continue;
1155
+ declarations.add(from).add(to);
1156
+ let callees = calls.get(from);
1157
+ if (!callees) {
1158
+ callees = /* @__PURE__ */ new Map();
1159
+ calls.set(from, callees);
1160
+ }
1161
+ callees.set(to, (callees.get(to) ?? 0) + 1);
1162
+ }
1163
+ if (!taskFiles.has(file)) continue;
1164
+ for (const finding of checkSourceFile({ ts, program, config, sourceFile })) {
1165
+ const declaration = `${file}#${declarationAt(ts, sourceFile, finding.line, finding.column)}`;
1166
+ declarations.add(declaration);
1167
+ withFindings.add(declaration);
1168
+ }
1169
+ }
1170
+ const callSites = (from, to) => calls.get(from)?.get(to) ?? 0;
1171
+ const incoming = /* @__PURE__ */ new Map();
1172
+ for (const callees of calls.values()) {
1173
+ for (const [callee, count] of callees) incoming.set(callee, (incoming.get(callee) ?? 0) + count);
1174
+ }
1175
+ const plan = planRefactor({
1176
+ files: [...declarations],
1177
+ dependencies: new Map([...calls].map(([from, callees]) => [from, [...callees.keys()]])),
1178
+ tasks: withFindings,
1179
+ maxGroupSize,
1180
+ weight: callSites
1181
+ });
1182
+ const recursion = plan.cycles.map((cycle) => {
1183
+ const cuts = [...new Set(cycle.closingEdges.map((edge) => edge.to))].map((declaration) => ({ declaration, callSites: incoming.get(declaration) ?? 0 })).sort((a, b) => a.callSites - b.callSites || byName2(a.declaration, b.declaration));
1184
+ return {
1185
+ size: cycle.size,
1186
+ declarations: cycle.files,
1187
+ tasks: cycle.tasks,
1188
+ files: [...new Set(cycle.files.map((declaration) => declaration.slice(0, declaration.indexOf("#"))))].sort(),
1189
+ closingEdges: cycle.closingEdges.map((edge) => ({ ...edge, callSites: callSites(edge.from, edge.to) })),
1190
+ freeze: cuts[0]
1191
+ };
1192
+ });
1193
+ return { order: plan.waves, recursion };
1194
+ }
1195
+ function formatItem(item, tooLarge) {
1196
+ if (typeof item === "string") return [` ${item}`];
1197
+ const how = tooLarge ? "circular imports, too large for one unit: follow its internal order below" : "circular imports, refactor together";
1198
+ return [` group of ${item.length} (${how}):`, ...item.map((file) => ` ${file}`)];
1199
+ }
1200
+ function formatClosingImport(edge) {
1201
+ return `closed by: ${edge.from} imports ${edge.names.join(", ")} from ${edge.to}`;
1202
+ }
1203
+ function formatDeclarations(item) {
1204
+ return typeof item === "string" ? item : `(${item.join(" + ")})`;
1205
+ }
1206
+ function formatRecursion(group, indent) {
1207
+ return [
1208
+ `${indent}${group.declarations.join(", ")}`,
1209
+ ...group.closingEdges.map((edge) => `${indent} closed by: ${edge.from} calls ${edge.to} (${edge.callSites} call site(s))`),
1210
+ `${indent} freeze a contract: write the return type of ${group.freeze.declaration} as a Result by hand (${group.freeze.callSites} call site(s) in the group); changes stop there`,
1211
+ `${indent} or iterate to a fixed point: refactor these declarations in passes until their inferred failure types stop growing (they only grow, so it ends)`
1212
+ ];
1213
+ }
1214
+ function formatRemaining(group, maxGroupSize, indent) {
1215
+ const tooLarge = group.tooLarge ? ` \u2014 still too large for one unit (more than ${maxGroupSize} files)` : "";
1216
+ const lines = [`${indent}${group.size} file(s), ${group.tasks.length} with findings${tooLarge}: ${group.files.join(", ")}`];
1217
+ for (const edge of group.closingEdges) lines.push(`${indent} ${formatClosingImport(edge)}`);
1218
+ const { order, recursion } = group;
1219
+ if (order) {
1220
+ const count = order.reduce((sum, wave) => sum + wave.reduce((inWave, item) => inWave + (typeof item === "string" ? 1 : item.length), 0), 0);
1221
+ lines.push(count === 0 ? `${indent} internal order: no declaration with findings` : `${indent} internal order of the ${count} declaration(s) with findings, callees first:`);
1222
+ order.forEach((wave, index) => lines.push(`${indent} ${index + 1}. ${wave.map(formatDeclarations).join(", ")}`));
1223
+ }
1224
+ if (recursion && recursion.length > 0) {
1225
+ lines.push(`${indent} mutual recursion (${recursion.length}): declarations that call each other in a circle, with two ways out`);
1226
+ for (const circle of recursion) lines.push(...formatRecursion(circle, `${indent} `));
1227
+ }
1228
+ return lines;
1229
+ }
1230
+ function formatCycle(cycle, maxGroupSize) {
1231
+ const tooLarge = cycle.tooLarge ? ` \u2014 too large for one unit (more than ${maxGroupSize} files)` : "";
1232
+ const lines = [` ${cycle.size} file(s), ${cycle.tasks.length} with findings${tooLarge}: ${cycle.files.join(", ")}`];
1233
+ for (const edge of cycle.closingEdges) lines.push(` ${formatClosingImport(edge)}`);
1234
+ const split = cycle.split;
1235
+ if (!split) return lines;
1236
+ const left = split.groups.length === 0 ? "no circular group left" : `${split.groups.length} circular group(s) left`;
1237
+ lines.push(` without the ${split.droppedEdges} import(s) that cannot carry a change (${split.keptEdges} kept): ${left}`);
1238
+ for (const group of split.groups) lines.push(...formatRemaining(group, maxGroupSize, " "));
1239
+ return lines;
1240
+ }
1241
+ function formatReport(report) {
1242
+ const { waves, cycles, warnings, summary } = report;
1243
+ const tooLarge = /* @__PURE__ */ new Set();
1244
+ for (const cycle of cycles) {
1245
+ for (const group of cycle.split ? cycle.split.groups : [cycle]) {
1246
+ if (group.tooLarge && group.tasks.length > 1) tooLarge.add(group.tasks[0]);
1247
+ }
1248
+ }
1249
+ const lines = [];
1250
+ waves.forEach((wave, index) => {
1251
+ lines.push(`Wave ${index + 1} of ${waves.length} (${wave.length} item(s)):`);
1252
+ for (const item of wave) lines.push(...formatItem(item, typeof item !== "string" && tooLarge.has(item[0])));
1253
+ });
1254
+ if (waves.length === 0) lines.push("No file with findings: nothing to refactor.");
1255
+ if (cycles.length > 0) {
1256
+ lines.push(`Circular import groups (${cycles.length}):`);
1257
+ for (const cycle of cycles) lines.push(...formatCycle(cycle, summary.maxGroupSize));
1258
+ }
1259
+ if (warnings.length > 0) {
1260
+ lines.push(`Computed import() the graph cannot follow (${warnings.length}):`);
1261
+ for (const warning of warnings) lines.push(` ${warning.file}:${warning.line}:${warning.column} import(${warning.specifier})`);
1262
+ }
1263
+ const source = summary.taskSource === "baseline" ? `the baseline ${summary.baseline}` : "a fresh check (no baseline file)";
1264
+ const imports = summary.valueOnly ? "value import(s)" : "import(s)";
1265
+ lines.push(
1266
+ `${summary.tasks} file(s) with findings in ${summary.items} work item(s) over ${waves.length} wave(s); ${summary.files} file(s) and ${summary.edges} ${imports} in the graph, ${summary.ignored} ignored file(s) skipped; findings from ${source}.`
1267
+ );
1268
+ return lines;
1269
+ }
1270
+ async function runRefactorCommand(options) {
1271
+ const maxGroupSize = options.maxGroupSize ?? DEFAULT_MAX_GROUP_SIZE;
1272
+ if (!Number.isInteger(maxGroupSize) || maxGroupSize < 1) {
1273
+ options.log("trust refactor: --max-group needs a whole number of files, 1 or more");
1274
+ return 2;
1275
+ }
1276
+ const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
1277
+ if ("missing" in resolved) {
1278
+ options.log(`trust refactor: no such file or directory: ${resolved.missing}`);
1279
+ return 2;
1280
+ }
1281
+ const configPath = resolve6(options.cwd, options.configFile);
1282
+ const rootDir = options.root === void 0 ? void 0 : resolve6(options.cwd, options.root);
1283
+ const config = existsSync3(configPath) ? loadTrustConfig(configPath, { rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
1284
+ logUnmatchedGlobs(options.log, "refactor", config);
1285
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
1286
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
1287
+ const baselineFile = resolve6(options.cwd, options.baselineFile ?? join3(config.rootDir, "trust-baseline.json"));
1288
+ const fromBaseline = existsSync3(baselineFile);
1289
+ if (!fromBaseline && options.baselineFile !== void 0) {
1290
+ options.log(`trust refactor: no such baseline: ${options.baselineFile}`);
1291
+ return 2;
1292
+ }
1293
+ const baseline = readBaseline(baselineFile);
1294
+ if ("error" in baseline) {
1295
+ options.log(`trust refactor: could not read the baseline: ${baseline.error}`);
1296
+ return 2;
1297
+ }
1298
+ const keyByPath = /* @__PURE__ */ new Map();
1299
+ for (const file of files) {
1300
+ const key = relativeTo(config.rootDir, file);
1301
+ keyByPath.set(file, key);
1302
+ keyByPath.set(realpathOrSelf(file), key);
1303
+ }
1304
+ const keyOfTarget = (target) => {
1305
+ if (!keyByPath.has(target)) {
1306
+ const key = keyByPath.get(realpathOrSelf(target));
1307
+ if (key === void 0) return void 0;
1308
+ keyByPath.set(target, key);
1309
+ }
1310
+ return keyByPath.get(target);
1311
+ };
1312
+ const outside = /* @__PURE__ */ new Set();
1313
+ const dependencies = /* @__PURE__ */ new Map();
1314
+ const imported = /* @__PURE__ */ new Map();
1315
+ const loaded = /* @__PURE__ */ new Map();
1316
+ const warnings = [];
1317
+ const checked = /* @__PURE__ */ new Set();
1318
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
1319
+ const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile, file }) => {
1320
+ const from = relativeTo(config.rootDir, file);
1321
+ const checker = program.getTypeChecker();
1322
+ const imports = collectImports(ts, program, sourceFile, changeOracleFor(ts, checker, policyFor(ts, checker, config)));
1323
+ const targets = /* @__PURE__ */ new Map();
1324
+ for (const edge of imports.edges) {
1325
+ if (options.valueOnly && edge.typeOnly || outside.has(edge.target)) continue;
1326
+ const to = keyOfTarget(policyFor(ts, checker, config).zones.virtualPaths.get(edge.target) ?? edge.target);
1327
+ if (to === void 0) outside.add(edge.target);
1328
+ if (to === void 0 || to === from) continue;
1329
+ let names = targets.get(to);
1330
+ if (!names) {
1331
+ names = { all: /* @__PURE__ */ new Set(), changing: /* @__PURE__ */ new Set() };
1332
+ targets.set(to, names);
1333
+ }
1334
+ names.all.add(edge.name);
1335
+ if (edge.carriesChange) names.changing.add(edge.name);
1336
+ }
1337
+ dependencies.set(from, new Set(targets.keys()));
1338
+ imported.set(from, targets);
1339
+ loaded.set(from, { ts, program, sourceFile });
1340
+ for (const computed of imports.computed) {
1341
+ const position = svelteFor(checker)?.position(sourceFile.fileName, computed);
1342
+ if (position !== null) warnings.push({ kind: "computed-import", file: from, ...computed, ...position });
1343
+ }
1344
+ if (!fromBaseline && checkSourceFile({ ts, program, config, sourceFile }).length > 0) checked.add(from);
1345
+ });
1346
+ if (walk.status !== "ok") {
1347
+ logWalkFailure(options.log, "refactor", walk);
1348
+ return 2;
1349
+ }
1350
+ const nodes = [...dependencies.keys()];
1351
+ const tasks = fromBaseline ? new Set(nodes.filter((file) => Object.hasOwn(baseline.counts, file) && hasFindings(baseline.counts[file]))) : checked;
1352
+ warnings.sort((a, b) => a.file !== b.file ? a.file < b.file ? -1 : 1 : a.line - b.line || a.column - b.column);
1353
+ const cutCost = (from, to) => {
1354
+ const names = imported.get(from)?.get(to);
1355
+ return names ? names.changing.size * CHANGING_NAME_COST + (names.all.size - names.changing.size) : 1;
1356
+ };
1357
+ const plan = planRefactor({
1358
+ files: nodes,
1359
+ dependencies,
1360
+ tasks,
1361
+ maxGroupSize,
1362
+ weight: cutCost,
1363
+ carriesChange: (from, to) => (imported.get(from)?.get(to)?.changing.size ?? 1) > 0
1364
+ });
1365
+ const closing = (edges, which) => {
1366
+ return edges.map(({ from, to }) => ({ from, to, names: [...imported.get(from)?.get(to)?.[which] ?? []].sort() }));
1367
+ };
1368
+ const remaining = (group) => ({
1369
+ size: group.size,
1370
+ files: group.files,
1371
+ tasks: group.tasks,
1372
+ tooLarge: group.tooLarge,
1373
+ closingEdges: closing(group.closingEdges, "changing"),
1374
+ ...group.tooLarge ? internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) : {}
1375
+ });
1376
+ const cycles = plan.cycles.map((cycle) => {
1377
+ const split = cycle.split;
1378
+ return {
1379
+ size: cycle.size,
1380
+ files: cycle.files,
1381
+ tasks: cycle.tasks,
1382
+ tooLarge: cycle.tooLarge,
1383
+ closingEdges: closing(cycle.closingEdges, "all"),
1384
+ ...split ? { split: { droppedEdges: split.droppedEdges, keptEdges: split.keptEdges, groups: split.groups.map(remaining) } } : {}
1385
+ };
1386
+ });
1387
+ const report = {
1388
+ waves: plan.waves,
1389
+ cycles,
1390
+ warnings,
1391
+ summary: {
1392
+ files: nodes.length,
1393
+ edges: [...dependencies.values()].reduce((sum, targets) => sum + targets.size, 0),
1394
+ tasks: tasks.size,
1395
+ items: plan.waves.reduce((sum, wave) => sum + wave.length, 0),
1396
+ ignored: resolved.files.length - files.length,
1397
+ taskSource: fromBaseline ? "baseline" : "check",
1398
+ baseline: fromBaseline ? baselineFile : null,
1399
+ valueOnly: options.valueOnly,
1400
+ maxGroupSize
1401
+ }
1402
+ };
1403
+ if (options.json) options.log(JSON.stringify(report, null, 2));
1404
+ else for (const line of formatReport(report)) options.log(line);
1405
+ return 0;
1406
+ }
1407
+
146
1408
  // src/cli/index.ts
147
1409
  var USAGE = `Usage:
148
- trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>]
149
- Print the origin each call on that line resolves to, and why it is (un)trusted.
150
- trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update]
151
- Lint with the project's ESLint config and fail on trust violations not in the baseline.
152
- --update rewrites the baseline from the current findings.`;
1410
+ trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]
1411
+ Print the origin each call on that line resolves to, and why it is (un)trusted: for failing
1412
+ ("trust" / "distrust") and for its types ("trust_type" / "distrust_type").
1413
+ Also prints every type claim starting on that line (type-claim): its kind and why it is a claim,
1414
+ and every untrusted value starting on it (untrusted-value): how it entered, the origin that
1415
+ declared its type, and whether its use is reported.
1416
+ trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig <path>] [--root <dir>]
1417
+ Check the files with TypeScript alone (no ESLint) and fail on trust violations not in the baseline.
1418
+ Files are found and skipped as in trust check; --update rewrites the baseline from the current findings.
1419
+ With paths, only the checked files' entries are reported as shrunk or rewritten by --update.
1420
+ trust check <paths...> [--strict] [--perf] [--json] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]
1421
+ Check with the native Rust engine (bundled Wasm fallback); .svelte conversion uses TypeScript in Node.
1422
+ Each file uses --tsconfig if given, else the first matching "tsconfig" entry of the trust config,
1423
+ else the nearest tsconfig.json above it.
1424
+ Files in the config's ignore zone are skipped. --strict also fails on written return types
1425
+ in every checked file; the config's "strict" globs do the same for the files they match.
1426
+ --perf adds performance warnings, which never fail the check. --json emits findings with severity.
1427
+ Exit codes: 0 clean or warnings only, 1 trust errors, 2 the check could not run.
1428
+ trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig <path>] [--root <dir>]
1429
+ Print the order to refactor the files with findings in: waves of work items, leaves of the import
1430
+ graph first. The items of a wave can be done in parallel; a circular-import group is one item.
1431
+ Findings come from the baseline, or from a fresh check when there is no baseline file.
1432
+ --json prints { "waves": [["a.ts", ["b.ts", "c.ts"]], ["d.ts"]], ... }; --value-only leaves
1433
+ type-only imports out of the graph. Every circular group lists the imports that close it.
1434
+ A circular group of more than --max-group <n> files (default 8) is too large for one item: the
1435
+ imports inside it that cannot carry a change (an interface, a constant, a written Result return
1436
+ type) are dropped; what is still too large gets an internal order of its declarations, callees
1437
+ first, and declarations that call each other in a circle are reported with the calls closing it.
1438
+ --root <dir> resolves the config's globs, tsconfig paths and baseline keys against <dir> instead of
1439
+ the config file's directory (for a config kept outside the project).`;
1440
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["update", "help", "strict", "json", "value-only", "perf"]);
153
1441
  function parseArgs(argv) {
154
1442
  const positional = [];
155
1443
  const flags = /* @__PURE__ */ new Map();
@@ -160,8 +1448,11 @@ function parseArgs(argv) {
160
1448
  continue;
161
1449
  }
162
1450
  const [name, inline] = arg.slice(2).split("=", 2);
1451
+ if (name === "rs" || name === "go") throw new Error("--rs and --go were removed; trust check uses the native engine automatically");
1452
+ if (!BOOLEAN_FLAGS.has(name) && !["config", "tsconfig", "root", "baseline", "max-group"].includes(name)) throw new Error(`unknown flag --${name}`);
1453
+ if (BOOLEAN_FLAGS.has(name) && inline !== void 0) throw new Error(`--${name} does not take a value`);
163
1454
  if (inline !== void 0) flags.set(name, inline);
164
- else if (name === "update" || name === "help") flags.set(name, true);
1455
+ else if (BOOLEAN_FLAGS.has(name)) flags.set(name, true);
165
1456
  else {
166
1457
  const value = argv[index + 1];
167
1458
  if (value === void 0) throw new Error(`--${name} needs a value`);
@@ -192,7 +1483,12 @@ async function main(argv) {
192
1483
  if (command === "explain") {
193
1484
  if (positional.length !== 1) throw new Error("explain takes exactly one <file>:<line>[:<column>]");
194
1485
  const location = parseLocation(positional[0]);
195
- console.log(formatExplanation(explain({ cwd, configFile, tsconfig: stringFlag(flags, "tsconfig"), ...location })));
1486
+ const explained = explain({ cwd, configFile, tsconfig: stringFlag(flags, "tsconfig"), root: stringFlag(flags, "root"), ...location });
1487
+ if (explained.kind !== "explained") {
1488
+ console.error(`trust explain: ${explained.message}`);
1489
+ return 2;
1490
+ }
1491
+ console.log(formatExplanation(explained.explanation));
196
1492
  return 0;
197
1493
  }
198
1494
  if (command === "baseline") {
@@ -202,6 +1498,36 @@ async function main(argv) {
202
1498
  configFile,
203
1499
  baselineFile: stringFlag(flags, "baseline"),
204
1500
  update: flags.get("update") === true,
1501
+ tsconfig: stringFlag(flags, "tsconfig"),
1502
+ root: stringFlag(flags, "root"),
1503
+ log: (line) => console.log(line)
1504
+ });
1505
+ }
1506
+ if (command === "check") {
1507
+ return runCheckCommand({
1508
+ cwd,
1509
+ paths: positional,
1510
+ configFile,
1511
+ strict: flags.get("strict") === true,
1512
+ tsconfig: stringFlag(flags, "tsconfig"),
1513
+ root: stringFlag(flags, "root"),
1514
+ perf: flags.get("perf") === true,
1515
+ json: flags.get("json") === true,
1516
+ log: (line) => console.log(line)
1517
+ });
1518
+ }
1519
+ if (command === "refactor") {
1520
+ const maxGroup = stringFlag(flags, "max-group");
1521
+ return runRefactorCommand({
1522
+ cwd,
1523
+ paths: positional,
1524
+ configFile,
1525
+ baselineFile: stringFlag(flags, "baseline"),
1526
+ json: flags.get("json") === true,
1527
+ valueOnly: flags.get("value-only") === true,
1528
+ maxGroupSize: maxGroup === void 0 ? void 0 : Number(maxGroup),
1529
+ tsconfig: stringFlag(flags, "tsconfig"),
1530
+ root: stringFlag(flags, "root"),
205
1531
  log: (line) => console.log(line)
206
1532
  });
207
1533
  }