browser-debugger-cli 0.12.0 → 0.13.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.
Files changed (180) hide show
  1. package/.claude/skills/bdg/SKILL.md +4 -4
  2. package/README.md +1 -0
  3. package/dist/commands/cdp.d.ts +22 -1
  4. package/dist/commands/cdp.js +100 -43
  5. package/dist/commands/console.d.ts +12 -0
  6. package/dist/commands/console.js +62 -12
  7. package/dist/commands/dom/DomElementResolver.d.ts +3 -1
  8. package/dist/commands/dom/DomElementResolver.js +10 -3
  9. package/dist/commands/dom/a11y.js +3 -2
  10. package/dist/commands/dom/eval.d.ts +3 -2
  11. package/dist/commands/dom/eval.js +11 -5
  12. package/dist/commands/dom/form.js +10 -9
  13. package/dist/commands/dom/formInteraction.js +8 -7
  14. package/dist/commands/dom/get.js +8 -8
  15. package/dist/commands/dom/helpers/index.d.ts +1 -1
  16. package/dist/commands/dom/helpers/index.js +1 -1
  17. package/dist/commands/dom/helpers/query.d.ts +27 -3
  18. package/dist/commands/dom/helpers/query.js +152 -64
  19. package/dist/commands/dom/helpers/screenshot.js +13 -13
  20. package/dist/commands/dom/index.js +4 -2
  21. package/dist/commands/dom/query.d.ts +19 -2
  22. package/dist/commands/dom/query.js +37 -6
  23. package/dist/commands/dom/screenshot.js +2 -1
  24. package/dist/commands/dom/semanticUtils.d.ts +3 -2
  25. package/dist/commands/dom/semanticUtils.js +40 -9
  26. package/dist/commands/helpJson.d.ts +82 -19
  27. package/dist/commands/helpJson.js +111 -40
  28. package/dist/commands/helpTopic.d.ts +16 -1
  29. package/dist/commands/helpTopic.js +59 -1
  30. package/dist/commands/installSkill.d.ts +15 -5
  31. package/dist/commands/installSkill.js +86 -16
  32. package/dist/commands/network/list.js +22 -12
  33. package/dist/commands/optionBehaviors.js +33 -11
  34. package/dist/commands/shared/daemonErrorHandler.d.ts +5 -2
  35. package/dist/commands/shared/daemonErrorHandler.js +20 -9
  36. package/dist/commands/shared/dataFetcher.d.ts +12 -4
  37. package/dist/commands/shared/dataFetcher.js +12 -4
  38. package/dist/commands/shared/followMode.d.ts +9 -1
  39. package/dist/commands/shared/followMode.js +22 -4
  40. package/dist/commands/shared/optionTypes.d.ts +4 -1
  41. package/dist/commands/shared/outputFile.js +6 -1
  42. package/dist/commands/start.d.ts +7 -5
  43. package/dist/commands/start.js +65 -21
  44. package/dist/commands/stop.d.ts +11 -0
  45. package/dist/commands/stop.js +24 -1
  46. package/dist/commands.js +1 -1
  47. package/dist/connection/cdp.d.ts +7 -0
  48. package/dist/connection/cdp.js +9 -0
  49. package/dist/connection/launcher.js +3 -2
  50. package/dist/daemon/SessionController.js +6 -1
  51. package/dist/daemon/launcher.d.ts +3 -2
  52. package/dist/daemon/launcher.js +47 -3
  53. package/dist/daemon/session/Session.d.ts +4 -1
  54. package/dist/daemon/session/Session.js +33 -2
  55. package/dist/daemon/session/TelemetryStore.d.ts +8 -1
  56. package/dist/daemon/session/TelemetryStore.js +13 -1
  57. package/dist/daemon/session/commandRegistry.js +29 -13
  58. package/dist/daemon/session/interactions.d.ts +2 -1
  59. package/dist/daemon/session/interactions.js +13 -1
  60. package/dist/daemon/session/plugins.js +16 -2
  61. package/dist/daemon/session/teardown.js +1 -1
  62. package/dist/daemon.js +1622 -748
  63. package/dist/errors/messages.d.ts +54 -11
  64. package/dist/errors/messages.js +109 -22
  65. package/dist/index.js +13733 -8796
  66. package/dist/ipc/client.d.ts +18 -2
  67. package/dist/ipc/client.js +26 -5
  68. package/dist/ipc/protocol/auditTypes.d.ts +8 -2
  69. package/dist/ipc/protocol/commands.d.ts +12 -0
  70. package/dist/ipc/protocol/domTypes.d.ts +12 -0
  71. package/dist/ipc/protocol/inspectTypes.d.ts +2 -0
  72. package/dist/ipc/session/types.d.ts +2 -0
  73. package/dist/runtime/dom/actionEffects.d.ts +5 -1
  74. package/dist/runtime/dom/actionEffects.js +26 -14
  75. package/dist/runtime/dom/audit.js +3 -2
  76. package/dist/runtime/dom/auditModel.js +6 -1
  77. package/dist/runtime/dom/auditScripts.d.ts +9 -3
  78. package/dist/runtime/dom/auditScripts.js +41 -5
  79. package/dist/runtime/dom/elementGeometry.d.ts +10 -3
  80. package/dist/runtime/dom/elementGeometry.js +27 -4
  81. package/dist/runtime/dom/elementInfo.d.ts +74 -18
  82. package/dist/runtime/dom/elementInfo.js +187 -40
  83. package/dist/runtime/dom/evalHelpers.d.ts +12 -2
  84. package/dist/runtime/dom/evalHelpers.js +67 -7
  85. package/dist/runtime/dom/formDiscovery.d.ts +6 -2
  86. package/dist/runtime/dom/formDiscovery.js +20 -3
  87. package/dist/runtime/dom/formFillHelpers/fill.js +7 -11
  88. package/dist/runtime/dom/formFillHelpers/pressKey.js +2 -2
  89. package/dist/runtime/dom/formFillHelpers/shared.d.ts +16 -10
  90. package/dist/runtime/dom/formFillHelpers/shared.js +19 -52
  91. package/dist/runtime/dom/formSubmitHelpers.js +4 -3
  92. package/dist/runtime/dom/frameLayout.js +1 -0
  93. package/dist/runtime/dom/inspect.js +5 -6
  94. package/dist/runtime/dom/inspectAllStyles.js +1 -0
  95. package/dist/runtime/dom/inspectHints.d.ts +1 -1
  96. package/dist/runtime/dom/inspectModel.d.ts +2 -1
  97. package/dist/runtime/dom/inspectModel.js +7 -3
  98. package/dist/runtime/dom/inspectPaintModel.d.ts +2 -0
  99. package/dist/runtime/dom/inspectPaintModel.js +3 -1
  100. package/dist/runtime/dom/inspectScripts.d.ts +29 -2
  101. package/dist/runtime/dom/inspectScripts.js +49 -10
  102. package/dist/runtime/dom/layout.js +9 -7
  103. package/dist/runtime/dom/reactEventHelpers.d.ts +14 -4
  104. package/dist/runtime/dom/reactEventHelpers.js +63 -27
  105. package/dist/runtime/dom/targetNode.d.ts +18 -5
  106. package/dist/runtime/dom/targetNode.js +268 -8
  107. package/dist/runtime/dom/wait.js +2 -1
  108. package/dist/runtime/page/bdgWorld.d.ts +57 -0
  109. package/dist/runtime/page/bdgWorld.js +180 -0
  110. package/dist/runtime/page/replacedBuiltins.d.ts +28 -0
  111. package/dist/runtime/page/replacedBuiltins.js +136 -0
  112. package/dist/session/QueryCacheManager.d.ts +4 -1
  113. package/dist/session/QueryCacheManager.js +5 -2
  114. package/dist/session/chrome.d.ts +4 -1
  115. package/dist/session/chrome.js +7 -1
  116. package/dist/session/cleanup/staleSession.d.ts +21 -4
  117. package/dist/session/cleanup/staleSession.js +79 -9
  118. package/dist/session/cleanup/userCommands.d.ts +4 -1
  119. package/dist/session/cleanup/userCommands.js +10 -5
  120. package/dist/session/daemonSocket.d.ts +10 -0
  121. package/dist/session/daemonSocket.js +22 -0
  122. package/dist/session/lastSession.d.ts +6 -3
  123. package/dist/session/lastSession.js +11 -5
  124. package/dist/session/paths.d.ts +3 -1
  125. package/dist/session/paths.js +5 -5
  126. package/dist/session/portClaims.js +4 -3
  127. package/dist/session/sessionList.d.ts +13 -5
  128. package/dist/session/sessionList.js +31 -7
  129. package/dist/telemetry/a11y.js +2 -2
  130. package/dist/telemetry/console.d.ts +2 -1
  131. package/dist/telemetry/console.js +30 -21
  132. package/dist/telemetry/pageCrash.d.ts +26 -0
  133. package/dist/telemetry/pageCrash.js +53 -0
  134. package/dist/types.d.ts +16 -0
  135. package/dist/ui/formatters/audit.js +14 -5
  136. package/dist/ui/formatters/cdp.d.ts +138 -0
  137. package/dist/ui/formatters/cdp.js +131 -0
  138. package/dist/ui/formatters/console/chronological.js +3 -1
  139. package/dist/ui/formatters/console/follow.d.ts +2 -1
  140. package/dist/ui/formatters/console/follow.js +2 -2
  141. package/dist/ui/formatters/console/json.d.ts +2 -2
  142. package/dist/ui/formatters/console/json.js +11 -5
  143. package/dist/ui/formatters/console/shared.d.ts +30 -0
  144. package/dist/ui/formatters/console/shared.js +16 -0
  145. package/dist/ui/formatters/console/summarize.d.ts +9 -2
  146. package/dist/ui/formatters/console/summarize.js +40 -9
  147. package/dist/ui/formatters/console.d.ts +2 -1
  148. package/dist/ui/formatters/console.js +7 -5
  149. package/dist/ui/formatters/details.js +3 -1
  150. package/dist/ui/formatters/dom.d.ts +1 -1
  151. package/dist/ui/formatters/dom.js +5 -6
  152. package/dist/ui/formatters/helpFormatters.js +1 -1
  153. package/dist/ui/formatters/inspect.js +9 -3
  154. package/dist/ui/formatters/installSkill.d.ts +9 -1
  155. package/dist/ui/formatters/installSkill.js +32 -6
  156. package/dist/ui/formatters/layout.js +2 -1
  157. package/dist/ui/formatters/networkList.d.ts +1 -1
  158. package/dist/ui/formatters/networkList.js +1 -2
  159. package/dist/ui/formatters/preview.d.ts +2 -0
  160. package/dist/ui/formatters/preview.js +17 -7
  161. package/dist/ui/formatters/sessions.d.ts +2 -2
  162. package/dist/ui/formatters/sessions.js +9 -2
  163. package/dist/ui/logging/logger.d.ts +1 -1
  164. package/dist/ui/messages/commands.d.ts +124 -4
  165. package/dist/ui/messages/commands.js +162 -7
  166. package/dist/ui/messages/consoleMessages.d.ts +24 -0
  167. package/dist/ui/messages/consoleMessages.js +32 -0
  168. package/dist/ui/messages/preview.d.ts +6 -0
  169. package/dist/ui/messages/preview.js +9 -1
  170. package/dist/ui/messages/session.d.ts +13 -2
  171. package/dist/ui/messages/session.js +22 -3
  172. package/dist/utils/directories.d.ts +34 -0
  173. package/dist/utils/directories.js +88 -0
  174. package/dist/utils/display.d.ts +16 -0
  175. package/dist/utils/display.js +42 -0
  176. package/dist/utils/exitCodes.d.ts +1 -0
  177. package/dist/utils/exitCodes.js +6 -0
  178. package/dist/utils/process.d.ts +12 -0
  179. package/dist/utils/process.js +25 -0
  180. package/package.json +1 -1
@@ -15,6 +15,7 @@ import { invalidSelectorError, waitTimeoutError } from '../../errors/messages.js
15
15
  import { isContextLostError } from './evalHelpers.js';
16
16
  import { DEEP_QUERY_JS, FILTER_MATCHING_JS, selectorArgsJS } from './targetNode.js';
17
17
  import { isWaitConditionMet, needsGoneConfirmation, normalizeWaitText, } from './waitCondition.js';
18
+ import { evaluateInBdgWorld } from '../page/bdgWorld.js';
18
19
  import { createLogger } from '../../ui/logging/index.js';
19
20
  import { delay, raceTimeout } from '../../utils/async.js';
20
21
  import { getErrorMessage } from '../../utils/errors.js';
@@ -157,7 +158,7 @@ async function nextSnapshot(cdp, condition, previous, deadline) {
157
158
  const selectorArgs = condition.selector === undefined ? 'null, null' : selectorArgsJS(condition.selector);
158
159
  const text = condition.text === undefined ? null : normalizeWaitText(condition.text);
159
160
  const args = `${selectorArgs}, ${JSON.stringify(text)}, ${JSON.stringify(previous)}, ${Math.min(remaining, WAIT_SLICE_MS)}`;
160
- const evaluated = cdp.send('Runtime.evaluate', {
161
+ const evaluated = evaluateInBdgWorld(cdp, {
161
162
  expression: `(${WAIT_SNAPSHOT_JS})(${args})`,
162
163
  awaitPromise: true,
163
164
  returnByValue: true,
@@ -0,0 +1,57 @@
1
+ /**
2
+ * bdg's own JavaScript world in the page (a CDP isolated world): it shares
3
+ * the DOM with the page but has its own built-ins, so a page that replaces
4
+ * `Element.prototype.querySelectorAll`, `JSON.stringify` or
5
+ * `Array.prototype.map` (polyfills, old frameworks, anti-bot scripts) cannot
6
+ * change what bdg's page scripts find or return.
7
+ *
8
+ * Only the entry points need the world: `Runtime.evaluate` runs in it with
9
+ * its `contextId`, and `DOM.resolveNode` hands out objects of it with its
10
+ * `executionContextId`; `Runtime.callFunctionOn` on such an object runs in
11
+ * the same world. The world belongs to the top frame (same-origin iframes are
12
+ * reached through it); a node of another frame, a connection without the
13
+ * Page domain (a frame-scoped one) or a failure to create it fall back to the
14
+ * main world, as before.
15
+ */
16
+ import type { CDPConnection } from '../../connection/cdp.js';
17
+ import type { Protocol } from '../../connection/typed-cdp.js';
18
+ /**
19
+ * What the world needs of a connection: commands, and events to forget the
20
+ * world when the page navigates (a sender without events, such as a test
21
+ * double, runs scripts in the main world)
22
+ */
23
+ type PageConnection = Pick<CDPConnection, 'send'> & Partial<Pick<CDPConnection, 'on'>>;
24
+ /** Name of bdg's isolated world (shown in DevTools' context selector) */
25
+ export declare const BDG_WORLD_NAME = "bdg";
26
+ /**
27
+ * `Runtime.evaluate` in bdg's world of the top frame. A call that names its
28
+ * own context is sent as it is.
29
+ *
30
+ * @param cdp - Connection to the page
31
+ * @param params - Evaluate parameters
32
+ * @returns Evaluate response
33
+ */
34
+ export declare function evaluateInBdgWorld(cdp: PageConnection, params: Protocol.Runtime.EvaluateRequest): Promise<Protocol.Runtime.EvaluateResponse>;
35
+ /**
36
+ * `DOM.resolveNode` into bdg's world of the top frame, so functions called on
37
+ * the node run there. A node the world cannot use (one of a cross-origin
38
+ * frame, or one no longer in the page) is resolved in its own frame's main
39
+ * world, as before.
40
+ *
41
+ * @param cdp - Connection to the page
42
+ * @param params - Resolve parameters
43
+ * @returns Resolve response
44
+ */
45
+ export declare function resolveNodeInBdgWorld(cdp: PageConnection, params: Protocol.DOM.ResolveNodeRequest): Promise<Protocol.DOM.ResolveNodeResponse>;
46
+ /**
47
+ * Send a CDP command for bdg's own scripts: `Runtime.evaluate` and
48
+ * `DOM.resolveNode` go to bdg's world, other methods as they are.
49
+ *
50
+ * @param cdp - Connection to the page
51
+ * @param method - CDP method
52
+ * @param params - Its parameters
53
+ * @returns The command's result
54
+ */
55
+ export declare function sendForBdgScript(cdp: PageConnection, method: string, params: Record<string, unknown>): Promise<unknown>;
56
+ export {};
57
+ //# sourceMappingURL=bdgWorld.d.ts.map
@@ -0,0 +1,180 @@
1
+ /**
2
+ * bdg's own JavaScript world in the page (a CDP isolated world): it shares
3
+ * the DOM with the page but has its own built-ins, so a page that replaces
4
+ * `Element.prototype.querySelectorAll`, `JSON.stringify` or
5
+ * `Array.prototype.map` (polyfills, old frameworks, anti-bot scripts) cannot
6
+ * change what bdg's page scripts find or return.
7
+ *
8
+ * Only the entry points need the world: `Runtime.evaluate` runs in it with
9
+ * its `contextId`, and `DOM.resolveNode` hands out objects of it with its
10
+ * `executionContextId`; `Runtime.callFunctionOn` on such an object runs in
11
+ * the same world. The world belongs to the top frame (same-origin iframes are
12
+ * reached through it); a node of another frame, a connection without the
13
+ * Page domain (a frame-scoped one) or a failure to create it fall back to the
14
+ * main world, as before.
15
+ */
16
+ import { createLogger } from '../../ui/logging/index.js';
17
+ import { getErrorMessage } from '../../utils/errors.js';
18
+ const log = createLogger('cdp');
19
+ /** Name of bdg's isolated world (shown in DevTools' context selector) */
20
+ export const BDG_WORLD_NAME = 'bdg';
21
+ /** Errors of a context that is gone (navigation, reload) */
22
+ const CONTEXT_GONE = /Cannot find context with specified id|Execution context was destroyed/;
23
+ /** The world's context id per connection, until the page navigates */
24
+ const worlds = new WeakMap();
25
+ /**
26
+ * The execution context id of bdg's world in the top frame, created on first
27
+ * use and forgotten when the top frame navigates or its contexts are cleared.
28
+ *
29
+ * @param cdp - Connection to the page
30
+ * @returns Context id, or null when no world can be made on this connection
31
+ */
32
+ function worldContext(cdp) {
33
+ const known = worlds.get(cdp);
34
+ if (known)
35
+ return known;
36
+ const created = createWorld(cdp);
37
+ worlds.set(cdp, created);
38
+ return created;
39
+ }
40
+ /**
41
+ * Create the world in the top frame and forget it when the page changes.
42
+ *
43
+ * @param cdp - Connection to the page
44
+ * @returns Context id, or null when it cannot be created
45
+ */
46
+ async function createWorld(cdp) {
47
+ const { on } = cdp;
48
+ if (!on)
49
+ return null;
50
+ try {
51
+ const { frameTree } = (await cdp.send('Page.getFrameTree'));
52
+ const { executionContextId } = (await cdp.send('Page.createIsolatedWorld', {
53
+ frameId: frameTree.frame.id,
54
+ worldName: BDG_WORLD_NAME,
55
+ grantUniveralAccess: false,
56
+ }));
57
+ const forget = () => {
58
+ if (worlds.get(cdp) === created)
59
+ worlds.delete(cdp);
60
+ stopNavigated();
61
+ stopCleared();
62
+ };
63
+ const created = worlds.get(cdp);
64
+ const stopNavigated = on.call(cdp, 'Page.frameNavigated', (params) => {
65
+ if (params.frame.parentId === undefined)
66
+ forget();
67
+ });
68
+ const stopCleared = on.call(cdp, 'Runtime.executionContextsCleared', forget);
69
+ return executionContextId;
70
+ }
71
+ catch (error) {
72
+ log.debug(`bdg's isolated world not available: ${getErrorMessage(error)}`);
73
+ worlds.delete(cdp);
74
+ return null;
75
+ }
76
+ }
77
+ /**
78
+ * Send a command with the world's context, once more with a new world when
79
+ * the context is gone, and in the main world when there is none.
80
+ *
81
+ * @param cdp - Connection to the page
82
+ * @param method - CDP method
83
+ * @param params - Its parameters
84
+ * @param withContext - The parameters with the world's context id
85
+ * @returns The command's result
86
+ */
87
+ async function sendInWorld(cdp, method, params, withContext) {
88
+ for (let attempt = 0; attempt < 2; attempt++) {
89
+ const contextId = await worldContext(cdp);
90
+ if (contextId === null)
91
+ break;
92
+ try {
93
+ return await cdp.send(method, withContext(contextId));
94
+ }
95
+ catch (error) {
96
+ if (!CONTEXT_GONE.test(getErrorMessage(error)))
97
+ throw error;
98
+ worlds.delete(cdp);
99
+ }
100
+ }
101
+ return cdp.send(method, params);
102
+ }
103
+ /**
104
+ * `Runtime.evaluate` in bdg's world of the top frame. A call that names its
105
+ * own context is sent as it is.
106
+ *
107
+ * @param cdp - Connection to the page
108
+ * @param params - Evaluate parameters
109
+ * @returns Evaluate response
110
+ */
111
+ export async function evaluateInBdgWorld(cdp, params) {
112
+ if (params.contextId !== undefined || params.uniqueContextId !== undefined) {
113
+ return (await cdp.send('Runtime.evaluate', { ...params }));
114
+ }
115
+ return (await sendInWorld(cdp, 'Runtime.evaluate', { ...params }, (contextId) => ({
116
+ ...params,
117
+ contextId,
118
+ })));
119
+ }
120
+ /**
121
+ * `DOM.resolveNode` into bdg's world of the top frame, so functions called on
122
+ * the node run there. A node the world cannot use (one of a cross-origin
123
+ * frame, or one no longer in the page) is resolved in its own frame's main
124
+ * world, as before.
125
+ *
126
+ * @param cdp - Connection to the page
127
+ * @param params - Resolve parameters
128
+ * @returns Resolve response
129
+ */
130
+ export async function resolveNodeInBdgWorld(cdp, params) {
131
+ if (params.executionContextId !== undefined) {
132
+ return (await cdp.send('DOM.resolveNode', { ...params }));
133
+ }
134
+ try {
135
+ const resolved = (await sendInWorld(cdp, 'DOM.resolveNode', { ...params }, (executionContextId) => ({ ...params, executionContextId })));
136
+ if (await usableInWorld(cdp, resolved.object.objectId))
137
+ return resolved;
138
+ }
139
+ catch (error) {
140
+ log.debug(`Node resolved in the page's world: ${getErrorMessage(error)}`);
141
+ }
142
+ return (await cdp.send('DOM.resolveNode', { ...params }));
143
+ }
144
+ /**
145
+ * Whether a node resolved into bdg's world can be used there: a node of a
146
+ * cross-origin frame resolves, but every access to it throws.
147
+ *
148
+ * @param cdp - Connection to the page
149
+ * @param objectId - The node in bdg's world
150
+ * @returns True when it can be read
151
+ */
152
+ async function usableInWorld(cdp, objectId) {
153
+ if (!objectId)
154
+ return false;
155
+ const probe = (await cdp.send('Runtime.callFunctionOn', {
156
+ objectId,
157
+ functionDeclaration: 'function () { try { return this.isConnected === true; } catch (e) { return false; } }',
158
+ returnByValue: true,
159
+ }));
160
+ return probe.result.value === true;
161
+ }
162
+ /**
163
+ * Send a CDP command for bdg's own scripts: `Runtime.evaluate` and
164
+ * `DOM.resolveNode` go to bdg's world, other methods as they are.
165
+ *
166
+ * @param cdp - Connection to the page
167
+ * @param method - CDP method
168
+ * @param params - Its parameters
169
+ * @returns The command's result
170
+ */
171
+ export function sendForBdgScript(cdp, method, params) {
172
+ if (method === 'Runtime.evaluate') {
173
+ return evaluateInBdgWorld(cdp, params);
174
+ }
175
+ if (method === 'DOM.resolveNode') {
176
+ return resolveNodeInBdgWorld(cdp, params);
177
+ }
178
+ return cdp.send(method, params);
179
+ }
180
+ //# sourceMappingURL=bdgWorld.js.map
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Which browser built-ins a page replaced (polyfills, old frameworks,
3
+ * anti-bot scripts). Scripts that must run in the page's own world (actions,
4
+ * `dom eval` results) depend on them.
5
+ *
6
+ * The check does not trust the page: a small page script only collects the
7
+ * functions (plain property reads and the page's
8
+ * `Object.getOwnPropertyDescriptor`, itself checked), and whether each is
9
+ * native comes from the description CDP gives a function, which V8 builds
10
+ * itself, so a replaced `Function.prototype.toString` or `.call` changes
11
+ * nothing. A getter or setter counts as the property (a page-defined getter
12
+ * on `window.getComputedStyle`, a replaced `value` setter); a property that
13
+ * throws or is gone counts as replaced. An iterator is not checked when the
14
+ * page replaced `Symbol` (iteration does not use it).
15
+ */
16
+ import type { CDPSender } from '../../telemetry/objectExpander.js';
17
+ /**
18
+ * The built-ins of a list that the page replaced.
19
+ *
20
+ * @param cdp - CDP connection (or session) of the page
21
+ * @param names - Dotted paths, e.g. `Element.prototype.matches`,
22
+ * `window.getComputedStyle`, `NodeList.prototype[Symbol.iterator]`
23
+ * @param objectId - An object of the realm to check (e.g. a frame's eval
24
+ * result); default: the page's main world
25
+ * @returns The replaced ones, in list order (empty when the check failed)
26
+ */
27
+ export declare function findReplacedBuiltins(cdp: CDPSender, names: readonly string[], objectId?: string): Promise<string[]>;
28
+ //# sourceMappingURL=replacedBuiltins.d.ts.map
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Which browser built-ins a page replaced (polyfills, old frameworks,
3
+ * anti-bot scripts). Scripts that must run in the page's own world (actions,
4
+ * `dom eval` results) depend on them.
5
+ *
6
+ * The check does not trust the page: a small page script only collects the
7
+ * functions (plain property reads and the page's
8
+ * `Object.getOwnPropertyDescriptor`, itself checked), and whether each is
9
+ * native comes from the description CDP gives a function, which V8 builds
10
+ * itself, so a replaced `Function.prototype.toString` or `.call` changes
11
+ * nothing. A getter or setter counts as the property (a page-defined getter
12
+ * on `window.getComputedStyle`, a replaced `value` setter); a property that
13
+ * throws or is gone counts as replaced. An iterator is not checked when the
14
+ * page replaced `Symbol` (iteration does not use it).
15
+ */
16
+ import { createLogger } from '../../ui/logging/index.js';
17
+ import { getErrorMessage } from '../../utils/errors.js';
18
+ const log = createLogger('dom');
19
+ /** Description V8 gives a native function, e.g. `function querySelector() { [native code] }` */
20
+ const NATIVE_FUNCTION = /\{\s*\[native code\]\s*\}$/;
21
+ /** Suffix naming a prototype's iterator, e.g. `NodeList.prototype[Symbol.iterator]` */
22
+ const ITERATOR_SUFFIX = '[Symbol.iterator]';
23
+ /** Path segment the collector reads as `Symbol.iterator` */
24
+ const ITERATOR_KEY = '@@iterator';
25
+ /** Object group of the collected functions (released after each check) */
26
+ const OBJECT_GROUP = 'bdg-builtins';
27
+ /**
28
+ * Page-side collector: for each name, the function(s) behind it, as a flat
29
+ * list of `index, function` pairs (`undefined` for one that throws or is
30
+ * gone). Uses no array or object helpers of the page.
31
+ *
32
+ * @param names - Dotted paths from the global object (a leading `window.` is
33
+ * skipped; a trailing `[Symbol.iterator]` names the iterator)
34
+ * @returns Function declaration
35
+ */
36
+ function collectorFunction(names) {
37
+ const paths = names.map((name) => name
38
+ .replace(/^window\./, '')
39
+ .replace(ITERATOR_SUFFIX, `.${ITERATOR_KEY}`)
40
+ .split('.'));
41
+ return `function () {
42
+ const paths = ${JSON.stringify(paths)};
43
+ const describe = Object.getOwnPropertyDescriptor;
44
+ const found = [];
45
+ const add = (i, value) => { found[found.length] = i; found[found.length] = value; };
46
+ for (let i = 0; i < paths.length; i++) {
47
+ const path = paths[i];
48
+ let key = path[path.length - 1];
49
+ let owner = window;
50
+ try {
51
+ for (let j = 0; j < path.length - 1; j++) owner = owner[path[j]];
52
+ } catch (e) { add(i, undefined); continue; }
53
+ if (key === '${ITERATOR_KEY}') {
54
+ try { key = Symbol.iterator; } catch (e) { continue; }
55
+ if (typeof key !== 'symbol') continue;
56
+ }
57
+ let own;
58
+ try { own = describe(owner, key); } catch (e) { own = undefined; }
59
+ if (own && (own.get || own.set)) {
60
+ if (own.get) add(i, own.get);
61
+ if (own.set) add(i, own.set);
62
+ } else if (own) {
63
+ add(i, own.value);
64
+ } else {
65
+ try { add(i, owner[key]); } catch (e) { continue; }
66
+ }
67
+ }
68
+ return found;
69
+ }`;
70
+ }
71
+ /**
72
+ * The built-ins of a list that the page replaced.
73
+ *
74
+ * @param cdp - CDP connection (or session) of the page
75
+ * @param names - Dotted paths, e.g. `Element.prototype.matches`,
76
+ * `window.getComputedStyle`, `NodeList.prototype[Symbol.iterator]`
77
+ * @param objectId - An object of the realm to check (e.g. a frame's eval
78
+ * result); default: the page's main world
79
+ * @returns The replaced ones, in list order (empty when the check failed)
80
+ */
81
+ export async function findReplacedBuiltins(cdp, names, objectId) {
82
+ const functionDeclaration = collectorFunction(names);
83
+ try {
84
+ const collected = (await (objectId
85
+ ? cdp.send('Runtime.callFunctionOn', {
86
+ objectId,
87
+ functionDeclaration,
88
+ objectGroup: OBJECT_GROUP,
89
+ })
90
+ : cdp.send('Runtime.evaluate', {
91
+ expression: `(${functionDeclaration})()`,
92
+ objectGroup: OBJECT_GROUP,
93
+ })));
94
+ const listId = collected.result.objectId;
95
+ if (collected.exceptionDetails || !listId)
96
+ return [];
97
+ const { result } = (await cdp.send('Runtime.getProperties', {
98
+ objectId: listId,
99
+ ownProperties: true,
100
+ }));
101
+ return replacedNames(names, result);
102
+ }
103
+ catch (error) {
104
+ log.debug(`Built-ins not checked: ${getErrorMessage(error)}`);
105
+ return [];
106
+ }
107
+ finally {
108
+ await cdp
109
+ .send('Runtime.releaseObjectGroup', { objectGroup: OBJECT_GROUP })
110
+ .catch((error) => log.debug(`Built-ins not released: ${getErrorMessage(error)}`));
111
+ }
112
+ }
113
+ /**
114
+ * Names whose collected function is not native.
115
+ *
116
+ * @param names - The names checked
117
+ * @param properties - Properties of the collected `index, function` list
118
+ * @returns Replaced names, in list order
119
+ */
120
+ function replacedNames(names, properties) {
121
+ const entries = new Map();
122
+ for (const property of properties) {
123
+ if (/^\d+$/.test(property.name))
124
+ entries.set(Number(property.name), property.value);
125
+ }
126
+ const replaced = new Set();
127
+ for (let i = 0; entries.has(i); i += 2) {
128
+ const index = entries.get(i)?.value;
129
+ const value = entries.get(i + 1);
130
+ const native = value?.type === 'function' && NATIVE_FUNCTION.test(value.description ?? '');
131
+ if (typeof index === 'number' && !native)
132
+ replaced.add(index);
133
+ }
134
+ return names.filter((_name, i) => replaced.has(i));
135
+ }
136
+ //# sourceMappingURL=replacedBuiltins.js.map
@@ -71,8 +71,11 @@ export declare class QueryCacheManager {
71
71
  * Store a query result.
72
72
  *
73
73
  * @param result - Query result whose nodes carry backend node ids
74
+ * @param document - Identity of the page document queried
75
+ * ({@link pageDocumentId}): backend node ids are only meaningful in it, and
76
+ * a page in a new renderer process reuses them for other elements
74
77
  */
75
- set(result: DomQueryResult): Promise<void>;
78
+ set(result: DomQueryResult, document?: string): Promise<void>;
76
79
  /**
77
80
  * Read the cache and check that it can be used.
78
81
  *
@@ -88,11 +88,14 @@ export class QueryCacheManager {
88
88
  * Store a query result.
89
89
  *
90
90
  * @param result - Query result whose nodes carry backend node ids
91
+ * @param document - Identity of the page document queried
92
+ * ({@link pageDocumentId}): backend node ids are only meaningful in it, and
93
+ * a page in a new renderer process reuses them for other elements
91
94
  */
92
- async set(result) {
95
+ async set(result, document) {
93
96
  try {
94
97
  const cachePath = this.getCachePath();
95
- await writeFile(cachePath, JSON.stringify({ version: CACHE_VERSION, ...result }), 'utf-8');
98
+ await writeFile(cachePath, JSON.stringify({ version: CACHE_VERSION, ...result, ...(document && { document }) }), 'utf-8');
96
99
  log.debug(`Cached ${result.nodes.length} query results to ${cachePath}`);
97
100
  }
98
101
  catch (error) {
@@ -41,8 +41,11 @@ export declare function readChromePid(): number | null;
41
41
  * Remove Chrome PID from persistent cache.
42
42
  *
43
43
  * Safe to call multiple times (idempotent).
44
+ *
45
+ * @param expectedPid - Remove it only while it still names this Chrome (a
46
+ * daemon clearing its own, which another daemon may have replaced)
44
47
  */
45
- export declare function clearChromePid(): void;
48
+ export declare function clearChromePid(expectedPid?: number): void;
46
49
  /** What `status --verbose` shows about the session's Chrome */
47
50
  export interface RunningChromeInfo {
48
51
  /** Executable the process was started from */
@@ -10,6 +10,7 @@ import { AtomicFileWriter } from '../utils/atomicFile.js';
10
10
  import { getErrorMessage } from '../utils/errors.js';
11
11
  import { getProcessCommand, isProcessAlive } from '../utils/process.js';
12
12
  import { getSessionFilePath, ensureSessionDir } from './paths.js';
13
+ import { readPidFromFile } from './pid.js';
13
14
  const log = createLogger('chrome');
14
15
  /**
15
16
  * Parse Chrome PID from cache file content.
@@ -100,9 +101,14 @@ export function readChromePid() {
100
101
  * Remove Chrome PID from persistent cache.
101
102
  *
102
103
  * Safe to call multiple times (idempotent).
104
+ *
105
+ * @param expectedPid - Remove it only while it still names this Chrome (a
106
+ * daemon clearing its own, which another daemon may have replaced)
103
107
  */
104
- export function clearChromePid() {
108
+ export function clearChromePid(expectedPid) {
105
109
  const cachePath = getSessionFilePath('CHROME_PID');
110
+ if (expectedPid !== undefined && readPidFromFile(cachePath) !== expectedPid)
111
+ return;
106
112
  try {
107
113
  fs.rmSync(cachePath, { force: true });
108
114
  }
@@ -9,9 +9,13 @@
9
9
  /**
10
10
  * Remove per-session files (metadata, query cache).
11
11
  *
12
- * Called by the daemon when its session ends, and by `bdg cleanup`.
12
+ * Called by the daemon when its session ends, and by `bdg cleanup`. A daemon
13
+ * passes its PID, so it never removes the files of another daemon that
14
+ * started in the same directory meanwhile.
15
+ *
16
+ * @param ownerPid - The daemon whose files these must be; omitted by cleanup
13
17
  */
14
- export declare function removeSessionFiles(): void;
18
+ export declare function removeSessionFiles(ownerPid?: number): void;
15
19
  /**
16
20
  * Remove daemon and session files if no daemon is listening.
17
21
  *
@@ -43,8 +47,21 @@ export declare function isSessionChrome(pid: number, sessionDir: string): boolea
43
47
  */
44
48
  export declare function killOrphanedChrome(): boolean;
45
49
  /**
46
- * Kill an orphaned Chrome (see {@link killOrphanedChrome}) and wait until it
47
- * has exited, so its debugging port is free for the next launch.
50
+ * Kill every Chrome launched for a session directory (its marker flag on the
51
+ * command line), whatever chrome.pid says: a Chrome whose PID file another
52
+ * daemon removed, or that a second start left behind, is found too. Only
53
+ * browser processes are signalled; their helper processes exit with them.
54
+ *
55
+ * @param sessionDir - Session directory
56
+ * @returns PIDs of the processes killed
57
+ */
58
+ export declare function killSessionChromes(sessionDir?: string): number[];
59
+ /**
60
+ * Kill the Chromes this session left behind and wait until they have exited,
61
+ * so their profile and debugging port are free for the next launch. The
62
+ * Chrome recorded in chrome.pid is killed (see {@link killOrphanedChrome});
63
+ * without a record (chrome.pid lost with its daemon), every Chrome carrying
64
+ * the session's marker is, unless another daemon of the session still runs.
48
65
  *
49
66
  * @returns True if a Chrome process was killed
50
67
  */
@@ -10,13 +10,14 @@ import { chromeSessionMarkerFlag } from '../../connection/launcher/flagsBuilder.
10
10
  import { QueryCacheManager } from '../QueryCacheManager.js';
11
11
  import { clearChromePid, readChromePid } from '../chrome.js';
12
12
  import { probeDaemonSocket } from '../daemonSocket.js';
13
+ import { readSessionMetadata } from '../metadata.js';
13
14
  import { getSessionDir, getSessionFilePath, sessionFilePathIn } from '../paths.js';
14
15
  import { readPidFromFile } from '../pid.js';
15
16
  import { createLogger, logDebugError } from '../../ui/logging/index.js';
16
17
  import { delay } from '../../utils/async.js';
17
18
  import { safeRemoveFile } from '../../utils/file.js';
18
19
  import { DAEMON_SCRIPT_PATH } from '../../utils/packageRoot.js';
19
- import { getProcessCommand, isProcessAlive, killChromeProcess } from '../../utils/process.js';
20
+ import { getProcessCommand, isProcessAlive, killChromeProcess, listProcesses, } from '../../utils/process.js';
20
21
  const log = createLogger('cleanup');
21
22
  /**
22
23
  * Check whether a process command line contains an exact argument.
@@ -30,12 +31,39 @@ function hasArgument(command, arg) {
30
31
  return false;
31
32
  return command.includes(`${arg} `) || command.endsWith(arg);
32
33
  }
34
+ /**
35
+ * Check whether a command line contains an exact argument, followed by the
36
+ * end or by another option: a session directory with a space in it
37
+ * (`/tmp/a b`) does not match the marker of `/tmp/a`.
38
+ *
39
+ * @param command - Full command line
40
+ * @param arg - Argument to look for
41
+ * @returns True if `arg` appears as a whole argument
42
+ */
43
+ function hasWholeArgument(command, arg) {
44
+ for (let at = command.indexOf(arg); at !== -1; at = command.indexOf(arg, at + 1)) {
45
+ const before = at === 0 || command[at - 1] === ' ';
46
+ const rest = command.slice(at + arg.length);
47
+ if (before && (rest === '' || rest.startsWith(' -')))
48
+ return true;
49
+ }
50
+ return false;
51
+ }
33
52
  /**
34
53
  * Remove per-session files (metadata, query cache).
35
54
  *
36
- * Called by the daemon when its session ends, and by `bdg cleanup`.
55
+ * Called by the daemon when its session ends, and by `bdg cleanup`. A daemon
56
+ * passes its PID, so it never removes the files of another daemon that
57
+ * started in the same directory meanwhile.
58
+ *
59
+ * @param ownerPid - The daemon whose files these must be; omitted by cleanup
37
60
  */
38
- export function removeSessionFiles() {
61
+ export function removeSessionFiles(ownerPid) {
62
+ if (ownerPid !== undefined) {
63
+ const owner = readSessionMetadata()?.bdgPid;
64
+ if (owner !== undefined && owner !== ownerPid)
65
+ return;
66
+ }
39
67
  safeRemoveFile(getSessionFilePath('METADATA'), 'metadata file', log);
40
68
  void QueryCacheManager.getInstance()
41
69
  .clear()
@@ -103,22 +131,64 @@ export function killOrphanedChrome() {
103
131
  clearChromePid();
104
132
  return true;
105
133
  }
134
+ /**
135
+ * Kill every Chrome launched for a session directory (its marker flag on the
136
+ * command line), whatever chrome.pid says: a Chrome whose PID file another
137
+ * daemon removed, or that a second start left behind, is found too. Only
138
+ * browser processes are signalled; their helper processes exit with them.
139
+ *
140
+ * @param sessionDir - Session directory
141
+ * @returns PIDs of the processes killed
142
+ */
143
+ export function killSessionChromes(sessionDir = getSessionDir()) {
144
+ const marker = chromeSessionMarkerFlag(sessionDir);
145
+ const killed = [];
146
+ for (const { pid, command } of listProcesses()) {
147
+ if (pid === process.pid || !hasWholeArgument(command, marker) || / --type=/.test(command)) {
148
+ continue;
149
+ }
150
+ try {
151
+ killChromeProcess(pid, 'SIGKILL');
152
+ killed.push(pid);
153
+ log.info(`Killed Chrome of this session (PID ${pid})`);
154
+ }
155
+ catch (error) {
156
+ logDebugError(log, `kill Chrome ${pid}`, error);
157
+ }
158
+ }
159
+ if (killed.length > 0)
160
+ clearChromePid();
161
+ return killed;
162
+ }
106
163
  /** How long to wait for a killed orphaned Chrome to exit (and free its port) */
107
164
  const ORPHAN_EXIT_WAIT_MS = 5000;
108
165
  /**
109
- * Kill an orphaned Chrome (see {@link killOrphanedChrome}) and wait until it
110
- * has exited, so its debugging port is free for the next launch.
166
+ * Kill the Chromes this session left behind and wait until they have exited,
167
+ * so their profile and debugging port are free for the next launch. The
168
+ * Chrome recorded in chrome.pid is killed (see {@link killOrphanedChrome});
169
+ * without a record (chrome.pid lost with its daemon), every Chrome carrying
170
+ * the session's marker is, unless another daemon of the session still runs.
111
171
  *
112
172
  * @returns True if a Chrome process was killed
113
173
  */
114
174
  export async function reapOrphanedChrome() {
115
175
  const chromePid = findOrphanedChrome();
116
- if (!killOrphanedChrome() || chromePid === null)
117
- return false;
176
+ const killed = chromePid !== null ? (killOrphanedChrome() ? [chromePid] : []) : killUnrecordedChromes();
118
177
  const deadline = Date.now() + ORPHAN_EXIT_WAIT_MS;
119
- while (isProcessAlive(chromePid) && Date.now() < deadline)
178
+ while (killed.some(isProcessAlive) && Date.now() < deadline)
120
179
  await delay(50);
121
- return true;
180
+ return killed.length > 0;
181
+ }
182
+ /**
183
+ * Kill the session's Chromes found by their marker (see
184
+ * {@link killSessionChromes}), unless a daemon of the session other than
185
+ * this process still runs: they could be its Chrome.
186
+ *
187
+ * @returns PIDs of the processes killed
188
+ */
189
+ function killUnrecordedChromes() {
190
+ const daemonPid = readLiveDaemonPid();
191
+ return daemonPid === null || daemonPid === process.pid ? killSessionChromes() : [];
122
192
  }
123
193
  /**
124
194
  * Read the PID of a live bdg daemon from daemon.pid.
@@ -27,7 +27,10 @@ export interface SessionCleanupResult {
27
27
  *
28
28
  * With `force`, a live daemon is killed first (after verifying its command
29
29
  * line). Then stale daemon files are removed and an orphaned bdg Chrome, if
30
- * any, is killed.
30
+ * any, is killed, and, once no daemon of the session runs, every other
31
+ * Chrome launched for this session directory (one chrome.pid lost track of).
32
+ * The record of a session that ended without `bdg stop` is removed too, and
33
+ * counts as cleaned session files.
31
34
  *
32
35
  * @param options - Cleanup options
33
36
  * @returns What was cleaned, plus warnings