@noego/trust 0.5.0-dev.2 → 0.5.0-dev.4

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.
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  ACCEPT_DIRECTIVE,
3
3
  ACCEPT_DIRECTIVE_MESSAGES,
4
+ BOUNDARY_MESSAGES,
5
+ BOUNDARY_RULE,
4
6
  CATCH_ORIGIN,
5
7
  DEFAULT_RULE_SETTINGS,
6
8
  DIRECTIVE_ORIGIN,
@@ -15,6 +17,9 @@ import {
15
17
  REDUNDANT_GUARD_MESSAGES,
16
18
  REDUNDANT_GUARD_ORIGIN,
17
19
  REDUNDANT_GUARD_RULE,
20
+ RESULT_CONDITION_MESSAGE,
21
+ RESULT_CONDITION_ORIGIN,
22
+ RESULT_CONDITION_RULE,
18
23
  THROW_MESSAGES,
19
24
  THROW_ORIGIN,
20
25
  THROW_RULE,
@@ -28,9 +33,11 @@ import {
28
33
  Zones,
29
34
  directiveDirectlyAbove,
30
35
  directiveProblem,
36
+ filesMatchingGroup,
31
37
  fillMessage,
32
38
  formatFailureKinds,
33
39
  formatMessage,
40
+ groupMatches,
34
41
  isAcceptDirective,
35
42
  isInsideValidator,
36
43
  isMarkedValidator,
@@ -40,7 +47,7 @@ import {
40
47
  realpathOrSelf,
41
48
  svelteFor,
42
49
  trustDirectivesIn
43
- } from "./chunk-UG6D3V4M.js";
50
+ } from "./chunk-6YBPW4NP.js";
44
51
 
45
52
  // src/core/guard.ts
46
53
  function unparen(ts, node) {
@@ -1164,6 +1171,205 @@ function droppedResultsIn(sourceFile, context) {
1164
1171
  return found.sort((a, b) => a.start - b.start);
1165
1172
  }
1166
1173
 
1174
+ // src/core/boundaries.ts
1175
+ function boundaryContext(ts, checker, program, policy, config) {
1176
+ return { ts, checker, program, policy, config, kinds: droppedResultContext(ts, checker, policy) };
1177
+ }
1178
+ function boundaryName(boundary) {
1179
+ return boundary.container === null ? boundary.member : `${boundary.container}.${boundary.member}`;
1180
+ }
1181
+ function excludeMatches(entry, boundary) {
1182
+ const dot = entry.indexOf(".");
1183
+ if (dot < 0) return boundary.container === null && boundary.member === entry;
1184
+ if (boundary.container === null) return false;
1185
+ const container = entry.slice(0, dot);
1186
+ const member = entry.slice(dot + 1);
1187
+ if (member === "*") return container !== "" && container === boundary.container;
1188
+ return boundary.member === member && (container === "" || container === boundary.container);
1189
+ }
1190
+ function itemLabel(item) {
1191
+ const slash = Math.max(item.source.lastIndexOf("/"), item.source.lastIndexOf("\\"));
1192
+ return `boundaries[${item.index}] in ${item.source.slice(slash + 1)}`;
1193
+ }
1194
+ function boundaryMessage(finding) {
1195
+ return fillMessage(BOUNDARY_MESSAGES[finding.origin], finding.data);
1196
+ }
1197
+ function realPath(context, fileName) {
1198
+ return realpathOrSelf(context.policy.zones.virtualPaths.get(fileName) ?? fileName);
1199
+ }
1200
+ function declaredName(ts, node) {
1201
+ const name = node.name;
1202
+ if (!name) return null;
1203
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return { text: name.text, node: name };
1204
+ return null;
1205
+ }
1206
+ function isTypeOnlyExport(ts, declaration) {
1207
+ if (ts.isExportSpecifier(declaration)) return declaration.isTypeOnly || declaration.parent.parent.isTypeOnly;
1208
+ if (ts.isNamespaceExport(declaration)) return declaration.parent.isTypeOnly;
1209
+ return false;
1210
+ }
1211
+ function verdictOfType(context, type) {
1212
+ const { ts, checker } = context;
1213
+ const awaited = checker.getAwaitedType(type) ?? type;
1214
+ if (awaited.flags & ts.TypeFlags.Any) return { kind: "unproven", type: "any" };
1215
+ if (awaited.flags & ts.TypeFlags.Unknown) return { kind: "unproven", type: "unknown" };
1216
+ const kinds = failureKinds(context.kinds, type);
1217
+ return kinds ? { kind: "result", kinds: [...kinds].sort() } : { kind: "plain" };
1218
+ }
1219
+ function verdictOfSignatures(context, signatures) {
1220
+ for (const signature of signatures) {
1221
+ const verdict = verdictOfType(context, context.checker.getReturnTypeOfSignature(signature));
1222
+ if (verdict.kind !== "plain") return verdict;
1223
+ }
1224
+ return { kind: "plain" };
1225
+ }
1226
+ function memberVerdict(context, declaration, type) {
1227
+ if (context.ts.isGetAccessorDeclaration(declaration)) return verdictOfType(context, type);
1228
+ const signatures = type.getCallSignatures();
1229
+ return signatures.length > 0 ? verdictOfSignatures(context, signatures) : null;
1230
+ }
1231
+ function isPublic(ts, declaration) {
1232
+ const name = declaration.name;
1233
+ if (name && ts.isPrivateIdentifier(name)) return false;
1234
+ return (ts.getCombinedModifierFlags(declaration) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) === 0;
1235
+ }
1236
+ function exportStarFor(context, sourceFile, name) {
1237
+ const { ts, checker } = context;
1238
+ for (const statement of sourceFile.statements) {
1239
+ if (!ts.isExportDeclaration(statement) || statement.exportClause || !statement.moduleSpecifier) continue;
1240
+ const module = checker.getSymbolAtLocation(statement.moduleSpecifier);
1241
+ if (module && checker.getExportsOfModule(module).some((exported) => exported.name === name)) return statement;
1242
+ }
1243
+ return null;
1244
+ }
1245
+ function boundariesIn(sourceFile, context) {
1246
+ const { ts, checker, policy } = context;
1247
+ const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
1248
+ if (!moduleSymbol) return [];
1249
+ const found = [];
1250
+ const startOf2 = (declaration, fallback) => {
1251
+ if (!declaration || declaration.getSourceFile() !== sourceFile) return fallback;
1252
+ return (declaredName(ts, declaration)?.node ?? declaration).getStart(sourceFile);
1253
+ };
1254
+ for (const exported of checker.getExportsOfModule(moduleSymbol)) {
1255
+ const alias = (exported.flags & ts.SymbolFlags.Alias) !== 0;
1256
+ const target = alias ? checker.getAliasedSymbol(exported) : exported;
1257
+ const own = (exported.declarations ?? []).find((declaration) => declaration.getSourceFile() === sourceFile);
1258
+ if (own && isTypeOnlyExport(ts, own)) continue;
1259
+ let at;
1260
+ if (own) at = own.getStart(sourceFile);
1261
+ else {
1262
+ const star = exportStarFor(context, sourceFile, exported.name);
1263
+ if (!star || star.isTypeOnly) continue;
1264
+ at = star.getStart(sourceFile);
1265
+ }
1266
+ const declarations = target.declarations ?? [];
1267
+ if (target.flags & ts.SymbolFlags.Class) {
1268
+ const classes = declarations.filter(ts.isClassLike);
1269
+ if (classes.length === 0) continue;
1270
+ const container = declaredName(ts, classes[0])?.text ?? "default";
1271
+ const seen = /* @__PURE__ */ new Set();
1272
+ for (const classLike of classes) {
1273
+ for (const member of classLike.members) {
1274
+ if (!ts.isMethodDeclaration(member) && !ts.isGetAccessorDeclaration(member) && !ts.isPropertyDeclaration(member)) continue;
1275
+ const name = declaredName(ts, member);
1276
+ if (!name || seen.has(name.text) || !isPublic(ts, member)) continue;
1277
+ const symbol = checker.getSymbolAtLocation(name.node);
1278
+ if (!symbol) continue;
1279
+ const verdict = memberVerdict(context, member, checker.getTypeOfSymbol(symbol));
1280
+ if (!verdict) continue;
1281
+ seen.add(name.text);
1282
+ found.push({ container, member: name.text, start: startOf2(member, at), verdict });
1283
+ }
1284
+ }
1285
+ } else if (target.flags & ts.SymbolFlags.Function) {
1286
+ const declaration = declarations.find(ts.isFunctionDeclaration) ?? declarations[0];
1287
+ const member = (declaration && declaredName(ts, declaration)?.text) ?? "default";
1288
+ found.push({ container: null, member, start: startOf2(declaration, at), verdict: verdictOfSignatures(context, checker.getTypeOfSymbol(target).getCallSignatures()) });
1289
+ } else if (target.flags & ts.SymbolFlags.Variable) {
1290
+ const declaration = target.valueDeclaration ?? declarations[0];
1291
+ const type = checker.getTypeOfSymbol(target);
1292
+ const name = (declaration && declaredName(ts, declaration)?.text) ?? exported.name;
1293
+ const signatures = type.getCallSignatures();
1294
+ if (signatures.length > 0) {
1295
+ found.push({ container: null, member: name, start: startOf2(declaration, at), verdict: verdictOfSignatures(context, signatures) });
1296
+ continue;
1297
+ }
1298
+ for (const property of checker.getPropertiesOfType(type)) {
1299
+ const propertyDeclaration = property.valueDeclaration ?? property.declarations?.[0];
1300
+ if (!propertyDeclaration || policy.zones.zoneOf(propertyDeclaration.getSourceFile().fileName) !== "checked" || !isPublic(ts, propertyDeclaration)) continue;
1301
+ const verdict = memberVerdict(context, propertyDeclaration, checker.getTypeOfSymbol(property));
1302
+ if (!verdict) continue;
1303
+ found.push({ container: name, member: property.name, start: startOf2(propertyDeclaration, at), verdict });
1304
+ }
1305
+ }
1306
+ }
1307
+ return found.sort((a, b) => a.start - b.start || (boundaryName(a) < boundaryName(b) ? -1 : boundaryName(a) > boundaryName(b) ? 1 : 0));
1308
+ }
1309
+ var SOURCE_FILE = /\.(?:[cm]?[jt]sx?|svelte)$/;
1310
+ function isSourceFile(path) {
1311
+ return SOURCE_FILE.test(path) && !/\.d\.[cm]?ts$/.test(path);
1312
+ }
1313
+ function itemFiles(item, context) {
1314
+ const { policy } = context;
1315
+ return context.program.getSourceFiles().filter((file) => !file.isDeclarationFile && policy.zones.zoneOf(file.fileName) === "checked" && groupMatches(item, realPath(context, file.fileName))).map((file) => ({ file, path: policy.zones.relativePath(file.fileName) })).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0).map((entry) => entry.file);
1316
+ }
1317
+ var completeness = /* @__PURE__ */ new WeakMap();
1318
+ function itemComplete(item, context) {
1319
+ let byItem = completeness.get(context.program);
1320
+ if (!byItem) {
1321
+ byItem = /* @__PURE__ */ new Map();
1322
+ completeness.set(context.program, byItem);
1323
+ }
1324
+ const cached = byItem.get(item);
1325
+ if (cached !== void 0) return cached;
1326
+ const { policy } = context;
1327
+ const loaded = new Set(context.program.getSourceFiles().map((file) => realPath(context, file.fileName)));
1328
+ const complete = filesMatchingGroup(item).filter((path) => isSourceFile(path) && policy.zones.zoneOf(path) !== "ignore").every((path) => loaded.has(realpathOrSelf(path)));
1329
+ byItem.set(item, complete);
1330
+ return complete;
1331
+ }
1332
+ function fileBoundaries(sourceFile, context) {
1333
+ const real = realPath(context, sourceFile.fileName);
1334
+ const items = context.config.boundaries.filter((item2) => groupMatches(item2, real));
1335
+ if (items.length === 0) return { kind: "none" };
1336
+ if (items.length > 1) return { kind: "overlap", items: [items[0], items[1]] };
1337
+ const item = items[0];
1338
+ const files = itemFiles(item, context);
1339
+ const first = files.length > 0 && files[0] === sourceFile && itemComplete(item, context);
1340
+ return { kind: "boundary", item, boundaries: boundariesIn(sourceFile, context), first };
1341
+ }
1342
+ function boundaryFindingsIn(sourceFile, context, strict) {
1343
+ const file = fileBoundaries(sourceFile, context);
1344
+ if (file.kind === "none") return [];
1345
+ const { policy } = context;
1346
+ if (file.kind === "overlap") {
1347
+ const [item2, other] = file.items;
1348
+ return [{ origin: "overlapping-items", start: 0, file: null, severity: "error", data: { file: policy.zones.relativePath(sourceFile.fileName), item: itemLabel(item2), other: itemLabel(other) } }];
1349
+ }
1350
+ const { item } = file;
1351
+ const label = itemLabel(item);
1352
+ const findings = [];
1353
+ if (file.first && item.exclude.length > 0) {
1354
+ const all = itemFiles(item, context).flatMap((other) => other === sourceFile ? file.boundaries : boundariesIn(other, context));
1355
+ for (const entry of item.exclude) {
1356
+ if (!all.some((boundary) => excludeMatches(entry, boundary))) {
1357
+ findings.push({ origin: "stale-exclude", start: 0, file: policy.zones.relativePath(item.source), severity: "error", data: { entry, item: label } });
1358
+ }
1359
+ }
1360
+ }
1361
+ for (const boundary of file.boundaries) {
1362
+ if (boundary.verdict.kind === "plain" || item.exclude.some((entry) => excludeMatches(entry, boundary))) continue;
1363
+ const member = boundaryName(boundary);
1364
+ if (boundary.verdict.kind === "result") {
1365
+ findings.push({ origin: "returns-result", start: boundary.start, file: null, severity: "error", data: { member, kinds: formatFailureKinds(boundary.verdict.kinds, ANY_KIND), item: label } });
1366
+ } else {
1367
+ findings.push({ origin: "unproven-return", start: boundary.start, file: null, severity: strict ? "error" : "warning", data: { member, type: boundary.verdict.type, item: label } });
1368
+ }
1369
+ }
1370
+ return findings;
1371
+ }
1372
+
1167
1373
  // src/core/rules.ts
1168
1374
  var PROMISE_COMBINATORS = /* @__PURE__ */ new Set(["all", "allSettled", "race", "any"]);
1169
1375
  function typedGuardContext(ts, checker, policy) {
@@ -1327,6 +1533,9 @@ function conditionOperands(ts, node) {
1327
1533
  function isPromiseCondition(checker, operand) {
1328
1534
  return isAlwaysThenable(checker, checker.getTypeAtLocation(operand), operand);
1329
1535
  }
1536
+ function isResultCondition(checker, policy, operand) {
1537
+ return policy.isResultType(checker.getTypeAtLocation(operand));
1538
+ }
1330
1539
  function returnsThenable(checker, type, node) {
1331
1540
  return unionParts(type).some(
1332
1541
  (part) => part.getCallSignatures().some((signature) => isSometimesThenable(checker, signature.getReturnType(), node))
@@ -2892,7 +3101,7 @@ var emptyConfigs = /* @__PURE__ */ new Map();
2892
3101
  function emptyTrustConfig(cwd) {
2893
3102
  let config = emptyConfigs.get(cwd);
2894
3103
  if (!config) {
2895
- config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [], strict: [], tsconfig: [], rules: DEFAULT_RULE_SETTINGS, unmatchedGlobs: [] };
3104
+ config = { file: "", rootDir: realpathOrSelf(cwd), levels: [], passthrough: [], ignore: [], strict: [], boundaries: [], tsconfig: [], rules: DEFAULT_RULE_SETTINGS, unmatchedGlobs: [] };
2896
3105
  emptyConfigs.set(cwd, config);
2897
3106
  }
2898
3107
  return config;
@@ -2911,6 +3120,9 @@ function policyFor(ts, checker, config, extraTrust = []) {
2911
3120
  byKey.set(key, { config, policy });
2912
3121
  return policy;
2913
3122
  }
3123
+ function isStrictByConfig(config, fileName) {
3124
+ return config.strict.some((group) => groupMatches(group, realpathOrSelf(fileName)));
3125
+ }
2914
3126
  function positionAt(ts, sourceFile, offset) {
2915
3127
  const position = ts.getLineAndCharacterOfPosition(sourceFile, offset);
2916
3128
  return { line: position.line + 1, column: position.character + 1 };
@@ -2948,6 +3160,9 @@ function checkSourceFileWithAccepted(options) {
2948
3160
  if (!acceptance) report(found.node, found.rule, found.origin, found.message);
2949
3161
  else accepted.push({ finding: findingAt(found.node.getStart(sourceFile), found.rule, found.origin, found.message), text: found.node.getText(sourceFile), acceptance });
2950
3162
  }
3163
+ for (const operand of conditionOperands(ts, node)) {
3164
+ if (isResultCondition(checker, policy, operand)) report(operand, RESULT_CONDITION_RULE, RESULT_CONDITION_ORIGIN, RESULT_CONDITION_MESSAGE);
3165
+ }
2951
3166
  if (claimContext) for (const claim2 of typeClaimsAt(node, claimContext)) reportClaim(claim2);
2952
3167
  const value = valueContext ? untrustedValueAt(node, valueContext) : null;
2953
3168
  if (value?.outcome === "finding") report(node, UNTRUSTED_VALUE_RULE, value.origin, untrustedValueMessage(value));
@@ -2967,6 +3182,13 @@ function checkSourceFileWithAccepted(options) {
2967
3182
  reportAt(guard.start, REDUNDANT_GUARD_RULE, REDUNDANT_GUARD_ORIGIN, redundantGuardMessage(guard));
2968
3183
  }
2969
3184
  }
3185
+ if (config.boundaries.length > 0) {
3186
+ const strict = options.strict ?? isStrictByConfig(config, sourceFile.fileName);
3187
+ for (const found of boundaryFindingsIn(sourceFile, boundaryContext(ts, checker, options.program, policy, config), strict)) {
3188
+ const finding = findingAt(found.start, BOUNDARY_RULE, found.origin, boundaryMessage(found));
3189
+ findings.push({ ...finding, file: found.file ?? finding.file, ...found.severity === "warning" ? { severity: "warning" } : {} });
3190
+ }
3191
+ }
2970
3192
  const svelte = svelteFor(checker);
2971
3193
  const snippetTrusted = policy.lookup("svelte.__renderSnippet", "svelte").trusted && !("distrustedBy" in policy.lookup("svelte.Snippet", "svelte"));
2972
3194
  return { findings: svelte ? findings.flatMap((finding) => {
@@ -2979,9 +3201,16 @@ export {
2979
3201
  alwaysExits,
2980
3202
  catchProblem,
2981
3203
  guardOf,
3204
+ ANY_KIND,
2982
3205
  droppedResultContext,
2983
3206
  droppedResultData,
2984
3207
  droppedResultsIn,
3208
+ boundaryContext,
3209
+ boundaryName,
3210
+ excludeMatches,
3211
+ itemLabel,
3212
+ fileBoundaries,
3213
+ boundaryFindingsIn,
2985
3214
  entryMatches,
2986
3215
  decide,
2987
3216
  TrustPolicy,
@@ -3008,9 +3237,10 @@ export {
3008
3237
  untrustedValueMessage,
3009
3238
  emptyTrustConfig,
3010
3239
  policyFor,
3240
+ isStrictByConfig,
3011
3241
  positionAt,
3012
3242
  startOf,
3013
3243
  checkSourceFile,
3014
3244
  checkSourceFileWithAccepted
3015
3245
  };
3016
- //# sourceMappingURL=chunk-7PY2Q6OX.js.map
3246
+ //# sourceMappingURL=chunk-LJJDRFO7.js.map