@hy-sde-org/dsh-browser 0.2.2-rc.1 → 0.2.2-rc.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.
@@ -10,6 +10,8 @@ class CdpConnection {
10
10
  claims = new Set();
11
11
  /** Real child session id → the session it was announced on; its events and detach go there. */
12
12
  childParents = new Map();
13
+ /** Real children this connection attached itself (`Target.attachToTarget`); their ownership survives an auto-attach opt-out. */
14
+ explicitChildren = new Set();
13
15
  constructor(id, socket) {
14
16
  this.id = id;
15
17
  this.socket = socket;
@@ -51,6 +53,14 @@ class TabState {
51
53
  attaching = null;
52
54
  /** Detach RPC still landing; a new attach must wait it out or the late detach undoes it. */
53
55
  detaching = null;
56
+ /**
57
+ * Settled by the tab's next extension-reported detach — the report a
58
+ * detach-killed command waits for before its failure reply. Replaced once
59
+ * settled so the next detach gets its own settlement.
60
+ */
61
+ chromeDetach = Promise.withResolvers();
62
+ /** Reason the tab's last extension-reported detach named; undefined until then. */
63
+ detachReason;
54
64
  /** True after the relay put this tab in the omp group; `ompGroupId` holds that group. */
55
65
  grouped = false;
56
66
  /** Group RPC in flight — suppresses duplicate requests from load-time tabUpdated bursts. */
@@ -81,8 +91,36 @@ class TabState {
81
91
  /** URLs `chrome.debugger` cannot attach to; hidden from downstream discovery entirely. */
82
92
  const INELIGIBLE_URL = /^(chrome|devtools|edge|view-source|chrome-extension|chrome-untrusted|chrome-search):/i;
83
93
  const RPC_TIMEOUT_MS = 20_000;
94
+ /**
95
+ * Deadline for page-bound work that legitimately outlives the default: an
96
+ * `awaitPromise` evaluate that waits on the page, or a navigation the client
97
+ * owns a timeout for. Matches Playwright's 180s protocol timeout, so the
98
+ * relay's deadline never cuts a command Playwright would still wait for.
99
+ */
100
+ const PAGE_BOUND_RPC_TIMEOUT_MS = 180_000;
84
101
  const CDP_ERROR_METHOD_NOT_FOUND = -32601;
85
102
  const CDP_ERROR_SERVER = -32000;
103
+ /** Chrome's answer to a command in flight when it ends the debugger attachment. */
104
+ const DETACHED_COMMAND_ERROR = /Detached while handling command/;
105
+ /**
106
+ * How long a root-session command Chrome killed with its in-flight detach
107
+ * answer waits for the extension's own detach report before the failure
108
+ * reply; bounded so a detach Chrome never reports still replies.
109
+ */
110
+ const CHROME_DETACH_REPORT_MS = 1_000;
111
+ /**
112
+ * Deadline for the page command that lets Chrome's detach report overtake a
113
+ * child-session failure reply: Chrome ends a cross-site frame's session the
114
+ * moment it detaches the debugger, ahead of the report.
115
+ */
116
+ const DETACH_REPORT_PROBE_MS = 500;
117
+ /** A relay RPC the bridge gave up on at its own deadline; Chrome never answered it. */
118
+ class RpcTimeoutError extends Error {
119
+ }
120
+ /** Resolves after `ms`; deadline for waits that have no in-flight rpc to time out. */
121
+ function sleep(ms) {
122
+ return new Promise(resolve => setTimeout(resolve, ms));
123
+ }
86
124
  function tabTargetId(tabId) {
87
125
  return `TAB${tabId}`;
88
126
  }
@@ -122,6 +160,13 @@ export class RelayBridge {
122
160
  #pendingRpc = new Map();
123
161
  /** Real child session id → owning tab, learned from `Target.attachedToTarget` events. */
124
162
  #realSessionTabs = new Map();
163
+ /**
164
+ * Each tab's last auto-attach transition, keyed by tab id: the extension
165
+ * starts RPCs independently, so overlapping transitions on one tab must
166
+ * settle in order, or a failed one's rollback would restore a state another
167
+ * transition had already changed.
168
+ */
169
+ #autoAttachTransitions = new Map();
125
170
  /** `Date.now()` when the last ready extension socket closed; null while one is ready or none ever was. */
126
171
  #extensionGoneSince = null;
127
172
  #log;
@@ -324,7 +369,16 @@ export class RelayBridge {
324
369
  const touched = new Set();
325
370
  for (const ref of conn.sessions.values())
326
371
  touched.add(ref.tabId);
372
+ // Collect the departing holder's armed tabs before its sessions go, then
373
+ // disarm Chrome once they no longer count toward {@link #autoAttaches}.
374
+ const armedTabs = new Set();
375
+ for (const ref of conn.sessions.values()) {
376
+ if (ref.autoAttach)
377
+ armedTabs.add(ref.tabId);
378
+ }
327
379
  conn.sessions.clear();
380
+ for (const tabId of armedTabs)
381
+ this.#releaseAutoAttach(tabId);
328
382
  // Tabs this client claimed leave the omp group unless another claimant
329
383
  // remains — session holders don't count: the long-lived registry
330
384
  // connection holds sessions on every tab without driving any of them.
@@ -370,27 +424,55 @@ export class RelayBridge {
370
424
  }
371
425
  if (ref?.kind === 'page') {
372
426
  if (msg.method === 'Target.setAutoAttach') {
373
- // Armed while in flight (Chrome reports existing children before it
374
- // answers); a failed request restores the previous state.
375
- const previous = ref.autoAttach;
376
- ref.autoAttach = msg.params?.autoAttach === true;
377
- const announce = () => {
378
- const parent = conn.childTargetSessionForTab(ref.tabId);
379
- if (parent && conn.sessions.get(sessionId) === ref)
380
- this.#announceChildren(conn, ref.tabId, undefined, parent);
381
- };
382
- if (!(await this.#forwardToTab(conn, msg, ref.tabId, undefined, ref.autoAttach ? announce : undefined))) {
383
- ref.autoAttach = previous;
384
- }
427
+ // Serialized per tab: the extension starts RPCs independently, so two
428
+ // transitions must not interleave — see {@link #serializeAutoAttach}.
429
+ await this.#serializeAutoAttach(ref.tabId, async () => {
430
+ // The session may have been released while this transition queued
431
+ // behind an earlier one on the tab.
432
+ if (conn.sessions.get(sessionId) !== ref) {
433
+ this.#replyError(conn, msg, `Unknown session id ${sessionId}`);
434
+ return;
435
+ }
436
+ // Armed while in flight (Chrome reports existing children before it
437
+ // answers); a failed request restores the previous state.
438
+ const previous = ref.autoAttach;
439
+ ref.autoAttach = msg.params?.autoAttach === true;
440
+ const announce = () => {
441
+ const parent = conn.childTargetSessionForTab(ref.tabId);
442
+ if (parent)
443
+ this.#announceChildren(conn, ref.tabId, undefined, parent);
444
+ };
445
+ if (!ref.autoAttach && this.#autoAttaches(ref.tabId)) {
446
+ // One debugger attachment backs every connection: with another
447
+ // holder still armed, keep Chrome armed and report success to
448
+ // this connection only.
449
+ this.#reply(conn, msg, {});
450
+ }
451
+ else if (!(await this.#forwardToTab(conn, msg, ref.tabId, undefined, ref.autoAttach ? announce : undefined))) {
452
+ ref.autoAttach = previous;
453
+ // A holder that departed while its arm was in flight must still
454
+ // reconcile Chrome after the failed enable rolls back.
455
+ if (previous && conn.sessions.get(sessionId) !== ref)
456
+ this.#releaseAutoAttach(ref.tabId);
457
+ return;
458
+ }
459
+ // With no armed session left on this connection, its automatic
460
+ // children are gone for it — announce their detaches locally.
461
+ const tab = this.#tabs.get(ref.tabId);
462
+ if (tab && !conn.childTargetSessionForTab(ref.tabId))
463
+ this.#forgetConnectionChildren(conn, tab, true);
464
+ });
385
465
  return;
386
466
  }
387
467
  await this.#forwardToTab(conn, msg, ref.tabId, undefined);
388
468
  return;
389
469
  }
390
470
  const realTab = this.#realSessionTabs.get(sessionId);
391
- if (realTab !== undefined) {
392
- const announce = msg.method === 'Target.setAutoAttach' && msg.params?.autoAttach === true && conn.childParents.has(sessionId)
393
- ? () => this.#announceChildren(conn, realTab, sessionId, sessionId)
471
+ // Only a connection that was told about the child may drive it: Chrome's
472
+ // session ids are unguessable, so anything else is a stale or foreign id.
473
+ if (realTab !== undefined && conn.childParents.has(sessionId)) {
474
+ const announce = msg.method === 'Target.setAutoAttach' && msg.params?.autoAttach === true
475
+ ? () => { this.#announceChildren(conn, realTab, sessionId, sessionId); }
394
476
  : undefined;
395
477
  await this.#forwardToTab(conn, msg, realTab, sessionId, announce);
396
478
  return;
@@ -431,22 +513,61 @@ export class RelayBridge {
431
513
  return true;
432
514
  }
433
515
  try {
434
- const result = await this.#rpc({
435
- op: 'send',
436
- tabId,
437
- ...(realSessionId !== undefined ? { sessionId: realSessionId } : {}),
438
- method: msg.method,
439
- ...(msg.params !== undefined ? { params: msg.params } : {}),
440
- });
516
+ const result = await this.#send(tabId, msg.method, msg.params, realSessionId);
517
+ const response = result ?? {};
518
+ // An explicit attach grants ownership even when this connection did not
519
+ // arm auto-attach: it drives the child directly.
520
+ if (msg.method === 'Target.attachToTarget' && msg.sessionId && typeof response.sessionId === 'string') {
521
+ conn.childParents.set(response.sessionId, msg.sessionId);
522
+ conn.explicitChildren.add(response.sessionId);
523
+ }
441
524
  beforeReply?.();
442
- this.#reply(conn, msg, result ?? {});
525
+ this.#reply(conn, msg, response);
443
526
  return true;
444
527
  }
445
528
  catch (err) {
446
- this.#replyError(conn, msg, err instanceof Error ? err.message : String(err));
529
+ const message = err instanceof Error ? err.message : String(err);
530
+ const tab = this.#tabs.get(tabId);
531
+ await this.#overtakeDetachReport(tab, realSessionId, message);
532
+ this.#replyError(conn, msg, this.#detachReport(tab, message));
447
533
  return false;
448
534
  }
449
535
  }
536
+ /**
537
+ * Give Chrome's detach report a chance to overtake a command failure, so the
538
+ * downstream client learns why the session died before the error reply:
539
+ * Chrome answers a command in flight with {@link DETACHED_COMMAND_ERROR}
540
+ * ahead of the extension's detach report. A root-session failure waits for
541
+ * that report ({@link CHROME_DETACH_REPORT_MS}); a child-session failure
542
+ * sends one page command Chrome answers only after reporting the detach
543
+ * ({@link DETACH_REPORT_PROBE_MS}).
544
+ */
545
+ async #overtakeDetachReport(tab, realSessionId, message) {
546
+ if (!tab?.attached || !DETACHED_COMMAND_ERROR.test(message))
547
+ return;
548
+ if (realSessionId === undefined) {
549
+ await Promise.race([tab.chromeDetach.promise, sleep(CHROME_DETACH_REPORT_MS)]);
550
+ return;
551
+ }
552
+ try {
553
+ await this.#rpc({ op: 'send', tabId: tab.tabId, method: 'Target.getTargetInfo' }, DETACH_REPORT_PROBE_MS);
554
+ }
555
+ catch {
556
+ // The probe itself failing is fine: its deadline fired or the tab is gone.
557
+ }
558
+ }
559
+ /**
560
+ * The text a failed command replies with: Chrome's in-flight detach answer
561
+ * names nothing, so once the tab's detach is reported the reply says what
562
+ * happened to the tab instead.
563
+ */
564
+ #detachReport(tab, message) {
565
+ if (!tab || tab.attached || tab.detachReason === undefined)
566
+ return message;
567
+ if (!DETACHED_COMMAND_ERROR.test(message))
568
+ return message;
569
+ return `Chrome detached the debugger from tab ${tab.tabId} (${tab.detachReason}) during this command`;
570
+ }
450
571
  /**
451
572
  * Record `conn` as a driver of the tab and reconcile grouping. Claims are
452
573
  * explicit (worker adoption or tab creation) rather than inferred from
@@ -694,10 +815,15 @@ export class RelayBridge {
694
815
  if (!conn.childParents.has(sourceSessionId))
695
816
  continue;
696
817
  conn.socket.send(payload);
697
- if (nested && method === 'Target.attachedToTarget')
698
- conn.childParents.set(nested, sourceSessionId);
699
- else if (nested && method === 'Target.detachedFromTarget')
818
+ if (nested && method === 'Target.attachedToTarget') {
819
+ // First teller owns the child; a later report does not re-own it.
820
+ if (!conn.childParents.has(nested))
821
+ conn.childParents.set(nested, sourceSessionId);
822
+ }
823
+ else if (nested && method === 'Target.detachedFromTarget') {
700
824
  conn.childParents.delete(nested);
825
+ conn.explicitChildren.delete(nested);
826
+ }
701
827
  }
702
828
  return;
703
829
  }
@@ -715,12 +841,13 @@ export class RelayBridge {
715
841
  let parent;
716
842
  if (method === 'Target.attachedToTarget') {
717
843
  parent = conn.childTargetSessionForTab(tabId);
718
- if (parent)
844
+ if (parent && !conn.childParents.has(child))
719
845
  conn.childParents.set(child, parent);
720
846
  }
721
847
  else {
722
848
  parent = conn.childParents.get(child);
723
849
  conn.childParents.delete(child);
850
+ conn.explicitChildren.delete(child);
724
851
  }
725
852
  if (parent)
726
853
  conn.socket.send(JSON.stringify({ sessionId: parent, method, params }));
@@ -742,8 +869,12 @@ export class RelayBridge {
742
869
  tab.attached = false;
743
870
  tab.attaching = null;
744
871
  tab.banned = true;
745
- // The user dismissed the debugger infobar (or the attach was torn
746
- // down): release the tab's omp-group membership too.
872
+ tab.detachReason = reason;
873
+ // A detach-killed command may be holding for this report; swap in a fresh
874
+ // settlement so the tab's next detach gets its own.
875
+ tab.chromeDetach.resolve();
876
+ tab.chromeDetach = Promise.withResolvers();
877
+ // A detached tab is no longer a group candidate — no claim holds it — so release its omp-group membership too.
747
878
  this.#syncTabGrouping(tab);
748
879
  this.#retractTab(tab);
749
880
  }
@@ -893,8 +1024,12 @@ export class RelayBridge {
893
1024
  this.#log('tab grouping failed', { error: err instanceof Error ? err.message : String(err) });
894
1025
  }
895
1026
  finally {
896
- for (const tab of batch)
1027
+ for (const tab of batch) {
897
1028
  tab.grouping = false;
1029
+ // The claim may have gone while the RPC was in flight (its client closed): undo the grouping.
1030
+ if (tab.grouped && !this.#groupWorthy(tab))
1031
+ this.#syncTabGrouping(tab);
1032
+ }
898
1033
  }
899
1034
  }
900
1035
  }
@@ -933,6 +1068,12 @@ export class RelayBridge {
933
1068
  if (!ref)
934
1069
  return;
935
1070
  conn.sessions.delete(sessionId);
1071
+ if (ref.autoAttach)
1072
+ this.#releaseAutoAttach(ref.tabId);
1073
+ const tab = this.#tabs.get(ref.tabId);
1074
+ if (ref.kind === 'page' && tab && !conn.childTargetSessionForTab(ref.tabId)) {
1075
+ this.#forgetConnectionChildren(conn, tab, true);
1076
+ }
936
1077
  const targetId = ref.kind === 'tab' ? tabTargetId(ref.tabId) : pageTargetId(ref.tabId);
937
1078
  this.#emit(conn, 'Target.detachedFromTarget', { sessionId, targetId }, parentSessionId);
938
1079
  // An explicit release of the last session must drop the attachment too,
@@ -946,17 +1087,80 @@ export class RelayBridge {
946
1087
  * before the children reported under it.
947
1088
  */
948
1089
  #forgetChildren(tab) {
949
- for (const child of [...tab.realSessions.keys()].reverse()) {
1090
+ for (const conn of this.#conns.values())
1091
+ this.#forgetConnectionChildren(conn, tab);
1092
+ for (const child of tab.realSessions.keys())
950
1093
  this.#realSessionTabs.delete(child);
951
- for (const conn of this.#conns.values()) {
952
- const parent = conn.childParents.get(child);
953
- if (parent === undefined)
1094
+ tab.realSessions.clear();
1095
+ }
1096
+ /**
1097
+ * Tell one connection that its known real children of the tab are gone —
1098
+ * nested children first, while their parent is still known. `automaticOnly`
1099
+ * spares subtrees the connection attached itself: its explicit children
1100
+ * outlive an auto-attach opt-out or a page release.
1101
+ */
1102
+ #forgetConnectionChildren(conn, tab, automaticOnly = false) {
1103
+ for (const child of [...tab.realSessions.keys()].reverse()) {
1104
+ const parent = conn.childParents.get(child);
1105
+ if (parent === undefined)
1106
+ continue;
1107
+ if (automaticOnly) {
1108
+ // Skip anything whose topmost owner is explicit: a connection that
1109
+ // attached a child itself keeps it, and keeps its descendants.
1110
+ let ancestor = child;
1111
+ while (!conn.explicitChildren.has(ancestor)) {
1112
+ const next = conn.childParents.get(ancestor);
1113
+ if (next === undefined)
1114
+ break;
1115
+ ancestor = next;
1116
+ }
1117
+ if (conn.explicitChildren.has(ancestor))
954
1118
  continue;
955
- conn.childParents.delete(child);
956
- this.#emit(conn, 'Target.detachedFromTarget', { sessionId: child }, parent);
957
1119
  }
1120
+ conn.childParents.delete(child);
1121
+ conn.explicitChildren.delete(child);
1122
+ this.#emit(conn, 'Target.detachedFromTarget', { sessionId: child }, parent);
958
1123
  }
959
- tab.realSessions.clear();
1124
+ }
1125
+ /** Whether any connection, on the tab's one debugger attachment, still arms auto-attach. */
1126
+ #autoAttaches(tabId) {
1127
+ for (const conn of this.#conns.values()) {
1128
+ if (conn.childTargetSessionForTab(tabId))
1129
+ return true;
1130
+ }
1131
+ return false;
1132
+ }
1133
+ /** Disarm auto-attach once no connection still arms it; a departed holder must not leave it on. */
1134
+ #releaseAutoAttach(tabId) {
1135
+ void this.#serializeAutoAttach(tabId, async () => {
1136
+ if (this.#autoAttaches(tabId))
1137
+ return;
1138
+ const tab = this.#tabs.get(tabId);
1139
+ if (!tab?.attached)
1140
+ return;
1141
+ await this.#send(tabId, 'Target.setAutoAttach', {
1142
+ autoAttach: false,
1143
+ waitForDebuggerOnStart: false,
1144
+ flatten: true,
1145
+ }).catch(() => { });
1146
+ });
1147
+ }
1148
+ /**
1149
+ * Run one tab's auto-attach transitions one at a time: the extension starts
1150
+ * RPCs independently, so overlapping transitions must settle in order, or a
1151
+ * failed one's rollback would restore a state another transition had
1152
+ * already changed on the tab.
1153
+ */
1154
+ #serializeAutoAttach(tabId, run) {
1155
+ const pending = this.#autoAttachTransitions.get(tabId);
1156
+ const result = pending ? pending.then(run) : run();
1157
+ const tail = result.catch(() => { });
1158
+ this.#autoAttachTransitions.set(tabId, tail);
1159
+ void tail.then(() => {
1160
+ if (this.#autoAttachTransitions.get(tabId) === tail)
1161
+ this.#autoAttachTransitions.delete(tabId);
1162
+ });
1163
+ return result;
960
1164
  }
961
1165
  /**
962
1166
  * Drop the debugger (and its infobar) from a tab nobody drives anymore.
@@ -970,6 +1174,8 @@ export class RelayBridge {
970
1174
  if (!tab?.attached)
971
1175
  return;
972
1176
  tab.attached = false;
1177
+ // This detach is the relay's own; any reported detach reason is from an earlier cycle.
1178
+ tab.detachReason = undefined;
973
1179
  this.#forgetChildren(tab);
974
1180
  const done = this.#rpc({ op: 'detach', tabId })
975
1181
  .then(() => { })
@@ -1015,6 +1221,8 @@ export class RelayBridge {
1015
1221
  const attempt = this.#rpc({ op: 'attach', tabId: tab.tabId })
1016
1222
  .then(() => {
1017
1223
  tab.attached = true;
1224
+ // A fresh attach leaves any earlier detach cycle's reason behind.
1225
+ tab.detachReason = undefined;
1018
1226
  return true;
1019
1227
  })
1020
1228
  .catch((err) => {
@@ -1069,6 +1277,31 @@ export class RelayBridge {
1069
1277
  #emit(conn, method, params, sessionId) {
1070
1278
  conn.socket.send(JSON.stringify({ sessionId, method, params }));
1071
1279
  }
1280
+ /**
1281
+ * Forward one CDP command to a tab under a deadline that fits the command:
1282
+ * page-bound work (`awaitPromise` evaluates, `Runtime.awaitPromise`,
1283
+ * `Page.navigate`) gets {@link PAGE_BOUND_RPC_TIMEOUT_MS}, everything else
1284
+ * {@link RPC_TIMEOUT_MS}. A deadline miss rejects with an error naming the
1285
+ * method and tab; other failures pass through unchanged.
1286
+ */
1287
+ async #send(tabId, method, params, sessionId) {
1288
+ const pageBound = params?.awaitPromise === true || method === 'Runtime.awaitPromise' || method === 'Page.navigate';
1289
+ const timeoutMs = pageBound ? PAGE_BOUND_RPC_TIMEOUT_MS : RPC_TIMEOUT_MS;
1290
+ try {
1291
+ return await this.#rpc({
1292
+ op: 'send',
1293
+ tabId,
1294
+ ...(sessionId !== undefined ? { sessionId } : {}),
1295
+ method,
1296
+ ...(params !== undefined ? { params } : {}),
1297
+ }, timeoutMs);
1298
+ }
1299
+ catch (err) {
1300
+ if (!(err instanceof RpcTimeoutError))
1301
+ throw err;
1302
+ throw new Error(`${method} on tab ${tabId}: Chrome sent no answer within ${timeoutMs}ms`, { cause: err });
1303
+ }
1304
+ }
1072
1305
  #rpc(req, timeoutMs = RPC_TIMEOUT_MS) {
1073
1306
  const ext = this.#ext;
1074
1307
  if (!ext)
@@ -1077,10 +1310,15 @@ export class RelayBridge {
1077
1310
  const { promise, resolve, reject } = Promise.withResolvers();
1078
1311
  const timer = setTimeout(() => {
1079
1312
  this.#pendingRpc.delete(id);
1080
- reject(new Error(`extension rpc '${req.op}' timed out after ${timeoutMs}ms`));
1313
+ reject(new RpcTimeoutError(`extension rpc '${req.op}' timed out after ${timeoutMs}ms`));
1081
1314
  }, timeoutMs);
1082
1315
  this.#pendingRpc.set(id, { resolve, reject, timer });
1083
- ext.send(JSON.stringify({ t: 'rpc', id, ...req }));
1316
+ // Only in a tab a downstream connection claims may the extension empty another extension's
1317
+ // frames to get past Chrome's refusal; the user's other tabs keep their menus.
1318
+ const sent = req.op === 'attach' || req.op === 'send'
1319
+ ? { ...req, clearForeignFrames: this.#claimed(req.tabId) }
1320
+ : req;
1321
+ ext.send(JSON.stringify({ t: 'rpc', id, ...sent }));
1084
1322
  return promise;
1085
1323
  }
1086
1324
  }