@ai-ecoverse/slicc-browsers 1.24.1 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -514,6 +514,1945 @@ async function sandboxedSrcdoc({
514
514
  };
515
515
  }
516
516
 
517
+ const pageFrameEvents = [
518
+ 'Page.frameAttached',
519
+ 'Page.frameStartedLoading',
520
+ 'Page.frameNavigated',
521
+ 'Page.frameRequestedNavigation',
522
+ 'Page.lifecycleEvent',
523
+ 'Page.navigatedWithinDocument',
524
+ ];
525
+
526
+ function midFrameIdsOf(raw) {
527
+ if (raw.midFrameIds?.size) return raw.midFrameIds;
528
+ return new Set([raw.midFrameId].filter(Boolean));
529
+ }
530
+
531
+ function frameEventHit(event, raw) {
532
+ if (!pageFrameEvents.includes(event.method)) return false;
533
+ const params = event.params ?? {};
534
+ const frame = params.frame ?? {};
535
+ const frameId = params.frameId ?? frame.id;
536
+ const parentId = params.parentFrameId ?? params.parentId ?? frame.parentId;
537
+ const url = params.url ?? frame.url ?? '';
538
+ if (frameId && raw.frameIds.has(frameId)) return true;
539
+ if (parentId && midFrameIdsOf(raw).has(parentId)) return true;
540
+ if (typeof url === 'string' && url.length > 0 && raw.urls.has(url)) return true;
541
+ return false;
542
+ }
543
+
544
+ function contextHit(event, raw) {
545
+ if (event.method !== 'Runtime.executionContextCreated') return false;
546
+ const context = event.params?.context;
547
+ const frameId = context?.auxData?.frameId;
548
+ if (frameId && raw.frameIds.has(frameId)) return true;
549
+ if (raw.frameIds.size) return false;
550
+ const origin = context?.origin ?? '';
551
+ return Boolean(origin && raw.origins.has(origin));
552
+ }
553
+
554
+ function treeMentions(tree, raw) {
555
+ const mids = midFrameIdsOf(raw);
556
+ for (const frame of walkFrames(tree)) {
557
+ if (raw.frameIds.has(frame.id)) return true;
558
+ if (typeof frame.url === 'string' && frame.url.length > 0 && raw.urls.has(frame.url))
559
+ return true;
560
+ if (frame.parentId && mids.has(frame.parentId)) return true;
561
+ }
562
+ const visit = (node, underMid) => {
563
+ if (!node?.frame) return false;
564
+ const here = underMid || mids.has(node.frame.id);
565
+ for (const child of node.childFrames ?? []) {
566
+ if (here) return true;
567
+ if (visit(child, here)) return true;
568
+ }
569
+ return false;
570
+ };
571
+ return visit(tree, false);
572
+ }
573
+
574
+ function resourceMentions(resource, raw) {
575
+ const frameTree = resource?.frameTree ?? resource;
576
+ if (treeMentions(frameTree, raw)) return true;
577
+ const text = JSON.stringify(resource ?? {});
578
+ for (const id of raw.frameIds) if (text.includes(id)) return true;
579
+ for (const url of raw.urls) if (url && text.includes(url)) return true;
580
+ for (const mid of midFrameIdsOf(raw)) {
581
+ if (text.includes(`"parentId":"${mid}"`)) return true;
582
+ }
583
+ return false;
584
+ }
585
+
586
+ function midFrameAttachedHit(event, raw) {
587
+ if (event.method !== 'Page.frameAttached') return false;
588
+ const frameId = event.params?.frameId;
589
+ return Boolean(frameId && midFrameIdsOf(raw).has(frameId));
590
+ }
591
+
592
+ function childMatches(url, innerNeedle) {
593
+ if (innerNeedle === 'about:srcdoc') return url === 'about:srcdoc';
594
+ return typeof url === 'string' && (url === innerNeedle || url.includes(innerNeedle));
595
+ }
596
+
597
+ function midMatches(midUrl, midHint) {
598
+ if (!midHint) return true;
599
+ try {
600
+ const hint = new URL(midHint);
601
+ const mid = new URL(midUrl);
602
+ return mid.origin === hint.origin;
603
+ } catch {
604
+ return midUrl.includes(midHint) || midUrl.startsWith(String(midHint).split('?')[0]);
605
+ }
606
+ }
607
+
608
+ function grandchildFromMid(mid, innerNeedle) {
609
+ const midUrl = mid.frame?.url ?? '';
610
+ for (const child of mid.childFrames ?? []) {
611
+ const url = child.frame?.url ?? '';
612
+ if (!childMatches(url, innerNeedle)) continue;
613
+ return {
614
+ midFrameId: mid.frame.id,
615
+ midUrl,
616
+ frameId: child.frame.id,
617
+ url,
618
+ parentId: child.frame.parentId ?? mid.frame.id,
619
+ };
620
+ }
621
+ return null;
622
+ }
623
+
624
+ function findGrandchild(tree, midHint, innerNeedle) {
625
+ if (!tree?.frame) return null;
626
+ for (const mid of tree.childFrames ?? []) {
627
+ if (!midMatches(mid.frame?.url ?? '', midHint)) continue;
628
+ const hit = grandchildFromMid(mid, innerNeedle);
629
+ if (hit) return hit;
630
+ }
631
+ for (const mid of tree.childFrames ?? []) {
632
+ if (!/\/oopif-(mid|srcdoc)/.test(mid.frame?.url ?? '')) continue;
633
+ const hit = grandchildFromMid(mid, innerNeedle);
634
+ if (hit) return hit;
635
+ }
636
+ return null;
637
+ }
638
+
639
+ function hitFromMidTree(midTree, innerNeedle, midUrl) {
640
+ if (!midTree?.frame) return null;
641
+ for (const child of midTree.childFrames ?? []) {
642
+ const url = child.frame?.url ?? '';
643
+ if (!childMatches(url, innerNeedle)) continue;
644
+ return {
645
+ midFrameId: midTree.frame.id,
646
+ midUrl: midTree.frame.url ?? midUrl ?? '',
647
+ frameId: child.frame.id,
648
+ url,
649
+ parentId: child.frame.parentId ?? midTree.frame.id,
650
+ };
651
+ }
652
+ return null;
653
+ }
654
+
655
+ function targetSnapshot(infos) {
656
+ return (infos ?? []).map((info) => ({
657
+ targetId: info.targetId,
658
+ type: info.type,
659
+ url: info.url,
660
+ parentId: info.parentId,
661
+ }));
662
+ }
663
+
664
+ async function listTargetSnapshot(reader) {
665
+ const listed = await outcome(reader.send('Target.getTargets', {}));
666
+ if (!answered(listed) || !listed.ok) return { unanswered: !answered(listed), targets: [] };
667
+ return { unanswered: false, targets: targetSnapshot(listed.result?.targetInfos) };
668
+ }
669
+
670
+ function liveNestPlan(pageUrl, innerKind, innerHint) {
671
+ const page = new URL(pageUrl);
672
+ const midRaw = page.searchParams.get('mid');
673
+ let midNeedle = null;
674
+ if (midRaw) {
675
+ try {
676
+ midNeedle = new URL(midRaw).searchParams.get('n');
677
+ } catch {
678
+ midNeedle = null;
679
+ }
680
+ }
681
+ page.searchParams.set('live', '1');
682
+ return {
683
+ liveUrl: page.toString(),
684
+ midUrl: midRaw,
685
+ innerHint: innerHint || (innerKind === 'srcdoc' ? 'about:srcdoc' : ''),
686
+ midNeedle,
687
+ };
688
+ }
689
+
690
+ function sameSiteOrigin(left, right) {
691
+ try {
692
+ return Boolean(left && right && new URL(left).origin === new URL(right).origin);
693
+ } catch {
694
+ return false;
695
+ }
696
+ }
697
+
698
+ function midUrlMatch(candidate, midUrls) {
699
+ if (!candidate) return false;
700
+ for (const mid of midUrls ?? []) {
701
+ if (!mid) continue;
702
+ if (candidate === mid) return true;
703
+ try {
704
+ const a = new URL(candidate);
705
+ const b = new URL(mid);
706
+ if (a.origin === b.origin && a.pathname === b.pathname) return true;
707
+ } catch {
708
+ if (candidate.startsWith(mid) || mid.startsWith(candidate)) return true;
709
+ }
710
+ }
711
+ return false;
712
+ }
713
+
714
+ function blockedNetworkFail(event, network) {
715
+ const url = network.get(event.params?.requestId);
716
+ if (
717
+ !url ||
718
+ !(event.params?.blockedReason || event.params?.errorText === 'net::ERR_BLOCKED_BY_CLIENT')
719
+ )
720
+ return null;
721
+ return {
722
+ url,
723
+ errorText: event.params?.errorText ?? null,
724
+ blockedReason: event.params?.blockedReason ?? null,
725
+ via: 'Network.loadingFailed',
726
+ };
727
+ }
728
+
729
+ function blockedFetchFail(event, fetchDocs) {
730
+ const url = fetchDocs.get(event.params?.requestId);
731
+ if (!url || (event.params?.errorReason && event.params.errorReason !== 'BlockedByClient'))
732
+ return null;
733
+ return {
734
+ url,
735
+ errorText: event.params?.errorReason ?? 'BlockedByClient',
736
+ blockedReason: 'Fetch',
737
+ via: 'Fetch.failRequest',
738
+ };
739
+ }
740
+
741
+ function trackMidDocument(event, midUrls, network, fetchDocs) {
742
+ if (event.method === 'Network.requestWillBeSent') {
743
+ const url = event.params?.request?.url;
744
+ if (event.params?.type === 'Document' && midUrlMatch(url, midUrls))
745
+ network.set(event.params.requestId, url);
746
+ return null;
747
+ }
748
+ if (event.method === 'Fetch.requestPaused') {
749
+ const url = event.params?.request?.url;
750
+ if (event.params?.resourceType === 'Document' && midUrlMatch(url, midUrls))
751
+ fetchDocs.set(event.params.requestId, url);
752
+ return null;
753
+ }
754
+ if (event.method === 'Network.loadingFailed') return blockedNetworkFail(event, network);
755
+ if (event.method === 'Fetch.failRequest') return blockedFetchFail(event, fetchDocs);
756
+ return null;
757
+ }
758
+
759
+ function liveMidBlocked(events, from, midUrls) {
760
+ if (!midUrls?.length) return null;
761
+ const network = new Map();
762
+ const fetchDocs = new Map();
763
+ for (const event of (events ?? []).slice(from)) {
764
+ const hit = trackMidDocument(event, midUrls, network, fetchDocs);
765
+ if (hit) return hit;
766
+ }
767
+ return null;
768
+ }
769
+
770
+ function liveMissingReason(pageUrl, midHint, raw) {
771
+ if (!raw.midTargetId && midHint && sameSiteOrigin(pageUrl, midHint))
772
+ return "grandchild missing in raw leg after post-attach navigation: mid host is same-site with {ordinary} (no mid target); seven's host should be cross-site from {ordinary} like {cross}";
773
+ return 'grandchild missing in raw leg after post-attach navigation';
774
+ }
775
+
776
+ async function armReaderNetwork(reader, sessionIds) {
777
+ for (const sessionId of [...new Set((sessionIds ?? []).filter(Boolean))])
778
+ await outcome(reader.send('Network.enable', {}, sessionId));
779
+ }
780
+
781
+ function stampedMidLive(midUrl, innerKind, innerHint) {
782
+ const stamp = `live-${Date.now().toString(36)}`;
783
+ try {
784
+ const mid = new URL(midUrl);
785
+ mid.searchParams.set('n', `${mid.searchParams.get('n') ?? 'mid'}-${stamp}`);
786
+ if (innerKind === 'srcdoc' || innerHint === 'about:srcdoc') {
787
+ return {
788
+ midUrl: mid.toString(),
789
+ innerHint: 'about:srcdoc',
790
+ midNeedle: mid.searchParams.get('n'),
791
+ };
792
+ }
793
+ const innerRaw = mid.searchParams.get('inner');
794
+ if (!innerRaw) {
795
+ return {
796
+ midUrl: mid.toString(),
797
+ innerHint,
798
+ midNeedle: mid.searchParams.get('n'),
799
+ };
800
+ }
801
+ const inner = new URL(innerRaw);
802
+ const prior = inner.searchParams.get('n') ?? `inner-${stamp}`;
803
+ inner.searchParams.set('n', `${prior}-${stamp}`);
804
+ mid.searchParams.set('inner', inner.toString());
805
+ return {
806
+ midUrl: mid.toString(),
807
+ innerHint: inner.searchParams.get('n'),
808
+ midNeedle: mid.searchParams.get('n'),
809
+ };
810
+ } catch {
811
+ return { midUrl, innerHint, midNeedle: null };
812
+ }
813
+ }
814
+
815
+ async function waitChildUnderMid(
816
+ reader,
817
+ midAttached,
818
+ innerHint,
819
+ budget,
820
+ internalSessions,
821
+ beforeIds,
822
+ midNeedle = null,
823
+ blockCheck = null
824
+ ) {
825
+ return until(async () => {
826
+ const blocked = blockCheck?.();
827
+ if (blocked) return { blocked };
828
+ return hitFromGrandchildTarget(
829
+ reader,
830
+ midAttached,
831
+ innerHint,
832
+ internalSessions,
833
+ beforeIds,
834
+ midNeedle
835
+ );
836
+ }, budget);
837
+ }
838
+
839
+ async function attachIframeTarget(reader, match, internalSessions) {
840
+ const listed = await outcome(reader.send('Target.getTargets', {}));
841
+ if (!answered(listed) || !listed.ok) return null;
842
+ const info = (listed.result?.targetInfos ?? []).find(
843
+ (entry) => entry.type === 'iframe' && match(entry)
844
+ );
845
+ if (!info?.targetId) return null;
846
+ const attached = await outcome(
847
+ reader.send('Target.attachToTarget', { targetId: info.targetId, flatten: true })
848
+ );
849
+ if (!answered(attached) || !attached.ok || !attached.result?.sessionId) return null;
850
+ internalSessions?.add(attached.result.sessionId);
851
+ await outcome(reader.send('Page.enable', {}, attached.result.sessionId));
852
+ await outcome(reader.send('Runtime.enable', {}, attached.result.sessionId));
853
+ return { info, sessionId: attached.result.sessionId };
854
+ }
855
+
856
+ async function armMidChildWatch(reader, midSession, waitMs = 1500) {
857
+ await outcome(
858
+ reader.send(
859
+ 'Target.setAutoAttach',
860
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
861
+ midSession
862
+ )
863
+ );
864
+ await until(async () => {
865
+ const evaled = await outcome(
866
+ reader.send(
867
+ 'Runtime.evaluate',
868
+ { expression: 'document.querySelector("iframe")?.src || ""', returnByValue: true },
869
+ midSession
870
+ )
871
+ );
872
+ if (!answered(evaled) || !evaled.ok) return null;
873
+ const src = evaled.result?.result?.value;
874
+ return typeof src === 'string' && src.length > 0 ? src : null;
875
+ }, waitMs);
876
+ }
877
+
878
+ async function hitFromGrandchildTarget(
879
+ reader,
880
+ midAttached,
881
+ innerHint,
882
+ internalSessions,
883
+ beforeIds = null,
884
+ midNeedle = null
885
+ ) {
886
+ if (!midAttached.armed) {
887
+ await armMidChildWatch(reader, midAttached.sessionId, 400);
888
+ midAttached.armed = true;
889
+ }
890
+ const midTree = await readTree(reader, midAttached.sessionId);
891
+ const midFrameId = midTree?.frame?.id;
892
+ const midUrl = midTree?.frame?.url ?? midAttached.info.url ?? '';
893
+ const tag = midTagFrom(midUrl, midNeedle);
894
+ const fromMid = hitFromMidTree(midTree, innerHint, midUrl);
895
+ if (fromMid) {
896
+ return {
897
+ tree: midTree,
898
+ hit: fromMid,
899
+ via: 'mid-target',
900
+ midSession: midAttached.sessionId,
901
+ midTargetId: midAttached.info.targetId,
902
+ };
903
+ }
904
+ const child = await attachIframeTarget(
905
+ reader,
906
+ (info) => {
907
+ if (beforeIds?.has(info.targetId)) return false;
908
+ if (!childMatches(info.url ?? '', innerHint)) return false;
909
+ return info.parentId === midAttached.info.targetId;
910
+ },
911
+ internalSessions
912
+ );
913
+ if (!child) return null;
914
+ if (innerHint === 'about:srcdoc' && tag) {
915
+ if (!(await srcdocDocHasTag(reader, child.sessionId, tag))) return null;
916
+ }
917
+ const childTree = await readTree(reader, child.sessionId);
918
+ if (!childTree?.frame) return null;
919
+ const frameId = childTree.frame.id;
920
+ const frameParentId = childTree.frame.parentId ?? midFrameId;
921
+ const linked =
922
+ innerHint !== 'about:srcdoc' ||
923
+ srcdocLinkedToMid(reader, midFrameId ?? midAttached.info.targetId, frameId, frameParentId) ||
924
+ child.info.parentId === midAttached.info.targetId;
925
+ if (innerHint === 'about:srcdoc' && !linked) return null;
926
+ return {
927
+ tree: childTree,
928
+ hit: {
929
+ midFrameId: midFrameId ?? midAttached.info.targetId,
930
+ midUrl,
931
+ frameId,
932
+ url: childTree.frame.url ?? child.info.url ?? '',
933
+ parentId: frameParentId,
934
+ },
935
+ via: 'grandchild-target',
936
+ midSession: midAttached.sessionId,
937
+ midTargetId: midAttached.info.targetId,
938
+ grandchildSession: child.sessionId,
939
+ grandchildTargetId: child.info.targetId,
940
+ };
941
+ }
942
+
943
+ function midTargetMatch(info, midHint, pageId, midNeedle, beforeIds) {
944
+ if (beforeIds?.has(info.targetId)) return false;
945
+ if (midNeedle && !(info.url ?? '').includes(midNeedle)) return false;
946
+ if (!midMatches(info.url ?? '', midHint)) return false;
947
+ if (pageId && info.parentId && info.parentId !== pageId) return false;
948
+ return true;
949
+ }
950
+
951
+ function midTagFrom(midUrl, midNeedle) {
952
+ if (typeof midNeedle === 'string' && midNeedle.length > 0) return midNeedle;
953
+ try {
954
+ return new URL(midUrl).searchParams.get('n');
955
+ } catch {
956
+ return null;
957
+ }
958
+ }
959
+
960
+ function localMidFrame(tree, midHint) {
961
+ if (!tree?.frame) return null;
962
+ for (const mid of tree.childFrames ?? []) {
963
+ if (!midMatches(mid.frame?.url ?? '', midHint)) continue;
964
+ return mid;
965
+ }
966
+ for (const mid of tree.childFrames ?? []) {
967
+ if (!/\/oopif-(mid|srcdoc)/.test(mid.frame?.url ?? '')) continue;
968
+ return mid;
969
+ }
970
+ return null;
971
+ }
972
+
973
+ async function srcdocDocHasTag(reader, sessionId, tag) {
974
+ if (!tag) return false;
975
+ const evaluated = await outcome(
976
+ reader.send(
977
+ 'Runtime.evaluate',
978
+ {
979
+ expression:
980
+ '(document.body && (document.body.innerText || document.body.textContent)) || ""',
981
+ returnByValue: true,
982
+ },
983
+ sessionId
984
+ )
985
+ );
986
+ if (!answered(evaluated) || !evaluated.ok) return false;
987
+ const text = evaluated.result?.result?.value;
988
+ return typeof text === 'string' && text.includes(tag);
989
+ }
990
+
991
+ function srcdocLinkedToMid(reader, midFrameId, frameId, frameParentId) {
992
+ if (midFrameId && frameParentId && frameParentId === midFrameId) return true;
993
+ if (!midFrameId || !frameId) return false;
994
+ for (const event of reader.events ?? []) {
995
+ if (event.method === 'Page.frameAttached') {
996
+ if (event.params?.frameId === frameId && event.params?.parentFrameId === midFrameId)
997
+ return true;
998
+ }
999
+ if (event.method === 'Page.frameNavigated') {
1000
+ const frame = event.params?.frame ?? {};
1001
+ if (frame.id === frameId && frame.parentId === midFrameId) return true;
1002
+ }
1003
+ }
1004
+ return false;
1005
+ }
1006
+
1007
+ function srcdocTargetCandidate(info, pageId, midFrameId, beforeIds) {
1008
+ if (info.type !== 'iframe') return false;
1009
+ if ((info.url ?? '') !== 'about:srcdoc') return false;
1010
+ if (beforeIds?.has(info.targetId)) return false;
1011
+ if (!pageId || !info.parentId) return true;
1012
+ return info.parentId === pageId || info.parentId === midFrameId;
1013
+ }
1014
+
1015
+ function finishSrcdocHit({ tree, mid, info, attached, childTree, notes, pageId, tag, reader }) {
1016
+ const midFrameId = mid.frame.id;
1017
+ const frameId = childTree?.frame?.id ?? info.targetId;
1018
+ const frameParentId = childTree?.frame?.parentId ?? null;
1019
+ const linked = srcdocLinkedToMid(reader, midFrameId, frameId, frameParentId);
1020
+ const topParentOnly = Boolean(pageId && info.parentId === pageId);
1021
+ if (!linked && !topParentOnly) return null;
1022
+ if (!linked && topParentOnly) {
1023
+ note(notes, 'protected-parent.srcdoc-top-parent', {
1024
+ midFrameId,
1025
+ frameId,
1026
+ targetId: info.targetId,
1027
+ targetParentId: info.parentId,
1028
+ tag,
1029
+ });
1030
+ }
1031
+ return {
1032
+ tree: childTree ?? tree,
1033
+ hit: {
1034
+ midFrameId,
1035
+ midUrl: mid.frame.url ?? '',
1036
+ frameId,
1037
+ url: childTree?.frame?.url ?? info.url ?? 'about:srcdoc',
1038
+ parentId: frameParentId ?? (linked ? midFrameId : info.parentId),
1039
+ },
1040
+ via: 'grandchild-target',
1041
+ grandchildSession: attached.sessionId,
1042
+ grandchildTargetId: topParentOnly ? undefined : info.targetId,
1043
+ };
1044
+ }
1045
+
1046
+ async function hitFromSrcdocUnderLocalMid(
1047
+ reader,
1048
+ tree,
1049
+ midHint,
1050
+ pageId,
1051
+ internalSessions,
1052
+ beforeIds,
1053
+ midNeedle,
1054
+ notes
1055
+ ) {
1056
+ const mid = localMidFrame(tree, midHint);
1057
+ if (!mid?.frame?.id) return null;
1058
+ const tag = midTagFrom(mid.frame.url ?? '', midNeedle);
1059
+ if (!tag) return null;
1060
+ const listed = await outcome(reader.send('Target.getTargets', {}));
1061
+ if (!answered(listed) || !listed.ok) return null;
1062
+ for (const info of listed.result?.targetInfos ?? []) {
1063
+ if (!srcdocTargetCandidate(info, pageId, mid.frame.id, beforeIds)) continue;
1064
+ const attached = await attachIframeTarget(
1065
+ reader,
1066
+ (entry) => entry.targetId === info.targetId,
1067
+ internalSessions
1068
+ );
1069
+ if (!attached) continue;
1070
+ if (!(await srcdocDocHasTag(reader, attached.sessionId, tag))) continue;
1071
+ const hit = finishSrcdocHit({
1072
+ tree,
1073
+ mid,
1074
+ info,
1075
+ attached,
1076
+ childTree: await readTree(reader, attached.sessionId),
1077
+ notes,
1078
+ pageId,
1079
+ tag,
1080
+ reader,
1081
+ });
1082
+ if (hit) return hit;
1083
+ }
1084
+ return null;
1085
+ }
1086
+
1087
+ async function waitGrandchild(
1088
+ reader,
1089
+ sessionId,
1090
+ midHint,
1091
+ innerHint,
1092
+ budget,
1093
+ notes,
1094
+ pageId,
1095
+ internalSessions,
1096
+ midNeedle = null,
1097
+ beforeIds = null,
1098
+ blockCheck = null
1099
+ ) {
1100
+ let midAttached;
1101
+ await outcome(reader.send('Target.setDiscoverTargets', { discover: true }));
1102
+ const found = await until(async () => {
1103
+ const blocked = blockCheck?.();
1104
+ if (blocked) return { blocked };
1105
+ const tree = await readTree(reader, sessionId);
1106
+ const hit = findGrandchild(tree, midHint, innerHint);
1107
+ if (hit) return { tree, hit, via: 'top' };
1108
+ if (innerHint === 'about:srcdoc') {
1109
+ const underTop = await hitFromSrcdocUnderLocalMid(
1110
+ reader,
1111
+ tree,
1112
+ midHint,
1113
+ pageId,
1114
+ internalSessions,
1115
+ beforeIds,
1116
+ midNeedle,
1117
+ notes
1118
+ );
1119
+ if (underTop) return underTop;
1120
+ }
1121
+ const listed = await outcome(reader.send('Target.getTargets', {}));
1122
+ const infos = answered(listed) && listed.ok ? (listed.result?.targetInfos ?? []) : [];
1123
+ if (
1124
+ midAttached &&
1125
+ !infos.some((info) => info.targetId === midAttached.info.targetId && info.type === 'iframe')
1126
+ )
1127
+ midAttached = null;
1128
+ midAttached ??= await attachIframeTarget(
1129
+ reader,
1130
+ (info) => midTargetMatch(info, midHint, pageId, midNeedle, beforeIds),
1131
+ internalSessions
1132
+ );
1133
+ if (!midAttached) return null;
1134
+ return hitFromGrandchildTarget(
1135
+ reader,
1136
+ midAttached,
1137
+ innerHint,
1138
+ internalSessions,
1139
+ beforeIds,
1140
+ midNeedle
1141
+ );
1142
+ }, budget);
1143
+ if (found?.blocked) return found;
1144
+ if (found) {
1145
+ const branch =
1146
+ found.via === 'top'
1147
+ ? 'top-tree'
1148
+ : found.via === 'mid-target'
1149
+ ? 'mid-target'
1150
+ : 'grandchild-target';
1151
+ note(notes, 'protected-parent.page-branch', { branch, via: found.via });
1152
+ note(notes, 'protected-parent.page-raw', {
1153
+ midFrameId: found.hit.midFrameId,
1154
+ midUrl: found.hit.midUrl,
1155
+ frameId: found.hit.frameId,
1156
+ url: found.hit.url,
1157
+ parentId: found.hit.parentId,
1158
+ via: found.via,
1159
+ branch,
1160
+ midTargetId: found.midTargetId,
1161
+ grandchildTargetId: found.grandchildTargetId,
1162
+ frames: walkFrames(found.tree).map((frame) => ({
1163
+ id: frame.id,
1164
+ url: frame.url,
1165
+ parentId: frame.parentId,
1166
+ })),
1167
+ });
1168
+ return found;
1169
+ }
1170
+ const tree = await readTree(reader, sessionId);
1171
+ const listed = await listTargetSnapshot(reader);
1172
+ note(notes, 'protected-parent.page-raw-missing', {
1173
+ midHint,
1174
+ innerHint,
1175
+ midNeedle,
1176
+ frames: walkFrames(tree).map((frame) => ({
1177
+ id: frame.id,
1178
+ url: frame.url,
1179
+ parentId: frame.parentId,
1180
+ })),
1181
+ targets: listed.targets,
1182
+ });
1183
+ return null;
1184
+ }
1185
+
1186
+ async function rawContexts(reader, sessionIds, raw, eventStart, budget, notes) {
1187
+ const allowed = new Set((sessionIds ?? []).filter(Boolean));
1188
+ const deadline = Date.now() + Math.min(budget, 1500);
1189
+ const contexts = [];
1190
+ while (Date.now() <= deadline) {
1191
+ for (const event of (reader.events ?? []).slice(eventStart)) {
1192
+ if (event.sessionId && allowed.size && !allowed.has(event.sessionId)) continue;
1193
+ if (!contextHit(event, raw)) continue;
1194
+ const context = event.params?.context;
1195
+ if (context?.id != null && !contexts.some((entry) => entry.id === context.id))
1196
+ contexts.push({
1197
+ id: context.id,
1198
+ origin: context.origin,
1199
+ frameId: context.auxData?.frameId,
1200
+ sessionId: event.sessionId,
1201
+ });
1202
+ }
1203
+ if (contexts.length) break;
1204
+ await pause(25);
1205
+ }
1206
+ note(notes, 'protected-parent.page-raw-contexts', { contexts });
1207
+ return contexts;
1208
+ }
1209
+
1210
+ function applyTreeSample(arm, sample, result, key, mentions) {
1211
+ takeFirst(arm, sample, (entry) => {
1212
+ if (entry.unanswered) return;
1213
+ if (entry.out.ok) {
1214
+ if (mentions(entry.out.result)) result[key] = true;
1215
+ else if (result[key] !== true) result[key] = false;
1216
+ } else if (result[key] !== true) result[key] = false;
1217
+ });
1218
+ }
1219
+
1220
+ async function attachOrdinaryTop(client, targetId, notes, internalSessions) {
1221
+ note(notes, 'protected-parent.page-attach-order', {
1222
+ midPresentBeforeAttach: true,
1223
+ targetId,
1224
+ });
1225
+ const attached = await outcome(client.send('Target.attachToTarget', { targetId, flatten: true }));
1226
+ if (!answered(attached)) {
1227
+ note(notes, 'protected-parent.page-attach', {
1228
+ ok: false,
1229
+ unanswered: true,
1230
+ error: String(attached.error?.message ?? attached.error ?? ''),
1231
+ });
1232
+ return { incomplete: 'Target.attachToTarget unanswered for ordinary top page' };
1233
+ }
1234
+ if (!attached.ok || !attached.result?.sessionId) {
1235
+ note(notes, 'protected-parent.page-attach', {
1236
+ ok: false,
1237
+ refused: refused(attached),
1238
+ error: String(attached.error?.message ?? attached.error ?? ''),
1239
+ });
1240
+ return {
1241
+ incomplete: `Target.attachToTarget on ordinary top failed: ${attached.error?.message ?? attached.error}`,
1242
+ };
1243
+ }
1244
+ internalSessions.add(attached.result.sessionId);
1245
+ return { sessionId: attached.result.sessionId };
1246
+ }
1247
+
1248
+ function adoptLiveRaw(raw, liveRaw) {
1249
+ if (liveRaw.midTargetId) raw.midTargetId = liveRaw.midTargetId;
1250
+ if (liveRaw.grandchildTargetId) raw.grandchildTargetId = liveRaw.grandchildTargetId;
1251
+ if (liveRaw.hit.midFrameId) {
1252
+ raw.midFrameIds = raw.midFrameIds ?? new Set([raw.midFrameId].filter(Boolean));
1253
+ raw.midFrameIds.add(liveRaw.hit.midFrameId);
1254
+ raw.midFrameId = liveRaw.hit.midFrameId;
1255
+ }
1256
+ if (liveRaw.hit.frameId) raw.frameIds.add(liveRaw.hit.frameId);
1257
+ if (typeof liveRaw.hit.url === 'string' && liveRaw.hit.url.length > 0)
1258
+ raw.urls.add(liveRaw.hit.url);
1259
+ try {
1260
+ raw.origins.add(new URL(liveRaw.hit.url).origin);
1261
+ } catch {
1262
+ if (liveRaw.hit.url === 'about:srcdoc') raw.origins.add('://');
1263
+ }
1264
+ }
1265
+
1266
+ async function evaluateContexts(client, sessionIds, contexts, evaluateArm, result) {
1267
+ const sessions = [...new Set((sessionIds ?? []).filter(Boolean))];
1268
+ let anyUnanswered = false;
1269
+ let unansweredId;
1270
+ for (const context of contexts) {
1271
+ const ordered = [
1272
+ context.sessionId,
1273
+ ...sessions.filter((id) => id && id !== context.sessionId),
1274
+ ].filter(Boolean);
1275
+ for (const sessionId of [...new Set(ordered)]) {
1276
+ const evaluated = await outcome(
1277
+ client.send(
1278
+ 'Runtime.evaluate',
1279
+ { expression: 'location.href', returnByValue: true, contextId: context.id },
1280
+ sessionId
1281
+ )
1282
+ );
1283
+ const message = String(evaluated.error?.message ?? evaluated.error ?? '');
1284
+ const gone =
1285
+ !evaluated.ok &&
1286
+ /Cannot find context|No context|Invalid context|Session with given id/i.test(message);
1287
+ if (!answered(evaluated) && !gone) {
1288
+ anyUnanswered = true;
1289
+ unansweredId ??= context.id;
1290
+ continue;
1291
+ }
1292
+ takeFirst(
1293
+ evaluateArm,
1294
+ { out: evaluated, unanswered: false, unansweredId: context.id },
1295
+ (sample) => {
1296
+ if (sample.out.ok) result.contextEvaluate = true;
1297
+ else result.contextEvaluate ??= false;
1298
+ }
1299
+ );
1300
+ if (result.contextEvaluate === true) {
1301
+ evaluateArm.unanswered = false;
1302
+ return;
1303
+ }
1304
+ }
1305
+ }
1306
+ if (result.contextEvaluate !== true && anyUnanswered) {
1307
+ evaluateArm.unanswered = true;
1308
+ evaluateArm.unansweredId ??= unansweredId;
1309
+ evaluateArm.out ??= { ok: false };
1310
+ }
1311
+ }
1312
+
1313
+ function collectAutoSessions(events, from) {
1314
+ const sessions = new Set();
1315
+ for (const event of events.slice(from)) {
1316
+ if (event.method !== 'Target.attachedToTarget') continue;
1317
+ const child = event.params?.sessionId;
1318
+ const type = event.params?.targetInfo?.type;
1319
+ if (child && (type === 'iframe' || type === 'page' || !type)) sessions.add(child);
1320
+ }
1321
+ return sessions;
1322
+ }
1323
+
1324
+ async function sampleTrees(client, sessionIds, treeArm, result, raw) {
1325
+ for (const sessionId of sessionIds) {
1326
+ const treeAgain = await outcome(client.send('Page.getFrameTree', {}, sessionId));
1327
+ applyTreeSample(
1328
+ treeArm,
1329
+ { out: treeAgain, unanswered: !answered(treeAgain) },
1330
+ result,
1331
+ 'frameTree',
1332
+ (payload) => treeMentions(payload?.frameTree, raw)
1333
+ );
1334
+ if (result.frameTree === true) return;
1335
+ }
1336
+ }
1337
+
1338
+ function recordChildEnable(out, label, child, childSessions, missing, result) {
1339
+ if (out.ok) return 'ok';
1340
+ if (refused(out)) {
1341
+ const message = String(out.error?.message ?? out.error ?? '');
1342
+ if (result) result.childEnableRefused = message;
1343
+ if (/No session with given id|Session with given id not found|Target closed/i.test(message))
1344
+ childSessions.delete(child);
1345
+ return 'refused';
1346
+ }
1347
+ if (!answered(out)) {
1348
+ missing.push(`${label} unanswered`);
1349
+ return 'missing';
1350
+ }
1351
+ missing.push(`${label} failed: ${out.error?.message ?? out.error}`);
1352
+ return 'missing';
1353
+ }
1354
+
1355
+ async function enableChildDomains(client, childSessions, missing, result) {
1356
+ for (const child of [...childSessions]) {
1357
+ const pageOut = await outcome(client.send('Page.enable', {}, child));
1358
+ const pageStatus = recordChildEnable(
1359
+ pageOut,
1360
+ 'Page.enable',
1361
+ child,
1362
+ childSessions,
1363
+ missing,
1364
+ result
1365
+ );
1366
+ if (pageStatus === 'missing') return;
1367
+ if (pageStatus === 'refused') continue;
1368
+ const runtimeOut = await outcome(client.send('Runtime.enable', {}, child));
1369
+ const runtimeStatus = recordChildEnable(
1370
+ runtimeOut,
1371
+ 'Runtime.enable',
1372
+ child,
1373
+ childSessions,
1374
+ missing,
1375
+ result
1376
+ );
1377
+ if (runtimeStatus === 'missing') return;
1378
+ }
1379
+ }
1380
+
1381
+ async function adoptLiveClientSessions(
1382
+ client,
1383
+ sessionId,
1384
+ clientEventStart,
1385
+ raw,
1386
+ childSessions,
1387
+ internalSessions,
1388
+ missing,
1389
+ result
1390
+ ) {
1391
+ await autoAttachSession(client, sessionId);
1392
+ pullAutoSessions(client, clientEventStart, childSessions);
1393
+ for (const targetId of [raw.midTargetId, raw.grandchildTargetId].filter(Boolean)) {
1394
+ const attached = await outcome(
1395
+ client.send('Target.attachToTarget', { targetId, flatten: true })
1396
+ );
1397
+ await adoptAttachedSession(attached, childSessions, internalSessions, null);
1398
+ }
1399
+ for (const child of [...childSessions]) await autoAttachSession(client, child);
1400
+ pullAutoSessions(client, clientEventStart, childSessions);
1401
+ await enableChildDomains(client, childSessions, missing, result);
1402
+ }
1403
+
1404
+ async function armNewChildSessions(client, events, childSessions, missing, result) {
1405
+ for (const child of collectAutoSessions(events, 0)) {
1406
+ if (childSessions.has(child)) continue;
1407
+ childSessions.add(child);
1408
+ const pageOut = await outcome(client.send('Page.enable', {}, child));
1409
+ const pageStatus = recordChildEnable(
1410
+ pageOut,
1411
+ 'Page.enable',
1412
+ child,
1413
+ childSessions,
1414
+ missing,
1415
+ result
1416
+ );
1417
+ if (pageStatus === 'missing') return;
1418
+ if (pageStatus === 'refused') continue;
1419
+ const runtimeOut = await outcome(client.send('Runtime.enable', {}, child));
1420
+ if (
1421
+ recordChildEnable(runtimeOut, 'Runtime.enable', child, childSessions, missing, result) ===
1422
+ 'missing'
1423
+ )
1424
+ return;
1425
+ }
1426
+ }
1427
+
1428
+ async function remasureLiveGrandchild({
1429
+ reader,
1430
+ readerSessionId,
1431
+ pageUrl,
1432
+ targetId,
1433
+ midHint,
1434
+ innerHint,
1435
+ innerKind,
1436
+ raw,
1437
+ budget,
1438
+ notes,
1439
+ internalSessions,
1440
+ }) {
1441
+ const before = await listTargetSnapshot(reader);
1442
+ const beforeIds = new Set(before.targets.map((info) => info.targetId).filter(Boolean));
1443
+ const kind = innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary');
1444
+ const childBudget = budget < 2000 ? budget : Math.max(budget, 4000);
1445
+ if (raw.midTargetId) {
1446
+ const midAttached = await attachIframeTarget(
1447
+ reader,
1448
+ (info) => info.targetId === raw.midTargetId,
1449
+ internalSessions
1450
+ );
1451
+ if (midAttached) {
1452
+ const stamp = stampedMidLive(midAttached.info.url ?? '', kind, innerHint);
1453
+ note(notes, 'protected-parent.page-live-nav', {
1454
+ via: 'mid-session-remeasure',
1455
+ url: stamp.midUrl,
1456
+ innerHint: stamp.innerHint,
1457
+ midNeedle: stamp.midNeedle,
1458
+ midTargetId: raw.midTargetId,
1459
+ });
1460
+ const navigated = await outcome(
1461
+ reader.send('Page.navigate', { url: stamp.midUrl }, midAttached.sessionId)
1462
+ );
1463
+ if (answered(navigated) && navigated.ok) {
1464
+ const found = await waitChildUnderMid(
1465
+ reader,
1466
+ midAttached,
1467
+ stamp.innerHint || innerHint,
1468
+ childBudget,
1469
+ internalSessions,
1470
+ beforeIds,
1471
+ stamp.midNeedle
1472
+ );
1473
+ if (found) return found;
1474
+ }
1475
+ }
1476
+ }
1477
+ const plan = liveNestPlan(pageUrl, kind, innerHint);
1478
+ let liveUrl = plan.liveUrl;
1479
+ try {
1480
+ const page = new URL(plan.liveUrl);
1481
+ page.searchParams.set('live', String((Number(page.searchParams.get('live')) || 1) + 1));
1482
+ liveUrl = page.toString();
1483
+ } catch {
1484
+ liveUrl = plan.liveUrl;
1485
+ }
1486
+ note(notes, 'protected-parent.page-live-nav', {
1487
+ via: 'top-session-remeasure',
1488
+ url: liveUrl,
1489
+ innerHint: plan.innerHint,
1490
+ midNeedle: plan.midNeedle,
1491
+ beforeTargetIds: [...beforeIds],
1492
+ });
1493
+ const navigated = await outcome(reader.send('Page.navigate', { url: liveUrl }, readerSessionId));
1494
+ if (!answered(navigated) || !navigated.ok) return null;
1495
+ return waitGrandchild(
1496
+ reader,
1497
+ readerSessionId,
1498
+ midHint,
1499
+ plan.innerHint || innerHint,
1500
+ childBudget,
1501
+ notes,
1502
+ targetId,
1503
+ internalSessions,
1504
+ plan.midNeedle,
1505
+ beforeIds
1506
+ );
1507
+ }
1508
+
1509
+ async function pollPageClient({
1510
+ client,
1511
+ sessionId,
1512
+ childSessions,
1513
+ clientEventStart,
1514
+ raw,
1515
+ liveContexts,
1516
+ treeArm,
1517
+ resourceArm,
1518
+ evaluateArm,
1519
+ result,
1520
+ missing,
1521
+ budget,
1522
+ skipEvaluate = false,
1523
+ }) {
1524
+ const windowMs = Math.min(budget, 1500);
1525
+ const deadline = Date.now() + windowMs;
1526
+ while (Date.now() <= deadline) {
1527
+ const events = (client.events ?? []).slice(clientEventStart);
1528
+ await armNewChildSessions(client, events, childSessions, missing, result);
1529
+ if (missing.length) break;
1530
+ result.frameEvents = events.some((event) => frameEventHit(event, raw))
1531
+ ? true
1532
+ : (result.frameEvents ?? false);
1533
+ result.midFrameAttached = events.some((event) => midFrameAttachedHit(event, raw))
1534
+ ? true
1535
+ : (result.midFrameAttached ?? false);
1536
+ if (liveContexts.length) {
1537
+ if (events.some((event) => contextHit(event, raw))) result.contextCreated = true;
1538
+ if (!skipEvaluate && result.contextEvaluate !== true)
1539
+ await evaluateContexts(
1540
+ client,
1541
+ [sessionId, ...childSessions],
1542
+ liveContexts,
1543
+ evaluateArm,
1544
+ result
1545
+ );
1546
+ }
1547
+ await sampleTrees(client, [sessionId, ...childSessions], treeArm, result, raw);
1548
+ await sampleResources(client, [sessionId, ...childSessions], resourceArm, result, raw);
1549
+ if (
1550
+ result.frameTree === true &&
1551
+ result.resourceTree === true &&
1552
+ result.frameEvents === true &&
1553
+ result.contextCreated === true &&
1554
+ (skipEvaluate || result.contextEvaluate === true) &&
1555
+ result.midFrameAttached === true
1556
+ )
1557
+ break;
1558
+ await pause(50);
1559
+ }
1560
+ return windowMs;
1561
+ }
1562
+
1563
+ function enableFailure(out, label, missing) {
1564
+ if (!answered(out)) missing.push(`${label} unanswered`);
1565
+ else if (!out.ok) missing.push(`${label} failed: ${out.error?.message ?? out.error}`);
1566
+ }
1567
+
1568
+ async function abortPageClient(client, sessionId, notes, missing, result = {}) {
1569
+ note(notes, 'protected-parent.page-client', {
1570
+ unanswered: missing,
1571
+ frameTree: result.frameTree ?? 'unmeasured',
1572
+ resourceTree: result.resourceTree ?? 'unmeasured',
1573
+ frameEvents: 'unmeasured',
1574
+ contextCreated: 'unmeasured',
1575
+ contextEvaluate: 'unmeasured',
1576
+ midFrameAttached: 'unmeasured',
1577
+ });
1578
+ await outcome(client.send('Target.detachFromTarget', { sessionId }));
1579
+ return { ...result, incomplete: missing.join('; ') };
1580
+ }
1581
+
1582
+ async function sampleResources(client, sessionIds, resourceArm, result, raw) {
1583
+ for (const sessionId of sessionIds) {
1584
+ if (result.resourceTree === true) return;
1585
+ const resourceOut = await outcome(client.send('Page.getResourceTree', {}, sessionId));
1586
+ if (!resourceOut.ok && refused(resourceOut)) continue;
1587
+ applyTreeSample(
1588
+ resourceArm,
1589
+ { out: resourceOut, unanswered: !answered(resourceOut) },
1590
+ result,
1591
+ 'resourceTree',
1592
+ (payload) => resourceMentions(payload, raw)
1593
+ );
1594
+ }
1595
+ }
1596
+
1597
+ async function liveViaMidSession({
1598
+ reader,
1599
+ raw,
1600
+ innerKind,
1601
+ innerHint,
1602
+ budget,
1603
+ notes,
1604
+ internalSessions,
1605
+ beforeIds,
1606
+ preferMidLive,
1607
+ eventStart,
1608
+ midUrls,
1609
+ }) {
1610
+ if (!preferMidLive || !raw.midTargetId) return null;
1611
+ const midAttached = await attachIframeTarget(
1612
+ reader,
1613
+ (info) => info.targetId === raw.midTargetId,
1614
+ internalSessions
1615
+ );
1616
+ if (!midAttached) return null;
1617
+ const midUrl = midAttached.info.url ?? '';
1618
+ const stamp = stampedMidLive(
1619
+ midUrl,
1620
+ innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary'),
1621
+ innerHint
1622
+ );
1623
+ midUrls.push(stamp.midUrl);
1624
+ await armReaderNetwork(reader, [midAttached.sessionId]);
1625
+ note(notes, 'protected-parent.page-live-nav', {
1626
+ via: 'mid-session',
1627
+ url: stamp.midUrl,
1628
+ innerHint: stamp.innerHint,
1629
+ midNeedle: stamp.midNeedle,
1630
+ midTargetId: raw.midTargetId,
1631
+ });
1632
+ const navigated = await outcome(
1633
+ reader.send('Page.navigate', { url: stamp.midUrl }, midAttached.sessionId)
1634
+ );
1635
+ if (!answered(navigated) || !navigated.ok) {
1636
+ const blocked = liveMidBlocked(reader.events, eventStart, midUrls);
1637
+ return blocked ? { blocked } : null;
1638
+ }
1639
+ const childBudget = budget < 2000 ? budget : Math.max(budget, 8000);
1640
+ const found = await waitChildUnderMid(
1641
+ reader,
1642
+ midAttached,
1643
+ stamp.innerHint || innerHint,
1644
+ childBudget,
1645
+ internalSessions,
1646
+ beforeIds,
1647
+ stamp.midNeedle,
1648
+ () => liveMidBlocked(reader.events, eventStart, midUrls)
1649
+ );
1650
+ if (found?.blocked) return found;
1651
+ if (!found) {
1652
+ const blocked = liveMidBlocked(reader.events, eventStart, midUrls);
1653
+ return blocked ? { blocked } : null;
1654
+ }
1655
+ const branch = found.via === 'mid-target' ? 'mid-target' : 'grandchild-target';
1656
+ note(notes, 'protected-parent.page-branch', { branch, via: found.via, live: 'mid-session' });
1657
+ return found;
1658
+ }
1659
+
1660
+ function acceptLiveBlocked(raw, notes, blocked) {
1661
+ raw.liveBlocked = blocked;
1662
+ note(notes, 'protected-parent.page-live-blocked', blocked);
1663
+ }
1664
+
1665
+ function protectLiveChannels(result, skipEvaluate = false) {
1666
+ result.resourceTree ??= false;
1667
+ result.frameEvents ??= false;
1668
+ if (!skipEvaluate) result.contextEvaluate ??= false;
1669
+ result.midFrameAttached ??= false;
1670
+ }
1671
+
1672
+ async function samplePreLiveChannels({
1673
+ client,
1674
+ sessionId,
1675
+ childSessions,
1676
+ clientEventStart,
1677
+ raw,
1678
+ contexts,
1679
+ resourceArm,
1680
+ evaluateArm,
1681
+ result,
1682
+ skipEvaluate = false,
1683
+ }) {
1684
+ const sessions = [sessionId, ...childSessions];
1685
+ await sampleResources(client, sessions, resourceArm, result, raw);
1686
+ const events = (client.events ?? []).slice(clientEventStart);
1687
+ result.frameEvents = events.some((event) => frameEventHit(event, raw))
1688
+ ? true
1689
+ : (result.frameEvents ?? false);
1690
+ result.midFrameAttached = events.some((event) => midFrameAttachedHit(event, raw))
1691
+ ? true
1692
+ : (result.midFrameAttached ?? false);
1693
+ if (!skipEvaluate && contexts.length)
1694
+ await evaluateContexts(client, sessions, contexts, evaluateArm, result);
1695
+ }
1696
+
1697
+ async function liveViaTopSession({
1698
+ reader,
1699
+ readerSessionId,
1700
+ targetId,
1701
+ pageUrl,
1702
+ midHint,
1703
+ innerHint,
1704
+ innerKind,
1705
+ liveBudget,
1706
+ notes,
1707
+ internalSessions,
1708
+ beforeIds,
1709
+ eventStart,
1710
+ midUrls,
1711
+ missing,
1712
+ }) {
1713
+ const plan = liveNestPlan(
1714
+ pageUrl,
1715
+ innerKind ?? (innerHint === 'about:srcdoc' ? 'srcdoc' : 'ordinary'),
1716
+ innerHint
1717
+ );
1718
+ if (plan.midUrl) midUrls.push(plan.midUrl);
1719
+ note(notes, 'protected-parent.page-live-nav', {
1720
+ via: 'top-session',
1721
+ url: plan.liveUrl,
1722
+ innerHint: plan.innerHint,
1723
+ midNeedle: plan.midNeedle,
1724
+ beforeTargetIds: [...beforeIds],
1725
+ });
1726
+ const navigated = await outcome(
1727
+ reader.send('Page.navigate', { url: plan.liveUrl }, readerSessionId)
1728
+ );
1729
+ if (!answered(navigated)) missing.push('unguarded Page.navigate unanswered after attach');
1730
+ else if (!navigated.ok)
1731
+ missing.push(`unguarded Page.navigate failed: ${navigated.error?.message ?? navigated.error}`);
1732
+ return waitGrandchild(
1733
+ reader,
1734
+ readerSessionId,
1735
+ midHint,
1736
+ plan.innerHint || innerHint,
1737
+ liveBudget,
1738
+ notes,
1739
+ targetId,
1740
+ internalSessions,
1741
+ plan.midNeedle,
1742
+ beforeIds,
1743
+ () => liveMidBlocked(reader.events, eventStart, midUrls)
1744
+ );
1745
+ }
1746
+
1747
+ async function liveGrandchild({
1748
+ reader,
1749
+ readerSessionId,
1750
+ readerSessions,
1751
+ targetId,
1752
+ pageUrl,
1753
+ midHint,
1754
+ innerHint,
1755
+ innerKind,
1756
+ preferMidLive,
1757
+ raw,
1758
+ contexts,
1759
+ budget,
1760
+ notes,
1761
+ internalSessions,
1762
+ missing,
1763
+ }) {
1764
+ const before = await listTargetSnapshot(reader);
1765
+ note(notes, 'protected-parent.page-targets-before', {
1766
+ unanswered: before.unanswered,
1767
+ targets: before.targets,
1768
+ midTargetId: raw.midTargetId ?? null,
1769
+ grandchildTargetId: raw.grandchildTargetId ?? null,
1770
+ urls: [...raw.urls],
1771
+ });
1772
+ const beforeIds = new Set(before.targets.map((info) => info.targetId).filter(Boolean));
1773
+ const liveBudget = budget < 2000 ? budget : Math.max(budget, 8000);
1774
+ const eventStart = reader.events?.length ?? 0;
1775
+ const midUrls = [];
1776
+ await armReaderNetwork(reader, [readerSessionId, ...(readerSessions ?? [])]);
1777
+ let liveRaw = await liveViaMidSession({
1778
+ reader,
1779
+ raw,
1780
+ innerKind,
1781
+ innerHint,
1782
+ budget: liveBudget,
1783
+ notes,
1784
+ internalSessions,
1785
+ beforeIds,
1786
+ preferMidLive,
1787
+ eventStart,
1788
+ midUrls,
1789
+ });
1790
+ if (liveRaw?.blocked) {
1791
+ acceptLiveBlocked(raw, notes, liveRaw.blocked);
1792
+ liveRaw = null;
1793
+ } else if (!liveRaw) {
1794
+ liveRaw = await liveViaTopSession({
1795
+ reader,
1796
+ readerSessionId,
1797
+ targetId,
1798
+ pageUrl,
1799
+ midHint,
1800
+ innerHint,
1801
+ innerKind,
1802
+ liveBudget,
1803
+ notes,
1804
+ internalSessions,
1805
+ beforeIds,
1806
+ eventStart,
1807
+ midUrls,
1808
+ missing,
1809
+ });
1810
+ if (liveRaw?.blocked) {
1811
+ acceptLiveBlocked(raw, notes, liveRaw.blocked);
1812
+ liveRaw = null;
1813
+ }
1814
+ }
1815
+ const after = await listTargetSnapshot(reader);
1816
+ note(notes, 'protected-parent.page-targets-after', {
1817
+ unanswered: after.unanswered,
1818
+ targets: after.targets,
1819
+ foundLive: Boolean(liveRaw),
1820
+ liveBlocked: Boolean(raw.liveBlocked),
1821
+ });
1822
+ if (!liveRaw) {
1823
+ if (!raw.liveBlocked) missing.push(liveMissingReason(pageUrl, midHint, raw));
1824
+ return contexts;
1825
+ }
1826
+ adoptLiveRaw(raw, liveRaw);
1827
+ note(notes, 'protected-parent.page-live-raw', {
1828
+ midFrameId: liveRaw.hit.midFrameId,
1829
+ frameId: liveRaw.hit.frameId,
1830
+ url: liveRaw.hit.url,
1831
+ via: liveRaw.via,
1832
+ });
1833
+ const liveSessions = [
1834
+ ...(readerSessions ?? []),
1835
+ readerSessionId,
1836
+ liveRaw.midSession,
1837
+ liveRaw.grandchildSession,
1838
+ ].filter(Boolean);
1839
+ const liveContexts = await rawContexts(
1840
+ reader,
1841
+ liveSessions,
1842
+ raw,
1843
+ reader.events?.length ? reader.events.length - 50 : 0,
1844
+ budget,
1845
+ notes
1846
+ );
1847
+ return liveContexts.length ? liveContexts : contexts;
1848
+ }
1849
+
1850
+ function targetInfoHit(info, raw) {
1851
+ if (!info) return false;
1852
+ if (raw.grandchildTargetId && info.targetId === raw.grandchildTargetId) return true;
1853
+ if (raw.midTargetId && info.parentId === raw.midTargetId) {
1854
+ const url = info.url ?? '';
1855
+ if ([...raw.urls].some((entry) => entry && (url === entry || url.includes(entry)))) return true;
1856
+ }
1857
+ const url = info.url ?? '';
1858
+ return [...raw.urls].some((entry) => entry && url === entry);
1859
+ }
1860
+
1861
+ function targetEventHit(event, raw) {
1862
+ if (
1863
+ !['Target.targetCreated', 'Target.targetInfoChanged', 'Target.attachedToTarget'].includes(
1864
+ event.method
1865
+ )
1866
+ )
1867
+ return false;
1868
+ return targetInfoHit(event.params?.targetInfo, raw);
1869
+ }
1870
+
1871
+ async function autoAttachSession(client, sessionId) {
1872
+ await outcome(
1873
+ client.send(
1874
+ 'Target.setAutoAttach',
1875
+ { autoAttach: true, waitForDebuggerOnStart: false, flatten: true },
1876
+ sessionId
1877
+ )
1878
+ );
1879
+ }
1880
+
1881
+ function pullAutoSessions(client, clientEventStart, childSessions) {
1882
+ for (const child of collectAutoSessions(client.events ?? [], clientEventStart))
1883
+ childSessions.add(child);
1884
+ }
1885
+
1886
+ async function adoptAttachedSession(out, childSessions, internalSessions, result) {
1887
+ if (!answered(out)) return 'unanswered';
1888
+ if (out.ok && out.result?.sessionId) {
1889
+ childSessions.add(out.result.sessionId);
1890
+ internalSessions?.add(out.result.sessionId);
1891
+ if (result) result.childAttach = true;
1892
+ return 'attached';
1893
+ }
1894
+ if (result) {
1895
+ result.childAttach ??= false;
1896
+ if (refused(out)) result.attachRefused = true;
1897
+ }
1898
+ return refused(out) ? 'refused' : 'failed';
1899
+ }
1900
+
1901
+ async function probeListedGrandchildren(
1902
+ client,
1903
+ raw,
1904
+ childSessions,
1905
+ internalSessions,
1906
+ result,
1907
+ missing
1908
+ ) {
1909
+ const listed = await outcome(client.send('Target.getTargets', {}));
1910
+ if (!answered(listed)) {
1911
+ missing.push('Target.getTargets unanswered');
1912
+ return;
1913
+ }
1914
+ if (!listed.ok) {
1915
+ result.targetInfo ??= false;
1916
+ return;
1917
+ }
1918
+ const infos = listed.result?.targetInfos ?? [];
1919
+ if (infos.some((info) => targetInfoHit(info, raw))) result.targetInfo = true;
1920
+ for (const info of infos) {
1921
+ if (info.type !== 'iframe') continue;
1922
+ if (!targetInfoHit(info, raw) && info.targetId !== raw.grandchildTargetId) continue;
1923
+ const attachedChild = await outcome(
1924
+ client.send('Target.attachToTarget', { targetId: info.targetId, flatten: true })
1925
+ );
1926
+ const status = await adoptAttachedSession(
1927
+ attachedChild,
1928
+ childSessions,
1929
+ internalSessions,
1930
+ result
1931
+ );
1932
+ if (status === 'unanswered')
1933
+ missing.push(`Target.attachToTarget unanswered (${info.targetId})`);
1934
+ }
1935
+ }
1936
+
1937
+ async function probeRawGrandchildTarget(
1938
+ client,
1939
+ raw,
1940
+ childSessions,
1941
+ internalSessions,
1942
+ result,
1943
+ missing
1944
+ ) {
1945
+ if (!raw.grandchildTargetId) {
1946
+ result.targetInfo ??= false;
1947
+ result.childAttach ??= false;
1948
+ return;
1949
+ }
1950
+ if (result.childAttach === true) return;
1951
+ const infoOut = await outcome(
1952
+ client.send('Target.getTargetInfo', { targetId: raw.grandchildTargetId })
1953
+ );
1954
+ if (!answered(infoOut)) missing.push('Target.getTargetInfo unanswered for grandchild');
1955
+ else if (infoOut.ok) result.targetInfo = true;
1956
+ else result.targetInfo ??= false;
1957
+ const attachedRaw = await outcome(
1958
+ client.send('Target.attachToTarget', {
1959
+ targetId: raw.grandchildTargetId,
1960
+ flatten: true,
1961
+ })
1962
+ );
1963
+ const status = await adoptAttachedSession(attachedRaw, childSessions, internalSessions, result);
1964
+ if (status === 'unanswered')
1965
+ missing.push('Target.attachToTarget unanswered for raw grandchild target');
1966
+ }
1967
+
1968
+ async function gatherChildSessions(
1969
+ client,
1970
+ sessionId,
1971
+ clientEventStart,
1972
+ raw,
1973
+ internalSessions,
1974
+ result,
1975
+ missing
1976
+ ) {
1977
+ const childSessions = new Set();
1978
+ await autoAttachSession(client, sessionId);
1979
+ await until(async () => {
1980
+ pullAutoSessions(client, clientEventStart, childSessions);
1981
+ return childSessions.size > 0 ? childSessions : null;
1982
+ }, 200);
1983
+ pullAutoSessions(client, clientEventStart, childSessions);
1984
+ if (raw.midTargetId) {
1985
+ const midAttached = await outcome(
1986
+ client.send('Target.attachToTarget', { targetId: raw.midTargetId, flatten: true })
1987
+ );
1988
+ await adoptAttachedSession(midAttached, childSessions, internalSessions, null);
1989
+ }
1990
+ for (const child of [...childSessions]) await autoAttachSession(client, child);
1991
+ const before = childSessions.size;
1992
+ await until(async () => {
1993
+ pullAutoSessions(client, clientEventStart, childSessions);
1994
+ return childSessions.size > before ? childSessions : null;
1995
+ }, 200);
1996
+ pullAutoSessions(client, clientEventStart, childSessions);
1997
+ result.targetEvents = (client.events ?? [])
1998
+ .slice(clientEventStart)
1999
+ .some((event) => targetEventHit(event, raw))
2000
+ ? true
2001
+ : (result.targetEvents ?? false);
2002
+ await probeListedGrandchildren(client, raw, childSessions, internalSessions, result, missing);
2003
+ await probeRawGrandchildTarget(client, raw, childSessions, internalSessions, result, missing);
2004
+ result.targetInfo ??= false;
2005
+ result.childAttach ??= false;
2006
+ result.targetEvents ??= false;
2007
+ return childSessions;
2008
+ }
2009
+
2010
+ async function measurePageClient({
2011
+ client,
2012
+ reader,
2013
+ readerSessionId,
2014
+ readerSessions,
2015
+ targetId,
2016
+ pageUrl,
2017
+ midHint,
2018
+ innerHint,
2019
+ innerKind,
2020
+ preferMidLive,
2021
+ raw,
2022
+ contexts,
2023
+ budget,
2024
+ notes,
2025
+ internalSessions,
2026
+ }) {
2027
+ const result = {};
2028
+ const missing = [];
2029
+ const attached = await attachOrdinaryTop(client, targetId, notes, internalSessions);
2030
+ if (attached.incomplete) return attached;
2031
+ const { sessionId } = attached;
2032
+ const clientEventStart = client.events?.length ?? 0;
2033
+ enableFailure(await outcome(client.send('Page.enable', {}, sessionId)), 'Page.enable', missing);
2034
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing);
2035
+ const treeArm = { out: undefined, unanswered: false };
2036
+ const resourceArm = { out: undefined, unanswered: false };
2037
+ const evaluateArm = { out: undefined, unanswered: false };
2038
+ const childSessions = await gatherChildSessions(
2039
+ client,
2040
+ sessionId,
2041
+ clientEventStart,
2042
+ raw,
2043
+ internalSessions,
2044
+ result,
2045
+ missing
2046
+ );
2047
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
2048
+ const sessions = [sessionId, ...childSessions];
2049
+ await sampleTrees(client, sessions, treeArm, result, raw);
2050
+ enableFailure(
2051
+ await outcome(client.send('Runtime.enable', {}, sessionId)),
2052
+ 'Runtime.enable',
2053
+ missing
2054
+ );
2055
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
2056
+ await enableChildDomains(client, childSessions, missing, result);
2057
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
2058
+ await outcome(client.send('Network.enable', {}, sessionId));
2059
+ if (contexts.length)
2060
+ result.contextCreated = (client.events ?? [])
2061
+ .slice(clientEventStart)
2062
+ .some((event) => contextHit(event, raw));
2063
+ await samplePreLiveChannels({
2064
+ client,
2065
+ sessionId,
2066
+ childSessions,
2067
+ clientEventStart,
2068
+ raw,
2069
+ contexts,
2070
+ resourceArm,
2071
+ evaluateArm,
2072
+ result,
2073
+ skipEvaluate: innerKind === 'srcdoc',
2074
+ });
2075
+ let liveContexts = await liveGrandchild({
2076
+ reader,
2077
+ readerSessionId,
2078
+ readerSessions,
2079
+ targetId,
2080
+ pageUrl,
2081
+ midHint,
2082
+ innerHint,
2083
+ innerKind,
2084
+ preferMidLive,
2085
+ raw,
2086
+ contexts,
2087
+ budget,
2088
+ notes,
2089
+ internalSessions,
2090
+ missing,
2091
+ });
2092
+ await adoptLiveClientSessions(
2093
+ client,
2094
+ sessionId,
2095
+ clientEventStart,
2096
+ raw,
2097
+ childSessions,
2098
+ internalSessions,
2099
+ missing,
2100
+ result
2101
+ );
2102
+ if (missing.length) return abortPageClient(client, sessionId, notes, missing, result);
2103
+ liveContexts = await continueAfterLive({
2104
+ client,
2105
+ reader,
2106
+ readerSessionId,
2107
+ sessionId,
2108
+ clientEventStart,
2109
+ pageUrl,
2110
+ targetId,
2111
+ midHint,
2112
+ innerHint,
2113
+ innerKind,
2114
+ raw,
2115
+ contexts,
2116
+ liveContexts,
2117
+ childSessions,
2118
+ internalSessions,
2119
+ treeArm,
2120
+ resourceArm,
2121
+ evaluateArm,
2122
+ result,
2123
+ missing,
2124
+ notes,
2125
+ budget,
2126
+ });
2127
+ if (missing.length) return { ...result, incomplete: missing.join('; ') };
2128
+ return result;
2129
+ }
2130
+
2131
+ async function continueAfterLive({
2132
+ client,
2133
+ reader,
2134
+ readerSessionId,
2135
+ sessionId,
2136
+ clientEventStart,
2137
+ pageUrl,
2138
+ targetId,
2139
+ midHint,
2140
+ innerHint,
2141
+ innerKind,
2142
+ raw,
2143
+ contexts,
2144
+ liveContexts,
2145
+ childSessions,
2146
+ internalSessions,
2147
+ treeArm,
2148
+ resourceArm,
2149
+ evaluateArm,
2150
+ result,
2151
+ missing,
2152
+ notes,
2153
+ budget,
2154
+ }) {
2155
+ const skipEvaluate = innerKind === 'srcdoc';
2156
+ if (raw.liveBlocked) {
2157
+ protectLiveChannels(result, skipEvaluate);
2158
+ if (!liveContexts.length) liveContexts = contexts;
2159
+ } else {
2160
+ await probeRawGrandchildTarget(client, raw, childSessions, internalSessions, result, missing);
2161
+ if (raw.midTargetId || raw.grandchildTargetId) {
2162
+ const remasured = await remasureLiveGrandchild({
2163
+ reader,
2164
+ readerSessionId,
2165
+ pageUrl,
2166
+ targetId,
2167
+ midHint,
2168
+ innerHint,
2169
+ innerKind,
2170
+ raw,
2171
+ budget,
2172
+ notes,
2173
+ internalSessions,
2174
+ });
2175
+ if (remasured) {
2176
+ adoptLiveRaw(raw, remasured);
2177
+ note(notes, 'protected-parent.page-live-raw', {
2178
+ midFrameId: remasured.hit.midFrameId,
2179
+ frameId: remasured.hit.frameId,
2180
+ url: remasured.hit.url,
2181
+ via: remasured.via,
2182
+ remasure: true,
2183
+ });
2184
+ await adoptLiveClientSessions(
2185
+ client,
2186
+ sessionId,
2187
+ clientEventStart,
2188
+ raw,
2189
+ childSessions,
2190
+ internalSessions,
2191
+ missing,
2192
+ result
2193
+ );
2194
+ if (!missing.length)
2195
+ await probeRawGrandchildTarget(
2196
+ client,
2197
+ raw,
2198
+ childSessions,
2199
+ internalSessions,
2200
+ result,
2201
+ missing
2202
+ );
2203
+ }
2204
+ }
2205
+ }
2206
+ if (missing.length) return liveContexts;
2207
+ const clientContexts = await rawContexts(
2208
+ client,
2209
+ [sessionId, ...childSessions],
2210
+ raw,
2211
+ clientEventStart,
2212
+ Math.min(budget, 1500),
2213
+ notes
2214
+ );
2215
+ if (clientContexts.length) liveContexts = clientContexts;
2216
+ await sampleResources(client, [sessionId, ...childSessions], resourceArm, result, raw);
2217
+ const windowMs = await pollPageClient({
2218
+ client,
2219
+ sessionId,
2220
+ childSessions,
2221
+ clientEventStart,
2222
+ raw,
2223
+ liveContexts,
2224
+ treeArm,
2225
+ resourceArm,
2226
+ evaluateArm,
2227
+ result,
2228
+ missing,
2229
+ budget,
2230
+ skipEvaluate,
2231
+ });
2232
+ if (missing.length) return liveContexts;
2233
+ await finishPageClient(
2234
+ client,
2235
+ sessionId,
2236
+ clientEventStart,
2237
+ raw,
2238
+ liveContexts,
2239
+ treeArm,
2240
+ resourceArm,
2241
+ evaluateArm,
2242
+ result,
2243
+ missing,
2244
+ notes,
2245
+ childSessions,
2246
+ windowMs,
2247
+ skipEvaluate
2248
+ );
2249
+ return liveContexts;
2250
+ }
2251
+
2252
+ function settlePageContexts(liveContexts, raw, evaluateArm, result, missing, skipEvaluate) {
2253
+ if (!liveContexts.length) {
2254
+ if (raw.liveBlocked) {
2255
+ protectLiveChannels(result, skipEvaluate);
2256
+ result.contextCreated ??= false;
2257
+ return;
2258
+ }
2259
+ missing.push('grandchild execution context missing in raw leg');
2260
+ return;
2261
+ }
2262
+ result.contextCreated ??= false;
2263
+ if (skipEvaluate) return;
2264
+ settleArm(
2265
+ result,
2266
+ 'contextEvaluate',
2267
+ evaluateArm.unanswered,
2268
+ evaluateArm.unansweredId
2269
+ ? `Runtime.evaluate unanswered (${evaluateArm.unansweredId})`
2270
+ : 'Runtime.evaluate unanswered',
2271
+ missing,
2272
+ { contextEvaluate: false }
2273
+ );
2274
+ }
2275
+
2276
+ function finishPageClient(
2277
+ client,
2278
+ sessionId,
2279
+ clientEventStart,
2280
+ raw,
2281
+ liveContexts,
2282
+ treeArm,
2283
+ resourceArm,
2284
+ evaluateArm,
2285
+ result,
2286
+ missing,
2287
+ notes,
2288
+ childSessions,
2289
+ windowMs,
2290
+ skipEvaluate = false
2291
+ ) {
2292
+ result.targetEvents = (client.events ?? [])
2293
+ .slice(clientEventStart)
2294
+ .some((event) => targetEventHit(event, raw))
2295
+ ? true
2296
+ : (result.targetEvents ?? false);
2297
+ settleArm(result, 'frameTree', treeArm.unanswered, 'Page.getFrameTree unanswered', missing, {
2298
+ frameTree: false,
2299
+ });
2300
+ settleArm(
2301
+ result,
2302
+ 'resourceTree',
2303
+ resourceArm.unanswered,
2304
+ 'Page.getResourceTree unanswered',
2305
+ missing,
2306
+ { resourceTree: false }
2307
+ );
2308
+ result.frameEvents ??= false;
2309
+ result.midFrameAttached ??= false;
2310
+ result.targetInfo ??= false;
2311
+ result.childAttach ??= false;
2312
+ result.targetEvents ??= false;
2313
+ result.childEnableRefused ??= false;
2314
+ settlePageContexts(liveContexts, raw, evaluateArm, result, missing, skipEvaluate);
2315
+ note(notes, 'protected-parent.page-client', {
2316
+ frameTree: result.frameTree ?? 'unmeasured',
2317
+ resourceTree: result.resourceTree ?? 'unmeasured',
2318
+ frameEvents: result.frameEvents ?? 'unmeasured',
2319
+ contextCreated: result.contextCreated ?? 'unmeasured',
2320
+ contextEvaluate: skipEvaluate ? 'skipped' : (result.contextEvaluate ?? 'unmeasured'),
2321
+ midFrameAttached: result.midFrameAttached ?? 'unmeasured',
2322
+ targetInfo: result.targetInfo ?? 'unmeasured',
2323
+ childAttach: result.childAttach ?? 'unmeasured',
2324
+ targetEvents: result.targetEvents ?? 'unmeasured',
2325
+ childEnableRefused: result.childEnableRefused ?? false,
2326
+ attachRefused: result.attachRefused ?? false,
2327
+ grandchildTargetId: raw.grandchildTargetId ?? null,
2328
+ liveBlocked: raw.liveBlocked ?? null,
2329
+ windowMs,
2330
+ childSessions: [...childSessions],
2331
+ firstTreeOk: treeArm.out?.ok,
2332
+ firstResourceOk: resourceArm.out?.ok,
2333
+ firstEvaluateOk: skipEvaluate ? false : evaluateArm.out?.ok,
2334
+ unanswered: missing,
2335
+ });
2336
+ return outcome(client.send('Target.detachFromTarget', { sessionId }));
2337
+ }
2338
+
2339
+ async function pageNested({
2340
+ reader,
2341
+ client,
2342
+ midOrigin,
2343
+ ordinary,
2344
+ tag,
2345
+ notes,
2346
+ budget,
2347
+ internalSessions,
2348
+ eventStart,
2349
+ innerKind,
2350
+ preferMidLive = false,
2351
+ }) {
2352
+ if (!midOrigin) return { incomplete: 'no middle origin mapped' };
2353
+ const inner = innerKind === 'srcdoc' ? 'about:srcdoc' : `${ordinary}/doc?n=inner-${tag}`;
2354
+ const mid =
2355
+ innerKind === 'srcdoc'
2356
+ ? `${midOrigin}/oopif-srcdoc?n=mid-${tag}`
2357
+ : `${midOrigin}/oopif-mid?inner=${encodeURIComponent(inner)}&n=mid-${tag}`;
2358
+ const page = `${ordinary}/oopif-nest?mid=${encodeURIComponent(mid)}&n=host-${tag}`;
2359
+ note(notes, 'protected-parent.page-urls', {
2360
+ top: ordinary,
2361
+ mid: midOrigin,
2362
+ inner,
2363
+ page,
2364
+ attachOrder: 'mid-already-present',
2365
+ });
2366
+ const opened = await openProtected(reader, page, notes, internalSessions);
2367
+ if (!opened.ok)
2368
+ return {
2369
+ incomplete: `observer setup failed: ${opened.error?.message ?? opened.error}`,
2370
+ };
2371
+ if (opened.result.incomplete) return { live: false, incomplete: opened.result.incomplete };
2372
+ const { targetId: pageId, sessionId } = opened.result;
2373
+ const midHint = midOrigin;
2374
+ const innerHint = innerKind === 'srcdoc' ? 'about:srcdoc' : `inner-${tag}`;
2375
+ const midNeedle = `mid-${tag}`;
2376
+ const rawFound = await waitGrandchild(
2377
+ reader,
2378
+ sessionId,
2379
+ midHint,
2380
+ innerHint,
2381
+ budget,
2382
+ notes,
2383
+ pageId,
2384
+ internalSessions,
2385
+ midNeedle
2386
+ );
2387
+ if (!rawFound) {
2388
+ return {
2389
+ live: true,
2390
+ incomplete:
2391
+ innerKind === 'srcdoc'
2392
+ ? 'srcdoc grandchild under the middle frame did not appear in the raw page frame tree within the budget'
2393
+ : 'ordinary grandchild under the middle frame did not appear in the raw page frame tree within the budget',
2394
+ pageId,
2395
+ };
2396
+ }
2397
+ const raw = {
2398
+ midFrameId: rawFound.hit.midFrameId,
2399
+ midTargetId: rawFound.midTargetId,
2400
+ grandchildTargetId: rawFound.grandchildTargetId,
2401
+ frameIds: new Set([rawFound.hit.frameId]),
2402
+ urls: new Set([rawFound.hit.url].filter((url) => typeof url === 'string' && url.length > 0)),
2403
+ origins: new Set(),
2404
+ };
2405
+ try {
2406
+ raw.origins.add(new URL(rawFound.hit.url).origin);
2407
+ } catch {
2408
+ if (rawFound.hit.url === 'about:srcdoc') raw.origins.add('://');
2409
+ }
2410
+ const readerEventStart = reader.events?.length ?? 0;
2411
+ const readerSessions = [sessionId, rawFound.midSession, rawFound.grandchildSession].filter(
2412
+ Boolean
2413
+ );
2414
+ const contexts = await rawContexts(
2415
+ reader,
2416
+ readerSessions,
2417
+ raw,
2418
+ Math.min(eventStart, readerEventStart),
2419
+ budget,
2420
+ notes
2421
+ );
2422
+ if (!contexts.length) {
2423
+ note(notes, 'protected-parent.page-no-context', {
2424
+ frameId: rawFound.hit.frameId,
2425
+ url: rawFound.hit.url,
2426
+ via: rawFound.via,
2427
+ });
2428
+ }
2429
+ const measured = await measurePageClient({
2430
+ client,
2431
+ reader,
2432
+ readerSessionId: sessionId,
2433
+ readerSessions,
2434
+ targetId: pageId,
2435
+ pageUrl: page,
2436
+ midHint,
2437
+ innerHint,
2438
+ innerKind,
2439
+ preferMidLive,
2440
+ raw,
2441
+ contexts,
2442
+ budget,
2443
+ notes,
2444
+ internalSessions,
2445
+ });
2446
+ return {
2447
+ live: true,
2448
+ pageId,
2449
+ frameIds: [...raw.frameIds],
2450
+ frameUrls: [...raw.urls],
2451
+ midFrameId: raw.midFrameId,
2452
+ ...measured,
2453
+ };
2454
+ }
2455
+
517
2456
  export async function protectedParentIframes({
518
2457
  client,
519
2458
  reader,
@@ -529,7 +2468,8 @@ export async function protectedParentIframes({
529
2468
  eventStart = 0,
530
2469
  }) {
531
2470
  if (!reader) return { incomplete: 'missing unguarded reader' };
532
- if (discovery) {
2471
+ const pageMode = ['page-nested', 'page-srcdoc', 'page-ordinary'].includes(mode);
2472
+ if (discovery && !pageMode) {
533
2473
  await outcome(client.send('Target.setDiscoverTargets', { discover: true }));
534
2474
  await outcome(reader.send('Target.setDiscoverTargets', { discover: true }));
535
2475
  notes.push('protected-parent.discovery: setDiscoverTargets discover=true');
@@ -561,7 +2501,49 @@ export async function protectedParentIframes({
561
2501
  internalSessions,
562
2502
  eventStart,
563
2503
  })
564
- : { incomplete: `unknown protectedParentIframes mode ${mode}` };
2504
+ : mode === 'page-nested'
2505
+ ? await pageNested({
2506
+ reader,
2507
+ client,
2508
+ midOrigin: protectedOrigin,
2509
+ ordinary,
2510
+ tag,
2511
+ notes,
2512
+ budget,
2513
+ internalSessions,
2514
+ eventStart,
2515
+ innerKind: 'ordinary',
2516
+ preferMidLive: true,
2517
+ })
2518
+ : mode === 'page-srcdoc'
2519
+ ? await pageNested({
2520
+ reader,
2521
+ client,
2522
+ midOrigin: protectedOrigin,
2523
+ ordinary,
2524
+ tag,
2525
+ notes,
2526
+ budget,
2527
+ internalSessions,
2528
+ eventStart,
2529
+ innerKind: 'srcdoc',
2530
+ preferMidLive: true,
2531
+ })
2532
+ : mode === 'page-ordinary'
2533
+ ? await pageNested({
2534
+ reader,
2535
+ client,
2536
+ midOrigin: cross,
2537
+ ordinary,
2538
+ tag,
2539
+ notes,
2540
+ budget,
2541
+ internalSessions,
2542
+ eventStart,
2543
+ innerKind: 'ordinary',
2544
+ preferMidLive: false,
2545
+ })
2546
+ : { incomplete: `unknown protectedParentIframes mode ${mode}` };
565
2547
  if (built.pageId) await outcome(reader.send('Target.closeTarget', { targetId: built.pageId }));
566
2548
  return built;
567
2549
  }