@noego/trust 0.4.0 → 0.5.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,75 +1,199 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  TrustPolicy,
4
+ callTypeVerdict,
5
+ checkSourceFile,
6
+ checkSourceFileWithAccepted,
7
+ claimSpan,
8
+ emptyTrustConfig,
9
+ guardCallOf,
10
+ policyFor,
11
+ positionAt,
12
+ startOf,
13
+ typeClaimContext,
14
+ typeClaimMessage,
15
+ typeClaimsIn,
16
+ untrustedValueContext,
17
+ untrustedValueMessage,
18
+ untrustedValuesIn
19
+ } from "../chunk-V72KWVWP.js";
20
+ import {
21
+ compareFindings,
22
+ createPrograms,
23
+ forEachSourceFile,
24
+ formatFinding,
25
+ logWalkFailure,
26
+ relativeTo,
27
+ resolveFiles,
28
+ sourceFileOf
29
+ } from "../chunk-OSSITT3R.js";
30
+ import {
31
+ DROPPED_RESULT_RULE,
32
+ TYPE_CLAIM_RULE,
33
+ UNTRUSTED_ENTRY_LABELS,
34
+ UNTRUSTED_VALUE_RULE,
35
+ WHOLE_BASELINE,
36
+ Zones,
4
37
  compareToBaseline,
5
- countFindings,
6
- fatalMessages,
7
- findingsFromResults,
38
+ describeBaselineDelta,
39
+ groupMatches,
40
+ isRuleEnabled,
8
41
  loadTrustConfig,
9
42
  loadTypeScript,
10
- parseBaseline,
43
+ readBaseline,
11
44
  realpathOrSelf,
12
- serializeBaseline
13
- } from "../chunk-YJYGTNJD.js";
45
+ serializeBaseline,
46
+ updateBaseline
47
+ } from "../chunk-NG4KYWVW.js";
14
48
 
15
49
  // src/cli/baseline-command.ts
16
- import { existsSync, readFileSync, writeFileSync } from "fs";
17
- import { createRequire } from "module";
50
+ import { existsSync, writeFileSync } from "fs";
18
51
  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
52
  async function runBaselineCommand(options) {
28
- const config = loadTrustConfig(resolve(options.cwd, options.configFile));
53
+ const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
54
+ if ("missing" in resolved) {
55
+ options.log(`trust baseline: no such file or directory: ${resolved.missing}`);
56
+ return 2;
57
+ }
58
+ const configPath = resolve(options.cwd, options.configFile);
59
+ const rootDir = options.root === void 0 ? void 0 : resolve(options.cwd, options.root);
60
+ const config = existsSync(configPath) ? loadTrustConfig(configPath, { validateGlobs: false, rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
29
61
  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}`);
62
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
63
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
64
+ const scope = options.paths.length === 0 ? WHOLE_BASELINE : { kind: "files", files: new Set(files.map((file) => relativeTo(config.rootDir, file))) };
65
+ const findings = [];
66
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
67
+ const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile }) => {
68
+ findings.push(...checkSourceFile({ ts, program, config, sourceFile }));
69
+ });
70
+ if (walk.status !== "ok") {
71
+ logWalkFailure(options.log, "baseline", walk);
72
+ return 2;
73
+ }
74
+ const baseline = options.update && scope.kind === "all" ? { counts: {} } : readBaseline(baselineFile);
75
+ if ("error" in baseline) {
76
+ options.log(`trust baseline: could not read the baseline: ${baseline.error}`);
37
77
  return 2;
38
78
  }
39
- const findings = findingsFromResults(results, config.rootDir);
40
79
  if (options.update) {
41
- writeFileSync(baselineFile, serializeBaseline(countFindings(findings)));
42
- options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${results.length} linted file(s).`);
80
+ const updated = updateBaseline(baseline.counts, findings, scope);
81
+ writeFileSync(baselineFile, serializeBaseline(updated.counts));
82
+ const kept = updated.kept > 0 ? ` Kept the entries of ${updated.kept} unchecked file(s).` : "";
83
+ options.log(`Wrote ${baselineFile}: ${findings.length} finding(s) in ${files.length} checked file(s).${kept}`);
43
84
  return 0;
44
85
  }
45
- const baseline = existsSync(baselineFile) ? parseBaseline(readFileSync(baselineFile, "utf8"), baselineFile) : {};
46
- const { added, stale } = compareToBaseline(findings, baseline);
86
+ const { added, stale } = compareToBaseline(findings, baseline.counts, scope);
47
87
  if (stale.length > 0) {
48
88
  options.log(`${stale.length} baseline entr${stale.length === 1 ? "y has" : "ies have"} fewer findings now; run with --update to shrink the baseline.`);
49
89
  }
50
90
  if (added.length === 0) {
51
- options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${results.length} file(s)).`);
91
+ options.log(`No new @noego/trust violations (${findings.length} baselined finding(s), ${files.length} file(s)).`);
52
92
  return 0;
53
93
  }
54
94
  const count = added.reduce((sum, delta) => sum + delta.found - delta.allowed, 0);
55
95
  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}`);
96
+ for (const delta of added) for (const line of describeBaselineDelta(delta)) options.log(` ${line}`);
57
97
  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.");
98
+ const hasTypeClaims = added.some((delta) => delta.rule === TYPE_CLAIM_RULE);
99
+ if (hasTypeClaims) options.log("Prove each claimed type (narrow or validate the value) instead of asserting it.");
100
+ const hasUntrustedValues = added.some((delta) => delta.rule === UNTRUSTED_VALUE_RULE);
101
+ if (hasUntrustedValues) {
102
+ 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.');
103
+ }
104
+ if (added.some((delta) => delta.rule === DROPPED_RESULT_RULE)) {
105
+ options.log("Return each dropped failure (`if (!r.ok) return r;`) or handle it with Trust.decide.");
106
+ }
107
+ const alsoShows = `${hasTypeClaims ? ", and why a line is a type claim" : ""}${hasUntrustedValues ? ", and where an untrusted value comes from" : ""}`;
108
+ options.log(`\`trust explain <file>:<line>\` shows which origin a call resolves to${alsoShows}.`);
59
109
  return 1;
60
110
  }
61
111
 
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"));
112
+ // src/cli/check-command.ts
113
+ import { existsSync as existsSync2 } from "fs";
114
+ import { resolve as resolve2 } from "path";
115
+
116
+ // src/cli/no-written-return-type.ts
117
+ var NO_WRITTEN_RETURN_TYPE_RULE = "no-written-return-type";
118
+ function isReportedKind(ts, node) {
119
+ return ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodDeclaration(node) || ts.isGetAccessorDeclaration(node);
120
+ }
121
+ function functionName(ts, node, sourceFile) {
122
+ if (ts.isArrowFunction(node)) return "(arrow function)";
123
+ const name = node.name;
124
+ if (!name) return "(anonymous function)";
125
+ if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {
126
+ return name.text;
127
+ }
128
+ return name.getText(sourceFile);
129
+ }
130
+ function findWrittenReturnTypes(ts, sourceFile) {
131
+ if (sourceFile.isDeclarationFile) return [];
132
+ const findings = [];
133
+ const visit = (node) => {
134
+ if (isReportedKind(ts, node) && node.body && node.type && node.type.kind !== ts.SyntaxKind.TypePredicate) {
135
+ const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.type.getStart(sourceFile));
136
+ findings.push({
137
+ rule: NO_WRITTEN_RETURN_TYPE_RULE,
138
+ line: line + 1,
139
+ column: character + 1,
140
+ message: `${functionName(ts, node, sourceFile)}: delete the return type annotation; the return type is inferred`
141
+ });
142
+ }
143
+ ts.forEachChild(node, visit);
144
+ };
145
+ visit(sourceFile);
146
+ return findings;
147
+ }
148
+
149
+ // src/cli/check-command.ts
150
+ async function runCheckCommand(options) {
151
+ if (options.paths.length === 0) {
152
+ options.log("trust check needs at least one path: trust check <paths...> [--strict] [--config trust.config.json] [--tsconfig <path>]");
153
+ return 2;
154
+ }
155
+ const resolved = resolveFiles(options.cwd, options.paths);
156
+ if ("missing" in resolved) {
157
+ options.log(`trust check: no such file or directory: ${resolved.missing}`);
158
+ return 2;
159
+ }
160
+ const configPath = resolve2(options.cwd, options.configFile);
161
+ const rootDir = options.root === void 0 ? void 0 : resolve2(options.cwd, options.root);
162
+ const config = existsSync2(configPath) ? loadTrustConfig(configPath, { validateGlobs: false, rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
163
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
164
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
165
+ const skipped = resolved.files.length - files.length;
166
+ const strictByConfig = new Set(
167
+ files.filter((file) => {
168
+ const real = realpathOrSelf(file);
169
+ return config.strict.some((group) => groupMatches(group, real));
170
+ })
171
+ );
172
+ const findings = [];
173
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
174
+ const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile, file }) => {
175
+ findings.push(...checkSourceFile({ ts, program, config, sourceFile }));
176
+ if (options.strict || strictByConfig.has(file)) {
177
+ const relative = relativeTo(config.rootDir, file);
178
+ findings.push(...findWrittenReturnTypes(ts, sourceFile).map((finding) => ({ file: relative, ...finding })));
70
179
  }
71
180
  });
72
- return parsed?.options ?? {};
181
+ if (walk.status !== "ok") {
182
+ logWalkFailure(options.log, "check", walk);
183
+ return 2;
184
+ }
185
+ findings.sort(compareFindings);
186
+ for (const finding of findings) options.log(formatFinding(finding));
187
+ const strictNote = options.strict ? " (strict)" : strictByConfig.size > 0 ? ` (${strictByConfig.size} strict by config)` : "";
188
+ options.log(`${findings.length} finding(s) in ${files.length} checked file(s), ${skipped} ignored file(s) skipped${strictNote}.`);
189
+ return findings.length > 0 ? 1 : 0;
190
+ }
191
+
192
+ // src/cli/explain.ts
193
+ import { resolve as resolve3 } from "path";
194
+ function clipText(raw) {
195
+ const text = raw.replace(/\s+/g, " ");
196
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
73
197
  }
74
198
  function declaredAt(ts, policy, node) {
75
199
  const resolved = policy.calleeDeclaration(node);
@@ -78,27 +202,43 @@ function declaredAt(ts, policy, node) {
78
202
  const { line } = ts.getLineAndCharacterOfPosition(source, resolved.declaration.getStart(source));
79
203
  return `${source.fileName}:${line + 1}`;
80
204
  }
205
+ function explainGuard(call, source, context) {
206
+ const guard = guardCallOf(call, context);
207
+ return guard ? { predicate: guard.predicate, narrows: clipText(guard.argument.getText(source)), asserts: guard.asserts, verdict: guard.verdict } : null;
208
+ }
209
+ var NOT_REPORTED = {
210
+ 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",
211
+ "no-claim": "not reported: its type claims nothing (`unknown`, `any`, an empty type or a function)",
212
+ validator: "not reported: it is inside a validator"
213
+ };
81
214
  function explain(options) {
82
215
  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));
216
+ const file = resolve3(options.cwd, options.file);
217
+ const rootDir = options.root === void 0 ? void 0 : resolve3(options.cwd, options.root);
218
+ const config = loadTrustConfig(resolve3(options.cwd, options.configFile), { rootDir });
219
+ const creation = createPrograms(ts, options.cwd, [file], options.tsconfig, config.tsconfig);
220
+ if (creation.kind !== "created") return creation;
221
+ const [{ program }] = creation.groups;
222
+ const source = sourceFileOf(program, file);
87
223
  if (!source) throw new Error(`could not load ${file} into a TypeScript program`);
88
224
  const checker = program.getTypeChecker();
89
- const policy = new TrustPolicy(ts, checker, loadTrustConfig(resolve2(options.cwd, options.configFile)));
225
+ const policy = new TrustPolicy(ts, checker, config);
226
+ const valueContext = untrustedValueContext(ts, checker, policy);
227
+ const here = (position) => {
228
+ const onLine = position.line === options.line;
229
+ return onLine && (options.column === void 0 || position.column === options.column) ? position : null;
230
+ };
90
231
  const calls = [];
91
232
  const visit = (node) => {
92
233
  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, " ");
234
+ const position = here(startOf(ts, source, node));
235
+ if (position) {
97
236
  calls.push({
98
- line: position.line + 1,
99
- column: position.character + 1,
100
- text: text.length > 80 ? `${text.slice(0, 77)}...` : text,
237
+ ...position,
238
+ text: clipText(node.getText(source)),
101
239
  verdict: policy.classify(node),
240
+ typeTrust: callTypeVerdict(node, valueContext),
241
+ guard: ts.isCallExpression(node) ? explainGuard(node, source, valueContext) : null,
102
242
  declaredAt: declaredAt(ts, policy, node)
103
243
  });
104
244
  }
@@ -106,7 +246,33 @@ function explain(options) {
106
246
  ts.forEachChild(node, visit);
107
247
  };
108
248
  visit(source);
109
- return { file, zone: policy.zones.zoneOf(file), calls };
249
+ const claimsOn = isRuleEnabled(config, TYPE_CLAIM_RULE);
250
+ const valuesOn = isRuleEnabled(config, UNTRUSTED_VALUE_RULE);
251
+ const explained = [TYPE_CLAIM_RULE, UNTRUSTED_VALUE_RULE];
252
+ const off = explained.filter((rule) => !isRuleEnabled(config, rule));
253
+ const claims = (claimsOn ? typeClaimsIn(source, typeClaimContext(ts, checker, void 0, policy)) : []).flatMap((claim) => {
254
+ const span = claimSpan(claim, source);
255
+ const position = here(positionAt(ts, source, span.start));
256
+ return position ? [{ ...position, text: clipText(source.text.slice(span.start, span.end)), origin: claim.origin, why: typeClaimMessage(claim) }] : [];
257
+ });
258
+ const found = valuesOn ? untrustedValuesIn(source, valueContext) : [];
259
+ const valueNodes = new Set(found.map((value) => value.node));
260
+ const isReadThrough = (node) => (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node && valueNodes.has(node.parent);
261
+ const isCall = (node) => ts.isCallExpression(node) || ts.isNewExpression(node);
262
+ const values = found.flatMap((value) => {
263
+ const position = here(startOf(ts, source, value.node));
264
+ if (!position || isReadThrough(value.node) || value.outcome === "no-claim" && isCall(value.node)) return [];
265
+ const why = value.outcome === "finding" ? untrustedValueMessage(value) : NOT_REPORTED[value.outcome];
266
+ return [{ ...position, text: clipText(value.node.getText(source)), entry: value.entry, origin: value.origin, type: value.type, outcome: value.outcome, why }];
267
+ });
268
+ const accepted = checkSourceFileWithAccepted({ ts, program, checker, config, sourceFile: source }).accepted.flatMap((entry) => {
269
+ const { finding, acceptance } = entry;
270
+ const position = here({ line: finding.line, column: finding.column });
271
+ if (!position) return [];
272
+ const directiveLine = positionAt(ts, source, acceptance.directive.pos).line;
273
+ return [{ ...position, text: clipText(entry.text), rule: finding.rule, origin: finding.origin, why: finding.message, reason: acceptance.reason, directiveLine }];
274
+ });
275
+ return { kind: "explained", explanation: { file, zone: policy.zones.zoneOf(file), calls, claims, values, accepted, off } };
110
276
  }
111
277
  function describe(verdict) {
112
278
  switch (verdict.kind) {
@@ -131,25 +297,903 @@ function describe(verdict) {
131
297
  ];
132
298
  }
133
299
  }
300
+ function describeTypeTrust(verdict) {
301
+ switch (verdict.kind) {
302
+ case "unresolved":
303
+ return [];
304
+ case "first-party":
305
+ return ["types: trusted (first-party code in a checked file is checked itself)"];
306
+ case "trust-package":
307
+ return ["types: trusted (declared by @noego/trust)"];
308
+ case "validator":
309
+ return ["types: trusted (the callee is a validator: //trust:validator_function)"];
310
+ case "type-trusted":
311
+ return [`types: type-trusted by "${verdict.by.entry}" in ${verdict.by.source}`];
312
+ case "caller-chosen-generic":
313
+ return [
314
+ "types: UNTRUSTED (the call picks its own return type: a type parameter found only in the return position, which no type trust proves)",
315
+ " validate the returned value"
316
+ ];
317
+ case "type-untrusted":
318
+ return [
319
+ verdict.distrustedBy ? `types: UNTRUSTED (type-distrusted by "${verdict.distrustedBy.entry}" in ${verdict.distrustedBy.source})` : "types: UNTRUSTED (no trust_type entry matches)",
320
+ ` validate what it returns, or add "${verdict.origin.origin}" (or a prefix of it) to "trust_type" in trust.config.json`
321
+ ];
322
+ }
323
+ }
324
+ function describeGuard(guard) {
325
+ const head = `guard: ${guard.asserts ? "asserts" : "narrows"} "${guard.narrows}" (${guard.predicate}), declared by "${guard.verdict.origin.origin}"`;
326
+ switch (guard.verdict.kind) {
327
+ case "first-party":
328
+ return [head, " not an untrusted value: first-party code in a checked file (its written predicate is a type claim, rule type-claim)"];
329
+ case "trust-package":
330
+ return [head, " trusted (declared by @noego/trust)"];
331
+ case "validator":
332
+ return [head, " trusted (the guard is a validator: //trust:validator_function)"];
333
+ case "built-in":
334
+ return [head, " trusted (a built-in check)"];
335
+ case "type-trusted":
336
+ return [head, ` type-trusted by "${guard.verdict.by.entry}" in ${guard.verdict.by.source}`];
337
+ case "type-untrusted":
338
+ return [
339
+ head,
340
+ 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})`,
341
+ ` validate the value instead, or add "${guard.verdict.origin.origin}" (or a prefix of it) to "trust_type" in trust.config.json`
342
+ ];
343
+ }
344
+ }
134
345
  function formatExplanation(explanation) {
135
346
  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");
347
+ if (explanation.zone !== "checked") {
348
+ lines.push("note: calls, type claims and untrusted values in this file are not checked (only checked-zone files are linted)");
349
+ }
350
+ for (const rule of explanation.off) {
351
+ 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`);
352
+ }
353
+ if (explanation.calls.length === 0 && explanation.claims.length === 0 && explanation.values.length === 0 && explanation.accepted.length === 0) {
354
+ lines.push("no call, `new` expression, type claim or untrusted value starts at that location");
355
+ }
356
+ for (const accepted of explanation.accepted) {
357
+ lines.push("", `${accepted.line}:${accepted.column} ${accepted.text}`);
358
+ lines.push(` accepted: ${accepted.rule} (${accepted.origin}) by //trust:accept on line ${accepted.directiveLine}`);
359
+ lines.push(` reason: ${accepted.reason}`);
360
+ lines.push(` finding: ${accepted.why}`);
361
+ }
138
362
  for (const call of explanation.calls) {
139
363
  lines.push("", `${call.line}:${call.column} ${call.text}`);
140
364
  for (const detail of describe(call.verdict)) lines.push(` ${detail}`);
365
+ for (const detail of describeTypeTrust(call.typeTrust)) lines.push(` ${detail}`);
366
+ if (call.guard) for (const detail of describeGuard(call.guard)) lines.push(` ${detail}`);
141
367
  if (call.declaredAt) lines.push(` declared: ${call.declaredAt}`);
142
368
  }
369
+ for (const claim of explanation.claims) {
370
+ lines.push("", `${claim.line}:${claim.column} ${claim.text}`);
371
+ lines.push(` claim: ${claim.origin} (rule ${TYPE_CLAIM_RULE})`);
372
+ lines.push(` why: ${claim.why}`);
373
+ }
374
+ for (const value of explanation.values) {
375
+ lines.push("", `${value.line}:${value.column} ${value.text}`);
376
+ lines.push(` value: untrusted "${value.type}", ${UNTRUSTED_ENTRY_LABELS[value.entry]} "${value.origin}" (rule ${UNTRUSTED_VALUE_RULE})`);
377
+ lines.push(` use: ${value.why}`);
378
+ }
143
379
  return lines.join("\n");
144
380
  }
145
381
 
382
+ // src/cli/refactor-command.ts
383
+ import { existsSync as existsSync3 } from "fs";
384
+ import { join as join2, resolve as resolve4 } from "path";
385
+
386
+ // src/core/call-graph.ts
387
+ var TOP_LEVEL = "(top level)";
388
+ function memberName(ts, member) {
389
+ if (ts.isConstructorDeclaration(member)) return "constructor";
390
+ const name = member.name;
391
+ if (!name) return void 0;
392
+ return ts.isIdentifier(name) || ts.isPrivateIdentifier(name) || ts.isStringLiteralLike(name) || ts.isNumericLiteral(name) ? name.text : void 0;
393
+ }
394
+ function nameIn(ts, chain, index, prefix) {
395
+ const statement = chain[index];
396
+ if (ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || ts.isEnumDeclaration(statement)) return null;
397
+ if (ts.isFunctionDeclaration(statement)) return prefix + (statement.name?.text ?? "default");
398
+ if (ts.isClassDeclaration(statement)) {
399
+ const owner = prefix + (statement.name?.text ?? "default");
400
+ const member = chain.at(index + 1);
401
+ const name = member && ts.isClassElement(member) ? memberName(ts, member) : void 0;
402
+ return name === void 0 ? owner : `${owner}.${name}`;
403
+ }
404
+ if (ts.isVariableStatement(statement)) {
405
+ const declaration = chain.at(index + 2);
406
+ return prefix + (declaration && ts.isVariableDeclaration(declaration) && ts.isIdentifier(declaration.name) ? declaration.name.text : TOP_LEVEL);
407
+ }
408
+ if (ts.isModuleDeclaration(statement)) {
409
+ const inner = `${prefix}${statement.name.text}.`;
410
+ const body = chain.at(index + 1);
411
+ if (body && ts.isModuleDeclaration(body)) return nameIn(ts, chain, index + 1, inner);
412
+ if (body && ts.isModuleBlock(body) && chain.length > index + 2) return nameIn(ts, chain, index + 2, inner);
413
+ return prefix + statement.name.text;
414
+ }
415
+ if (ts.isExportAssignment(statement)) return `${prefix}default`;
416
+ return prefix + TOP_LEVEL;
417
+ }
418
+ function declarationOf(ts, node) {
419
+ const chain = [];
420
+ for (let current = node; !ts.isSourceFile(current); current = current.parent) chain.push(current);
421
+ if (chain.length === 0) return null;
422
+ return nameIn(ts, chain.reverse(), 0, "");
423
+ }
424
+ function declarationAt(ts, sourceFile, line, column) {
425
+ const position = ts.getPositionOfLineAndCharacter(sourceFile, line - 1, column - 1);
426
+ let node = sourceFile;
427
+ for (; ; ) {
428
+ const child = ts.forEachChild(node, (candidate) => candidate.getStart(sourceFile) <= position && position < candidate.end ? candidate : void 0);
429
+ if (!child) break;
430
+ node = child;
431
+ }
432
+ return declarationOf(ts, node) ?? TOP_LEVEL;
433
+ }
434
+ function collectCalls(ts, policy, change, sourceFile) {
435
+ const calls = [];
436
+ const visit = (node) => {
437
+ if (ts.isCallExpression(node) && node.expression.kind !== ts.SyntaxKind.ImportKeyword || ts.isNewExpression(node)) {
438
+ const from = declarationOf(ts, node);
439
+ const callee = from === null ? null : policy.calleeDeclaration(node);
440
+ if (from !== null && callee && change.declarationCanChange(callee.declaration)) {
441
+ const to = declarationOf(ts, callee.declaration);
442
+ if (to !== null) calls.push({ from, targetFile: callee.declaration.getSourceFile().fileName, to });
443
+ }
444
+ }
445
+ ts.forEachChild(node, visit);
446
+ };
447
+ visit(sourceFile);
448
+ return calls;
449
+ }
450
+
451
+ // src/core/change.ts
452
+ var ChangeOracle = class {
453
+ constructor(ts, checker, policy) {
454
+ this.ts = ts;
455
+ this.checker = checker;
456
+ this.policy = policy;
457
+ }
458
+ ts;
459
+ checker;
460
+ policy;
461
+ known = /* @__PURE__ */ new Map();
462
+ /** Declarations being judged right now: meeting one again (a type that mentions itself) assumes "cannot change". */
463
+ open = /* @__PURE__ */ new Set();
464
+ assumptions = 0;
465
+ /** Can what the symbol names change? Follows an import to what it imports; a symbol nothing declares can. */
466
+ symbolCanChange(symbol) {
467
+ if (!symbol) return true;
468
+ const target = symbol.flags & this.ts.SymbolFlags.Alias ? this.checker.getAliasedSymbol(symbol) : symbol;
469
+ const declarations = target.declarations ?? [];
470
+ return declarations.length === 0 || declarations.some((declaration) => this.declarationCanChange(declaration));
471
+ }
472
+ declarationCanChange(declaration) {
473
+ const known = this.known.get(declaration);
474
+ if (known !== void 0) return known;
475
+ if (this.open.has(declaration)) {
476
+ this.assumptions += 1;
477
+ return false;
478
+ }
479
+ this.open.add(declaration);
480
+ const before = this.assumptions;
481
+ const result = this.judge(declaration);
482
+ this.open.delete(declaration);
483
+ if (result || this.assumptions === before || this.open.size === 0) this.known.set(declaration, result);
484
+ return result;
485
+ }
486
+ judge(node) {
487
+ const ts = this.ts;
488
+ if (node.getSourceFile().isDeclarationFile) return false;
489
+ if (ts.isSourceFile(node)) return this.exportsCanChange(node);
490
+ if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return this.mentionsChange(node);
491
+ if (ts.isEnumDeclaration(node) || ts.isEnumMember(node) || ts.isTypeParameterDeclaration(node)) return false;
492
+ if (ts.isFunctionLike(node)) {
493
+ const body = node.body;
494
+ return body ? !this.frozen(node) : this.mentionsChange(node);
495
+ }
496
+ if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isParameter(node)) {
497
+ if (node.type) return this.mentionsChange(node.type);
498
+ if (ts.isPropertySignature(node)) return false;
499
+ return node.initializer ? this.expressionCanChange(node.initializer) : true;
500
+ }
501
+ if (ts.isPropertyAssignment(node)) return this.expressionCanChange(node.initializer);
502
+ if (ts.isExportAssignment(node)) return this.expressionCanChange(node.expression);
503
+ if (ts.isClassLike(node)) {
504
+ const base = (node.heritageClauses ?? []).filter((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword);
505
+ return base.some((clause) => this.mentionsChange(clause)) || node.members.some((member) => this.memberCanChange(member));
506
+ }
507
+ return true;
508
+ }
509
+ memberCanChange(member) {
510
+ const ts = this.ts;
511
+ if (ts.isClassStaticBlockDeclaration(member) || ts.isSemicolonClassElement(member)) return false;
512
+ return this.declarationCanChange(member);
513
+ }
514
+ exportsCanChange(sourceFile) {
515
+ const module = this.checker.getSymbolAtLocation(sourceFile);
516
+ if (!module) return false;
517
+ return this.checker.getExportsOfModule(module).some((exported) => this.symbolCanChange(exported));
518
+ }
519
+ /** A written return type that is a Result (or a promise of one) and mentions nothing that can change. */
520
+ frozen(node) {
521
+ if (!node.type) return false;
522
+ const written = this.checker.getTypeFromTypeNode(node.type);
523
+ const awaited = this.checker.getAwaitedType(written) ?? written;
524
+ return this.policy.isResultType(awaited) && !this.mentionsChange(node.type);
525
+ }
526
+ /** The type of a value without a written type: fixed for a literal, open for a call, a name or anything computed. */
527
+ expressionCanChange(expression) {
528
+ const ts = this.ts;
529
+ if (ts.isParenthesizedExpression(expression) || ts.isSatisfiesExpression(expression) || ts.isNonNullExpression(expression)) {
530
+ return this.expressionCanChange(expression.expression);
531
+ }
532
+ if (ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) {
533
+ return ts.isConstTypeReference(expression.type) ? this.expressionCanChange(expression.expression) : this.mentionsChange(expression.type);
534
+ }
535
+ if (ts.isLiteralExpression(expression) || ts.isTemplateExpression(expression)) return false;
536
+ const kind = expression.kind;
537
+ if (kind === ts.SyntaxKind.TrueKeyword || kind === ts.SyntaxKind.FalseKeyword || kind === ts.SyntaxKind.NullKeyword) return false;
538
+ if (ts.isPrefixUnaryExpression(expression)) return this.expressionCanChange(expression.operand);
539
+ if (ts.isArrowFunction(expression) || ts.isFunctionExpression(expression) || ts.isClassExpression(expression)) return this.declarationCanChange(expression);
540
+ if (ts.isArrayLiteralExpression(expression)) {
541
+ return expression.elements.some((element) => ts.isSpreadElement(element) || this.expressionCanChange(element));
542
+ }
543
+ if (ts.isObjectLiteralExpression(expression)) return expression.properties.some((property) => this.declarationCanChange(property));
544
+ return true;
545
+ }
546
+ /** Does a written type (or a declaration made of written types) name something that can change? */
547
+ mentionsChange(node) {
548
+ const ts = this.ts;
549
+ const visit = (child) => {
550
+ if (ts.isTypeReferenceNode(child) && this.symbolCanChange(this.named(child.typeName))) return true;
551
+ if (ts.isTypeQueryNode(child) && this.symbolCanChange(this.named(child.exprName))) return true;
552
+ if (ts.isExpressionWithTypeArguments(child)) {
553
+ const expression = child.expression;
554
+ if (this.symbolCanChange(this.checker.getSymbolAtLocation(ts.isPropertyAccessExpression(expression) ? expression.name : expression))) return true;
555
+ }
556
+ if (ts.isImportTypeNode(child)) {
557
+ const name = child.qualifier ?? (ts.isLiteralTypeNode(child.argument) ? child.argument.literal : void 0);
558
+ if (!name || this.symbolCanChange(ts.isStringLiteral(name) ? this.checker.getSymbolAtLocation(name) : this.named(name))) return true;
559
+ }
560
+ return ts.forEachChild(child, visit) ?? false;
561
+ };
562
+ return visit(node);
563
+ }
564
+ named(name) {
565
+ return this.checker.getSymbolAtLocation(this.ts.isQualifiedName(name) ? name.right : name);
566
+ }
567
+ };
568
+ var oracles = /* @__PURE__ */ new WeakMap();
569
+ function changeOracleFor(ts, checker, policy) {
570
+ let oracle = oracles.get(policy);
571
+ if (!oracle) {
572
+ oracle = new ChangeOracle(ts, checker, policy);
573
+ oracles.set(policy, oracle);
574
+ }
575
+ return oracle;
576
+ }
577
+
578
+ // src/core/import-graph.ts
579
+ var WHOLE_MODULE = "*";
580
+ var resolutionCaches = /* @__PURE__ */ new WeakMap();
581
+ function resolutionCache(ts, program) {
582
+ let cache = resolutionCaches.get(program);
583
+ if (!cache) {
584
+ cache = ts.createModuleResolutionCache(program.getCurrentDirectory(), (name) => name, program.getCompilerOptions());
585
+ resolutionCaches.set(program, cache);
586
+ }
587
+ return cache;
588
+ }
589
+ function declarationFiles(symbol) {
590
+ return [...new Set((symbol?.declarations ?? []).map((declaration) => declaration.getSourceFile().fileName))];
591
+ }
592
+ function collectImports(ts, program, sourceFile, change) {
593
+ const checker = program.getTypeChecker();
594
+ const edges = [];
595
+ const computed = [];
596
+ const add = (imported, name, typeOnly) => {
597
+ for (const target of imported.files) edges.push({ target, typeOnly, name, carriesChange: imported.carriesChange });
598
+ };
599
+ const moduleFiles = (specifier) => {
600
+ const declared = declarationFiles(checker.getSymbolAtLocation(specifier));
601
+ if (declared.length > 0 || !ts.isStringLiteralLike(specifier)) return declared;
602
+ const resolved = ts.resolveModuleName(specifier.text, sourceFile.fileName, program.getCompilerOptions(), ts.sys, resolutionCache(ts, program));
603
+ return resolved.resolvedModule ? [resolved.resolvedModule.resolvedFileName] : [];
604
+ };
605
+ const wholeModule = (specifier) => {
606
+ return { files: moduleFiles(specifier), carriesChange: change ? change.symbolCanChange(checker.getSymbolAtLocation(specifier)) : true };
607
+ };
608
+ const loadedOnly = (specifier) => {
609
+ return { files: moduleFiles(specifier), carriesChange: change === void 0 };
610
+ };
611
+ const declaring = (name, specifier) => {
612
+ const symbol = checker.getSymbolAtLocation(name);
613
+ const target = symbol && symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
614
+ const declared = declarationFiles(target);
615
+ if (declared.length === 0) return { files: moduleFiles(specifier), carriesChange: true };
616
+ return { files: declared, carriesChange: change ? change.symbolCanChange(target) : true };
617
+ };
618
+ const visitImport = (node) => {
619
+ const clause = node.importClause;
620
+ if (!clause) {
621
+ add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, false);
622
+ return;
623
+ }
624
+ if (clause.name) add(declaring(clause.name, node.moduleSpecifier), "default", clause.isTypeOnly);
625
+ const bindings = clause.namedBindings;
626
+ if (!bindings) return;
627
+ if (ts.isNamespaceImport(bindings)) {
628
+ add(wholeModule(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);
629
+ return;
630
+ }
631
+ if (bindings.elements.length === 0) add(loadedOnly(node.moduleSpecifier), WHOLE_MODULE, clause.isTypeOnly);
632
+ for (const element of bindings.elements) {
633
+ add(declaring(element.name, node.moduleSpecifier), (element.propertyName ?? element.name).text, clause.isTypeOnly || element.isTypeOnly);
634
+ }
635
+ };
636
+ const visitExport = (node, specifier) => {
637
+ const clause = node.exportClause;
638
+ if (!clause || !ts.isNamedExports(clause)) {
639
+ add(wholeModule(specifier), WHOLE_MODULE, node.isTypeOnly);
640
+ return;
641
+ }
642
+ if (clause.elements.length === 0) add(loadedOnly(specifier), WHOLE_MODULE, node.isTypeOnly);
643
+ for (const element of clause.elements) {
644
+ add(declaring(element.name, specifier), (element.propertyName ?? element.name).text, node.isTypeOnly || element.isTypeOnly);
645
+ }
646
+ };
647
+ const visitImportType = (node) => {
648
+ if (!ts.isLiteralTypeNode(node.argument) || !ts.isStringLiteral(node.argument.literal)) return;
649
+ const specifier = node.argument.literal;
650
+ let name = node.qualifier;
651
+ while (name && ts.isQualifiedName(name)) name = name.left;
652
+ if (name) add(declaring(name, specifier), name.text, true);
653
+ else add(wholeModule(specifier), WHOLE_MODULE, true);
654
+ };
655
+ const visitDynamicImport = (node) => {
656
+ const specifier = node.arguments.at(0);
657
+ if (!specifier) return;
658
+ if (ts.isStringLiteralLike(specifier)) add(wholeModule(specifier), WHOLE_MODULE, false);
659
+ else computed.push({ ...startOf(ts, sourceFile, specifier), specifier: specifier.getText(sourceFile) });
660
+ };
661
+ const visit = (node) => {
662
+ if (ts.isImportDeclaration(node)) visitImport(node);
663
+ else if (ts.isExportDeclaration(node) && node.moduleSpecifier) visitExport(node, node.moduleSpecifier);
664
+ else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
665
+ add(wholeModule(node.moduleReference.expression), WHOLE_MODULE, node.isTypeOnly);
666
+ } else if (ts.isImportTypeNode(node)) visitImportType(node);
667
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) visitDynamicImport(node);
668
+ ts.forEachChild(node, visit);
669
+ };
670
+ visit(sourceFile);
671
+ return { edges, computed };
672
+ }
673
+
674
+ // src/core/refactor-plan.ts
675
+ function indexGraph(files, dependencies) {
676
+ const sorted = [...new Set(files)].sort();
677
+ const indexOf = new Map(sorted.map((file, index) => [file, index]));
678
+ const imports = sorted.map((file, index) => {
679
+ const targets = /* @__PURE__ */ new Set();
680
+ for (const dependency of dependencies.get(file) ?? []) {
681
+ const target = indexOf.get(dependency);
682
+ if (target !== void 0 && target !== index) targets.add(target);
683
+ }
684
+ return [...targets].sort((a, b) => a - b);
685
+ });
686
+ return { files: sorted, imports };
687
+ }
688
+ function components(graph) {
689
+ const count = graph.files.length;
690
+ const order = new Array(count).fill(-1);
691
+ const low = new Array(count).fill(0);
692
+ const onStack = new Array(count).fill(false);
693
+ const stack = [];
694
+ const found = [];
695
+ let next = 0;
696
+ for (let root = 0; root < count; root += 1) {
697
+ if (order[root] !== -1) continue;
698
+ const frames = [];
699
+ const open = (file) => {
700
+ order[file] = next;
701
+ low[file] = next;
702
+ next += 1;
703
+ stack.push(file);
704
+ onStack[file] = true;
705
+ frames.push({ file, followed: 0 });
706
+ };
707
+ open(root);
708
+ while (frames.length > 0) {
709
+ const frame = frames[frames.length - 1];
710
+ const targets = graph.imports[frame.file];
711
+ if (frame.followed < targets.length) {
712
+ const target = targets[frame.followed];
713
+ frame.followed += 1;
714
+ if (order[target] === -1) open(target);
715
+ else if (onStack[target]) low[frame.file] = Math.min(low[frame.file], order[target]);
716
+ continue;
717
+ }
718
+ frames.pop();
719
+ if (frames.length > 0) {
720
+ const parent = frames[frames.length - 1].file;
721
+ low[parent] = Math.min(low[parent], low[frame.file]);
722
+ }
723
+ if (low[frame.file] !== order[frame.file]) continue;
724
+ const component = [];
725
+ for (; ; ) {
726
+ const member = stack.pop();
727
+ onStack[member] = false;
728
+ component.push(member);
729
+ if (member === frame.file) break;
730
+ }
731
+ found.push(component.sort((a, b) => a - b));
732
+ }
733
+ }
734
+ return found;
735
+ }
736
+ function firstFile(item) {
737
+ return typeof item === "string" ? item : item[0];
738
+ }
739
+ function byName(a, b) {
740
+ return a < b ? -1 : a > b ? 1 : 0;
741
+ }
742
+ function reaches(edges, from, to) {
743
+ const seen = /* @__PURE__ */ new Set([from]);
744
+ const queue = [from];
745
+ while (queue.length > 0) {
746
+ const file = queue.pop();
747
+ if (file === to) return true;
748
+ for (const target of edges.get(file) ?? []) {
749
+ if (seen.has(target)) continue;
750
+ seen.add(target);
751
+ queue.push(target);
752
+ }
753
+ }
754
+ return false;
755
+ }
756
+ function closingEdgesOf(graph, members, cost) {
757
+ if (members.length < 2) return [];
758
+ const inside = new Set(members);
759
+ const out = new Map(members.map((member) => [member, []]));
760
+ const into = new Map(members.map((member) => [member, []]));
761
+ const degree = new Map(members.map((member) => [member, { out: 0, in: 0, outCost: 0, inCost: 0 }]));
762
+ const degreeOf = (member) => {
763
+ return degree.get(member);
764
+ };
765
+ for (const member of members) {
766
+ for (const target of graph.imports[member]) {
767
+ if (!inside.has(target)) continue;
768
+ out.get(member).push(target);
769
+ into.get(target).push(member);
770
+ const edgeCost = cost(member, target);
771
+ degreeOf(member).out += 1;
772
+ degreeOf(member).outCost += edgeCost;
773
+ degreeOf(target).in += 1;
774
+ degreeOf(target).inCost += edgeCost;
775
+ }
776
+ }
777
+ const left = new Set(members);
778
+ const first = [];
779
+ const last = [];
780
+ const gap = (member) => degreeOf(member).outCost - degreeOf(member).inCost;
781
+ while (left.size > 0) {
782
+ let sink;
783
+ let source;
784
+ let widest;
785
+ for (const member of left) {
786
+ if (degreeOf(member).out === 0) {
787
+ sink = member;
788
+ break;
789
+ }
790
+ if (source !== void 0) continue;
791
+ if (degreeOf(member).in === 0) source = member;
792
+ else if (widest === void 0 || gap(member) > gap(widest)) widest = member;
793
+ }
794
+ const picked = sink ?? source ?? widest;
795
+ if (sink !== void 0) last.push(picked);
796
+ else first.push(picked);
797
+ left.delete(picked);
798
+ for (const target of out.get(picked)) {
799
+ degreeOf(target).in -= 1;
800
+ degreeOf(target).inCost -= cost(picked, target);
801
+ }
802
+ for (const importer of into.get(picked)) {
803
+ degreeOf(importer).out -= 1;
804
+ degreeOf(importer).outCost -= cost(importer, picked);
805
+ }
806
+ }
807
+ const position = new Map([...first, ...last.reverse()].map((member, index) => [member, index]));
808
+ const kept = new Map(members.map((member) => [member, /* @__PURE__ */ new Set()]));
809
+ const candidates = [];
810
+ for (const member of members) {
811
+ for (const target of out.get(member)) {
812
+ if (position.get(member) > position.get(target)) candidates.push([member, target]);
813
+ else kept.get(member).add(target);
814
+ }
815
+ }
816
+ candidates.sort((a, b) => cost(b[0], b[1]) - cost(a[0], a[1]) || a[0] - b[0] || a[1] - b[1]);
817
+ const closing = [];
818
+ for (const [from, to] of candidates) {
819
+ if (reaches(kept, to, from)) closing.push([from, to]);
820
+ else kept.get(from).add(to);
821
+ }
822
+ return closing.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
823
+ }
824
+ function planGraph(graph, input) {
825
+ const units = components(graph);
826
+ const unitOf = new Array(graph.files.length).fill(0);
827
+ units.forEach((members, unit) => {
828
+ for (const member of members) unitOf[member] = unit;
829
+ });
830
+ const weight = input.weight;
831
+ const cost = weight ? (from, to) => weight(graph.files[from], graph.files[to]) : () => 1;
832
+ const depth = [];
833
+ const waves = [];
834
+ const cycles = [];
835
+ const work = units.map((members) => members.map((member) => graph.files[member]).filter((file) => input.tasks.has(file)));
836
+ units.forEach((members, unit) => {
837
+ let below = 0;
838
+ for (const member of members) {
839
+ for (const target of graph.imports[member]) {
840
+ const imported = unitOf[target];
841
+ if (imported !== unit) below = Math.max(below, depth[imported] + (work[imported].length > 0 ? 1 : 0));
842
+ }
843
+ }
844
+ depth[unit] = below;
845
+ const tasks = work[unit];
846
+ if (members.length > 1) {
847
+ const files = members.map((member) => graph.files[member]);
848
+ const closingEdges = closingEdgesOf(graph, members, cost).map(([from, to]) => ({ from: graph.files[from], to: graph.files[to] }));
849
+ cycles.push({ size: files.length, files, tasks, tooLarge: files.length > input.maxGroupSize, closingEdges });
850
+ }
851
+ if (tasks.length === 0) return;
852
+ while (waves.length <= below) waves.push([]);
853
+ waves[below].push(tasks.length === 1 ? tasks[0] : tasks);
854
+ });
855
+ for (const wave of waves) wave.sort((a, b) => byName(firstFile(a), firstFile(b)));
856
+ cycles.sort((a, b) => b.size - a.size || byName(a.files[0], b.files[0]));
857
+ return { waves, cycles };
858
+ }
859
+ function planRefactor(input) {
860
+ const graph = indexGraph(input.files, input.dependencies);
861
+ const full = planGraph(graph, input);
862
+ const carriesChange = input.carriesChange;
863
+ if (!carriesChange || !full.cycles.some((cycle) => cycle.tooLarge)) return full;
864
+ const groupOf = /* @__PURE__ */ new Map();
865
+ full.cycles.forEach((cycle, index) => {
866
+ if (cycle.tooLarge) for (const file of cycle.files) groupOf.set(file, index);
867
+ });
868
+ const dropped = /* @__PURE__ */ new Map();
869
+ const kept = /* @__PURE__ */ new Map();
870
+ const imports = graph.imports.map((targets, file) => {
871
+ const group = groupOf.get(graph.files[file]);
872
+ if (group === void 0) return targets;
873
+ return targets.filter((target) => {
874
+ if (groupOf.get(graph.files[target]) !== group) return true;
875
+ const carries = carriesChange(graph.files[file], graph.files[target]);
876
+ const counts = carries ? kept : dropped;
877
+ counts.set(group, (counts.get(group) ?? 0) + 1);
878
+ return carries;
879
+ });
880
+ });
881
+ const pruned = planGraph({ files: graph.files, imports }, input);
882
+ const cycles = full.cycles.map((cycle, index) => {
883
+ if (!cycle.tooLarge) return cycle;
884
+ const groups = pruned.cycles.filter((left) => groupOf.get(left.files[0]) === index);
885
+ return { ...cycle, split: { droppedEdges: dropped.get(index) ?? 0, keptEdges: kept.get(index) ?? 0, groups } };
886
+ });
887
+ return { waves: pruned.waves, cycles };
888
+ }
889
+
890
+ // src/cli/refactor-command.ts
891
+ var DEFAULT_MAX_GROUP_SIZE = 8;
892
+ var CHANGING_NAME_COST = 10;
893
+ function hasFindings(byRule) {
894
+ return Object.values(byRule).some((byOrigin) => Object.values(byOrigin).some((count) => count > 0));
895
+ }
896
+ function byName2(a, b) {
897
+ return a < b ? -1 : a > b ? 1 : 0;
898
+ }
899
+ function internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) {
900
+ const inGroup = new Set(group.files);
901
+ const taskFiles = new Set(group.tasks);
902
+ const calls = /* @__PURE__ */ new Map();
903
+ const declarations = /* @__PURE__ */ new Set();
904
+ const withFindings = /* @__PURE__ */ new Set();
905
+ for (const file of group.files) {
906
+ const entry = loaded.get(file);
907
+ if (!entry) continue;
908
+ const { ts, program, sourceFile } = entry;
909
+ const checker = program.getTypeChecker();
910
+ const policy = policyFor(ts, checker, config);
911
+ for (const call of collectCalls(ts, policy, changeOracleFor(ts, checker, policy), sourceFile)) {
912
+ const targetFile = keyOfTarget(call.targetFile);
913
+ if (targetFile === void 0 || !inGroup.has(targetFile)) continue;
914
+ const from = `${file}#${call.from}`;
915
+ const to = `${targetFile}#${call.to}`;
916
+ if (from === to) continue;
917
+ declarations.add(from).add(to);
918
+ let callees = calls.get(from);
919
+ if (!callees) {
920
+ callees = /* @__PURE__ */ new Map();
921
+ calls.set(from, callees);
922
+ }
923
+ callees.set(to, (callees.get(to) ?? 0) + 1);
924
+ }
925
+ if (!taskFiles.has(file)) continue;
926
+ for (const finding of checkSourceFile({ ts, program, config, sourceFile })) {
927
+ const declaration = `${file}#${declarationAt(ts, sourceFile, finding.line, finding.column)}`;
928
+ declarations.add(declaration);
929
+ withFindings.add(declaration);
930
+ }
931
+ }
932
+ const callSites = (from, to) => calls.get(from)?.get(to) ?? 0;
933
+ const incoming = /* @__PURE__ */ new Map();
934
+ for (const callees of calls.values()) {
935
+ for (const [callee, count] of callees) incoming.set(callee, (incoming.get(callee) ?? 0) + count);
936
+ }
937
+ const plan = planRefactor({
938
+ files: [...declarations],
939
+ dependencies: new Map([...calls].map(([from, callees]) => [from, [...callees.keys()]])),
940
+ tasks: withFindings,
941
+ maxGroupSize,
942
+ weight: callSites
943
+ });
944
+ const recursion = plan.cycles.map((cycle) => {
945
+ 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));
946
+ return {
947
+ size: cycle.size,
948
+ declarations: cycle.files,
949
+ tasks: cycle.tasks,
950
+ files: [...new Set(cycle.files.map((declaration) => declaration.slice(0, declaration.indexOf("#"))))].sort(),
951
+ closingEdges: cycle.closingEdges.map((edge) => ({ ...edge, callSites: callSites(edge.from, edge.to) })),
952
+ freeze: cuts[0]
953
+ };
954
+ });
955
+ return { order: plan.waves, recursion };
956
+ }
957
+ function formatItem(item, tooLarge) {
958
+ if (typeof item === "string") return [` ${item}`];
959
+ const how = tooLarge ? "circular imports, too large for one unit: follow its internal order below" : "circular imports, refactor together";
960
+ return [` group of ${item.length} (${how}):`, ...item.map((file) => ` ${file}`)];
961
+ }
962
+ function formatClosingImport(edge) {
963
+ return `closed by: ${edge.from} imports ${edge.names.join(", ")} from ${edge.to}`;
964
+ }
965
+ function formatDeclarations(item) {
966
+ return typeof item === "string" ? item : `(${item.join(" + ")})`;
967
+ }
968
+ function formatRecursion(group, indent) {
969
+ return [
970
+ `${indent}${group.declarations.join(", ")}`,
971
+ ...group.closingEdges.map((edge) => `${indent} closed by: ${edge.from} calls ${edge.to} (${edge.callSites} call site(s))`),
972
+ `${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`,
973
+ `${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)`
974
+ ];
975
+ }
976
+ function formatRemaining(group, maxGroupSize, indent) {
977
+ const tooLarge = group.tooLarge ? ` \u2014 still too large for one unit (more than ${maxGroupSize} files)` : "";
978
+ const lines = [`${indent}${group.size} file(s), ${group.tasks.length} with findings${tooLarge}: ${group.files.join(", ")}`];
979
+ for (const edge of group.closingEdges) lines.push(`${indent} ${formatClosingImport(edge)}`);
980
+ const { order, recursion } = group;
981
+ if (order) {
982
+ const count = order.reduce((sum, wave) => sum + wave.reduce((inWave, item) => inWave + (typeof item === "string" ? 1 : item.length), 0), 0);
983
+ lines.push(count === 0 ? `${indent} internal order: no declaration with findings` : `${indent} internal order of the ${count} declaration(s) with findings, callees first:`);
984
+ order.forEach((wave, index) => lines.push(`${indent} ${index + 1}. ${wave.map(formatDeclarations).join(", ")}`));
985
+ }
986
+ if (recursion && recursion.length > 0) {
987
+ lines.push(`${indent} mutual recursion (${recursion.length}): declarations that call each other in a circle, with two ways out`);
988
+ for (const circle of recursion) lines.push(...formatRecursion(circle, `${indent} `));
989
+ }
990
+ return lines;
991
+ }
992
+ function formatCycle(cycle, maxGroupSize) {
993
+ const tooLarge = cycle.tooLarge ? ` \u2014 too large for one unit (more than ${maxGroupSize} files)` : "";
994
+ const lines = [` ${cycle.size} file(s), ${cycle.tasks.length} with findings${tooLarge}: ${cycle.files.join(", ")}`];
995
+ for (const edge of cycle.closingEdges) lines.push(` ${formatClosingImport(edge)}`);
996
+ const split = cycle.split;
997
+ if (!split) return lines;
998
+ const left = split.groups.length === 0 ? "no circular group left" : `${split.groups.length} circular group(s) left`;
999
+ lines.push(` without the ${split.droppedEdges} import(s) that cannot carry a change (${split.keptEdges} kept): ${left}`);
1000
+ for (const group of split.groups) lines.push(...formatRemaining(group, maxGroupSize, " "));
1001
+ return lines;
1002
+ }
1003
+ function formatReport(report) {
1004
+ const { waves, cycles, warnings, summary } = report;
1005
+ const tooLarge = /* @__PURE__ */ new Set();
1006
+ for (const cycle of cycles) {
1007
+ for (const group of cycle.split ? cycle.split.groups : [cycle]) {
1008
+ if (group.tooLarge && group.tasks.length > 1) tooLarge.add(group.tasks[0]);
1009
+ }
1010
+ }
1011
+ const lines = [];
1012
+ waves.forEach((wave, index) => {
1013
+ lines.push(`Wave ${index + 1} of ${waves.length} (${wave.length} item(s)):`);
1014
+ for (const item of wave) lines.push(...formatItem(item, typeof item !== "string" && tooLarge.has(item[0])));
1015
+ });
1016
+ if (waves.length === 0) lines.push("No file with findings: nothing to refactor.");
1017
+ if (cycles.length > 0) {
1018
+ lines.push(`Circular import groups (${cycles.length}):`);
1019
+ for (const cycle of cycles) lines.push(...formatCycle(cycle, summary.maxGroupSize));
1020
+ }
1021
+ if (warnings.length > 0) {
1022
+ lines.push(`Computed import() the graph cannot follow (${warnings.length}):`);
1023
+ for (const warning of warnings) lines.push(` ${warning.file}:${warning.line}:${warning.column} import(${warning.specifier})`);
1024
+ }
1025
+ const source = summary.taskSource === "baseline" ? `the baseline ${summary.baseline}` : "a fresh check (no baseline file)";
1026
+ const imports = summary.valueOnly ? "value import(s)" : "import(s)";
1027
+ lines.push(
1028
+ `${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}.`
1029
+ );
1030
+ return lines;
1031
+ }
1032
+ async function runRefactorCommand(options) {
1033
+ const maxGroupSize = options.maxGroupSize ?? DEFAULT_MAX_GROUP_SIZE;
1034
+ if (!Number.isInteger(maxGroupSize) || maxGroupSize < 1) {
1035
+ options.log("trust refactor: --max-group needs a whole number of files, 1 or more");
1036
+ return 2;
1037
+ }
1038
+ const resolved = resolveFiles(options.cwd, options.paths.length > 0 ? options.paths : ["."]);
1039
+ if ("missing" in resolved) {
1040
+ options.log(`trust refactor: no such file or directory: ${resolved.missing}`);
1041
+ return 2;
1042
+ }
1043
+ const configPath = resolve4(options.cwd, options.configFile);
1044
+ const rootDir = options.root === void 0 ? void 0 : resolve4(options.cwd, options.root);
1045
+ const config = existsSync3(configPath) ? loadTrustConfig(configPath, { validateGlobs: false, rootDir }) : emptyTrustConfig(rootDir ?? options.cwd);
1046
+ const zones = new Zones(config.rootDir, config.passthrough, config.ignore);
1047
+ const files = resolved.files.filter((file) => zones.zoneOf(file) !== "ignore");
1048
+ const baselineFile = resolve4(options.cwd, options.baselineFile ?? join2(config.rootDir, "trust-baseline.json"));
1049
+ const fromBaseline = existsSync3(baselineFile);
1050
+ if (!fromBaseline && options.baselineFile !== void 0) {
1051
+ options.log(`trust refactor: no such baseline: ${options.baselineFile}`);
1052
+ return 2;
1053
+ }
1054
+ const baseline = readBaseline(baselineFile);
1055
+ if ("error" in baseline) {
1056
+ options.log(`trust refactor: could not read the baseline: ${baseline.error}`);
1057
+ return 2;
1058
+ }
1059
+ const keyByPath = /* @__PURE__ */ new Map();
1060
+ for (const file of files) {
1061
+ const key = relativeTo(config.rootDir, file);
1062
+ keyByPath.set(file, key);
1063
+ keyByPath.set(realpathOrSelf(file), key);
1064
+ }
1065
+ const keyOfTarget = (target) => {
1066
+ if (!keyByPath.has(target)) {
1067
+ const key = keyByPath.get(realpathOrSelf(target));
1068
+ if (key === void 0) return void 0;
1069
+ keyByPath.set(target, key);
1070
+ }
1071
+ return keyByPath.get(target);
1072
+ };
1073
+ const outside = /* @__PURE__ */ new Set();
1074
+ const dependencies = /* @__PURE__ */ new Map();
1075
+ const imported = /* @__PURE__ */ new Map();
1076
+ const loaded = /* @__PURE__ */ new Map();
1077
+ const warnings = [];
1078
+ const checked = /* @__PURE__ */ new Set();
1079
+ const programs = { tsconfig: options.tsconfig, mappings: config.tsconfig };
1080
+ const walk = forEachSourceFile(options.cwd, files, programs, ({ ts, program, sourceFile, file }) => {
1081
+ const from = relativeTo(config.rootDir, file);
1082
+ const checker = program.getTypeChecker();
1083
+ const imports = collectImports(ts, program, sourceFile, changeOracleFor(ts, checker, policyFor(ts, checker, config)));
1084
+ const targets = /* @__PURE__ */ new Map();
1085
+ for (const edge of imports.edges) {
1086
+ if (options.valueOnly && edge.typeOnly || outside.has(edge.target)) continue;
1087
+ const to = keyOfTarget(edge.target);
1088
+ if (to === void 0) outside.add(edge.target);
1089
+ if (to === void 0 || to === from) continue;
1090
+ let names = targets.get(to);
1091
+ if (!names) {
1092
+ names = { all: /* @__PURE__ */ new Set(), changing: /* @__PURE__ */ new Set() };
1093
+ targets.set(to, names);
1094
+ }
1095
+ names.all.add(edge.name);
1096
+ if (edge.carriesChange) names.changing.add(edge.name);
1097
+ }
1098
+ dependencies.set(from, new Set(targets.keys()));
1099
+ imported.set(from, targets);
1100
+ loaded.set(from, { ts, program, sourceFile });
1101
+ for (const computed of imports.computed) warnings.push({ kind: "computed-import", file: from, ...computed });
1102
+ if (!fromBaseline && checkSourceFile({ ts, program, config, sourceFile }).length > 0) checked.add(from);
1103
+ });
1104
+ if (walk.status !== "ok") {
1105
+ logWalkFailure(options.log, "refactor", walk);
1106
+ return 2;
1107
+ }
1108
+ const nodes = [...dependencies.keys()];
1109
+ const tasks = fromBaseline ? new Set(nodes.filter((file) => Object.hasOwn(baseline.counts, file) && hasFindings(baseline.counts[file]))) : checked;
1110
+ warnings.sort((a, b) => a.file !== b.file ? a.file < b.file ? -1 : 1 : a.line - b.line || a.column - b.column);
1111
+ const cutCost = (from, to) => {
1112
+ const names = imported.get(from)?.get(to);
1113
+ return names ? names.changing.size * CHANGING_NAME_COST + (names.all.size - names.changing.size) : 1;
1114
+ };
1115
+ const plan = planRefactor({
1116
+ files: nodes,
1117
+ dependencies,
1118
+ tasks,
1119
+ maxGroupSize,
1120
+ weight: cutCost,
1121
+ carriesChange: (from, to) => (imported.get(from)?.get(to)?.changing.size ?? 1) > 0
1122
+ });
1123
+ const closing = (edges, which) => {
1124
+ return edges.map(({ from, to }) => ({ from, to, names: [...imported.get(from)?.get(to)?.[which] ?? []].sort() }));
1125
+ };
1126
+ const remaining = (group) => ({
1127
+ size: group.size,
1128
+ files: group.files,
1129
+ tasks: group.tasks,
1130
+ tooLarge: group.tooLarge,
1131
+ closingEdges: closing(group.closingEdges, "changing"),
1132
+ ...group.tooLarge ? internalOrder(group, loaded, config, keyOfTarget, maxGroupSize) : {}
1133
+ });
1134
+ const cycles = plan.cycles.map((cycle) => {
1135
+ const split = cycle.split;
1136
+ return {
1137
+ size: cycle.size,
1138
+ files: cycle.files,
1139
+ tasks: cycle.tasks,
1140
+ tooLarge: cycle.tooLarge,
1141
+ closingEdges: closing(cycle.closingEdges, "all"),
1142
+ ...split ? { split: { droppedEdges: split.droppedEdges, keptEdges: split.keptEdges, groups: split.groups.map(remaining) } } : {}
1143
+ };
1144
+ });
1145
+ const report = {
1146
+ waves: plan.waves,
1147
+ cycles,
1148
+ warnings,
1149
+ summary: {
1150
+ files: nodes.length,
1151
+ edges: [...dependencies.values()].reduce((sum, targets) => sum + targets.size, 0),
1152
+ tasks: tasks.size,
1153
+ items: plan.waves.reduce((sum, wave) => sum + wave.length, 0),
1154
+ ignored: resolved.files.length - files.length,
1155
+ taskSource: fromBaseline ? "baseline" : "check",
1156
+ baseline: fromBaseline ? baselineFile : null,
1157
+ valueOnly: options.valueOnly,
1158
+ maxGroupSize
1159
+ }
1160
+ };
1161
+ if (options.json) options.log(JSON.stringify(report, null, 2));
1162
+ else for (const line of formatReport(report)) options.log(line);
1163
+ return 0;
1164
+ }
1165
+
146
1166
  // src/cli/index.ts
147
1167
  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.`;
1168
+ trust explain <file>:<line>[:<column>] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]
1169
+ Print the origin each call on that line resolves to, and why it is (un)trusted: for failing
1170
+ ("trust" / "distrust") and for its types ("trust_type" / "distrust_type").
1171
+ Also prints every type claim starting on that line (type-claim): its kind and why it is a claim,
1172
+ and every untrusted value starting on it (untrusted-value): how it entered, the origin that
1173
+ declared its type, and whether its use is reported.
1174
+ trust baseline [paths...] [--config trust.config.json] [--baseline trust-baseline.json] [--update] [--tsconfig <path>] [--root <dir>]
1175
+ Check the files with TypeScript alone (no ESLint) and fail on trust violations not in the baseline.
1176
+ Files are found and skipped as in trust check; --update rewrites the baseline from the current findings.
1177
+ With paths, only the checked files' entries are reported as shrunk or rewritten by --update.
1178
+ trust check <paths...> [--strict] [--config trust.config.json] [--tsconfig <path>] [--root <dir>]
1179
+ Check the files with TypeScript alone (no ESLint) and fail on any trust violation (no baseline).
1180
+ Each file uses --tsconfig if given, else the first matching "tsconfig" entry of the trust config,
1181
+ else the nearest tsconfig.json above it.
1182
+ Files in the config's ignore zone are skipped. --strict also fails on written return types
1183
+ in every checked file; the config's "strict" globs do the same for the files they match.
1184
+ trust refactor [paths...] [--json] [--value-only] [--max-group <n>] [--config trust.config.json] [--baseline trust-baseline.json] [--tsconfig <path>] [--root <dir>]
1185
+ Print the order to refactor the files with findings in: waves of work items, leaves of the import
1186
+ graph first. The items of a wave can be done in parallel; a circular-import group is one item.
1187
+ Findings come from the baseline, or from a fresh check when there is no baseline file.
1188
+ --json prints { "waves": [["a.ts", ["b.ts", "c.ts"]], ["d.ts"]], ... }; --value-only leaves
1189
+ type-only imports out of the graph. Every circular group lists the imports that close it.
1190
+ A circular group of more than --max-group <n> files (default 8) is too large for one item: the
1191
+ imports inside it that cannot carry a change (an interface, a constant, a written Result return
1192
+ type) are dropped; what is still too large gets an internal order of its declarations, callees
1193
+ first, and declarations that call each other in a circle are reported with the calls closing it.
1194
+ --root <dir> resolves the config's globs, tsconfig paths and baseline keys against <dir> instead of
1195
+ the config file's directory (for a config kept outside the project).`;
1196
+ var BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["update", "help", "strict", "json", "value-only"]);
153
1197
  function parseArgs(argv) {
154
1198
  const positional = [];
155
1199
  const flags = /* @__PURE__ */ new Map();
@@ -161,7 +1205,7 @@ function parseArgs(argv) {
161
1205
  }
162
1206
  const [name, inline] = arg.slice(2).split("=", 2);
163
1207
  if (inline !== void 0) flags.set(name, inline);
164
- else if (name === "update" || name === "help") flags.set(name, true);
1208
+ else if (BOOLEAN_FLAGS.has(name)) flags.set(name, true);
165
1209
  else {
166
1210
  const value = argv[index + 1];
167
1211
  if (value === void 0) throw new Error(`--${name} needs a value`);
@@ -192,7 +1236,12 @@ async function main(argv) {
192
1236
  if (command === "explain") {
193
1237
  if (positional.length !== 1) throw new Error("explain takes exactly one <file>:<line>[:<column>]");
194
1238
  const location = parseLocation(positional[0]);
195
- console.log(formatExplanation(explain({ cwd, configFile, tsconfig: stringFlag(flags, "tsconfig"), ...location })));
1239
+ const explained = explain({ cwd, configFile, tsconfig: stringFlag(flags, "tsconfig"), root: stringFlag(flags, "root"), ...location });
1240
+ if (explained.kind !== "explained") {
1241
+ console.error(`trust explain: ${explained.message}`);
1242
+ return 2;
1243
+ }
1244
+ console.log(formatExplanation(explained.explanation));
196
1245
  return 0;
197
1246
  }
198
1247
  if (command === "baseline") {
@@ -202,6 +1251,34 @@ async function main(argv) {
202
1251
  configFile,
203
1252
  baselineFile: stringFlag(flags, "baseline"),
204
1253
  update: flags.get("update") === true,
1254
+ tsconfig: stringFlag(flags, "tsconfig"),
1255
+ root: stringFlag(flags, "root"),
1256
+ log: (line) => console.log(line)
1257
+ });
1258
+ }
1259
+ if (command === "check") {
1260
+ return runCheckCommand({
1261
+ cwd,
1262
+ paths: positional,
1263
+ configFile,
1264
+ strict: flags.get("strict") === true,
1265
+ tsconfig: stringFlag(flags, "tsconfig"),
1266
+ root: stringFlag(flags, "root"),
1267
+ log: (line) => console.log(line)
1268
+ });
1269
+ }
1270
+ if (command === "refactor") {
1271
+ const maxGroup = stringFlag(flags, "max-group");
1272
+ return runRefactorCommand({
1273
+ cwd,
1274
+ paths: positional,
1275
+ configFile,
1276
+ baselineFile: stringFlag(flags, "baseline"),
1277
+ json: flags.get("json") === true,
1278
+ valueOnly: flags.get("value-only") === true,
1279
+ maxGroupSize: maxGroup === void 0 ? void 0 : Number(maxGroup),
1280
+ tsconfig: stringFlag(flags, "tsconfig"),
1281
+ root: stringFlag(flags, "root"),
205
1282
  log: (line) => console.log(line)
206
1283
  });
207
1284
  }