@noego/trust 0.5.1-dev.3 → 0.5.1-dev.5

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.
@@ -8,6 +8,9 @@ import {
8
8
  DIRECTIVE_ORIGIN,
9
9
  DROPPED_RESULT_MESSAGES,
10
10
  DROPPED_RESULT_RULE,
11
+ FINALLY_RETURN_MESSAGES,
12
+ FINALLY_RETURN_ORIGIN,
13
+ FINALLY_RETURN_RULE,
11
14
  FLOATING_PROMISE_MESSAGE,
12
15
  FLOATING_PROMISE_ORIGIN,
13
16
  FLOATING_PROMISE_RULE,
@@ -53,7 +56,7 @@ import {
53
56
  resultLookalikeMessage,
54
57
  svelteFor,
55
58
  trustDirectivesIn
56
- } from "./chunk-VJGGEY4G.js";
59
+ } from "./chunk-4XGOH7JE.js";
57
60
 
58
61
  // src/core/guard.ts
59
62
  function unparen(ts, node) {
@@ -351,7 +354,7 @@ var TrustPolicy = class {
351
354
  // src/core/dropped-results.ts
352
355
  var ANY_KIND = "*";
353
356
  function droppedResultContext(ts, checker, policy) {
354
- return { ts, checker, policy, kindCache: /* @__PURE__ */ new WeakMap() };
357
+ return { ts, checker, policy, kindCache: /* @__PURE__ */ new WeakMap(), stateCache: /* @__PURE__ */ new WeakMap() };
355
358
  }
356
359
  function droppedResultData(dropped) {
357
360
  return { subject: dropped.subject, kinds: formatFailureKinds(dropped.kinds, ANY_KIND) };
@@ -359,6 +362,13 @@ function droppedResultData(dropped) {
359
362
  function droppedResultMessage(dropped) {
360
363
  return fillMessage(DROPPED_RESULT_MESSAGES[dropped.origin], droppedResultData(dropped));
361
364
  }
365
+ var State = class extends Map {
366
+ outstandingIterables;
367
+ constructor(source) {
368
+ super(source);
369
+ this.outstandingIterables = new Set(source?.outstandingIterables);
370
+ }
371
+ };
362
372
  var NOTHING = /* @__PURE__ */ new Set();
363
373
  var ELEMENT_METHODS = /* @__PURE__ */ new Set([
364
374
  "filter",
@@ -394,19 +404,108 @@ function union(a, b) {
394
404
  if (b.size === 0) return a;
395
405
  return /* @__PURE__ */ new Set([...a, ...b]);
396
406
  }
407
+ function intersectPeers(a, b) {
408
+ if (!a?.size || !b?.size) return void 0;
409
+ const out = /* @__PURE__ */ new Set();
410
+ for (const s of a) if (b.has(s)) out.add(s);
411
+ return out.size ? out : void 0;
412
+ }
413
+ function sideKinds(side, other, symbol) {
414
+ const entry = side.get(symbol);
415
+ if (!entry) return NOTHING;
416
+ if (!entry.peers?.size || entry.version === void 0) return entry.kinds;
417
+ let groupKinds = NOTHING;
418
+ let hasSurvivor = false;
419
+ for (const p of entry.peers) {
420
+ const pv = side.get(p);
421
+ if (pv?.kinds.size) groupKinds = union(groupKinds, pv.kinds);
422
+ if (other.get(p)?.version === entry.version) hasSurvivor = true;
423
+ }
424
+ if (!groupKinds.size) return NOTHING;
425
+ if (!hasSurvivor) return entry.kinds;
426
+ return other.get(symbol)?.version === entry.version ? groupKinds : NOTHING;
427
+ }
397
428
  function merge(a, b) {
398
- if (!a) return b ? new Map(b) : null;
399
- const merged = new Map(a);
400
- if (!b) return merged;
429
+ if (!a) return b ? new State(b) : null;
430
+ if (!b) return new State(a);
431
+ const merged = new State();
432
+ for (const path of [a, b]) for (const loop of path.outstandingIterables) merged.outstandingIterables.add(loop);
433
+ for (const [symbol, left] of a) {
434
+ const right = b.get(symbol);
435
+ if (right) {
436
+ let peers = intersectPeers(left.peers, right.peers);
437
+ if (peers && peers.size <= 1) peers = void 0;
438
+ const version = left.version !== void 0 && left.version === right.version ? left.version : void 0;
439
+ const kinds = union(sideKinds(a, b, symbol), sideKinds(b, a, symbol));
440
+ merged.set(symbol, {
441
+ kinds,
442
+ err: left.err && right.err,
443
+ ...peers ? { peers } : {},
444
+ ...version !== void 0 ? { version } : {}
445
+ });
446
+ } else {
447
+ merged.set(symbol, {
448
+ kinds: sideKinds(a, b, symbol),
449
+ err: left.err
450
+ });
451
+ }
452
+ }
401
453
  for (const [symbol, right] of b) {
402
- const left = merged.get(symbol);
403
- merged.set(symbol, left ? { kinds: union(left.kinds, right.kinds), err: left.err && right.err } : right);
454
+ if (!a.has(symbol)) {
455
+ merged.set(symbol, {
456
+ kinds: sideKinds(b, a, symbol),
457
+ err: right.err
458
+ });
459
+ }
460
+ }
461
+ const byPeerGroup = /* @__PURE__ */ new Map();
462
+ for (const [symbol, val] of merged) {
463
+ if (!val.peers?.size) continue;
464
+ let foundKey;
465
+ for (const k of byPeerGroup.keys()) {
466
+ if (k.size === val.peers.size && [...k].every((s) => val.peers.has(s))) {
467
+ foundKey = k;
468
+ break;
469
+ }
470
+ }
471
+ if (foundKey) byPeerGroup.get(foundKey).push(symbol);
472
+ else byPeerGroup.set(val.peers, [symbol]);
473
+ }
474
+ for (const [groupKey, membersList] of byPeerGroup) {
475
+ let combined = NOTHING;
476
+ for (const s of membersList) {
477
+ const sv = merged.get(s);
478
+ if (sv?.kinds.size) combined = union(combined, sv.kinds);
479
+ }
480
+ if (combined.size) {
481
+ const owner = membersList[0];
482
+ for (const s of membersList) {
483
+ const sv = merged.get(s);
484
+ merged.set(s, {
485
+ kinds: s === owner ? combined : NOTHING,
486
+ err: sv.err,
487
+ peers: groupKey,
488
+ ...sv.version !== void 0 ? { version: sv.version } : {}
489
+ });
490
+ }
491
+ }
404
492
  }
405
493
  return merged;
406
494
  }
495
+ function memberAccessName(ts, node) {
496
+ if (ts.isPropertyAccessExpression(node)) return node.name.text;
497
+ if (ts.isElementAccessExpression(node) && node.argumentExpression) return stringLiteral(ts, node.argumentExpression);
498
+ return void 0;
499
+ }
407
500
  function mergeAll(states) {
408
501
  return states.reduce((merged, state) => merge(merged, state), null);
409
502
  }
503
+ function replaceState(state, joined) {
504
+ state.clear();
505
+ for (const [symbol, value] of joined) state.set(symbol, value);
506
+ state.outstandingIterables.clear();
507
+ for (const loop of joined.outstandingIterables) state.outstandingIterables.add(loop);
508
+ }
410
509
  function argumentsOf(call) {
411
510
  return call.arguments ?? [];
412
511
  }
@@ -456,6 +555,31 @@ function failureKinds(context, type) {
456
555
  context.kindCache.set(type, result);
457
556
  return result;
458
557
  }
558
+ function okStateKinds(context, type, states) {
559
+ const { ts, checker, policy } = context;
560
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return;
561
+ for (const member of members(checker.getAwaitedType(type) ?? type)) {
562
+ for (const name of policy.okStates(member) ?? []) states.add(name);
563
+ }
564
+ }
565
+ function stateKinds(context, type) {
566
+ const cached = context.stateCache?.get(type);
567
+ if (cached !== void 0) return cached;
568
+ const { ts, checker, policy } = context;
569
+ let result = null;
570
+ if (!(type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never))) {
571
+ const states = /* @__PURE__ */ new Set();
572
+ okStateKinds(context, type, states);
573
+ for (const member of members(checker.getAwaitedType(type) ?? type)) {
574
+ if (member.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any) || policy.resultVariant(member) !== null) continue;
575
+ const element = checker.getIndexTypeOfType(member, ts.IndexKind.Number);
576
+ if (element) okStateKinds(context, element, states);
577
+ }
578
+ result = states.size ? states : null;
579
+ }
580
+ context.stateCache?.set(type, result);
581
+ return result;
582
+ }
459
583
  function subjectOf(node, sourceFile) {
460
584
  const text = node.getText(sourceFile).replace(/\s+/g, " ").trim();
461
585
  return text.length > SUBJECT_LIMIT ? `${text.slice(0, SUBJECT_LIMIT - 1)}\u2026` : text;
@@ -508,18 +632,25 @@ var DropWalk = class {
508
632
  failureCarriers = /* @__PURE__ */ new Map();
509
633
  targets = [];
510
634
  reported = /* @__PURE__ */ new Set();
635
+ callStates = /* @__PURE__ */ new Map();
636
+ activeForOfs = /* @__PURE__ */ new Map();
637
+ handedSnapshots = /* @__PURE__ */ new Map();
638
+ handedSources = /* @__PURE__ */ new Map();
639
+ handedVersions = /* @__PURE__ */ new Map();
640
+ spliceEmptyBeforeCall = /* @__PURE__ */ new Set();
641
+ nextVersion = 1;
511
642
  /** Where `var` declarations live. */
512
643
  functionScope;
513
644
  run() {
514
645
  const ts = this.ts;
515
646
  const owner = this.owner;
516
647
  if (ts.isSourceFile(owner)) {
517
- this.statements(owner.statements, /* @__PURE__ */ new Map(), owner);
648
+ this.statements(owner.statements, new State(), owner);
518
649
  return;
519
650
  }
520
651
  const body = owner.body;
521
652
  if (!body) return;
522
- const state = /* @__PURE__ */ new Map();
653
+ const state = new State();
523
654
  if (!ts.isClassStaticBlockDeclaration(owner) && !this.isPredicateCallback(owner)) {
524
655
  for (const parameter of owner.parameters) this.declare(parameter.name, body, state, true);
525
656
  }
@@ -530,14 +661,31 @@ var DropWalk = class {
530
661
  this.visit(body, state);
531
662
  this.checkReturn(body, body, state);
532
663
  }
533
- /** The function is the predicate of `xs.filter(…)` / `find` / `some` / …: it looks at elements its receiver keeps. */
664
+ /** The function is the callback of `xs.forEach(…)` (or another call whose signature ignores the callback return value). */
665
+ isDiscardedReturnCallback(owner) {
666
+ const ts = this.ts;
667
+ if (!ts.isArrowFunction(owner) && !ts.isFunctionExpression(owner)) return false;
668
+ const call = esParent(ts, owner);
669
+ if (!call || !(ts.isCallExpression(call) || ts.isNewExpression(call))) return false;
670
+ const args = argumentsOf(call);
671
+ const argIndex = args.findIndex((a) => unparen(ts, a) === owner);
672
+ if (argIndex < 0) return false;
673
+ const callee = ts.isCallExpression(call) ? unparen(ts, call.expression) : void 0;
674
+ if (callee && memberAccessName(ts, callee) === "forEach") return argIndex === 0;
675
+ const paramType = this.instantiatedParameterType(call, argIndex) ?? this.declaredParameterType(call, argIndex);
676
+ if (!paramType) return false;
677
+ const sigs = members(paramType).flatMap((m) => m.getCallSignatures());
678
+ if (!sigs.length) return false;
679
+ return sigs.every((sig) => (sig.getReturnType().flags & ts.TypeFlags.Void) !== 0 && !this.typeKinds(sig.getReturnType()));
680
+ }
534
681
  isPredicateCallback(owner) {
535
682
  const ts = this.ts;
536
683
  if (!ts.isArrowFunction(owner) && !ts.isFunctionExpression(owner)) return false;
537
684
  const call = owner.parent;
538
685
  if (!ts.isCallExpression(call) || !call.arguments.includes(owner)) return false;
539
686
  const callee = unparen(ts, call.expression);
540
- return ts.isPropertyAccessExpression(callee) && PREDICATE_METHODS.has(callee.name.text);
687
+ const methodName = memberAccessName(ts, callee);
688
+ return methodName !== void 0 && PREDICATE_METHODS.has(methodName);
541
689
  }
542
690
  // ---- reporting ----
543
691
  report(origin, at, subject, kinds) {
@@ -552,12 +700,48 @@ var DropWalk = class {
552
700
  /** Reports and forgets the variables living in `scope` (or, with `inside`, anywhere inside it) that can still fail. */
553
701
  leaveScope(scope, state, at, inside = false, keep) {
554
702
  if (!state) return null;
555
- const left = new Map(state);
703
+ const left = new State(state);
556
704
  for (const [symbol, info] of this.tracked) {
557
705
  const leaving = inside ? within(info.scope, scope) : info.scope === scope;
558
706
  if (!leaving || keep?.(info)) continue;
559
707
  const value = left.get(symbol);
560
- if (value && value.kinds.size > 0) this.reportVariable("end", at, symbol, value.kinds);
708
+ if (value && value.kinds.size > 0) {
709
+ let transferred = false;
710
+ if (this.stateFound && value.peers?.size) {
711
+ const surviving = [...value.peers].filter((peer) => {
712
+ if (peer === symbol || !left.has(peer)) return false;
713
+ const pInfo = this.tracked.get(peer);
714
+ if (!pInfo) return false;
715
+ const pLeaving = inside ? within(pInfo.scope, scope) : pInfo.scope === scope;
716
+ return !pLeaving || Boolean(keep?.(pInfo));
717
+ });
718
+ if (surviving.length) {
719
+ const owner = surviving[0];
720
+ const existing = left.get(owner);
721
+ if (existing) {
722
+ const nextPeers = new Set(surviving);
723
+ left.set(owner, { kinds: union(existing.kinds, value.kinds), err: existing.err, peers: nextPeers, ...existing.version !== void 0 ? { version: existing.version } : {} });
724
+ for (const s of surviving.slice(1)) {
725
+ const sv = left.get(s);
726
+ if (sv) left.set(s, { kinds: sv.kinds, err: sv.err, peers: nextPeers, ...sv.version !== void 0 ? { version: sv.version } : {} });
727
+ }
728
+ transferred = true;
729
+ }
730
+ }
731
+ }
732
+ if (!transferred) this.reportVariable("end", at, symbol, value.kinds);
733
+ }
734
+ if (value?.peers?.size) {
735
+ for (const peer of value.peers) {
736
+ if (peer === symbol) continue;
737
+ const pv = left.get(peer);
738
+ if (pv?.peers?.has(symbol)) {
739
+ const nextPeers = new Set(pv.peers);
740
+ nextPeers.delete(symbol);
741
+ left.set(peer, { kinds: pv.kinds, err: pv.err, ...nextPeers.size > 1 ? { peers: nextPeers } : {}, ...pv.version !== void 0 ? { version: pv.version } : {} });
742
+ }
743
+ }
744
+ }
561
745
  left.delete(symbol);
562
746
  }
563
747
  return left;
@@ -568,12 +752,7 @@ var DropWalk = class {
568
752
  }
569
753
  typeKinds(type) {
570
754
  if (!type) return null;
571
- if (!this.stateFound) return failureKinds(this.context, type);
572
- const states = /* @__PURE__ */ new Set();
573
- for (const member of members(this.checker.getAwaitedType(type) ?? type)) {
574
- for (const name of this.context.policy.okStates(member) ?? []) states.add(name);
575
- }
576
- return states.size ? states : null;
755
+ return this.stateFound ? stateKinds(this.context, type) : failureKinds(this.context, type);
577
756
  }
578
757
  trackedSymbol(node, state) {
579
758
  const inner = unparen(this.ts, node);
@@ -586,38 +765,99 @@ var DropWalk = class {
586
765
  const name = this.context.policy.trustFunctionName(call);
587
766
  return name === "decide" || name === "translate";
588
767
  }
768
+ tupleSlotAt(ref, idx, sourceLen) {
769
+ const flags = ref.target.elementFlags;
770
+ const elems = this.checker.getTypeArguments(ref);
771
+ const varIdx = elems.findIndex((_, ti) => (flags[ti] & this.ts.ElementFlags.Variable) !== 0);
772
+ if (varIdx < 0) return elems[idx];
773
+ if (idx < varIdx) return elems[idx];
774
+ const suffixCount = elems.length - 1 - varIdx;
775
+ if (sourceLen !== void 0 && suffixCount > 0 && idx >= sourceLen - suffixCount) {
776
+ return elems[elems.length - (sourceLen - idx)];
777
+ }
778
+ return this.checker.getIndexTypeOfType(elems[varIdx], this.ts.IndexKind.Number) ?? elems[varIdx];
779
+ }
780
+ tupleSlotFromEnd(ref, fromEnd) {
781
+ const flags = ref.target.elementFlags;
782
+ const elems = this.checker.getTypeArguments(ref);
783
+ const varIdx = elems.findIndex((_, ti) => (flags[ti] & this.ts.ElementFlags.Variable) !== 0);
784
+ if (varIdx >= 0) {
785
+ const suffixCount = elems.length - 1 - varIdx;
786
+ if (fromEnd <= suffixCount) return elems[elems.length - fromEnd];
787
+ return this.checker.getIndexTypeOfType(elems[varIdx], this.ts.IndexKind.Number) ?? elems[varIdx];
788
+ }
789
+ return elems.length >= fromEnd ? elems[elems.length - fromEnd] : void 0;
790
+ }
791
+ restSlotTypes(call, restStart, restType, offset, totalRestArgs, fromEndOffset, fullRestSpread) {
792
+ const unwrapped = this.checker.getAwaitedType(restType) ?? restType;
793
+ const rawMs = members(unwrapped);
794
+ const compatible = fullRestSpread && typeof this.checker.isTypeAssignableTo === "function" ? rawMs.filter((tm) => this.checker.isTypeAssignableTo(fullRestSpread, tm)) : rawMs.length > 1 && typeof this.checker.isTypeAssignableTo === "function" && !argumentsOf(call).some(this.ts.isSpreadElement) ? rawMs.filter((tm) => {
795
+ if (this.checker.isTupleType(tm)) {
796
+ const tuple = tm.target;
797
+ const count = argumentsOf(call).length - restStart;
798
+ if (count < tuple.minLength || !(tuple.combinedFlags & this.ts.ElementFlags.Variable) && count > tuple.elementFlags.length) return false;
799
+ }
800
+ return argumentsOf(call).slice(restStart).every((a, i) => {
801
+ const slot = this.checker.isTupleType(tm) ? this.tupleSlotAt(tm, i, totalRestArgs) : this.checker.getIndexTypeOfType(tm, this.ts.IndexKind.Number);
802
+ return slot && this.checker.isTypeAssignableTo(this.checker.getTypeAtLocation(a), slot);
803
+ });
804
+ }) : [];
805
+ const ms = compatible.length ? compatible : rawMs;
806
+ const out = [];
807
+ for (const m of ms) {
808
+ if (this.checker.isTupleType(m)) {
809
+ const ref = m;
810
+ const slot = fromEndOffset !== void 0 ? this.tupleSlotFromEnd(ref, fromEndOffset) : this.tupleSlotAt(ref, offset, totalRestArgs);
811
+ if (slot) out.push(slot);
812
+ } else {
813
+ const indexed = this.checker.getIndexTypeOfType(m, this.ts.IndexKind.Number);
814
+ if (indexed) out.push(indexed);
815
+ }
816
+ }
817
+ return out;
818
+ }
589
819
  /** The declared (not instantiated) type of the parameter that receives argument `index`. */
590
- declaredParameterType(call, index) {
820
+ declaredParameterTypes(call, index, totalArgs, fromEndArgs, fullRestSpread) {
591
821
  const ts = this.ts;
592
822
  const declaration = this.checker.getResolvedSignature(call)?.getDeclaration();
593
- if (!declaration || ts.isJSDocSignature(declaration)) return void 0;
823
+ if (!declaration || ts.isJSDocSignature(declaration)) return [];
594
824
  const parameters = declaration.parameters;
595
825
  const last = parameters[parameters.length - 1];
596
826
  if (last?.dotDotDotToken && index >= parameters.length - 1) {
827
+ const restStart = parameters.length - 1;
597
828
  const restType = this.checker.getTypeAtLocation(last);
598
- return this.checker.getIndexTypeOfType(restType, ts.IndexKind.Number);
829
+ const totalRest = totalArgs !== void 0 && totalArgs >= restStart ? totalArgs - restStart : void 0;
830
+ return this.restSlotTypes(call, restStart, restType, index - restStart, totalRest, fromEndArgs, fullRestSpread);
599
831
  }
600
832
  const parameter = parameters[index];
601
- return parameter ? this.checker.getTypeAtLocation(parameter) : void 0;
833
+ return parameter ? [this.checker.getTypeAtLocation(parameter)] : [];
834
+ }
835
+ declaredParameterType(call, index, totalArgs, fromEndArgs) {
836
+ return this.declaredParameterTypes(call, index, totalArgs, fromEndArgs)[0];
602
837
  }
603
838
  /**
604
839
  * The type of the parameter that receives argument `index` at this call: type parameters filled in, so
605
840
  * `resolve` of a `new Promise<Result<…>>`, `map.set(id, pending)` on a `Map<string, Promise<Result<…>>>` or
606
841
  * `Result.ok(() => …)` take a Result here.
607
842
  */
608
- instantiatedParameterType(call, index) {
843
+ instantiatedParameterTypes(call, index, totalArgs, fromEndArgs, fullRestSpread) {
609
844
  const ts = this.ts;
610
845
  const signature = this.checker.getResolvedSignature(call);
611
- if (!signature) return void 0;
846
+ if (!signature) return [];
612
847
  const parameters = signature.getParameters();
613
848
  const last = parameters[parameters.length - 1];
614
849
  const lastDeclaration = last?.valueDeclaration;
615
850
  const isRest = lastDeclaration !== void 0 && ts.isParameter(lastDeclaration) && lastDeclaration.dotDotDotToken !== void 0;
616
851
  if (isRest && index >= parameters.length - 1) {
617
- return this.checker.getIndexTypeOfType(this.checker.getTypeOfSymbolAtLocation(last, call), ts.IndexKind.Number);
852
+ const restStart = parameters.length - 1;
853
+ const totalRest = totalArgs !== void 0 && totalArgs >= restStart ? totalArgs - restStart : void 0;
854
+ return this.restSlotTypes(call, restStart, this.checker.getTypeOfSymbolAtLocation(last, call), index - restStart, totalRest, fromEndArgs, fullRestSpread);
618
855
  }
619
856
  const parameter = parameters[index];
620
- return parameter ? this.checker.getTypeOfSymbolAtLocation(parameter, call) : void 0;
857
+ return parameter ? [this.checker.getTypeOfSymbolAtLocation(parameter, call)] : [];
858
+ }
859
+ instantiatedParameterType(call, index, totalArgs, fromEndArgs) {
860
+ return this.instantiatedParameterTypes(call, index, totalArgs, fromEndArgs)[0];
621
861
  }
622
862
  /** A Result, or a function returning one. */
623
863
  takesResult(type) {
@@ -625,26 +865,262 @@ var DropWalk = class {
625
865
  if (this.typeKinds(type)) return true;
626
866
  return members(type).some((member) => member.getCallSignatures().some((signature) => this.typeKinds(signature.getReturnType()) !== null));
627
867
  }
868
+ targetTakesValue(sourceType, targetType, seen = /* @__PURE__ */ new Set()) {
869
+ if (!targetType) return false;
870
+ const targetUnwrapped = this.checker.getAwaitedType(targetType) ?? targetType;
871
+ const sourceUnwrapped = this.checker.getAwaitedType(sourceType) ?? sourceType;
872
+ const sId = sourceUnwrapped.id;
873
+ const tId = targetUnwrapped.id;
874
+ if (sId !== void 0 && tId !== void 0) {
875
+ const pairKey = `${sId}:${tId}`;
876
+ if (seen.has(pairKey)) return this.takesResult(targetType);
877
+ seen.add(pairKey);
878
+ }
879
+ const tms = members(targetUnwrapped);
880
+ const nonNullishTms = tms.filter((tm) => !(tm.flags & (this.ts.TypeFlags.Undefined | this.ts.TypeFlags.Null | this.ts.TypeFlags.Void)));
881
+ if (nonNullishTms.length && nonNullishTms.every((tm) => this.checker.isTupleType(tm))) {
882
+ const sms = members(sourceUnwrapped);
883
+ for (const sm of sms) {
884
+ if (sm.flags & (this.ts.TypeFlags.Undefined | this.ts.TypeFlags.Null | this.ts.TypeFlags.Void)) continue;
885
+ const compatibleTargets = typeof this.checker.isTypeAssignableTo === "function" ? nonNullishTms.filter((tm) => this.checker.isTypeAssignableTo(sm, tm)) : [];
886
+ const activeTargets = compatibleTargets.length ? compatibleTargets : nonNullishTms;
887
+ if (this.checker.isTupleType(sm)) {
888
+ const sRef = sm;
889
+ const sFlags = sRef.target.elementFlags;
890
+ const sElems = this.checker.getTypeArguments(sRef);
891
+ const sHasVar = Boolean(sRef.target.combinedFlags & this.ts.ElementFlags.Variable);
892
+ for (const tm of activeTargets) {
893
+ const tRef = tm;
894
+ const tFlags = tRef.target.elementFlags;
895
+ const tElems = this.checker.getTypeArguments(tRef);
896
+ const tVarIdx = tElems.findIndex((_, ti) => (tFlags[ti] & this.ts.ElementFlags.Variable) !== 0);
897
+ const tSuffixCount = tVarIdx >= 0 ? tElems.length - 1 - tVarIdx : 0;
898
+ for (let k = 0; k < sElems.length; k++) {
899
+ const sIsVar = (sFlags[k] & this.ts.ElementFlags.Variable) !== 0;
900
+ const sElem = sIsVar ? this.checker.getIndexTypeOfType(sElems[k], this.ts.IndexKind.Number) ?? sElems[k] : sElems[k];
901
+ if (!this.typeKinds(sElem)) continue;
902
+ if (sIsVar) {
903
+ const sSuffixCount = sElems.length - 1 - k;
904
+ if (tVarIdx >= 0) {
905
+ const varType = this.checker.getIndexTypeOfType(tElems[tVarIdx], this.ts.IndexKind.Number) ?? tElems[tVarIdx];
906
+ if (!this.targetTakesValue(sElem, varType, seen)) return false;
907
+ for (let p = k; p < tVarIdx; p++) if (!this.targetTakesValue(sElem, tElems[p], seen)) return false;
908
+ const extraSuffix = tSuffixCount - sSuffixCount;
909
+ for (let s = 0; s < extraSuffix; s++) {
910
+ if (!this.targetTakesValue(sElem, tElems[tVarIdx + 1 + s], seen)) return false;
911
+ }
912
+ } else {
913
+ const end = Math.max(tElems.length - sSuffixCount, k);
914
+ for (let p = k; p < end; p++) if (!this.targetTakesValue(sElem, tElems[p], seen)) return false;
915
+ }
916
+ } else {
917
+ let pt;
918
+ if (!sHasVar) {
919
+ pt = this.tupleSlotAt(tRef, k, sElems.length);
920
+ } else {
921
+ const sVarIdx = sElems.findIndex((_, si) => (sFlags[si] & this.ts.ElementFlags.Variable) !== 0);
922
+ if (k < sVarIdx) pt = this.tupleSlotAt(tRef, k);
923
+ else {
924
+ const offsetFromEnd = sElems.length - k;
925
+ if (tVarIdx >= 0) {
926
+ if (offsetFromEnd <= tSuffixCount) pt = tElems[tElems.length - offsetFromEnd];
927
+ else pt = this.checker.getIndexTypeOfType(tElems[tVarIdx], this.ts.IndexKind.Number) ?? tElems[tVarIdx];
928
+ } else {
929
+ pt = tElems.length >= offsetFromEnd ? tElems[tElems.length - offsetFromEnd] : void 0;
930
+ }
931
+ }
932
+ }
933
+ if (!this.targetTakesValue(sElem, pt, seen)) return false;
934
+ }
935
+ }
936
+ }
937
+ } else {
938
+ const sElem = this.checker.getIndexTypeOfType(sm, this.ts.IndexKind.Number);
939
+ if (!sElem || !this.typeKinds(sElem)) continue;
940
+ for (const tm of activeTargets) {
941
+ const tRef = tm;
942
+ const tFlags = tRef.target.elementFlags;
943
+ const tElems = this.checker.getTypeArguments(tRef);
944
+ for (let p = 0; p < tElems.length; p++) {
945
+ const pt = (tFlags[p] & this.ts.ElementFlags.Variable) !== 0 ? this.checker.getIndexTypeOfType(tElems[p], this.ts.IndexKind.Number) ?? tElems[p] : tElems[p];
946
+ if (!this.targetTakesValue(sElem, pt, seen)) return false;
947
+ }
948
+ }
949
+ }
950
+ }
951
+ return this.takesResult(targetType);
952
+ }
953
+ return this.takesResult(targetType);
954
+ }
955
+ callEffectiveParamCount(call) {
956
+ const signature = this.checker.getResolvedSignature(call);
957
+ if (!signature) return 0;
958
+ const parameters = signature.getParameters();
959
+ const last = parameters[parameters.length - 1];
960
+ const lastDecl = last?.valueDeclaration;
961
+ if (lastDecl && this.ts.isParameter(lastDecl) && lastDecl.dotDotDotToken) {
962
+ const restType = this.checker.getTypeOfSymbolAtLocation(last, call);
963
+ const unwrapped = this.checker.getAwaitedType(restType) ?? restType;
964
+ let maxExtra = 1;
965
+ for (const m of members(unwrapped)) {
966
+ if (this.checker.isTupleType(m)) maxExtra = Math.max(maxExtra, this.checker.getTypeArguments(m).length);
967
+ }
968
+ return parameters.length - 1 + maxExtra;
969
+ }
970
+ return parameters.length;
971
+ }
972
+ callExactArgCount(call) {
973
+ const ts = this.ts;
974
+ let total = 0;
975
+ for (const current of argumentsOf(call)) {
976
+ if (!ts.isSpreadElement(current)) {
977
+ total += 1;
978
+ continue;
979
+ }
980
+ const type = this.checker.getTypeAtLocation(current.expression);
981
+ const unwrapped = this.checker.getAwaitedType(type) ?? type;
982
+ const ms = members(unwrapped);
983
+ if (!ms.length || !ms.every((m) => this.checker.isTupleType(m))) return void 0;
984
+ let len;
985
+ for (const m of ms) {
986
+ const ref = m;
987
+ if (ref.target.combinedFlags & ts.ElementFlags.NonRequired) return void 0;
988
+ const mLen = this.checker.getTypeArguments(ref).length;
989
+ if (len === void 0) len = mLen;
990
+ else if (len !== mLen) return void 0;
991
+ }
992
+ total += len ?? 0;
993
+ }
994
+ return total;
995
+ }
628
996
  /**
629
997
  * The callee takes the failure over: its parameter is a Result (or a function returning one), as declared or as
630
998
  * this call fills in its type parameters. `console.log(…)` (`any`) and `String(…)` (`unknown`) take nothing.
631
999
  */
632
1000
  acceptsArgument(call, argument) {
633
- const index = argumentsOf(call).indexOf(argument);
634
- if (index < 0) return false;
635
- return this.takesResult(this.declaredParameterType(call, index)) || this.takesResult(this.instantiatedParameterType(call, index));
1001
+ const ts = this.ts;
1002
+ const args = argumentsOf(call);
1003
+ const totalArgs = this.callExactArgCount(call);
1004
+ const signature = this.checker.getResolvedSignature(call);
1005
+ const sigParams = signature?.getParameters() ?? [];
1006
+ const lastParam = sigParams[sigParams.length - 1];
1007
+ const lastDecl = lastParam?.valueDeclaration;
1008
+ const hasRestParam = Boolean(lastDecl && ts.isParameter(lastDecl) && lastDecl.dotDotDotToken);
1009
+ const restStart = sigParams.length - 1;
1010
+ const takesValueAt = (sourceType, index, fromEndArgs, fullRestSpread) => {
1011
+ const declTypes = this.declaredParameterTypes(call, index, totalArgs, fromEndArgs, fullRestSpread);
1012
+ if (declTypes.length && declTypes.every((pt) => this.targetTakesValue(sourceType, pt))) return true;
1013
+ const instTypes = this.instantiatedParameterTypes(call, index, totalArgs, fromEndArgs, fullRestSpread);
1014
+ return instTypes.length > 0 && instTypes.every((pt) => this.targetTakesValue(sourceType, pt));
1015
+ };
1016
+ const paramCount = this.callEffectiveParamCount(call);
1017
+ let cursor = 0;
1018
+ let seenVariadic = false;
1019
+ for (let argIdx = 0; argIdx < args.length; argIdx++) {
1020
+ const current = args[argIdx];
1021
+ if (current === argument) {
1022
+ const trailingFixedArgs = (() => {
1023
+ let count = 0;
1024
+ for (let j = argIdx + 1; j < args.length; j++) {
1025
+ const nextArg = args[j];
1026
+ if (!ts.isSpreadElement(nextArg)) {
1027
+ count += 1;
1028
+ continue;
1029
+ }
1030
+ const nt = this.checker.getTypeAtLocation(nextArg.expression);
1031
+ const nu = this.checker.getAwaitedType(nt) ?? nt;
1032
+ const nms = members(nu);
1033
+ if (!nms.length || !nms.every((m) => this.checker.isTupleType(m))) return void 0;
1034
+ let len;
1035
+ for (const m of nms) {
1036
+ const r = m;
1037
+ if (r.target.combinedFlags & ts.ElementFlags.NonRequired) return void 0;
1038
+ const mLen = this.checker.getTypeArguments(r).length;
1039
+ if (len === void 0) len = mLen;
1040
+ else if (len !== mLen) return void 0;
1041
+ }
1042
+ count += len ?? 0;
1043
+ }
1044
+ return count;
1045
+ })();
1046
+ if (!ts.isSpreadElement(argument)) {
1047
+ const fromEnd = seenVariadic && trailingFixedArgs !== void 0 ? trailingFixedArgs + 1 : void 0;
1048
+ return takesValueAt(this.checker.getTypeAtLocation(argument), cursor, fromEnd);
1049
+ }
1050
+ const type = this.checker.getTypeAtLocation(argument.expression);
1051
+ const unwrapped = this.checker.getAwaitedType(type) ?? type;
1052
+ const ms = members(unwrapped);
1053
+ const isSoleRestSpread = hasRestParam && cursor === restStart && !seenVariadic && argIdx === args.length - 1;
1054
+ if (ms.length && ms.every((m) => this.checker.isTupleType(m))) {
1055
+ let checked = false;
1056
+ for (const m of ms) {
1057
+ const fullRest = isSoleRestSpread ? m : void 0;
1058
+ const ref = m;
1059
+ const flags = ref.target.elementFlags;
1060
+ const elemTypes = this.checker.getTypeArguments(ref);
1061
+ const varIdx = elemTypes.findIndex((_, si) => (flags[si] & ts.ElementFlags.Variable) !== 0);
1062
+ for (let i = 0; i < elemTypes.length; i++) {
1063
+ const isVar = (flags[i] & ts.ElementFlags.Variable) !== 0;
1064
+ const elemType2 = isVar ? this.checker.getIndexTypeOfType(elemTypes[i], ts.IndexKind.Number) ?? elemTypes[i] : elemTypes[i];
1065
+ if (!this.typeKinds(elemType2)) continue;
1066
+ checked = true;
1067
+ if (isVar) {
1068
+ if (!takesValueAt(elemType2, cursor + i, void 0, fullRest)) return false;
1069
+ for (let p = cursor + i + 1; p < paramCount; p++) if (!takesValueAt(elemType2, p, void 0, fullRest)) return false;
1070
+ } else {
1071
+ const hasAfterVar = varIdx >= 0 && i > varIdx;
1072
+ const fromEnd = (seenVariadic || hasAfterVar) && trailingFixedArgs !== void 0 ? trailingFixedArgs + (elemTypes.length - i) : void 0;
1073
+ if (!takesValueAt(elemType2, cursor + i, fromEnd, fullRest)) return false;
1074
+ }
1075
+ }
1076
+ }
1077
+ return checked || takesValueAt(type, cursor);
1078
+ }
1079
+ if (paramCount <= cursor) return false;
1080
+ const elemType = this.checker.getIndexTypeOfType(unwrapped, ts.IndexKind.Number) ?? unwrapped;
1081
+ for (let p = cursor; p < paramCount; p++) if (!takesValueAt(elemType, p)) return false;
1082
+ return true;
1083
+ }
1084
+ if (ts.isSpreadElement(current)) {
1085
+ const type = this.checker.getTypeAtLocation(current.expression);
1086
+ const unwrapped = this.checker.getAwaitedType(type) ?? type;
1087
+ const ms = members(unwrapped);
1088
+ if (ms.length && ms.every((m) => this.checker.isTupleType(m))) {
1089
+ const allExactSameLen = ms.every((m) => !(m.target.combinedFlags & ts.ElementFlags.NonRequired)) && new Set(ms.map((m) => this.checker.getTypeArguments(m).length)).size === 1;
1090
+ if (allExactSameLen) {
1091
+ cursor += this.checker.getTypeArguments(ms[0]).length;
1092
+ continue;
1093
+ }
1094
+ }
1095
+ seenVariadic = true;
1096
+ }
1097
+ cursor += 1;
1098
+ }
1099
+ return false;
636
1100
  }
637
1101
  /** `results.push(f())`: the receiver is itself a collection of Results, so the value is kept in it. */
638
1102
  receiverKeeps(call) {
639
1103
  const callee = this.ts.isCallExpression(call) ? unparen(this.ts, call.expression) : void 0;
640
- return callee !== void 0 && this.ts.isPropertyAccessExpression(callee) && this.kindsOf(callee.expression) !== null;
1104
+ return callee !== void 0 && memberAccessName(this.ts, callee) !== void 0 && (this.ts.isPropertyAccessExpression(callee) || this.ts.isElementAccessExpression(callee)) && this.kindsOf(callee.expression) !== null;
641
1105
  }
642
1106
  // ---- flow of a value to the place its fate is decided ----
643
1107
  /** The expression `child`'s value flows into unchanged (wrappers, branches, collections, calls returning it), else null. */
1108
+ receiverOfIdentityCall(node) {
1109
+ const ts = this.ts;
1110
+ if (!this.stateFound || !ts.isCallExpression(node)) return;
1111
+ const access = node.expression;
1112
+ if ((ts.isPropertyAccessExpression(access) || ts.isElementAccessExpression(access)) && ["reverse", "sort"].includes(memberAccessName(ts, access) ?? "") && this.libOrigin(node) !== null) return access.expression;
1113
+ }
1114
+ identitySource(expr) {
1115
+ const inner = unparen(this.ts, expr);
1116
+ const receiver = this.receiverOfIdentityCall(inner);
1117
+ return receiver ? this.identitySource(receiver) : inner;
1118
+ }
644
1119
  flowsInto(child) {
645
1120
  const ts = this.ts;
646
1121
  const parent = child.parent;
647
1122
  if (!parent) return null;
1123
+ if (parent.parent && this.receiverOfIdentityCall(parent.parent) === child) return parent.parent;
648
1124
  if (ts.isParenthesizedExpression(parent) || ts.isAwaitExpression(parent) || ts.isAsExpression(parent) || ts.isNonNullExpression(parent) || ts.isSatisfiesExpression(parent) || ts.isTypeAssertionExpression(parent)) {
649
1125
  return parent;
650
1126
  }
@@ -711,8 +1187,9 @@ var DropWalk = class {
711
1187
  }
712
1188
  if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === carrier) {
713
1189
  const call = parent.parent;
714
- const predicate = ts.isPropertyAccessExpression(parent) && PREDICATE_METHODS.has(parent.name.text);
715
- const handsOver = !predicate && ts.isCallExpression(call) && call.expression === parent && call.arguments.some((argument) => isOwner(ts, unparen(ts, argument)));
1190
+ const methodName = memberAccessName(ts, parent);
1191
+ const predicate = methodName !== void 0 && PREDICATE_METHODS.has(methodName);
1192
+ const handsOver = !predicate && ts.isCallExpression(call) && call.expression === parent && call.arguments.some((argument, argIndex) => this.isElementCallbackPosition(call, parent, argIndex) && isOwner(ts, unparen(ts, argument)));
716
1193
  return handsOver ? "consume" : "discarded";
717
1194
  }
718
1195
  if ((ts.isForOfStatement(parent) || ts.isForInStatement(parent)) && parent.expression === carrier) return "consume";
@@ -725,45 +1202,468 @@ var DropWalk = class {
725
1202
  }
726
1203
  return "discarded";
727
1204
  }
1205
+ libOrigin(node) {
1206
+ const resolved = this.context.policy.calleeDeclaration(node);
1207
+ const origin = resolved && this.context.policy.origins.originOf(resolved.declaration);
1208
+ return origin?.kind === "external" && origin.origin.startsWith("js:") ? origin.origin : null;
1209
+ }
1210
+ isEmptyArrayInitializer(node) {
1211
+ const ts = this.ts;
1212
+ const inner = unparen(ts, node);
1213
+ if (ts.isArrayLiteralExpression(inner)) return inner.elements.length === 0;
1214
+ if (ts.isCallExpression(inner) || ts.isNewExpression(inner)) {
1215
+ const origin = this.libOrigin(inner);
1216
+ if (origin === "js:Array.of") return argumentsOf(inner).length === 0;
1217
+ if (origin === "js:Array") {
1218
+ const args = argumentsOf(inner);
1219
+ if (args.length === 0) return true;
1220
+ if (args.length === 1 && !ts.isSpreadElement(args[0])) {
1221
+ const argType = this.checker.getTypeAtLocation(args[0]);
1222
+ return (argType.flags & ts.TypeFlags.NumberLike) !== 0;
1223
+ }
1224
+ }
1225
+ }
1226
+ return false;
1227
+ }
1228
+ /** Unbound states left when `pattern` destructures a value of `type` (empty set when every stated element is bound). */
1229
+ unboundPatternStates(pattern, type) {
1230
+ const ts = this.ts;
1231
+ const target = unparen(ts, pattern);
1232
+ const kindStates = this.typeKinds(type);
1233
+ if (!type || !kindStates || !kindStates.size) return NOTHING;
1234
+ if (ts.isIdentifier(target)) return this.moduleHeld(target) ? kindStates : NOTHING;
1235
+ const unwrapped = this.checker.getAwaitedType(type) ?? type;
1236
+ if (ts.isArrayBindingPattern(target)) {
1237
+ const restIndex = target.elements.findIndex((e) => !ts.isOmittedExpression(e) && e.dotDotDotToken !== void 0);
1238
+ const hasRest = restIndex >= 0;
1239
+ const prefixLen = hasRest ? restIndex : target.elements.length;
1240
+ const unbound = /* @__PURE__ */ new Set();
1241
+ for (const m of members(unwrapped)) {
1242
+ if (m.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any) || this.context.policy.resultVariant(m) !== null) continue;
1243
+ if (this.checker.isTupleType(m)) {
1244
+ const ref = m;
1245
+ const flags = ref.target.elementFlags;
1246
+ const elemTypes = this.checker.getTypeArguments(ref);
1247
+ const hasMidVariadic = elemTypes.some((_, idx) => (flags[idx] & ts.ElementFlags.Variable) !== 0 && idx < prefixLen);
1248
+ if (hasMidVariadic && hasRest && target.elements.every((el) => !ts.isOmittedExpression(el) && ts.isIdentifier(el.name) && !this.moduleHeld(el.name))) continue;
1249
+ if (hasMidVariadic) {
1250
+ for (const s of this.typeKinds(m) ?? []) unbound.add(s);
1251
+ continue;
1252
+ }
1253
+ for (let i = 0; i < elemTypes.length; i++) {
1254
+ const isVar = (flags[i] & ts.ElementFlags.Variable) !== 0;
1255
+ const slotType = isVar ? this.checker.getIndexTypeOfType(elemTypes[i], ts.IndexKind.Number) ?? elemTypes[i] : elemTypes[i];
1256
+ if (i < prefixLen && !isVar) {
1257
+ const el = target.elements[i];
1258
+ if (ts.isOmittedExpression(el)) {
1259
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1260
+ } else {
1261
+ for (const s of this.unboundPatternStates(el.name, slotType)) unbound.add(s);
1262
+ }
1263
+ } else if (hasRest) {
1264
+ const restEl = target.elements[restIndex];
1265
+ if (!ts.isIdentifier(restEl.name)) {
1266
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1267
+ }
1268
+ } else {
1269
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1270
+ }
1271
+ }
1272
+ } else {
1273
+ const elem = this.checker.getIndexTypeOfType(m, ts.IndexKind.Number);
1274
+ if (!elem) continue;
1275
+ for (let i = 0; i < prefixLen; i++) {
1276
+ const el = target.elements[i];
1277
+ if (ts.isOmittedExpression(el)) {
1278
+ for (const s of this.typeKinds(elem) ?? []) unbound.add(s);
1279
+ } else {
1280
+ for (const s of this.unboundPatternStates(el.name, elem)) unbound.add(s);
1281
+ }
1282
+ }
1283
+ if (!hasRest || !ts.isIdentifier(target.elements[restIndex].name)) {
1284
+ for (const s of this.typeKinds(elem) ?? []) unbound.add(s);
1285
+ }
1286
+ }
1287
+ }
1288
+ return unbound;
1289
+ }
1290
+ if (ts.isArrayLiteralExpression(target)) {
1291
+ const restIndex = target.elements.findIndex((e) => ts.isSpreadElement(e));
1292
+ const hasRest = restIndex >= 0;
1293
+ const prefixLen = hasRest ? restIndex : target.elements.length;
1294
+ const unbound = /* @__PURE__ */ new Set();
1295
+ for (const m of members(unwrapped)) {
1296
+ if (m.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any) || this.context.policy.resultVariant(m) !== null) continue;
1297
+ if (this.checker.isTupleType(m)) {
1298
+ const ref = m;
1299
+ const flags = ref.target.elementFlags;
1300
+ const elemTypes = this.checker.getTypeArguments(ref);
1301
+ const hasMidVariadic = elemTypes.some((_, idx) => (flags[idx] & ts.ElementFlags.Variable) !== 0 && idx < prefixLen);
1302
+ if (hasMidVariadic && hasRest && target.elements.every((el) => ts.isIdentifier(ts.isSpreadElement(el) ? el.expression : el) && !this.moduleHeld(ts.isSpreadElement(el) ? el.expression : el))) continue;
1303
+ if (hasMidVariadic) {
1304
+ for (const s of this.typeKinds(m) ?? []) unbound.add(s);
1305
+ continue;
1306
+ }
1307
+ for (let i = 0; i < elemTypes.length; i++) {
1308
+ const isVar = (flags[i] & ts.ElementFlags.Variable) !== 0;
1309
+ const slotType = isVar ? this.checker.getIndexTypeOfType(elemTypes[i], ts.IndexKind.Number) ?? elemTypes[i] : elemTypes[i];
1310
+ if (i < prefixLen && !isVar) {
1311
+ const el = target.elements[i];
1312
+ const elInner = ts.isBinaryExpression(el) && el.operatorToken.kind === ts.SyntaxKind.EqualsToken ? el.left : el;
1313
+ if (ts.isOmittedExpression(elInner)) {
1314
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1315
+ } else {
1316
+ for (const s of this.unboundPatternStates(elInner, slotType)) unbound.add(s);
1317
+ }
1318
+ } else if (hasRest) {
1319
+ const spread = target.elements[restIndex];
1320
+ const spreadTarget = unparen(ts, spread.expression);
1321
+ if (!ts.isIdentifier(spreadTarget) || this.moduleHeld(spreadTarget)) {
1322
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1323
+ }
1324
+ } else {
1325
+ for (const s of this.typeKinds(slotType) ?? []) unbound.add(s);
1326
+ }
1327
+ }
1328
+ } else {
1329
+ const elem = this.checker.getIndexTypeOfType(m, ts.IndexKind.Number);
1330
+ if (!elem) continue;
1331
+ for (let i = 0; i < prefixLen; i++) {
1332
+ const el = target.elements[i];
1333
+ const elInner = ts.isBinaryExpression(el) && el.operatorToken.kind === ts.SyntaxKind.EqualsToken ? el.left : el;
1334
+ if (ts.isOmittedExpression(elInner)) {
1335
+ for (const s of this.typeKinds(elem) ?? []) unbound.add(s);
1336
+ } else {
1337
+ for (const s of this.unboundPatternStates(elInner, elem)) unbound.add(s);
1338
+ }
1339
+ }
1340
+ if (!hasRest) {
1341
+ for (const s of this.typeKinds(elem) ?? []) unbound.add(s);
1342
+ } else {
1343
+ const spread = target.elements[restIndex];
1344
+ const spreadTarget = unparen(ts, spread.expression);
1345
+ if (!ts.isIdentifier(spreadTarget) || this.moduleHeld(spreadTarget)) {
1346
+ for (const s of this.typeKinds(elem) ?? []) unbound.add(s);
1347
+ }
1348
+ }
1349
+ }
1350
+ }
1351
+ return unbound;
1352
+ }
1353
+ return kindStates;
1354
+ }
1355
+ patternStoresModuleHeld(pattern) {
1356
+ const ts = this.ts;
1357
+ const target = unparen(ts, pattern);
1358
+ if (ts.isOmittedExpression(target)) return false;
1359
+ if (ts.isIdentifier(target)) return this.moduleHeld(target);
1360
+ if (ts.isArrayLiteralExpression(target)) {
1361
+ return target.elements.some((el) => {
1362
+ if (ts.isOmittedExpression(el)) return false;
1363
+ if (ts.isSpreadElement(el)) return this.patternStoresModuleHeld(el.expression);
1364
+ if (ts.isBinaryExpression(el) && el.operatorToken.kind === ts.SyntaxKind.EqualsToken) return this.patternStoresModuleHeld(el.left);
1365
+ return this.patternStoresModuleHeld(el);
1366
+ });
1367
+ }
1368
+ if (ts.isObjectLiteralExpression(target)) return true;
1369
+ return true;
1370
+ }
1371
+ forOfElementKinds(node) {
1372
+ const ts = this.ts;
1373
+ const exprType = this.checker.getTypeAtLocation(node.expression);
1374
+ const unwrapped = node.awaitModifier ? this.checker.getAwaitedType(exprType) ?? exprType : exprType;
1375
+ if (ts.isVariableDeclarationList(node.initializer)) {
1376
+ const decl = node.initializer.declarations[0];
1377
+ if (decl && ts.isIdentifier(decl.name)) return this.kindsOf(decl.name) ?? NOTHING;
1378
+ }
1379
+ const states = /* @__PURE__ */ new Set();
1380
+ for (const m of members(unwrapped)) {
1381
+ const elem = this.checker.getIndexTypeOfType(m, ts.IndexKind.Number);
1382
+ if (elem) {
1383
+ const elemUnwrapped = node.awaitModifier ? this.checker.getAwaitedType(elem) ?? elem : elem;
1384
+ for (const s of this.typeKinds(elemUnwrapped) ?? []) states.add(s);
1385
+ }
1386
+ }
1387
+ if (states.size) return states;
1388
+ if (!ts.isVariableDeclarationList(node.initializer)) return this.kindsOf(node.initializer) ?? NOTHING;
1389
+ return NOTHING;
1390
+ }
1391
+ forOfUnboundStates(node, pattern) {
1392
+ const ts = this.ts;
1393
+ const exprType = this.checker.getTypeAtLocation(node.expression);
1394
+ const unwrapped = node.awaitModifier ? this.checker.getAwaitedType(exprType) ?? exprType : exprType;
1395
+ if (ts.isVariableDeclarationList(node.initializer)) {
1396
+ const decl = node.initializer.declarations[0];
1397
+ if (decl && ts.isIdentifier(decl.name)) return this.unboundPatternStates(pattern, this.checker.getTypeAtLocation(decl.name));
1398
+ }
1399
+ const unbound = /* @__PURE__ */ new Set();
1400
+ let anyElem = false;
1401
+ for (const m of members(unwrapped)) {
1402
+ const elem = this.checker.getIndexTypeOfType(m, ts.IndexKind.Number);
1403
+ if (elem) {
1404
+ anyElem = true;
1405
+ const elemUnwrapped = node.awaitModifier ? this.checker.getAwaitedType(elem) ?? elem : elem;
1406
+ for (const s of this.unboundPatternStates(pattern, elemUnwrapped)) unbound.add(s);
1407
+ }
1408
+ }
1409
+ if (anyElem) return unbound;
1410
+ if (!ts.isVariableDeclarationList(node.initializer)) return this.unboundPatternStates(pattern, this.checker.getTypeAtLocation(node.initializer));
1411
+ return NOTHING;
1412
+ }
1413
+ initializerKinds(expr) {
1414
+ return this.stateFound && this.isEmptyArrayInitializer(expr) ? null : this.kindsOf(expr);
1415
+ }
1416
+ consumesCallbackElements(argument, rejectStatedReturn = false, elementIndex) {
1417
+ const ts = this.ts;
1418
+ const inner = unparen(ts, argument);
1419
+ if (isOwner(ts, inner) && !ts.isClassStaticBlockDeclaration(inner)) {
1420
+ if (!inner.parameters.some((parameter, i) => (elementIndex === void 0 || i === elementIndex) && this.kindsOf(parameter) !== null)) return false;
1421
+ if (rejectStatedReturn) {
1422
+ const sig = this.checker.getSignatureFromDeclaration(inner);
1423
+ if (sig && this.typeKinds(this.checker.getReturnTypeOfSignature(sig)) !== null) return false;
1424
+ }
1425
+ return true;
1426
+ }
1427
+ const type = this.checker.getTypeAtLocation(inner);
1428
+ let anyAccepted = false;
1429
+ for (const member of members(type)) {
1430
+ for (const signature of member.getCallSignatures()) {
1431
+ const declaration = signature.getDeclaration();
1432
+ if (!declaration || ts.isJSDocSignature(declaration)) continue;
1433
+ const origin = this.context.policy.origins.originOf(declaration);
1434
+ if (origin.kind === "local" && origin.zone === "checked" && signature.getParameters().some((parameter, i) => (elementIndex === void 0 || i === elementIndex) && this.typeKinds(this.checker.getTypeOfSymbolAtLocation(parameter, inner)) !== null)) {
1435
+ if (rejectStatedReturn && this.typeKinds(this.checker.getReturnTypeOfSignature(signature)) !== null) return false;
1436
+ anyAccepted = true;
1437
+ }
1438
+ }
1439
+ }
1440
+ return anyAccepted;
1441
+ }
728
1442
  /** The state pass reuses the control-flow engine, but not failure handoff rules. */
729
- stateUse(node, states, temporary = true) {
1443
+ stateUse(node, states, temporary = true, state) {
730
1444
  if (!states.size) return false;
731
1445
  const ts = this.ts;
732
- const parent = node.parent;
1446
+ const arg = ts.isSpreadElement(node.parent) && (ts.isCallExpression(node.parent.parent) || ts.isNewExpression(node.parent.parent)) ? node.parent : node;
1447
+ const parent = arg.parent;
733
1448
  let origin;
734
1449
  let callee;
1450
+ let reportStates = states;
735
1451
  if (ts.isPropertyDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent)) origin = "stored-state";
736
1452
  else if (ts.isVariableDeclaration(parent)) {
1453
+ if (parent.initializer !== node) return false;
737
1454
  if (ts.isSourceFile(this.owner)) origin = "stored-state";
738
- else return true;
1455
+ else if (ts.isIdentifier(parent.name)) return temporary || this.kindsOf(parent.name) !== null;
1456
+ else if (ts.isArrayBindingPattern(parent.name)) {
1457
+ const unbound = this.unboundPatternStates(parent.name, this.checker.getTypeAtLocation(node));
1458
+ const remaining = new Set([...unbound].filter((s) => states.has(s)));
1459
+ if (remaining.size === 0) return true;
1460
+ if (!temporary) return remaining;
1461
+ origin = "unchecked-state";
1462
+ reportStates = remaining;
1463
+ } else origin = "unchecked-state";
739
1464
  } else if (ts.isBinaryExpression(parent) && isPlainOrLogicalAssignment(ts, parent.operatorToken.kind) && parent.right === node) {
740
- if (!ts.isIdentifier(unparen(ts, parent.left)) || this.moduleHeld(parent.left)) origin = "stored-state";
1465
+ const target = unparen(ts, parent.left);
1466
+ if (this.patternStoresModuleHeld(target)) origin = "stored-state";
1467
+ else if (ts.isIdentifier(target)) {
1468
+ const symbol = this.checker.getSymbolAtLocation(target);
1469
+ return temporary || Boolean(symbol && this.tracked.has(symbol));
1470
+ } else if (ts.isArrayLiteralExpression(target)) {
1471
+ const unbound = this.unboundPatternStates(target, this.checker.getTypeAtLocation(node));
1472
+ const remaining = new Set([...unbound].filter((s) => states.has(s)));
1473
+ if (remaining.size === 0) return true;
1474
+ if (!temporary) return remaining;
1475
+ origin = "unchecked-state";
1476
+ reportStates = remaining;
1477
+ } else origin = "stored-state";
1478
+ } else if (ts.isReturnStatement(parent) && parent.expression === node) {
1479
+ if (!ts.isSourceFile(this.owner) && this.isDiscardedReturnCallback(this.owner)) origin = "unchecked-state";
1480
+ else return true;
1481
+ } else if (ts.isYieldExpression(parent) || ts.isArrowFunction(parent) && parent.body === node) {
1482
+ if (ts.isArrowFunction(parent) && parent.body === node && this.isDiscardedReturnCallback(parent)) origin = "unchecked-state";
741
1483
  else return true;
742
- } else if (ts.isReturnStatement(parent) || ts.isYieldExpression(parent) || ts.isArrowFunction(parent) && parent.body === node) return true;
743
- else if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && argumentsOf(parent).includes(node)) {
744
- const index = argumentsOf(parent).indexOf(node);
745
- if (ts.isCallExpression(parent) && index === 0 && (this.isDecideOrTranslate(parent) || this.context.policy.trustFunctionName(parent) === "match")) return true;
1484
+ } else if (ts.isForOfStatement(parent) && parent.expression === node) {
1485
+ let remaining;
1486
+ if (ts.isVariableDeclarationList(parent.initializer)) {
1487
+ const decl = parent.initializer.declarations[0];
1488
+ if (!decl) origin = "unchecked-state";
1489
+ else {
1490
+ const unbound = this.forOfUnboundStates(parent, decl.name);
1491
+ remaining = new Set([...unbound].filter((s) => states.has(s)));
1492
+ }
1493
+ } else if (this.patternStoresModuleHeld(parent.initializer)) origin = "stored-state";
1494
+ else {
1495
+ const unbound = this.forOfUnboundStates(parent, parent.initializer);
1496
+ remaining = new Set([...unbound].filter((s) => states.has(s)));
1497
+ }
1498
+ if (remaining !== void 0) {
1499
+ const bound = new Set([...states].filter((s) => !remaining.has(s)));
1500
+ if (bound.size) {
1501
+ const trackedSym = !temporary && state ? this.trackedSymbol(node, state) ?? void 0 : void 0;
1502
+ const trackedVer = trackedSym && state ? state.get(trackedSym)?.version : void 0;
1503
+ const prev = this.activeForOfs.get(parent);
1504
+ const symbol = trackedSym ?? prev?.symbol;
1505
+ const version = trackedVer ?? prev?.version;
1506
+ this.activeForOfs.set(parent, {
1507
+ ...symbol ? { symbol } : {},
1508
+ ...version !== void 0 ? { version } : {},
1509
+ node,
1510
+ states: union(prev?.states ?? NOTHING, bound)
1511
+ });
1512
+ }
1513
+ if (remaining.size === 0) return true;
1514
+ if (!temporary) return remaining;
1515
+ origin = "unchecked-state";
1516
+ reportStates = remaining;
1517
+ }
1518
+ } else if ((ts.isCallExpression(parent) || ts.isNewExpression(parent)) && argumentsOf(parent).includes(arg)) {
1519
+ const index = argumentsOf(parent).indexOf(arg);
1520
+ if (ts.isCallExpression(parent) && index === 0 && arg === node && (this.isDecideOrTranslate(parent) || this.context.policy.trustFunctionName(parent) === "match")) return true;
746
1521
  const expression = unparen(ts, parent.expression);
747
- const receiver = ts.isPropertyAccessExpression(expression) ? expression.expression : void 0;
1522
+ const methodName = memberAccessName(ts, expression);
1523
+ const receiver = methodName !== void 0 && (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) ? expression.expression : void 0;
748
1524
  const resolved = this.context.policy.calleeDeclaration(parent);
749
1525
  const external = resolved ? this.context.policy.origins.originOf(resolved.declaration) : void 0;
750
1526
  const lib = external?.kind === "external" && external.origin.startsWith("js:");
751
- if (lib && receiver && this.moduleHeld(receiver) && ts.isPropertyAccessExpression(expression) && ["push", "unshift", "set", "add"].includes(expression.name.text)) origin = "stored-state";
752
- else if (external && !(external.kind === "local" && external.zone === "checked") && !(lib && this.typeKinds(this.instantiatedParameterType(parent, index)))) {
1527
+ const container = lib && receiver && state && methodName !== void 0 && ["push", "unshift", "splice"].includes(methodName) ? this.trackedSymbol(receiver, state) : null;
1528
+ if (lib && receiver && this.moduleHeld(receiver) && methodName !== void 0 && ["push", "unshift", "splice", "set", "add"].includes(methodName)) origin = "stored-state";
1529
+ else if (container) {
1530
+ const existing = state.get(container);
1531
+ if (existing) {
1532
+ const source = ts.isSpreadElement(arg) && this.trackedSymbol(arg.expression, state);
1533
+ if (source && (source === container || existing.peers?.has(source))) return false;
1534
+ let owner = container;
1535
+ let ownerState = existing;
1536
+ if (existing.peers?.size) {
1537
+ const activePeer = [...existing.peers].find((p) => (state.get(p)?.kinds.size ?? 0) > 0);
1538
+ if (activePeer) {
1539
+ owner = activePeer;
1540
+ ownerState = state.get(activePeer);
1541
+ }
1542
+ }
1543
+ state.set(owner, {
1544
+ kinds: union(ownerState.kinds, states),
1545
+ err: ownerState.err,
1546
+ ...ownerState.peers ? { peers: ownerState.peers } : {},
1547
+ ...ownerState.version !== void 0 ? { version: ownerState.version } : {}
1548
+ });
1549
+ }
1550
+ return true;
1551
+ } else if (external && !(external.kind === "local" && external.zone === "checked") && !(lib && (this.typeKinds(this.instantiatedParameterType(parent, index)) || this.kindsOf(parent)))) {
753
1552
  origin = "stated-leaves";
754
1553
  callee = parent.expression.getText(this.sourceFile);
755
- } else if (this.acceptsArgument(parent, node)) return true;
756
- else return false;
757
- } else if (ts.isExpressionStatement(parent) || ts.isVoidExpression(parent) || (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node) origin = "unchecked-state";
1554
+ } else if (this.acceptsArgument(parent, arg) || lib && this.kindsOf(parent) !== null) {
1555
+ if (lib && ts.isCallExpression(parent) && methodName !== void 0 && ["concat", "toSpliced"].includes(methodName)) {
1556
+ this.callStates.set(parent, union(this.callStates.get(parent) ?? NOTHING, states));
1557
+ }
1558
+ return true;
1559
+ } else return false;
1560
+ } else if ((ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) && parent.expression === node) {
1561
+ const call = parent.parent;
1562
+ const accessMethod = memberAccessName(ts, parent);
1563
+ if ((accessMethod === "concat" || accessMethod === "slice" && ts.isCallExpression(call) && call.arguments.length === 0) && ts.isCallExpression(call) && call.expression === parent && this.libOrigin(call) !== null && !["discarded", "read"].includes(this.fate(this.carrier(call)))) {
1564
+ this.callStates.set(call, union(this.callStates.get(call) ?? NOTHING, states));
1565
+ return true;
1566
+ }
1567
+ const predicate = accessMethod !== void 0 && PREDICATE_METHODS.has(accessMethod);
1568
+ const isForEach = accessMethod === "forEach";
1569
+ const handsOver = !predicate && ts.isCallExpression(call) && call.expression === parent && call.arguments.some((argument, argIndex) => {
1570
+ if (!this.isElementCallbackPosition(call, parent, argIndex)) return false;
1571
+ let rejectStatedReturn = isForEach;
1572
+ if (!rejectStatedReturn) {
1573
+ const paramType = this.instantiatedParameterType(call, argIndex) ?? this.declaredParameterType(call, argIndex);
1574
+ if (paramType) {
1575
+ const sigs = members(paramType).flatMap((m) => m.getCallSignatures());
1576
+ if (sigs.length && sigs.every((sig) => (sig.getReturnType().flags & ts.TypeFlags.Void) !== 0 && !this.typeKinds(sig.getReturnType()))) {
1577
+ rejectStatedReturn = true;
1578
+ }
1579
+ }
1580
+ }
1581
+ const reduce = (accessMethod === "reduce" || accessMethod === "reduceRight") && this.libOrigin(call) !== null;
1582
+ return (!reduce || call.arguments.length > 1 || this.consumesCallbackElements(argument, rejectStatedReturn, 0)) && this.consumesCallbackElements(argument, rejectStatedReturn, reduce ? 1 : void 0);
1583
+ });
1584
+ if (handsOver) return true;
1585
+ origin = "unchecked-state";
1586
+ } else if (ts.isExpressionStatement(parent) || ts.isVoidExpression(parent)) origin = "unchecked-state";
758
1587
  if (!origin || origin === "unchecked-state" && !temporary) return false;
759
1588
  const key = node;
760
1589
  if (!this.reported.has(key)) {
761
1590
  this.reported.add(key);
762
- this.stateFound?.push({ origin, start: node.getStart(this.sourceFile), subject: subjectOf(node, this.sourceFile), states: [...states].sort(), ...callee ? { callee } : {} });
1591
+ this.stateFound?.push({ origin, start: node.getStart(this.sourceFile), subject: subjectOf(node, this.sourceFile), states: [...reportStates].sort(), ...callee ? { callee } : {} });
763
1592
  }
764
1593
  return true;
765
1594
  }
766
- /** Fields and module variables are not followed; containers local to a function are. */
1595
+ isElementCallbackPosition(call, propAccess, argIndex) {
1596
+ if (this.libOrigin(call) !== null && memberAccessName(this.ts, propAccess) !== void 0) {
1597
+ return argIndex === 0;
1598
+ }
1599
+ const paramType = this.instantiatedParameterType(call, argIndex) ?? this.declaredParameterType(call, argIndex);
1600
+ if (!paramType) return argIndex === 0;
1601
+ const sigs = members(paramType).flatMap((m) => m.getCallSignatures());
1602
+ if (!sigs.length) return false;
1603
+ return sigs.some(
1604
+ (sig) => sig.getParameters().some((p) => this.typeKinds(this.checker.getTypeOfSymbolAtLocation(p, call)) !== null)
1605
+ );
1606
+ }
1607
+ isStateContainerType(type) {
1608
+ if (!type) return false;
1609
+ const unwrapped = this.checker.getAwaitedType(type) ?? type;
1610
+ if (unwrapped.flags & (this.ts.TypeFlags.Any | this.ts.TypeFlags.Unknown | this.ts.TypeFlags.Never)) return false;
1611
+ for (const m of members(unwrapped)) {
1612
+ if (m.flags & (this.ts.TypeFlags.StringLike | this.ts.TypeFlags.Any) || this.context.policy.resultVariant(m) !== null) continue;
1613
+ const elem = this.checker.getIndexTypeOfType(m, this.ts.IndexKind.Number);
1614
+ if (elem && this.typeKinds(elem) !== null) return true;
1615
+ }
1616
+ return false;
1617
+ }
1618
+ detachFromPeers(symbol, state) {
1619
+ const current = state.get(symbol);
1620
+ if (!current?.peers?.size) return;
1621
+ const survivors = [...current.peers].filter((p) => p !== symbol && state.has(p));
1622
+ let nextKinds = current.kinds;
1623
+ if (current.kinds.size > 0 && survivors.length > 0) {
1624
+ const owner = survivors[0];
1625
+ const ov = state.get(owner);
1626
+ if (ov) {
1627
+ state.set(owner, { ...ov, kinds: union(ov.kinds, current.kinds) });
1628
+ nextKinds = NOTHING;
1629
+ }
1630
+ }
1631
+ const nextGroup = survivors.length > 1 ? new Set(survivors) : void 0;
1632
+ for (const p of survivors) {
1633
+ const pv = state.get(p);
1634
+ if (pv) state.set(p, { kinds: pv.kinds, err: pv.err, ...nextGroup ? { peers: nextGroup } : {}, ...pv.version !== void 0 ? { version: pv.version } : {} });
1635
+ }
1636
+ state.set(symbol, { kinds: nextKinds, err: current.err, ...current.version !== void 0 ? { version: current.version } : {} });
1637
+ }
1638
+ linkContainerAlias(targetSym, rhs, state) {
1639
+ if (!this.stateFound) return;
1640
+ const inner = this.identitySource(rhs);
1641
+ if (!this.ts.isIdentifier(inner)) return;
1642
+ const sourceSym = this.handedSources.get(inner) ?? this.trackedSymbol(inner, state);
1643
+ if (!sourceSym || sourceSym === targetSym || !state.has(sourceSym) || !state.has(targetSym)) return;
1644
+ if (!this.isStateContainerType(this.checker.getTypeOfSymbol(sourceSym))) return;
1645
+ const sourceState = state.get(sourceSym);
1646
+ const sharedVersion = sourceState.version ?? this.handedVersions.get(inner) ?? this.nextVersion++;
1647
+ const group = new Set(sourceState.peers ?? [sourceSym]);
1648
+ group.add(sourceSym);
1649
+ group.add(targetSym);
1650
+ for (const member of group) {
1651
+ const mv = state.get(member);
1652
+ if (mv) state.set(member, { kinds: mv.kinds, err: mv.err, peers: group, version: sharedVersion });
1653
+ }
1654
+ }
1655
+ clearPeerGroup(symbol, state, remaining = NOTHING) {
1656
+ const current = state.get(symbol);
1657
+ if (!current) return;
1658
+ if (current.peers?.size) {
1659
+ for (const peer of current.peers) {
1660
+ if (peer === symbol) continue;
1661
+ const pv = state.get(peer);
1662
+ if (pv) state.set(peer, { kinds: NOTHING, err: pv.err, peers: pv.peers, ...pv.version !== void 0 ? { version: pv.version } : {} });
1663
+ }
1664
+ }
1665
+ state.set(symbol, { kinds: remaining, err: current.err, ...current.peers ? { peers: current.peers } : {}, ...current.version !== void 0 ? { version: current.version } : {} });
1666
+ }
767
1667
  moduleHeld(node) {
768
1668
  const ts = this.ts;
769
1669
  const inner = unparen(ts, node);
@@ -782,8 +1682,42 @@ var DropWalk = class {
782
1682
  const ts = this.ts;
783
1683
  const current = state.get(symbol);
784
1684
  if (!current) return;
1685
+ if (current.version !== void 0 && state.outstandingIterables.size) {
1686
+ const arg = this.carrier(node);
1687
+ const call = arg.parent;
1688
+ if ((ts.isCallExpression(call) || ts.isNewExpression(call)) && argumentsOf(call).includes(arg) && this.acceptsArgument(call, arg)) {
1689
+ for (const target of this.targets) if (target.activeIterable?.version === current.version) state.outstandingIterables.delete(target.node);
1690
+ }
1691
+ }
785
1692
  if (!current.kinds.size) {
786
- this.stateUse(this.carrier(node), this.typeKinds(this.checker.getTypeOfSymbol(symbol)) ?? NOTHING, false);
1693
+ if (current.peers?.size) {
1694
+ const activePeer = [...current.peers].find((p) => (state.get(p)?.kinds.size ?? 0) > 0);
1695
+ if (activePeer) {
1696
+ const activeCurrent = state.get(activePeer);
1697
+ const carrier3 = this.carrier(node);
1698
+ if (ts.isBinaryExpression(carrier3.parent) && carrier3.parent.left === carrier3 && isPlainOrLogicalAssignment(ts, carrier3.parent.operatorToken.kind)) return;
1699
+ if ((ts.isForOfStatement(carrier3.parent) || ts.isForInStatement(carrier3.parent)) && carrier3.parent.initializer === carrier3) return;
1700
+ const outcome2 = this.stateUse(carrier3, activeCurrent.kinds, false, state);
1701
+ if (outcome2 === true) {
1702
+ this.handedSnapshots.set(node, activeCurrent.kinds);
1703
+ this.handedSources.set(node, symbol);
1704
+ const ver = activeCurrent.version ?? current.version;
1705
+ if (ver !== void 0) this.handedVersions.set(node, ver);
1706
+ this.clearPeerGroup(activePeer, state, NOTHING);
1707
+ } else if (outcome2) {
1708
+ this.clearPeerGroup(activePeer, state, outcome2);
1709
+ }
1710
+ return;
1711
+ }
1712
+ }
1713
+ const carrier2 = this.carrier(node);
1714
+ if (ts.isBinaryExpression(carrier2.parent) && carrier2.parent.left === carrier2 && isPlainOrLogicalAssignment(ts, carrier2.parent.operatorToken.kind)) return;
1715
+ if ((ts.isForOfStatement(carrier2.parent) || ts.isForInStatement(carrier2.parent)) && carrier2.parent.initializer === carrier2) return;
1716
+ const value = this.checker.getTypeAtLocation(node);
1717
+ if (this.context.policy.isResultType(value)) this.stateUse(carrier2, this.typeKinds(value) ?? NOTHING, false);
1718
+ this.handedSnapshots.set(node, NOTHING);
1719
+ this.handedSources.set(node, symbol);
1720
+ if (current.version !== void 0) this.handedVersions.set(node, current.version);
787
1721
  return;
788
1722
  }
789
1723
  let wrapped = node;
@@ -792,16 +1726,24 @@ var DropWalk = class {
792
1726
  const property = ts.isPropertyAccessExpression(parent) && parent.expression === wrapped ? parent.name.text : ts.isElementAccessExpression(parent) && parent.expression === wrapped && parent.argumentExpression ? stringLiteral(ts, parent.argumentExpression) : void 0;
793
1727
  const destructured = ts.isVariableDeclaration(parent) && parent.initializer === wrapped && ts.isObjectBindingPattern(parent.name) && parent.name.elements.some((element) => (element.propertyName ?? element.name).getText(this.sourceFile) === "value");
794
1728
  if (property === "value" || destructured) {
795
- if (current.kinds.size === 1 && current.err) state.set(symbol, { kinds: NOTHING, err: false });
796
- else if (this.typeKinds(this.checker.getTypeOfSymbol(symbol))?.size === 1) {
1729
+ const symbolType = this.checker.getTypeOfSymbol(symbol);
1730
+ if (current.kinds.size === 1 && current.err) state.set(symbol, { kinds: NOTHING, err: false, ...current.peers ? { peers: current.peers } : {}, ...current.version !== void 0 ? { version: current.version } : {} });
1731
+ else if (members(symbolType).some((m) => this.context.policy.resultVariant(m) === "ok") && this.typeKinds(symbolType)?.size === 1) {
797
1732
  this.stateFound?.push({ origin: "unnarrowed-value", start: parent.getStart(this.sourceFile), subject: node.text, states: [...current.kinds].sort() });
798
- state.set(symbol, { kinds: NOTHING, err: false });
1733
+ state.set(symbol, { kinds: NOTHING, err: false, ...current.peers ? { peers: current.peers } : {}, ...current.version !== void 0 ? { version: current.version } : {} });
799
1734
  }
800
1735
  return;
801
1736
  }
802
- if (property !== void 0) return;
803
- if (ts.isBinaryExpression(parent) && parent.left === node && isPlainOrLogicalAssignment(ts, parent.operatorToken.kind)) return;
804
- if (this.stateUse(this.carrier(node), current.kinds, false)) state.set(symbol, { kinds: NOTHING, err: current.err });
1737
+ const carrier = this.carrier(node);
1738
+ if (ts.isBinaryExpression(carrier.parent) && carrier.parent.left === carrier && isPlainOrLogicalAssignment(ts, carrier.parent.operatorToken.kind)) return;
1739
+ if ((ts.isForOfStatement(carrier.parent) || ts.isForInStatement(carrier.parent)) && carrier.parent.initializer === carrier) return;
1740
+ const outcome = this.stateUse(carrier, current.kinds, false, state);
1741
+ if (outcome === true) {
1742
+ this.handedSnapshots.set(node, current.kinds);
1743
+ this.handedSources.set(node, symbol);
1744
+ if (current.version !== void 0) this.handedVersions.set(node, current.version);
1745
+ this.clearPeerGroup(symbol, state, NOTHING);
1746
+ } else if (outcome) this.clearPeerGroup(symbol, state, outcome);
805
1747
  }
806
1748
  // ---- expressions ----
807
1749
  /** Visits the expressions under `node` (not into nested functions) in source order, deciding the fate of each value that can fail. */
@@ -815,11 +1757,70 @@ var DropWalk = class {
815
1757
  if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
816
1758
  this.visit(node.right, state);
817
1759
  this.visit(node.left, state);
818
- this.assign(node, state);
1760
+ let pattern = node;
1761
+ while (ts.isArrayLiteralExpression(pattern.parent)) pattern = pattern.parent;
1762
+ if (!(this.stateFound && pattern !== node && ts.isBinaryExpression(pattern.parent) && pattern.parent.left === pattern && pattern.parent.operatorToken.kind === ts.SyntaxKind.EqualsToken)) this.assign(node, state);
1763
+ return;
1764
+ }
1765
+ if (this.stateFound && ts.isBinaryExpression(node) && node.operatorToken.kind !== ts.SyntaxKind.EqualsToken && isPlainOrLogicalAssignment(ts, node.operatorToken.kind)) {
1766
+ this.visit(node.left, state);
1767
+ const taken = new State(state);
1768
+ const target = unparen(ts, node.left);
1769
+ const symbol = ts.isIdentifier(target) ? this.checker.getSymbolAtLocation(target) : void 0;
1770
+ const held = symbol ? taken.get(symbol) : void 0;
1771
+ if (symbol && held && node.operatorToken.kind !== ts.SyntaxKind.AmpersandAmpersandEqualsToken) taken.set(symbol, { ...held, kinds: NOTHING });
1772
+ this.visit(node.right, taken);
1773
+ this.assign(node, taken);
1774
+ replaceState(state, merge(taken, state));
1775
+ return;
1776
+ }
1777
+ if (this.stateFound && ts.isConditionalExpression(node)) {
1778
+ this.visit(node.condition, state);
1779
+ const yes = this.branch(node.condition, state, true), no = this.branch(node.condition, state, false);
1780
+ this.visit(node.whenTrue, yes);
1781
+ this.visit(node.whenFalse, no);
1782
+ replaceState(state, merge(yes, no));
1783
+ return;
1784
+ }
1785
+ if (this.stateFound && ts.isBinaryExpression(node) && [ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(node.operatorToken.kind)) {
1786
+ this.visit(node.left, state);
1787
+ const op = node.operatorToken.kind;
1788
+ const taken = op === ts.SyntaxKind.QuestionQuestionToken ? new State(state) : this.branch(node.left, state, op === ts.SyntaxKind.AmpersandAmpersandToken);
1789
+ const skipped = op === ts.SyntaxKind.QuestionQuestionToken ? new State(state) : this.branch(node.left, state, op !== ts.SyntaxKind.AmpersandAmpersandToken);
1790
+ this.visit(node.right, taken);
1791
+ replaceState(state, merge(taken, skipped));
819
1792
  return;
820
1793
  }
1794
+ if (this.stateFound && ts.isCallExpression(node)) {
1795
+ const callee = unparen(ts, node.expression);
1796
+ const methodName = memberAccessName(ts, callee);
1797
+ if (methodName === "splice" && (ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee))) {
1798
+ this.visit(node.expression, state);
1799
+ const recvSym = this.trackedSymbol(callee.expression, state);
1800
+ if (recvSym) {
1801
+ const existing = state.get(recvSym);
1802
+ let hasLiveStates = Boolean(existing && existing.kinds.size > 0);
1803
+ if (!hasLiveStates && existing?.peers?.size) {
1804
+ hasLiveStates = [...existing.peers].some((p) => (state.get(p)?.kinds.size ?? 0) > 0);
1805
+ }
1806
+ if (!hasLiveStates) this.spliceEmptyBeforeCall.add(node);
1807
+ else if (node.arguments.length === 1 && this.libOrigin(node) !== null) {
1808
+ const start = unparen(ts, node.arguments[0]);
1809
+ if (ts.isNumericLiteral(start) && Number(start.text) === 0) {
1810
+ let removed = existing?.kinds ?? NOTHING;
1811
+ for (const peer of existing?.peers ?? []) removed = union(removed, state.get(peer)?.kinds ?? NOTHING);
1812
+ this.callStates.set(node, removed);
1813
+ this.clearPeerGroup(recvSym, state, NOTHING);
1814
+ }
1815
+ }
1816
+ }
1817
+ for (const arg of node.arguments) this.visit(arg, state);
1818
+ this.temporary(node, state);
1819
+ return;
1820
+ }
1821
+ }
821
1822
  ts.forEachChild(node, (child) => this.visit(child, state));
822
- if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isTaggedTemplateExpression(node)) this.temporary(node);
1823
+ if (ts.isCallExpression(node) || ts.isNewExpression(node) || ts.isTaggedTemplateExpression(node)) this.temporary(node, state);
823
1824
  else if (ts.isIdentifier(node)) this.reference(node, state);
824
1825
  }
825
1826
  /**
@@ -831,20 +1832,27 @@ var DropWalk = class {
831
1832
  const ts = this.ts;
832
1833
  if (!ts.isCallExpression(node)) return false;
833
1834
  const callee = unparen(ts, node.expression);
834
- if (!ts.isPropertyAccessExpression(callee) || !ELEMENT_METHODS.has(callee.name.text)) return false;
1835
+ const methodName = memberAccessName(ts, callee);
1836
+ if (this.stateFound && methodName === "splice" && (ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee)) && this.libOrigin(node) !== null) {
1837
+ const isNoDelete = node.arguments.length === 0 || Boolean(node.arguments.length >= 2 && ts.isNumericLiteral(unparen(ts, node.arguments[1])) && Number(unparen(ts, node.arguments[1]).text) === 0);
1838
+ if (isNoDelete) return true;
1839
+ if (this.moduleHeld(callee.expression)) return false;
1840
+ if (this.spliceEmptyBeforeCall.has(node)) return true;
1841
+ return false;
1842
+ }
1843
+ if (this.stateFound && this.callStates.has(node)) return false;
1844
+ if (!methodName || !ts.isPropertyAccessExpression(callee) && !ts.isElementAccessExpression(callee) || !ELEMENT_METHODS.has(methodName)) return false;
835
1845
  return this.kindsOf(callee.expression) !== null;
836
1846
  }
837
1847
  /** A call's value: reported where it is dropped; followed when it is kept in a variable. */
838
- temporary(node) {
1848
+ temporary(node, state) {
839
1849
  if (!this.kindsOf(node) || this.derivedFromReceiver(node)) return;
840
- if (this.stateFound && this.ts.isCallExpression(node)) {
841
- const resolved = this.context.policy.calleeDeclaration(node);
842
- const origin = resolved && this.context.policy.origins.originOf(resolved.declaration);
843
- if (origin?.kind === "external" && origin.origin.startsWith("js:") && node.arguments.some((arg) => this.kindsOf(arg))) return;
844
- }
1850
+ if (this.stateFound && (this.ts.isCallExpression(node) || this.ts.isNewExpression(node)) && this.isEmptyArrayInitializer(node)) return;
845
1851
  const carrier = this.carrier(node);
846
1852
  if (this.stateFound) {
847
- this.stateUse(carrier, this.kindsOf(node) ?? NOTHING);
1853
+ const contributed = this.callStates.get(node);
1854
+ const kinds = contributed || carrier !== node && this.kindsOf(carrier) || this.kindsOf(node) || NOTHING;
1855
+ this.stateUse(carrier, kinds, true, state);
848
1856
  return;
849
1857
  }
850
1858
  const fate = this.fate(carrier);
@@ -897,24 +1905,78 @@ var DropWalk = class {
897
1905
  if (!kinds || this.kindsOf(call) !== null || this.acceptsArgument(call, node)) return;
898
1906
  this.report("callback", node, subjectOf(call.expression, this.sourceFile), kinds);
899
1907
  }
1908
+ patternIdentifiers(pattern) {
1909
+ const ts = this.ts;
1910
+ const target = unparen(ts, pattern);
1911
+ if (ts.isIdentifier(target)) return [target];
1912
+ if (ts.isArrayLiteralExpression(target)) {
1913
+ const out = [];
1914
+ for (const el of target.elements) {
1915
+ if (ts.isOmittedExpression(el)) continue;
1916
+ if (ts.isSpreadElement(el)) out.push(...this.patternIdentifiers(el.expression));
1917
+ else if (ts.isBinaryExpression(el) && el.operatorToken.kind === ts.SyntaxKind.EqualsToken) out.push(...this.patternIdentifiers(el.left));
1918
+ else out.push(...this.patternIdentifiers(el));
1919
+ }
1920
+ return out;
1921
+ }
1922
+ return [];
1923
+ }
1924
+ rhsStateKinds(expr, state) {
1925
+ const ts = this.ts;
1926
+ const inner = this.identitySource(expr);
1927
+ if (this.stateFound) {
1928
+ const contributed = this.callStates.get(inner);
1929
+ if (contributed) return contributed;
1930
+ if (ts.isIdentifier(inner)) {
1931
+ const snapshot = this.handedSnapshots.get(inner);
1932
+ if (snapshot !== void 0) return snapshot;
1933
+ const sym = this.trackedSymbol(inner, state);
1934
+ if (sym) return state.get(sym)?.kinds ?? NOTHING;
1935
+ }
1936
+ }
1937
+ return this.initializerKinds(expr);
1938
+ }
900
1939
  assign(node, state) {
901
1940
  const ts = this.ts;
902
1941
  const target = unparen(ts, node.left);
903
- const names = ts.isIdentifier(target) ? [target] : ts.isArrayLiteralExpression(target) ? target.elements.filter(ts.isIdentifier) : [];
1942
+ const names = this.patternIdentifiers(target);
1943
+ const live = this.stateFound && ts.isArrayLiteralExpression(target) ? this.rhsStateKinds(node.right, state) : null;
1944
+ const rhsInner = this.identitySource(node.right);
1945
+ const rhsSym = ts.isIdentifier(target) && ts.isIdentifier(rhsInner) ? this.handedSources.get(rhsInner) ?? this.trackedSymbol(node.right, state) : null;
1946
+ const rhsVersion = this.stateFound && ts.isIdentifier(target) && ts.isIdentifier(rhsInner) ? this.handedVersions.get(rhsInner) ?? (rhsSym ? state.get(rhsSym)?.version : void 0) : void 0;
904
1947
  for (const name of names) {
905
1948
  const symbol = this.checker.getSymbolAtLocation(name);
906
1949
  if (!symbol || !this.tracked.has(symbol)) continue;
1950
+ if (this.stateFound) {
1951
+ const existing = state.get(symbol);
1952
+ if (existing?.peers?.size && (!rhsSym || !existing.peers.has(rhsSym))) {
1953
+ this.detachFromPeers(symbol, state);
1954
+ }
1955
+ }
907
1956
  const current = state.get(symbol);
908
- if (current && current.kinds.size > 0) this.reportVariable("overwritten", node, symbol, current.kinds);
909
- const kinds = ts.isIdentifier(target) ? this.kindsOf(node.right) : this.kindsOf(name);
910
- state.set(symbol, { kinds: kinds ?? NOTHING, err: false });
1957
+ if (current && current.kinds.size > 0 && (!this.stateFound || !current.peers?.size || (rhsSym && current.peers.has(rhsSym) ? false : true))) {
1958
+ this.reportVariable("overwritten", node, symbol, current.kinds);
1959
+ }
1960
+ let kinds = ts.isIdentifier(target) ? this.rhsStateKinds(node.right, state) : this.kindsOf(name);
1961
+ if (live && kinds) {
1962
+ let available = live;
1963
+ for (let child = name; child !== target; child = child.parent) {
1964
+ const parent = child.parent;
1965
+ if (ts.isBinaryExpression(parent) && parent.left === child && parent.operatorToken.kind === ts.SyntaxKind.EqualsToken)
1966
+ available = union(available, this.rhsStateKinds(parent.right, state) ?? NOTHING);
1967
+ }
1968
+ kinds = new Set([...kinds].filter((k) => available.has(k)));
1969
+ }
1970
+ const version = this.stateFound ? rhsVersion ?? this.nextVersion++ : void 0;
1971
+ state.set(symbol, { kinds: kinds ?? NOTHING, err: false, ...version !== void 0 ? { version } : {} });
1972
+ if (ts.isIdentifier(target)) this.linkContainerAlias(symbol, node.right, state);
911
1973
  }
912
1974
  }
913
1975
  /**
914
1976
  * Starts following the variables `name` binds that can fail (a module-level variable is never followed). With an
915
1977
  * `initializer`, what can fail is what the initializer holds (`let scope: Result<…> | null = null` holds nothing yet).
916
1978
  */
917
- declare(name, scope, state, assigned, initializer) {
1979
+ declare(name, scope, state, assigned, initializer, live) {
918
1980
  const ts = this.ts;
919
1981
  if (ts.isSourceFile(this.owner)) return;
920
1982
  if (ts.isIdentifier(name)) {
@@ -922,11 +1984,28 @@ var DropWalk = class {
922
1984
  const kinds = symbol ? this.kindsOf(name) : null;
923
1985
  if (!symbol || !kinds) return;
924
1986
  this.tracked.set(symbol, { name: name.text, scope });
925
- if (assigned) state.set(symbol, { kinds: initializer ? this.kindsOf(initializer) ?? NOTHING : kinds, err: false });
1987
+ if (assigned) {
1988
+ let initVersion;
1989
+ if (this.stateFound && initializer) {
1990
+ const inner = this.identitySource(initializer);
1991
+ if (ts.isIdentifier(inner)) {
1992
+ const srcSym = this.handedSources.get(inner) ?? this.trackedSymbol(initializer, state);
1993
+ initVersion = this.handedVersions.get(inner) ?? (srcSym ? state.get(srcSym)?.version : void 0);
1994
+ }
1995
+ }
1996
+ const version = this.stateFound ? initVersion ?? this.nextVersion++ : void 0;
1997
+ state.set(symbol, {
1998
+ kinds: initializer ? this.rhsStateKinds(initializer, state) ?? NOTHING : live ? new Set([...kinds].filter((k) => live.has(k))) : kinds,
1999
+ err: false,
2000
+ ...version !== void 0 ? { version } : {}
2001
+ });
2002
+ if (initializer) this.linkContainerAlias(symbol, initializer, state);
2003
+ }
926
2004
  return;
927
2005
  }
2006
+ const source = this.stateFound && initializer && ts.isArrayBindingPattern(name) ? this.rhsStateKinds(initializer, state) ?? void 0 : live;
928
2007
  for (const element of name.elements) {
929
- if (!ts.isOmittedExpression(element)) this.declare(element.name, scope, state, assigned);
2008
+ if (!ts.isOmittedExpression(element)) this.declare(element.name, scope, state, assigned, void 0, element.initializer ? void 0 : source);
930
2009
  }
931
2010
  }
932
2011
  declarations(list, scope, state) {
@@ -937,7 +2016,7 @@ var DropWalk = class {
937
2016
  this.visit(declaration.initializer, state);
938
2017
  this.recordErrorAlias(declaration, state);
939
2018
  }
940
- const initializer = ts.isIdentifier(declaration.name) ? declaration.initializer : void 0;
2019
+ const initializer = declaration.initializer;
941
2020
  this.declare(declaration.name, blockScoped ? scope : this.functionScope, state, declaration.initializer !== void 0, initializer);
942
2021
  }
943
2022
  }
@@ -999,10 +2078,17 @@ var DropWalk = class {
999
2078
  return this.trackedSymbol(error.expression, state);
1000
2079
  }
1001
2080
  withOk(state, symbol, isOk) {
1002
- const narrowed = new Map(state);
2081
+ const narrowed = new State(state);
1003
2082
  const current = state.get(symbol);
1004
2083
  if (this.stateFound) {
1005
- if (current && !isOk) narrowed.set(symbol, { kinds: NOTHING, err: false });
2084
+ if (current && !isOk) {
2085
+ narrowed.set(symbol, {
2086
+ kinds: NOTHING,
2087
+ err: false,
2088
+ ...current.peers ? { peers: current.peers } : {},
2089
+ ...current.version !== void 0 ? { version: current.version } : {}
2090
+ });
2091
+ }
1006
2092
  return narrowed;
1007
2093
  }
1008
2094
  if (current) narrowed.set(symbol, isOk ? { kinds: NOTHING, err: false } : { kinds: current.kinds, err: true });
@@ -1010,18 +2096,19 @@ var DropWalk = class {
1010
2096
  }
1011
2097
  /** A branch that names `kind` handles it; the other branch keeps the kinds that are not `kind`. */
1012
2098
  withKind(state, symbol, kind, isKind) {
1013
- const narrowed = new Map(state);
2099
+ const narrowed = new State(state);
1014
2100
  const current = state.get(symbol);
1015
2101
  if (current) {
1016
2102
  const rest = new Set(current.kinds);
1017
2103
  rest.delete(kind);
1018
- narrowed.set(symbol, isKind ? { kinds: NOTHING, err: true } : { kinds: rest, err: this.stateFound ? current.err || rest.size < current.kinds.size : true });
2104
+ const extra = this.stateFound ? { ...current.peers ? { peers: current.peers } : {}, ...current.version !== void 0 ? { version: current.version } : {} } : {};
2105
+ narrowed.set(symbol, isKind ? { kinds: NOTHING, err: true, ...extra } : { kinds: rest, err: this.stateFound ? current.err || rest.size < current.kinds.size : true, ...extra });
1019
2106
  }
1020
2107
  return narrowed;
1021
2108
  }
1022
2109
  /** The state a branch starts with: narrowed by its condition, and its own copy (a branch's declarations stay in it). */
1023
2110
  branch(condition, state, outcome) {
1024
- return new Map(this.narrow(condition, state, outcome));
2111
+ return new State(this.narrow(condition, state, outcome));
1025
2112
  }
1026
2113
  narrow(condition, state, outcome) {
1027
2114
  const ts = this.ts;
@@ -1074,8 +2161,16 @@ var DropWalk = class {
1074
2161
  return truthy && !outcome ? this.withNothing(state, truthy) : state;
1075
2162
  }
1076
2163
  withNothing(state, symbol) {
1077
- const narrowed = new Map(state);
1078
- if (narrowed.has(symbol)) narrowed.set(symbol, { kinds: NOTHING, err: false });
2164
+ const narrowed = new State(state);
2165
+ const current = narrowed.get(symbol);
2166
+ if (current) {
2167
+ narrowed.set(symbol, {
2168
+ kinds: NOTHING,
2169
+ err: false,
2170
+ ...this.stateFound && current.peers ? { peers: current.peers } : {},
2171
+ ...this.stateFound && current.version !== void 0 ? { version: current.version } : {}
2172
+ });
2173
+ }
1079
2174
  return narrowed;
1080
2175
  }
1081
2176
  // ---- statements ----
@@ -1138,7 +2233,66 @@ var DropWalk = class {
1138
2233
  */
1139
2234
  checkReturn(at, expression, state) {
1140
2235
  if (this.stateFound) {
1141
- for (const [symbol, value] of state) if (value.kinds.size) this.reportVariable("return", at, symbol, value.kinds);
2236
+ if (!this.ts.isSourceFile(this.owner) && this.isDiscardedReturnCallback(this.owner) && expression) {
2237
+ const inner = unparen(this.ts, expression);
2238
+ const retStates = this.ts.isIdentifier(inner) ? this.handedSnapshots.get(inner) : void 0;
2239
+ if (retStates?.size) {
2240
+ const sym = this.checker.getSymbolAtLocation(inner);
2241
+ if (sym && this.tracked.has(sym)) this.reportVariable("return", at, sym, retStates);
2242
+ }
2243
+ }
2244
+ const returnedSymbols = /* @__PURE__ */ new Set();
2245
+ let returnedVersion;
2246
+ if (expression) {
2247
+ const inner = this.identitySource(expression);
2248
+ if (this.ts.isIdentifier(inner)) {
2249
+ const sym = this.checker.getSymbolAtLocation(inner);
2250
+ if (sym) returnedSymbols.add(sym);
2251
+ returnedVersion = this.handedVersions.get(inner) ?? (sym ? state.get(sym)?.version : void 0);
2252
+ }
2253
+ }
2254
+ const restored = new State(state);
2255
+ for (const candidate of this.targets) {
2256
+ const active = candidate.activeIterable;
2257
+ if (!active?.states.size || !state.outstandingIterables.has(candidate.node)) continue;
2258
+ if (active.symbol) {
2259
+ if (active.version !== void 0) {
2260
+ if (returnedVersion !== void 0 && returnedVersion === active.version) continue;
2261
+ let holder;
2262
+ if (restored.get(active.symbol)?.version === active.version) {
2263
+ holder = active.symbol;
2264
+ } else {
2265
+ for (const [sym, val] of restored) {
2266
+ if (val.version === active.version) {
2267
+ holder = sym;
2268
+ break;
2269
+ }
2270
+ }
2271
+ }
2272
+ if (holder) {
2273
+ const prev = restored.get(holder);
2274
+ restored.set(holder, {
2275
+ kinds: union(prev.kinds, active.states),
2276
+ err: prev.err,
2277
+ ...prev.peers ? { peers: prev.peers } : {},
2278
+ ...prev.version !== void 0 ? { version: prev.version } : {}
2279
+ });
2280
+ } else {
2281
+ this.reportVariable("return", at, active.symbol, active.states);
2282
+ }
2283
+ } else {
2284
+ const prev = restored.get(active.symbol);
2285
+ const groupPeers = prev?.peers;
2286
+ const groupReturned = returnedSymbols.has(active.symbol) || Boolean(groupPeers && [...groupPeers].some((p) => returnedSymbols.has(p)));
2287
+ if (groupReturned) continue;
2288
+ restored.set(active.symbol, { kinds: union(prev?.kinds ?? NOTHING, active.states), err: prev?.err ?? false, ...prev?.peers ? { peers: prev.peers } : {} });
2289
+ }
2290
+ } else if (!this.reported.has(active.node)) {
2291
+ this.reported.add(active.node);
2292
+ this.stateFound.push({ origin: "unchecked-state", start: active.node.getStart(this.sourceFile), subject: subjectOf(active.node, this.sourceFile), states: [...active.states].sort() });
2293
+ }
2294
+ }
2295
+ for (const [symbol, value] of restored) if (value.kinds.size) this.reportVariable("return", at, symbol, value.kinds);
1142
2296
  return;
1143
2297
  }
1144
2298
  const ts = this.ts;
@@ -1187,15 +2341,61 @@ var DropWalk = class {
1187
2341
  const ts = this.ts;
1188
2342
  const label = node.label?.text;
1189
2343
  const isBreak = ts.isBreakStatement(node);
1190
- let target;
1191
- for (let index = this.targets.length - 1; index >= 0 && !target; index -= 1) {
2344
+ let targetIndex = -1;
2345
+ for (let index = this.targets.length - 1; index >= 0 && targetIndex < 0; index -= 1) {
1192
2346
  const candidate = this.targets[index];
1193
- if (label !== void 0 ? candidate.label === label : isBreak ? candidate.kind !== "labeled" : candidate.kind === "loop") target = candidate;
2347
+ if (label !== void 0 ? candidate.label === label : isBreak ? candidate.kind !== "labeled" : candidate.kind === "loop") targetIndex = index;
1194
2348
  }
1195
- if (!target) return null;
1196
- const to = target;
2349
+ if (targetIndex < 0) return null;
2350
+ const to = this.targets[targetIndex];
1197
2351
  const keeps = (info) => !isBreak && ts.isForStatement(to.node) && info.scope === to.node;
1198
- const left = this.leaveScope(to.node, state, node, true, keeps) ?? state;
2352
+ let left = this.leaveScope(to.node, state, node, true, keeps) ?? new State(state);
2353
+ if (this.stateFound) {
2354
+ for (let idx = this.targets.length - 1; idx >= targetIndex; idx -= 1) {
2355
+ if (!isBreak && idx === targetIndex) continue;
2356
+ const exited = this.targets[idx];
2357
+ const active = exited.activeIterable;
2358
+ if (!active?.states.size || !state.outstandingIterables.has(exited.node)) continue;
2359
+ if (active.symbol) {
2360
+ const info = this.tracked.get(active.symbol);
2361
+ const alsoLeaving = info !== void 0 && within(info.scope, to.node) && !keeps(info);
2362
+ if (alsoLeaving && active.version === void 0) {
2363
+ this.reportVariable("end", node, active.symbol, active.states);
2364
+ } else if (active.version !== void 0) {
2365
+ let holder;
2366
+ if (left.get(active.symbol)?.version === active.version) {
2367
+ holder = active.symbol;
2368
+ } else {
2369
+ for (const [sym, val] of left) {
2370
+ if (val.version === active.version) {
2371
+ holder = sym;
2372
+ break;
2373
+ }
2374
+ }
2375
+ }
2376
+ if (holder) {
2377
+ const prev = left.get(holder);
2378
+ left = new State(left);
2379
+ left.set(holder, {
2380
+ kinds: union(prev.kinds, active.states),
2381
+ err: prev.err,
2382
+ ...prev.peers ? { peers: prev.peers } : {},
2383
+ ...prev.version !== void 0 ? { version: prev.version } : {}
2384
+ });
2385
+ } else {
2386
+ this.reportVariable("end", node, active.symbol, active.states);
2387
+ }
2388
+ } else {
2389
+ const prev = left.get(active.symbol);
2390
+ left = new State(left);
2391
+ left.set(active.symbol, { kinds: union(prev?.kinds ?? NOTHING, active.states), err: prev?.err ?? false, ...prev?.peers ? { peers: prev.peers } : {} });
2392
+ }
2393
+ } else if (!this.reported.has(active.node)) {
2394
+ this.reported.add(active.node);
2395
+ this.stateFound.push({ origin: "unchecked-state", start: active.node.getStart(this.sourceFile), subject: subjectOf(active.node, this.sourceFile), states: [...active.states].sort() });
2396
+ }
2397
+ }
2398
+ }
1199
2399
  (isBreak ? to.breaks : to.continues).push(left);
1200
2400
  return null;
1201
2401
  }
@@ -1219,7 +2419,7 @@ var DropWalk = class {
1219
2419
  return kind === void 0 ? [] : [kind];
1220
2420
  });
1221
2421
  const rest = () => {
1222
- if (!kindOf) return new Map(state);
2422
+ if (!kindOf) return new State(state);
1223
2423
  let narrowed = state;
1224
2424
  for (const kind of labels) narrowed = this.withKind(narrowed, kindOf, kind, false);
1225
2425
  return narrowed;
@@ -1233,7 +2433,7 @@ var DropWalk = class {
1233
2433
  if (ts.isCaseClause(clause)) {
1234
2434
  this.visit(clause.expression, state);
1235
2435
  const kind = stringLiteral(ts, clause.expression);
1236
- entry = kindOf && kind !== void 0 ? this.withKind(state, kindOf, kind, true) : new Map(state);
2436
+ entry = kindOf && kind !== void 0 ? this.withKind(state, kindOf, kind, true) : new State(state);
1237
2437
  } else {
1238
2438
  hasDefault = true;
1239
2439
  entry = rest();
@@ -1246,7 +2446,7 @@ var DropWalk = class {
1246
2446
  }
1247
2447
  loop(node, state, label) {
1248
2448
  const ts = this.ts;
1249
- let entry = new Map(state);
2449
+ let entry = new State(state);
1250
2450
  let skip = entry;
1251
2451
  if (ts.isForStatement(node)) {
1252
2452
  if (node.initializer && ts.isVariableDeclarationList(node.initializer)) this.declarations(node.initializer, node, entry);
@@ -1259,12 +2459,33 @@ var DropWalk = class {
1259
2459
  skip = null;
1260
2460
  }
1261
2461
  } else if (ts.isForOfStatement(node) || ts.isForInStatement(node)) {
1262
- this.visit(node.expression, entry);
1263
- skip = new Map(entry);
2462
+ const iterable = unparen(ts, node.expression);
2463
+ if (this.stateFound && ts.isForOfStatement(node) && ts.isConditionalExpression(iterable)) {
2464
+ this.visit(iterable.condition, entry);
2465
+ const yes = this.branch(iterable.condition, entry, true), no = this.branch(iterable.condition, entry, false);
2466
+ this.visit(iterable.whenTrue, yes);
2467
+ this.visit(iterable.whenFalse, no);
2468
+ entry = merge(yes, no);
2469
+ } else this.visit(node.expression, entry);
2470
+ skip = new State(entry);
2471
+ const live = this.stateFound && ts.isForOfStatement(node) ? this.rhsStateKinds(node.expression, entry) ?? void 0 : void 0;
1264
2472
  if (ts.isVariableDeclarationList(node.initializer)) {
1265
- for (const declaration of node.initializer.declarations) this.declare(declaration.name, node, entry, true);
2473
+ for (const declaration of node.initializer.declarations) this.declare(declaration.name, node, entry, true, void 0, live);
1266
2474
  } else {
1267
2475
  this.visit(node.initializer, entry);
2476
+ if (ts.isForOfStatement(node)) {
2477
+ const elemKinds = this.forOfElementKinds(node);
2478
+ const target2 = unparen(ts, node.initializer);
2479
+ for (const name of this.patternIdentifiers(target2)) {
2480
+ const symbol = this.checker.getSymbolAtLocation(name);
2481
+ if (!symbol || !this.tracked.has(symbol)) continue;
2482
+ if (this.stateFound) this.detachFromPeers(symbol, entry);
2483
+ const current = entry.get(symbol);
2484
+ if (current && current.kinds.size > 0) this.reportVariable("overwritten", node.initializer, symbol, current.kinds);
2485
+ const kinds = ts.isIdentifier(target2) ? elemKinds.size ? elemKinds : this.kindsOf(name) : this.kindsOf(name);
2486
+ entry.set(symbol, { kinds: live && kinds ? new Set([...kinds].filter((k) => live.has(k))) : kinds ?? NOTHING, err: false, ...this.stateFound ? { version: this.nextVersion++ } : {} });
2487
+ }
2488
+ }
1268
2489
  }
1269
2490
  } else if (ts.isWhileStatement(node)) {
1270
2491
  this.visit(node.expression, entry);
@@ -1273,7 +2494,9 @@ var DropWalk = class {
1273
2494
  } else {
1274
2495
  skip = null;
1275
2496
  }
1276
- const target = { node, label, kind: "loop", breaks: [], continues: [] };
2497
+ const activeIterable = ts.isForOfStatement(node) ? this.activeForOfs.get(node) : void 0;
2498
+ const target = { node, label, kind: "loop", breaks: [], continues: [], ...activeIterable ? { activeIterable } : {} };
2499
+ if (activeIterable) entry.outstandingIterables.add(node);
1277
2500
  this.targets.push(target);
1278
2501
  let out = this.statement(node.statement, entry, node);
1279
2502
  this.targets.pop();
@@ -1282,15 +2505,16 @@ var DropWalk = class {
1282
2505
  if (ts.isDoStatement(node) && repeat) this.visit(node.expression, repeat);
1283
2506
  if (ts.isForOfStatement(node) || ts.isForInStatement(node)) out = this.leaveScope(node, out, node.statement.end - 1);
1284
2507
  const exit = mergeAll([skip, out, ...target.continues, ...target.breaks]);
2508
+ exit?.outstandingIterables.delete(node);
1285
2509
  return ts.isForStatement(node) ? this.leaveScope(node, exit, node.end - 1) : exit;
1286
2510
  }
1287
2511
  tryStatement(node, state) {
1288
- const tried = this.block(node.tryBlock, new Map(state));
2512
+ const tried = this.block(node.tryBlock, new State(state));
1289
2513
  let caught = null;
1290
- if (node.catchClause) caught = this.block(node.catchClause.block, new Map(state));
2514
+ if (node.catchClause) caught = this.block(node.catchClause.block, new State(state));
1291
2515
  const out = node.catchClause ? merge(tried, caught) : tried;
1292
2516
  if (!node.finallyBlock) return out;
1293
- const finished = this.block(node.finallyBlock, out ?? new Map(state));
2517
+ const finished = this.block(node.finallyBlock, out ?? new State(state));
1294
2518
  return out ? finished : null;
1295
2519
  }
1296
2520
  };
@@ -1820,6 +3044,29 @@ function acceptDirectiveFindings(ts, sourceFile, context) {
1820
3044
  return found;
1821
3045
  }
1822
3046
 
3047
+ // src/core/finally-returns.ts
3048
+ function isScopeBoundary(ts, node) {
3049
+ return isFunctionBoundary(ts, node) || ts.isClassLike(node) || ts.isClassStaticBlockDeclaration(node);
3050
+ }
3051
+ function finallyReturnsIn(ts, sourceFile) {
3052
+ const found = [];
3053
+ const visit = (node, inFinally) => {
3054
+ if (inFinally && ts.isReturnStatement(node)) {
3055
+ found.push({ start: node.getStart(sourceFile) });
3056
+ }
3057
+ if (ts.isTryStatement(node)) {
3058
+ visit(node.tryBlock, inFinally);
3059
+ if (node.catchClause) visit(node.catchClause, inFinally);
3060
+ if (node.finallyBlock) visit(node.finallyBlock, true);
3061
+ return;
3062
+ }
3063
+ const nextInFinally = isScopeBoundary(ts, node) ? false : inFinally;
3064
+ ts.forEachChild(node, (child) => visit(child, nextInFinally));
3065
+ };
3066
+ visit(sourceFile, false);
3067
+ return found;
3068
+ }
3069
+
1823
3070
  // src/core/redundant-guards.ts
1824
3071
  var ORIGIN_LIMIT = 3;
1825
3072
  function redundantGuardData(guard) {
@@ -2045,6 +3292,43 @@ function trustedStatesIn(sourceFile, context) {
2045
3292
  const stated = members2.filter((m) => policy.resultVariant(m) === "ok" && policy.okStates(m) !== null);
2046
3293
  return { stated: stated.length > 0, states: [...new Set(stated.flatMap((m) => policy.okStates(m) ?? []))].sort() };
2047
3294
  };
3295
+ const isPresentResult = (type) => {
3296
+ const present = (type.isUnion() ? type.types : [type]).filter((t) => !(t.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
3297
+ return present.length > 0 && present.every((t) => policy.isResultType(t));
3298
+ };
3299
+ const isStatelessResultArray = (type) => {
3300
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return false;
3301
+ const members2 = type.isUnion() ? type.types : [type];
3302
+ if (!members2.length) return false;
3303
+ return members2.every((m) => {
3304
+ if (m.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never) || policy.resultVariant(m) !== null) return false;
3305
+ const element = checker.getIndexTypeOfType(m, ts.IndexKind.Number);
3306
+ if (!element) return false;
3307
+ const unwrapped = awaited(element);
3308
+ if (unwrapped.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return false;
3309
+ const present = (unwrapped.isUnion() ? unwrapped.types : [unwrapped]).filter((t) => !(t.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)));
3310
+ return present.length > 0 && present.every((t) => policy.isResultType(t) && !stateInfo(t).stated);
3311
+ });
3312
+ };
3313
+ const arrayStateInfo = (type) => {
3314
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return { stated: false, states: [] };
3315
+ const members2 = type.isUnion() ? type.types : [type];
3316
+ let stated = false;
3317
+ const states = /* @__PURE__ */ new Set();
3318
+ for (const m of members2) {
3319
+ if (m.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never) || policy.resultVariant(m) !== null) continue;
3320
+ const element = checker.getIndexTypeOfType(m, ts.IndexKind.Number);
3321
+ if (!element) continue;
3322
+ const unwrapped = awaited(element);
3323
+ if (unwrapped.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) continue;
3324
+ const info = stateInfo(unwrapped);
3325
+ if (info.stated) {
3326
+ stated = true;
3327
+ for (const s of info.states) states.add(s);
3328
+ }
3329
+ }
3330
+ return { stated, states: [...states].sort() };
3331
+ };
2048
3332
  const subjectOf2 = (node) => {
2049
3333
  const text = node.getText(sourceFile).replace(/\s+/g, " ").trim();
2050
3334
  return text.length > 60 ? `${text.slice(0, 59)}\u2026` : text;
@@ -2062,23 +3346,173 @@ function trustedStatesIn(sourceFile, context) {
2062
3346
  report(name, "unnarrowed-value", { subject: subjectOf2(receiver), states: formatStates(info.states) });
2063
3347
  }
2064
3348
  };
2065
- const erasure = (expr, target) => {
3349
+ const recordErasedArg = (expr) => {
3350
+ const argument = unparen(ts, expr);
3351
+ const callArg = ts.isSpreadElement(expr.parent) ? expr.parent : expr;
3352
+ if (ts.isCallExpression(callArg.parent) && callArg.parent.arguments.includes(callArg) && ts.isIdentifier(argument)) {
3353
+ const symbol = checker.getSymbolAtLocation(argument);
3354
+ const statement = callArg.parent.parent;
3355
+ if (symbol && ts.isExpressionStatement(statement) && ts.isBlock(statement.parent)) {
3356
+ const entries = erasedArguments.get(symbol) ?? [];
3357
+ entries.push({ after: statement.end, exit: statement.parent.end - 1 });
3358
+ erasedArguments.set(symbol, entries);
3359
+ }
3360
+ }
3361
+ };
3362
+ const tupleSlotAt = (tRef, idx, sourceLen) => {
3363
+ const tFlags = tRef.target.elementFlags;
3364
+ const tElems = checker.getTypeArguments(tRef);
3365
+ const varIdx = tElems.findIndex((_, ti) => (tFlags[ti] & ts.ElementFlags.Variable) !== 0);
3366
+ if (varIdx < 0) return tElems[idx];
3367
+ if (idx < varIdx) return tElems[idx];
3368
+ const suffixCount = tElems.length - 1 - varIdx;
3369
+ if (sourceLen !== void 0 && suffixCount > 0 && idx >= sourceLen - suffixCount) {
3370
+ return tElems[tElems.length - (sourceLen - idx)];
3371
+ }
3372
+ return checker.getIndexTypeOfType(tElems[varIdx], ts.IndexKind.Number) ?? tElems[varIdx];
3373
+ };
3374
+ const erasedStatesFor = (sourceType, target, seen = /* @__PURE__ */ new Set()) => {
2066
3375
  target = awaited(target);
2067
- if (!policy.isResultType(target) || stateInfo(target).stated) return;
2068
- const info = stateInfo(awaited(checker.getTypeAtLocation(expr)));
2069
- if (info.stated) {
2070
- report(expr, "erased-state", { subject: subjectOf2(expr), states: formatStates(info.states) });
2071
- const argument = unparen(ts, expr);
2072
- if (ts.isCallExpression(expr.parent) && expr.parent.arguments.includes(expr) && ts.isIdentifier(argument)) {
2073
- const symbol = checker.getSymbolAtLocation(argument);
2074
- const statement = expr.parent.parent;
2075
- if (symbol && ts.isExpressionStatement(statement) && ts.isBlock(statement.parent)) {
2076
- const entries = erasedArguments.get(symbol) ?? [];
2077
- entries.push({ after: statement.end, exit: statement.parent.end - 1 });
2078
- erasedArguments.set(symbol, entries);
3376
+ if (target.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return { states: [], allAccountedFor: false };
3377
+ sourceType = awaited(sourceType);
3378
+ if (sourceType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never)) return { states: [], allAccountedFor: false };
3379
+ if (sourceType === target) return { states: [], allAccountedFor: true };
3380
+ const sId = sourceType.id;
3381
+ const tId = target.id;
3382
+ if (sId !== void 0 && tId !== void 0) {
3383
+ const pairKey = `${sId}:${tId}`;
3384
+ if (seen.has(pairKey)) return { states: [], allAccountedFor: true };
3385
+ seen.add(pairKey);
3386
+ }
3387
+ if (isPresentResult(target)) {
3388
+ if (stateInfo(target).stated) return { states: [], allAccountedFor: true };
3389
+ const info = stateInfo(sourceType);
3390
+ return { states: info.stated ? info.states : [], allAccountedFor: true };
3391
+ }
3392
+ const targetMembers = target.isUnion() ? target.types : [target];
3393
+ const sourceMembers = sourceType.isUnion() ? sourceType.types : [sourceType];
3394
+ if (targetMembers.length && targetMembers.some((tm) => checker.isTupleType(tm))) {
3395
+ const nonNullishTargets = targetMembers.filter((tm) => !(tm.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)));
3396
+ if (nonNullishTargets.length && nonNullishTargets.every((tm) => checker.isTupleType(tm))) {
3397
+ const states = /* @__PURE__ */ new Set();
3398
+ let allAccountedFor = true;
3399
+ for (const sm of sourceMembers) {
3400
+ if (sm.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never | ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void) || policy.resultVariant(sm) !== null) continue;
3401
+ const compatibleTargets = typeof checker.isTypeAssignableTo === "function" ? nonNullishTargets.filter((tm) => checker.isTypeAssignableTo(sm, tm)) : [];
3402
+ const activeTargets = compatibleTargets.length ? compatibleTargets : nonNullishTargets;
3403
+ if (checker.isTupleType(sm)) {
3404
+ const sRef = sm;
3405
+ const sFlags = sRef.target.elementFlags;
3406
+ const sElems = checker.getTypeArguments(sRef);
3407
+ const sHasVar = Boolean(sRef.target.combinedFlags & ts.ElementFlags.Variable);
3408
+ for (const tm of activeTargets) {
3409
+ const tRef = tm;
3410
+ const tFlags = tRef.target.elementFlags;
3411
+ const tElems = checker.getTypeArguments(tRef);
3412
+ const tVarIdx = tElems.findIndex((_, ti) => (tFlags[ti] & ts.ElementFlags.Variable) !== 0);
3413
+ const tSuffixCount = tVarIdx >= 0 ? tElems.length - 1 - tVarIdx : 0;
3414
+ for (let k = 0; k < sElems.length; k++) {
3415
+ const sIsVar = (sFlags[k] & ts.ElementFlags.Variable) !== 0;
3416
+ const sElem = sIsVar ? checker.getIndexTypeOfType(sElems[k], ts.IndexKind.Number) ?? sElems[k] : sElems[k];
3417
+ if (!stateInfo(awaited(sElem)).stated) continue;
3418
+ const applyTarget = (pt) => {
3419
+ if (!pt) {
3420
+ allAccountedFor = false;
3421
+ return;
3422
+ }
3423
+ const sub = erasedStatesFor(sElem, pt, seen);
3424
+ for (const st of sub.states) states.add(st);
3425
+ if (!sub.allAccountedFor) allAccountedFor = false;
3426
+ };
3427
+ if (sIsVar) {
3428
+ const sSuffixCount = sElems.length - 1 - k;
3429
+ if (tVarIdx >= 0) {
3430
+ applyTarget(checker.getIndexTypeOfType(tElems[tVarIdx], ts.IndexKind.Number) ?? tElems[tVarIdx]);
3431
+ for (let p = k; p < tVarIdx; p++) applyTarget(tElems[p]);
3432
+ const extraSuffix = tSuffixCount - sSuffixCount;
3433
+ for (let s = 0; s < extraSuffix; s++) applyTarget(tElems[tVarIdx + 1 + s]);
3434
+ } else {
3435
+ const end = Math.max(tElems.length - sSuffixCount, k);
3436
+ if (end <= k) allAccountedFor = false;
3437
+ for (let p = k; p < end; p++) applyTarget(tElems[p]);
3438
+ }
3439
+ } else {
3440
+ let pt;
3441
+ if (!sHasVar) {
3442
+ pt = tupleSlotAt(tRef, k, sElems.length);
3443
+ } else {
3444
+ const sVarIdx = sElems.findIndex((_, si) => (sFlags[si] & ts.ElementFlags.Variable) !== 0);
3445
+ if (k < sVarIdx) pt = tupleSlotAt(tRef, k);
3446
+ else {
3447
+ const offsetFromEnd = sElems.length - k;
3448
+ if (tVarIdx >= 0) {
3449
+ if (offsetFromEnd <= tSuffixCount) pt = tElems[tElems.length - offsetFromEnd];
3450
+ else pt = checker.getIndexTypeOfType(tElems[tVarIdx], ts.IndexKind.Number) ?? tElems[tVarIdx];
3451
+ } else {
3452
+ pt = tElems.length >= offsetFromEnd ? tElems[tElems.length - offsetFromEnd] : void 0;
3453
+ }
3454
+ }
3455
+ }
3456
+ applyTarget(pt);
3457
+ }
3458
+ }
3459
+ }
3460
+ } else {
3461
+ const sElem = checker.getIndexTypeOfType(sm, ts.IndexKind.Number);
3462
+ if (!sElem || !stateInfo(awaited(sElem)).stated) continue;
3463
+ for (const tm of activeTargets) {
3464
+ const tRef = tm;
3465
+ const tFlags = tRef.target.elementFlags;
3466
+ const tElems = checker.getTypeArguments(tRef);
3467
+ for (let p = 0; p < tElems.length; p++) {
3468
+ const pt = (tFlags[p] & ts.ElementFlags.Variable) !== 0 ? checker.getIndexTypeOfType(tElems[p], ts.IndexKind.Number) ?? tElems[p] : tElems[p];
3469
+ const sub = erasedStatesFor(sElem, pt, seen);
3470
+ for (const st of sub.states) states.add(st);
3471
+ if (!sub.allAccountedFor) allAccountedFor = false;
3472
+ }
3473
+ }
3474
+ }
3475
+ }
3476
+ return { states: [...states].sort(), allAccountedFor };
3477
+ }
3478
+ }
3479
+ const erasedArrayStates = /* @__PURE__ */ new Set();
3480
+ let arrayHandled = false;
3481
+ let arrayAllAccounted = true;
3482
+ for (const sm of sourceMembers) {
3483
+ if (sm.flags & (ts.TypeFlags.StringLike | ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Never | ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void) || policy.resultVariant(sm) !== null) continue;
3484
+ const sInfo = arrayStateInfo(sm);
3485
+ if (!sInfo.stated) continue;
3486
+ arrayHandled = true;
3487
+ const compatibleTargets = typeof checker.isTypeAssignableTo === "function" ? targetMembers.filter((tm) => checker.isTypeAssignableTo(sm, tm)) : [];
3488
+ const activeTargets = compatibleTargets.length ? compatibleTargets : targetMembers.filter((tm) => !(tm.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Null | ts.TypeFlags.Void)));
3489
+ if (!activeTargets.length) {
3490
+ arrayAllAccounted = false;
3491
+ continue;
3492
+ }
3493
+ for (const tm of activeTargets) {
3494
+ if (checker.isTupleType(tm)) {
3495
+ const sub = erasedStatesFor(sm, tm, seen);
3496
+ for (const st of sub.states) erasedArrayStates.add(st);
3497
+ if (!sub.allAccountedFor) arrayAllAccounted = false;
3498
+ } else if (isStatelessResultArray(tm)) {
3499
+ for (const st of sInfo.states) erasedArrayStates.add(st);
3500
+ } else if (!arrayStateInfo(tm).stated) {
3501
+ arrayAllAccounted = false;
2079
3502
  }
2080
3503
  }
2081
3504
  }
3505
+ if (arrayHandled) {
3506
+ return { states: [...erasedArrayStates].sort(), allAccountedFor: arrayAllAccounted };
3507
+ }
3508
+ return { states: [], allAccountedFor: false };
3509
+ };
3510
+ const erasure = (expr, target) => {
3511
+ const { states, allAccountedFor } = erasedStatesFor(checker.getTypeAtLocation(expr), target);
3512
+ if (states.length) {
3513
+ report(expr, "erased-state", { subject: subjectOf2(expr), states: formatStates(states) });
3514
+ if (allAccountedFor) recordErasedArg(expr);
3515
+ }
2082
3516
  };
2083
3517
  const visit = (node) => {
2084
3518
  if (ts.isPropertyAccessExpression(node) && node.name.text === "value") valueRead(node.expression, node.name);
@@ -2092,6 +3526,24 @@ function trustedStatesIn(sourceFile, context) {
2092
3526
  }
2093
3527
  if ((ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node)) && node.type && node.initializer) erasure(node.initializer, checker.getTypeFromTypeNode(node.type));
2094
3528
  if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) erasure(node.right, checker.getTypeAtLocation(node.left));
3529
+ if (ts.isYieldExpression(node) && node.expression && !node.asteriskToken) {
3530
+ const target = checker.getContextualType(node.expression);
3531
+ if (target) erasure(node.expression, target);
3532
+ }
3533
+ if (ts.isYieldExpression(node) && node.expression && node.asteriskToken) {
3534
+ let fn = node.parent;
3535
+ while (fn && !ts.isFunctionLike(fn)) fn = fn.parent;
3536
+ const declared = fn && ts.isFunctionLike(fn) && fn.type ? checker.getTypeFromTypeNode(fn.type) : void 0;
3537
+ const yielded = declared && declared.flags & ts.TypeFlags.Object && declared.objectFlags & ts.ObjectFlags.Reference ? checker.getTypeArguments(declared)[0] : void 0;
3538
+ const element = yielded && checker.getIndexTypeOfType(checker.getTypeAtLocation(node.expression), ts.IndexKind.Number);
3539
+ if (yielded && element) {
3540
+ const { states, allAccountedFor } = erasedStatesFor(element, yielded);
3541
+ if (states.length) {
3542
+ report(node.expression, "erased-state", { subject: subjectOf2(node.expression), states: formatStates(states) });
3543
+ if (allAccountedFor) recordErasedArg(node.expression);
3544
+ }
3545
+ }
3546
+ }
2095
3547
  if (ts.isReturnStatement(node) && node.expression) {
2096
3548
  let parent = node.parent;
2097
3549
  while (parent && !ts.isFunctionLike(parent)) parent = parent.parent;
@@ -2103,14 +3555,228 @@ function trustedStatesIn(sourceFile, context) {
2103
3555
  const file = resolved?.declaration.getSourceFile().fileName;
2104
3556
  const signature = checker.getResolvedSignature(node);
2105
3557
  if (file && !isTrustPackageFile(file) && policy.zones.zoneOf(file) === "checked" && signature) {
2106
- node.arguments.forEach((arg, i) => {
2107
- const parameter = signature.parameters[i] ?? signature.parameters[signature.parameters.length - 1];
2108
- if (!parameter) return;
2109
- let type = checker.getTypeOfSymbolAtLocation(parameter, node);
2110
- const declaration = parameter.valueDeclaration;
2111
- if (declaration && ts.isParameter(declaration) && declaration.dotDotDotToken) type = checker.getIndexTypeOfType(type, ts.IndexKind.Number) ?? type;
2112
- erasure(arg, type);
2113
- });
3558
+ const parameters = signature.parameters;
3559
+ const lastParam = parameters[parameters.length - 1];
3560
+ const lastDecl = lastParam?.valueDeclaration;
3561
+ const hasRestParam = Boolean(lastDecl && ts.isParameter(lastDecl) && lastDecl.dotDotDotToken);
3562
+ const exactArgCount = (() => {
3563
+ let total = 0;
3564
+ for (const a of node.arguments) {
3565
+ if (!ts.isSpreadElement(a)) {
3566
+ total += 1;
3567
+ continue;
3568
+ }
3569
+ const st = awaited(checker.getTypeAtLocation(a.expression));
3570
+ const sms = st.isUnion() ? st.types : [st];
3571
+ if (!sms.length || !sms.every((m) => checker.isTupleType(m))) return void 0;
3572
+ let len;
3573
+ for (const m of sms) {
3574
+ const r = m;
3575
+ if (r.target.combinedFlags & ts.ElementFlags.NonRequired) return void 0;
3576
+ const mLen = checker.getTypeArguments(r).length;
3577
+ if (len === void 0) len = mLen;
3578
+ else if (len !== mLen) return void 0;
3579
+ }
3580
+ total += len ?? 0;
3581
+ }
3582
+ return total;
3583
+ })();
3584
+ const restStart = parameters.length - 1;
3585
+ const totalRestArgs = hasRestParam && exactArgCount !== void 0 && exactArgCount >= restStart ? exactArgCount - restStart : void 0;
3586
+ const tupleSlotTypes = (type, offset, fromEndOffset, fullRestSpread) => {
3587
+ const unwrapped = awaited(type);
3588
+ const rawMs = unwrapped.isUnion() ? unwrapped.types : [unwrapped];
3589
+ const compatible = fullRestSpread && typeof checker.isTypeAssignableTo === "function" ? rawMs.filter((tm) => checker.isTypeAssignableTo(fullRestSpread, tm)) : rawMs.length > 1 && typeof checker.isTypeAssignableTo === "function" && !node.arguments.some(ts.isSpreadElement) ? rawMs.filter((tm) => {
3590
+ if (checker.isTupleType(tm)) {
3591
+ const tuple = tm.target;
3592
+ const count = node.arguments.length - restStart;
3593
+ if (count < tuple.minLength || !(tuple.combinedFlags & ts.ElementFlags.Variable) && count > tuple.elementFlags.length) return false;
3594
+ }
3595
+ return node.arguments.slice(restStart).every((a, i) => {
3596
+ const slot = checker.isTupleType(tm) ? tupleSlotAt(tm, i, totalRestArgs) : checker.getIndexTypeOfType(tm, ts.IndexKind.Number);
3597
+ return slot && checker.isTypeAssignableTo(checker.getTypeAtLocation(a), slot);
3598
+ });
3599
+ }) : [];
3600
+ const ms = compatible.length ? compatible : rawMs;
3601
+ const out = [];
3602
+ for (const m of ms) {
3603
+ if (checker.isTupleType(m)) {
3604
+ const ref = m;
3605
+ if (fromEndOffset !== void 0) {
3606
+ const flags = ref.target.elementFlags;
3607
+ const elems = checker.getTypeArguments(ref);
3608
+ const varIdx = elems.findIndex((_, ti) => (flags[ti] & ts.ElementFlags.Variable) !== 0);
3609
+ if (varIdx >= 0) {
3610
+ const suffixCount = elems.length - 1 - varIdx;
3611
+ if (fromEndOffset <= suffixCount) out.push(elems[elems.length - fromEndOffset]);
3612
+ else out.push(checker.getIndexTypeOfType(elems[varIdx], ts.IndexKind.Number) ?? elems[varIdx]);
3613
+ } else if (elems.length >= fromEndOffset) {
3614
+ out.push(elems[elems.length - fromEndOffset]);
3615
+ }
3616
+ } else {
3617
+ const slot = tupleSlotAt(ref, offset, totalRestArgs);
3618
+ if (slot) out.push(slot);
3619
+ }
3620
+ } else {
3621
+ const indexed = checker.getIndexTypeOfType(m, ts.IndexKind.Number);
3622
+ if (indexed) out.push(indexed);
3623
+ }
3624
+ }
3625
+ return out;
3626
+ };
3627
+ const paramElementTypesAt = (index, fromEndArgs, fullRestSpread) => {
3628
+ if (hasRestParam && index >= restStart) {
3629
+ const restType = checker.getTypeOfSymbolAtLocation(lastParam, node);
3630
+ return tupleSlotTypes(restType, index - restStart, fromEndArgs, fullRestSpread);
3631
+ }
3632
+ const param = parameters[index];
3633
+ return param ? [checker.getTypeOfSymbolAtLocation(param, node)] : [];
3634
+ };
3635
+ const effectiveParamCount = () => {
3636
+ if (!hasRestParam) return parameters.length;
3637
+ const restType = awaited(checker.getTypeOfSymbolAtLocation(lastParam, node));
3638
+ const ms = restType.isUnion() ? restType.types : [restType];
3639
+ let maxExtra = 1;
3640
+ for (const m of ms) {
3641
+ if (checker.isTupleType(m)) {
3642
+ maxExtra = Math.max(maxExtra, checker.getTypeArguments(m).length);
3643
+ }
3644
+ }
3645
+ return parameters.length - 1 + maxExtra;
3646
+ };
3647
+ const totalPositions = effectiveParamCount();
3648
+ let cursor = 0;
3649
+ let seenVariadic = false;
3650
+ for (let argIdx = 0; argIdx < node.arguments.length; argIdx++) {
3651
+ const arg = node.arguments[argIdx];
3652
+ const trailingFixedArgs = (() => {
3653
+ let count = 0;
3654
+ for (let j = argIdx + 1; j < node.arguments.length; j++) {
3655
+ const nextArg = node.arguments[j];
3656
+ if (!ts.isSpreadElement(nextArg)) {
3657
+ count += 1;
3658
+ continue;
3659
+ }
3660
+ const st = awaited(checker.getTypeAtLocation(nextArg.expression));
3661
+ const sms = st.isUnion() ? st.types : [st];
3662
+ if (!sms.length || !sms.every((m) => checker.isTupleType(m))) return void 0;
3663
+ let len;
3664
+ for (const m of sms) {
3665
+ const r = m;
3666
+ if (r.target.combinedFlags & ts.ElementFlags.NonRequired) return void 0;
3667
+ const mLen = checker.getTypeArguments(r).length;
3668
+ if (len === void 0) len = mLen;
3669
+ else if (len !== mLen) return void 0;
3670
+ }
3671
+ count += len ?? 0;
3672
+ }
3673
+ return count;
3674
+ })();
3675
+ if (!ts.isSpreadElement(arg)) {
3676
+ const fromEnd = seenVariadic && trailingFixedArgs !== void 0 ? trailingFixedArgs + 1 : void 0;
3677
+ const paramTypes = paramElementTypesAt(cursor, fromEnd);
3678
+ const states = /* @__PURE__ */ new Set();
3679
+ let allAccountedFor2 = paramTypes.length > 0;
3680
+ const argType = checker.getTypeAtLocation(arg);
3681
+ for (const pt of paramTypes) {
3682
+ const res = erasedStatesFor(argType, pt);
3683
+ for (const s of res.states) states.add(s);
3684
+ if (!res.allAccountedFor) allAccountedFor2 = false;
3685
+ }
3686
+ if (states.size) {
3687
+ report(arg, "erased-state", { subject: subjectOf2(arg), states: formatStates([...states].sort()) });
3688
+ if (allAccountedFor2) recordErasedArg(arg);
3689
+ }
3690
+ cursor += 1;
3691
+ continue;
3692
+ }
3693
+ const expr = arg.expression;
3694
+ const spreadType = awaited(checker.getTypeAtLocation(expr));
3695
+ const ms = spreadType.isUnion() ? spreadType.types : [spreadType];
3696
+ const erasedStates = /* @__PURE__ */ new Set();
3697
+ let allAccountedFor = true;
3698
+ const isSoleRestSpread = hasRestParam && cursor === restStart && !seenVariadic && argIdx === node.arguments.length - 1;
3699
+ const checkParamPos = (elemType, pos, fromEnd, fullRestSpread) => {
3700
+ const pts = paramElementTypesAt(pos, fromEnd, fullRestSpread);
3701
+ if (!pts.length) return false;
3702
+ let ok = true;
3703
+ for (const pt of pts) {
3704
+ const res = erasedStatesFor(elemType, pt);
3705
+ for (const s of res.states) erasedStates.add(s);
3706
+ if (!res.allAccountedFor) ok = false;
3707
+ }
3708
+ return ok;
3709
+ };
3710
+ if (ms.length && ms.every((m) => checker.isTupleType(m))) {
3711
+ for (const m of ms) {
3712
+ const fullRest = isSoleRestSpread ? m : void 0;
3713
+ const ref = m;
3714
+ const flags = ref.target.elementFlags;
3715
+ const elemTypes = checker.getTypeArguments(ref);
3716
+ const varIdx = elemTypes.findIndex((_, si) => (flags[si] & ts.ElementFlags.Variable) !== 0);
3717
+ for (let k = 0; k < elemTypes.length; k++) {
3718
+ const isVar = (flags[k] & ts.ElementFlags.Variable) !== 0;
3719
+ const elemType = isVar ? checker.getIndexTypeOfType(elemTypes[k], ts.IndexKind.Number) ?? elemTypes[k] : elemTypes[k];
3720
+ if (!stateInfo(awaited(elemType)).stated) continue;
3721
+ if (isVar) {
3722
+ const end = Math.max(totalPositions, cursor + k + 1);
3723
+ for (let p = cursor + k; p < end; p++) {
3724
+ if (!checkParamPos(elemType, p, void 0, fullRest)) allAccountedFor = false;
3725
+ }
3726
+ } else {
3727
+ const hasAfterVar = varIdx >= 0 && k > varIdx;
3728
+ const fromEnd = (seenVariadic || hasAfterVar) && trailingFixedArgs !== void 0 ? trailingFixedArgs + (elemTypes.length - k) : void 0;
3729
+ if (!checkParamPos(elemType, cursor + k, fromEnd, fullRest)) allAccountedFor = false;
3730
+ }
3731
+ }
3732
+ }
3733
+ if (ms.length === 1) {
3734
+ const ref = ms[0];
3735
+ if (!(ref.target.combinedFlags & ts.ElementFlags.NonRequired)) {
3736
+ cursor += checker.getTypeArguments(ref).length;
3737
+ } else {
3738
+ seenVariadic = true;
3739
+ cursor += 1;
3740
+ }
3741
+ } else {
3742
+ const allExactSameLen = ms.every((m) => !(m.target.combinedFlags & ts.ElementFlags.NonRequired)) && new Set(ms.map((m) => checker.getTypeArguments(m).length)).size === 1;
3743
+ if (allExactSameLen) cursor += checker.getTypeArguments(ms[0]).length;
3744
+ else {
3745
+ seenVariadic = true;
3746
+ cursor += 1;
3747
+ }
3748
+ }
3749
+ } else {
3750
+ seenVariadic = true;
3751
+ const elemInfo = arrayStateInfo(spreadType);
3752
+ if (elemInfo.stated) {
3753
+ const end = Math.max(totalPositions, cursor + 1);
3754
+ for (let p = cursor; p < end; p++) {
3755
+ const pts = paramElementTypesAt(p);
3756
+ if (!pts.length) {
3757
+ allAccountedFor = false;
3758
+ continue;
3759
+ }
3760
+ for (const pt of pts) {
3761
+ const unwrappedTarget = awaited(pt);
3762
+ if (!isPresentResult(unwrappedTarget)) {
3763
+ allAccountedFor = false;
3764
+ continue;
3765
+ }
3766
+ if (!stateInfo(unwrappedTarget).stated) {
3767
+ for (const s of elemInfo.states) erasedStates.add(s);
3768
+ }
3769
+ }
3770
+ }
3771
+ }
3772
+ cursor += 1;
3773
+ }
3774
+ if (erasedStates.size) {
3775
+ const sorted = [...erasedStates].sort();
3776
+ report(expr, "erased-state", { subject: subjectOf2(expr), states: formatStates(sorted) });
3777
+ if (allAccountedFor) recordErasedArg(expr);
3778
+ }
3779
+ }
2114
3780
  }
2115
3781
  }
2116
3782
  if (ts.isFunctionLike(node) && "body" in node && node.body) {
@@ -2176,13 +3842,74 @@ function trustedStatesIn(sourceFile, context) {
2176
3842
  const symbol = checker.getSymbolsInScope(at, ts.SymbolFlags.Variable).find((s) => s.name === flow.subject);
2177
3843
  if (symbol && erasedArguments.get(symbol)?.some(({ after, exit }) => {
2178
3844
  if (flow.start < after || flow.start > exit) return false;
2179
- let reassigned = false;
3845
+ const connectedSymbols = /* @__PURE__ */ new Set([symbol]);
3846
+ const collectAliases = (node) => {
3847
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) {
3848
+ const rhs = unparen(ts, node.initializer);
3849
+ if (ts.isIdentifier(rhs)) {
3850
+ const lhsSym = checker.getSymbolAtLocation(node.name);
3851
+ const rhsSym = checker.getSymbolAtLocation(rhs);
3852
+ if (lhsSym && rhsSym && (connectedSymbols.has(lhsSym) || connectedSymbols.has(rhsSym))) {
3853
+ connectedSymbols.add(lhsSym);
3854
+ connectedSymbols.add(rhsSym);
3855
+ }
3856
+ }
3857
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
3858
+ const lhs = unparen(ts, node.left);
3859
+ const rhs = unparen(ts, node.right);
3860
+ if (ts.isIdentifier(lhs) && ts.isIdentifier(rhs)) {
3861
+ const lhsSym = checker.getSymbolAtLocation(lhs);
3862
+ const rhsSym = checker.getSymbolAtLocation(rhs);
3863
+ if (lhsSym && rhsSym && (connectedSymbols.has(lhsSym) || connectedSymbols.has(rhsSym))) {
3864
+ connectedSymbols.add(lhsSym);
3865
+ connectedSymbols.add(rhsSym);
3866
+ }
3867
+ }
3868
+ }
3869
+ ts.forEachChild(node, collectAliases);
3870
+ };
3871
+ collectAliases(sourceFile);
3872
+ const matchesSymbol = (expr) => {
3873
+ const inner = unparen(ts, expr);
3874
+ if (!ts.isIdentifier(inner)) return false;
3875
+ const s = checker.getSymbolAtLocation(inner);
3876
+ return Boolean(s && connectedSymbols.has(s));
3877
+ };
3878
+ const patternMentionsSymbol = (pat) => {
3879
+ const inner = unparen(ts, pat);
3880
+ if (ts.isIdentifier(inner)) return matchesSymbol(inner);
3881
+ if (ts.isArrayLiteralExpression(inner)) {
3882
+ return inner.elements.some((el) => {
3883
+ if (ts.isOmittedExpression(el)) return false;
3884
+ if (ts.isSpreadElement(el)) return patternMentionsSymbol(el.expression);
3885
+ if (ts.isBinaryExpression(el) && el.operatorToken.kind === ts.SyntaxKind.EqualsToken) return patternMentionsSymbol(el.left);
3886
+ return patternMentionsSymbol(el);
3887
+ });
3888
+ }
3889
+ return false;
3890
+ };
3891
+ let refreshed = false;
2180
3892
  const writes = (node) => {
2181
- if (node.getStart(sourceFile) >= after && node.getStart(sourceFile) < flow.start && ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment && checker.getSymbolAtLocation(unparen(ts, node.left)) === symbol) reassigned = true;
3893
+ const pos = node.getStart(sourceFile);
3894
+ if (pos >= after && pos < flow.start) {
3895
+ if (ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment) {
3896
+ const lhs = unparen(ts, node.left);
3897
+ if (patternMentionsSymbol(lhs)) refreshed = true;
3898
+ else if (ts.isElementAccessExpression(lhs) && matchesSymbol(lhs.expression)) refreshed = true;
3899
+ } else if ((ts.isForOfStatement(node) || ts.isForInStatement(node)) && !ts.isVariableDeclarationList(node.initializer) && patternMentionsSymbol(node.initializer)) {
3900
+ refreshed = true;
3901
+ } else if (ts.isCallExpression(node)) {
3902
+ const callee = unparen(ts, node.expression);
3903
+ const methodName = ts.isPropertyAccessExpression(callee) ? callee.name.text : ts.isElementAccessExpression(callee) && callee.argumentExpression && (ts.isStringLiteral(unparen(ts, callee.argumentExpression)) || ts.isNoSubstitutionTemplateLiteral(unparen(ts, callee.argumentExpression))) ? unparen(ts, callee.argumentExpression).text : void 0;
3904
+ if (methodName && ["push", "unshift", "splice", "fill", "copyWithin"].includes(methodName) && (ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee)) && matchesSymbol(callee.expression)) {
3905
+ refreshed = true;
3906
+ }
3907
+ }
3908
+ }
2182
3909
  ts.forEachChild(node, writes);
2183
3910
  };
2184
3911
  writes(sourceFile);
2185
- return !reassigned;
3912
+ return !refreshed;
2186
3913
  })) continue;
2187
3914
  }
2188
3915
  findings.push({ start: flow.start, origin: flow.origin, data: {
@@ -3603,6 +5330,11 @@ function checkSourceFileWithAccepted(options) {
3603
5330
  reportAt(guard.start, REDUNDANT_GUARD_RULE, REDUNDANT_GUARD_ORIGIN, redundantGuardMessage(guard));
3604
5331
  }
3605
5332
  }
5333
+ if (isRuleEnabled(config, FINALLY_RETURN_RULE)) {
5334
+ for (const found of finallyReturnsIn(ts, sourceFile)) {
5335
+ reportAt(found.start, FINALLY_RETURN_RULE, FINALLY_RETURN_ORIGIN, FINALLY_RETURN_MESSAGES.return);
5336
+ }
5337
+ }
3606
5338
  if (config.boundaries.length > 0) {
3607
5339
  for (const found of boundaryFindingsIn(sourceFile, boundaryContext(ts, checker, options.program, policy, config), strict)) {
3608
5340
  const finding = findingAt(found.start, BOUNDARY_RULE, found.origin, boundaryMessage(found));
@@ -3640,6 +5372,7 @@ export {
3640
5372
  untrustedCallProblem,
3641
5373
  acceptanceOf,
3642
5374
  acceptDirectiveFindings,
5375
+ finallyReturnsIn,
3643
5376
  redundantGuardData,
3644
5377
  redundantGuardsIn,
3645
5378
  trustedStateContext,
@@ -3665,4 +5398,4 @@ export {
3665
5398
  checkSourceFile,
3666
5399
  checkSourceFileWithAccepted
3667
5400
  };
3668
- //# sourceMappingURL=chunk-3IIEQHH2.js.map
5401
+ //# sourceMappingURL=chunk-QTS55J43.js.map