@deeeed/metamask-harness 0.79.0 → 0.81.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 (252) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +1 -1
  3. package/adapters/extension/ensure-browser.sh +2 -2
  4. package/adapters/extension/inject.mjs +0 -1
  5. package/adapters/extension/launch-browser.cjs +39 -613
  6. package/adapters/extension/readiness.mjs +2 -5
  7. package/adapters/extension/reattach.sh +2 -2
  8. package/adapters/extension/stamp-runtime-title.cjs +1 -1
  9. package/adapters/manifest.json +16 -64
  10. package/adapters/mobile/bridge-runtime/cdp-bridge.cjs +57 -1358
  11. package/adapters/mobile/bridge-runtime/teaching.cjs +20 -0
  12. package/adapters/mobile/inject.sh +16 -0
  13. package/adapters/mobile/launch-console-forwarder.cjs +1 -2
  14. package/adapters/mobile/open-device.sh +2 -2
  15. package/adapters/mobile/reload-app.mjs +4 -4
  16. package/adapters/mobile/reset-app-data.sh +1 -1
  17. package/adapters/mobile/start-console-forwarder.sh +3 -2
  18. package/adapters/mobile/start-metro.sh +17 -12
  19. package/adapters/mobile/wait-for-bridge.cjs +2 -2
  20. package/adapters/shared/harness-source-fingerprint.mjs +13 -8
  21. package/adapters/shared/open-debug.mjs +2 -2
  22. package/adapters/shared/sync-wallet-fixture.sh +8 -5
  23. package/adapters/terminal/cleanup.mjs +2 -1
  24. package/adapters/terminal/inject.mjs +2 -1
  25. package/adapters/terminal/launch.mjs +17 -13
  26. package/adapters/terminal/lib/mainnet-guard.mjs +9 -0
  27. package/adapters/terminal/lib/readiness.mjs +20 -12
  28. package/adapters/terminal/policy.mjs +35 -0
  29. package/adapters/terminal/verify.mjs +10 -3
  30. package/adapters/terminal/wallet-host.mjs +43 -225
  31. package/bin/mm-harness +9 -28
  32. package/dist/adapters/checkout-files.js +16 -0
  33. package/dist/adapters/console-capture.js +14 -1
  34. package/dist/adapters/core/actions.js +8 -4
  35. package/dist/adapters/core/overlay.js +1 -1
  36. package/dist/adapters/core/readiness.js +28 -1
  37. package/dist/adapters/core/run.js +2 -2
  38. package/dist/adapters/core/surface.js +16 -1
  39. package/dist/adapters/extension/actions.js +6 -2
  40. package/dist/adapters/extension/browser-pid.js +56 -0
  41. package/dist/adapters/extension/console-capture.js +1 -1
  42. package/dist/adapters/extension/doctor-checks.js +1 -1
  43. package/dist/adapters/extension/ensure-ready.js +5 -4
  44. package/dist/adapters/extension/extension-id.js +1 -1
  45. package/dist/adapters/extension/feature-flags.js +1 -1
  46. package/dist/adapters/extension/fixtures.js +1 -2
  47. package/dist/adapters/extension/launch.js +4 -5
  48. package/dist/adapters/extension/launched-browser.js +1 -2
  49. package/dist/adapters/extension/network-observer.js +14 -1
  50. package/dist/adapters/extension/overlay.js +1 -1
  51. package/dist/adapters/extension/product-config.js +1 -1
  52. package/dist/adapters/extension/readiness.js +1 -1
  53. package/dist/adapters/extension/reload.js +1 -1
  54. package/dist/adapters/extension/run.js +135 -14
  55. package/dist/adapters/extension/runtime-decision.js +2 -1
  56. package/dist/adapters/extension/runtime.js +9 -5
  57. package/dist/adapters/extension/surface.js +15 -2
  58. package/dist/adapters/extension/verify.js +2 -2
  59. package/dist/adapters/harness-freshness.js +2 -1
  60. package/dist/adapters/mobile/actions.js +4 -1
  61. package/dist/adapters/mobile/android-gfxinfo-performance.js +1 -3
  62. package/dist/adapters/mobile/app-identity.js +10 -0
  63. package/dist/adapters/mobile/doctor-checks.js +1 -1
  64. package/dist/adapters/mobile/fixtures.js +1 -1
  65. package/dist/adapters/mobile/launch.js +27 -28
  66. package/dist/adapters/mobile/lifecycle.js +1 -1
  67. package/dist/adapters/mobile/metro-env.js +9 -59
  68. package/dist/adapters/mobile/network-observer.js +68 -0
  69. package/dist/adapters/mobile/performance-observer.js +2 -4
  70. package/dist/adapters/mobile/prepare-target.js +1 -1
  71. package/dist/adapters/mobile/prepare.js +3 -4
  72. package/dist/adapters/mobile/provision.js +1 -1
  73. package/dist/adapters/mobile/readiness.js +1 -1
  74. package/dist/adapters/mobile/recording-target.js +15 -0
  75. package/dist/adapters/mobile/release-artifact-state.js +1 -1
  76. package/dist/adapters/mobile/reload.js +1 -1
  77. package/dist/adapters/mobile/run.js +39 -15
  78. package/dist/adapters/mobile/runtime-decision.js +2 -4
  79. package/dist/adapters/mobile/source-freshness.js +22 -126
  80. package/dist/adapters/mobile/surface.js +26 -3
  81. package/dist/adapters/mobile/ui.js +16 -5
  82. package/dist/adapters/mobile/verify.js +2 -3
  83. package/dist/adapters/performance/cdp-trace.js +1 -1
  84. package/dist/adapters/performance/device-platform.js +1 -1
  85. package/dist/adapters/perps-order-inputs.js +36 -0
  86. package/dist/adapters/proof-failure.js +11 -0
  87. package/dist/adapters/slot-ports.js +1 -1
  88. package/dist/adapters/surface.js +1 -0
  89. package/dist/adapters/terminal/actions.js +4 -1
  90. package/dist/adapters/terminal/console-capture.js +1 -1
  91. package/dist/adapters/terminal/doctor-checks.js +2 -0
  92. package/dist/adapters/terminal/launch.js +4 -1
  93. package/dist/adapters/terminal/overlay.js +8 -1
  94. package/dist/adapters/terminal/run.js +33 -5
  95. package/dist/adapters/terminal/surface.js +9 -1
  96. package/dist/adapters.js +27 -7
  97. package/dist/advisor-policy.js +1 -1
  98. package/dist/checkout-view.js +1 -2
  99. package/dist/cli.js +59 -21
  100. package/dist/command-contract.js +1 -26
  101. package/dist/commands/check.js +33 -10
  102. package/dist/commands/checklist.js +1 -1
  103. package/dist/commands/completion-candidates.js +6 -14
  104. package/dist/commands/config.js +2 -2
  105. package/dist/commands/core-readiness.js +12 -7
  106. package/dist/commands/debug.js +3 -3
  107. package/dist/commands/device-target.js +5 -5
  108. package/dist/commands/doctor.js +2 -14
  109. package/dist/commands/domain.js +2 -2
  110. package/dist/commands/ensure-ready.js +1 -7
  111. package/dist/commands/fixtures.js +5 -6
  112. package/dist/commands/help.js +3 -4
  113. package/dist/commands/launch/device.js +10 -17
  114. package/dist/commands/launch/extension.js +2 -8
  115. package/dist/commands/launch/mobile.js +1 -1
  116. package/dist/commands/logs.js +3 -3
  117. package/dist/commands/mobile-device-view.js +4 -2
  118. package/dist/commands/overlay.js +110 -0
  119. package/dist/commands/pin.js +1 -1
  120. package/dist/commands/pr-body.js +2 -2
  121. package/dist/commands/prepare.js +4 -9
  122. package/dist/commands/provision.js +3 -12
  123. package/dist/commands/recipe-advice.js +1 -2
  124. package/dist/commands/recipe-quality.js +2 -3
  125. package/dist/commands/resolve-extension.js +1 -7
  126. package/dist/commands/review.js +4 -4
  127. package/dist/commands/runtime-decision.js +1 -6
  128. package/dist/commands/runtime-health.js +1 -7
  129. package/dist/commands/runtime-launch.js +1 -13
  130. package/dist/commands/self-test.js +5 -8
  131. package/dist/commands/status-watch.js +1 -2
  132. package/dist/commands/status.js +2 -5
  133. package/dist/commands/task-init.js +2 -3
  134. package/dist/commands/tutorial.js +2 -2
  135. package/dist/commands/update.js +1 -1
  136. package/dist/completions-cache.js +1 -1
  137. package/dist/console-classifier.js +19 -0
  138. package/dist/doctor.js +2 -3
  139. package/dist/engine.js +57 -0
  140. package/dist/funding-execution-context.js +96 -1
  141. package/dist/host.js +32 -0
  142. package/dist/index.js +1 -6
  143. package/dist/live-tsx.js +49 -0
  144. package/dist/mm-harness-cli.js +4 -6
  145. package/dist/paths.js +34 -64
  146. package/dist/performance-observation.js +3 -5
  147. package/dist/progress.js +1 -1
  148. package/dist/recipe-assistance-context.js +6 -9
  149. package/dist/recipe-security.js +2 -59
  150. package/dist/review/knowledge.js +2 -2
  151. package/dist/runner.js +7 -4
  152. package/dist/runtime-context.js +1 -1
  153. package/dist/task-view.js +2 -3
  154. package/docs/CONTRIBUTING.md +5 -3
  155. package/docs/RECIPES.md +31 -3
  156. package/docs/cli-contract.md +2 -2
  157. package/docs/feature-guard.md +90 -0
  158. package/library/README.md +3 -1
  159. package/library/actions/core/perps/_controller.mjs +153 -134
  160. package/library/actions/core/perps/_rewards.mjs +186 -0
  161. package/library/actions/core/perps/close_positions.mjs +1 -1
  162. package/library/actions/core/perps/place_order.mjs +167 -45
  163. package/library/actions/core/perps/quote_fees.mjs +61 -0
  164. package/library/actions/core/wallet/list_accounts.mjs +14 -57
  165. package/library/actions/extension/feature_flags/state.mjs +1 -1
  166. package/library/actions/extension/perps/close_visible_position.mjs +5 -0
  167. package/library/actions/extension/perps/edit_margin.mjs +4 -0
  168. package/library/actions/extension/perps/mutation-receipt.mjs +95 -3
  169. package/library/actions/extension/perps/perps.mjs +320 -3
  170. package/library/actions/extension/perps/place_order.mjs +3 -1
  171. package/library/actions/extension/perps/update_position_tpsl.mjs +4 -0
  172. package/library/actions/extension/platform/cdp.mjs +73 -11
  173. package/library/actions/harness-exports.mjs +1 -6
  174. package/library/actions/mobile/app/network-control.mjs +6 -8
  175. package/library/actions/mobile/perps/perps.mjs +216 -11
  176. package/library/actions/mobile/perps/place_order.mjs +3 -1
  177. package/library/actions/mobile/perps/prepare_local_snapshot_endpoint.mjs +1 -1
  178. package/library/actions/mobile/platform/bridge.mjs +8 -8
  179. package/library/actions/mobile/platform/native-session-name.mjs +21 -1
  180. package/library/actions/mobile/platform/native-session.mjs +3 -4
  181. package/library/actions/mobile/platform/observe-ui.mjs +12 -6
  182. package/library/actions/mobile/ui/native-navigation.mjs +4 -3
  183. package/library/actions/mobile/wallet/native-ui.mjs +3 -2
  184. package/library/actions/shared/analytics/_adapter.mjs +1 -1
  185. package/library/actions/shared/console-findings.mjs +1 -1
  186. package/library/actions/shared/perps/order-policy.mjs +177 -0
  187. package/library/actions/shared/wallet/fixture-accounts.mjs +84 -0
  188. package/library/actions/terminal/app/launch.mjs +3 -2
  189. package/library/actions/terminal/platform/hud.mjs +2 -1
  190. package/library/actions/terminal/platform/page.mjs +2 -1
  191. package/library/actions/terminal/platform/runtime.mjs +2 -1
  192. package/library/actions/terminal/wallet/_signature-log.mjs +40 -161
  193. package/library/actions/terminal/wallet/assert_signatures.mjs +6 -12
  194. package/library/actions/terminal/wallet/read_signatures.mjs +10 -9
  195. package/library/manifests/core.action-manifest.json +87 -13
  196. package/library/manifests/extension.action-manifest.json +4 -0
  197. package/library/manifests/mobile.action-manifest.json +12 -0
  198. package/package.json +8 -9
  199. package/site/assets/help-recipes.json +1 -0
  200. package/adapters/extension/lib/slot-title.cjs +0 -292
  201. package/adapters/mobile/bridge-runtime/console-forwarder.cjs +0 -472
  202. package/adapters/mobile/bridge-runtime/lib/bridge-errors.cjs +0 -125
  203. package/adapters/mobile/bridge-runtime/lib/cdp-broker.cjs +0 -1055
  204. package/adapters/mobile/bridge-runtime/lib/cdp-eval.cjs +0 -110
  205. package/adapters/mobile/bridge-runtime/lib/config.cjs +0 -61
  206. package/adapters/mobile/bridge-runtime/lib/console-format.cjs +0 -53
  207. package/adapters/mobile/bridge-runtime/lib/devtools-proxy.cjs +0 -177
  208. package/adapters/mobile/bridge-runtime/lib/issue-capture.cjs +0 -446
  209. package/adapters/mobile/bridge-runtime/lib/match-bridge-target.cjs +0 -84
  210. package/adapters/mobile/bridge-runtime/lib/target-discovery.cjs +0 -403
  211. package/adapters/mobile/bridge-runtime/lib/ws-client.cjs +0 -116
  212. package/adapters/mobile/coalesce-metro-log.cjs +0 -24
  213. package/adapters/mobile/launch-metro.cjs +0 -77
  214. package/adapters/mobile/metro-config.cjs +0 -98
  215. package/adapters/mobile/metro-log-generation.cjs +0 -106
  216. package/adapters/terminal/lib/origin.mjs +0 -30
  217. package/adapters/terminal/lib/page-script.mjs +0 -246
  218. package/adapters/terminal/lib/strict-wallet.mjs +0 -138
  219. package/dist/adapters/mobile/frame-metrics.js +0 -118
  220. package/dist/adapters/mobile/video-recorder.js +0 -289
  221. package/dist/artifact-files.js +0 -92
  222. package/dist/checkout-lock.js +0 -149
  223. package/dist/cli-color.js +0 -98
  224. package/dist/command-journal.js +0 -308
  225. package/dist/commands/call.js +0 -685
  226. package/dist/commands/last.js +0 -60
  227. package/dist/commands/launch/index.js +0 -109
  228. package/dist/commands/list-executables.js +0 -247
  229. package/dist/commands/manifest.js +0 -488
  230. package/dist/commands/parse-args.js +0 -279
  231. package/dist/commands/reload.js +0 -41
  232. package/dist/commands/run-engine.js +0 -1340
  233. package/dist/commands/run-report.js +0 -241
  234. package/dist/commands/run.js +0 -751
  235. package/dist/commands/shared.js +0 -323
  236. package/dist/commands/stop.js +0 -60
  237. package/dist/devices.js +0 -100
  238. package/dist/discovery.js +0 -15
  239. package/dist/execution-provenance.js +0 -332
  240. package/dist/harness.js +0 -451
  241. package/dist/heal-bounds.js +0 -137
  242. package/dist/json-stream.js +0 -60
  243. package/dist/leaf-invoke.js +0 -19
  244. package/dist/library-provenance.js +0 -33
  245. package/dist/live-adapter-contract.js +0 -380
  246. package/dist/metamask-action-validation.js +0 -68
  247. package/dist/network-observation.js +0 -290
  248. package/dist/recording-target.js +0 -120
  249. package/dist/run-diagnostics.js +0 -364
  250. package/dist/run-recording.js +0 -481
  251. package/dist/runtime-proof.js +0 -90
  252. package/library/actions/mobile/platform/tool-paths.mjs +0 -123
@@ -1,110 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Evaluate a JS expression in the app's Hermes runtime via CDP Runtime.evaluate.
5
- * Returns the evaluated value (primitives and JSON-serialisable objects).
6
- */
7
- async function cdpEval(client, expression) {
8
- // Hermes doesn't support async in Runtime.evaluate, use a plain IIFE
9
- const wrapped = `(function() { return (${expression}); })()`;
10
- const result = await client.send('Runtime.evaluate', {
11
- expression: wrapped,
12
- returnByValue: true,
13
- awaitPromise: false,
14
- generatePreview: false,
15
- });
16
-
17
- if (result.exceptionDetails) {
18
- const desc =
19
- result.exceptionDetails.exception?.description ||
20
- result.exceptionDetails.text ||
21
- JSON.stringify(result.exceptionDetails);
22
- throw new Error(`Evaluation error: ${desc}`);
23
- }
24
-
25
- return result.result?.value;
26
- }
27
-
28
- /**
29
- * Evaluate a JS expression that returns a Promise.
30
- * Hermes CDP doesn't support awaitPromise, so we store the result on
31
- * globalThis.__cdp_async__ and poll for it.
32
- */
33
- async function cdpEvalAsync(client, expression, timeoutMs = cdpMessageTimeout()) {
34
- // Unique key per call to avoid collisions
35
- const key = `__cdp_async_${Date.now()}_${Math.random().toString(36).slice(2)}__`;
36
-
37
- // Kick off the promise, store result when done.
38
- // The try/catch guards against synchronous throws during argument evaluation
39
- // of Promise.resolve(<expression>) — without it, a sync error escapes the
40
- // IIFE and globalThis[key] stays 'pending' forever.
41
- const kickoff = `(function() {
42
- globalThis['${key}'] = { status: 'pending' };
43
- try {
44
- Promise.resolve(${expression})
45
- .then(function(v) { globalThis['${key}'] = { status: 'resolved', value: v }; })
46
- .catch(function(e) { globalThis['${key}'] = { status: 'rejected', error: String(e) }; });
47
- } catch(e) {
48
- globalThis['${key}'] = { status: 'rejected', error: String(e) };
49
- }
50
- return 'started';
51
- })()`;
52
-
53
- const kickoffResult = await client.send('Runtime.evaluate', {
54
- expression: kickoff,
55
- returnByValue: true,
56
- awaitPromise: false,
57
- }, timeoutMs);
58
-
59
- // If the IIFE itself failed to evaluate (syntax error, etc.), bail early
60
- if (kickoffResult.exceptionDetails) {
61
- const desc =
62
- kickoffResult.exceptionDetails.exception?.description ||
63
- kickoffResult.exceptionDetails.text ||
64
- JSON.stringify(kickoffResult.exceptionDetails);
65
- throw new Error(`Async evaluation error: ${desc}`);
66
- }
67
-
68
- // Best-effort cleanup — swallow errors so a disconnected WebSocket
69
- // doesn't obscure the actual result or diagnostic error.
70
- const cleanup = () =>
71
- client
72
- .send('Runtime.evaluate', {
73
- expression: `delete globalThis['${key}']`,
74
- returnByValue: true,
75
- awaitPromise: false,
76
- })
77
- // eslint-disable-next-line no-empty-function
78
- .catch(() => {});
79
-
80
- // Poll for completion
81
- const pollInterval = 200;
82
- const deadline = Date.now() + timeoutMs;
83
- try {
84
- while (Date.now() < deadline) {
85
- await new Promise((r) => setTimeout(r, pollInterval));
86
- const check = await client.send('Runtime.evaluate', {
87
- expression: `(function() { return globalThis['${key}']; })()`,
88
- returnByValue: true,
89
- awaitPromise: false,
90
- }, timeoutMs);
91
- const val = check.result?.value;
92
- if (val?.status === 'resolved') {
93
- return val.value;
94
- }
95
- if (val?.status === 'rejected') {
96
- throw new Error(`Async evaluation error: ${val.error}`);
97
- }
98
- }
99
- throw new Error(`Async evaluation timed out after ${timeoutMs}ms`);
100
- } finally {
101
- await cleanup();
102
- }
103
- }
104
-
105
- function cdpMessageTimeout() {
106
- const timeoutMs = Number.parseInt(process.env.CDP_TIMEOUT || '30000', 10);
107
- return Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 30000;
108
- }
109
-
110
- module.exports = { cdpEval, cdpEvalAsync };
@@ -1,61 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
-
6
- /** Read a value from .js.env */
7
- function loadEnvValue(key, appRoot = process.env.APP_ROOT || process.cwd()) {
8
- try {
9
- const envPath = path.resolve(appRoot, '.js.env');
10
- const content = fs.readFileSync(envPath, 'utf8');
11
- // .js.env uses `export KEY="value"` (shell-sourceable format),
12
- // so we handle the optional `export` prefix and strip surrounding quotes.
13
- const match = content.match(new RegExp(String.raw`^(?:export\s+)?${key}=(.+)$`, 'm'));
14
- if (match) return match[1].trim().replace(/^["']/, '').replace(/["']$/, '');
15
- } catch {
16
- // .js.env may not exist — fall through to undefined
17
- }
18
- return undefined;
19
- }
20
-
21
- function resolvePort(env = process.env, appRoot = env.APP_ROOT || process.cwd()) {
22
- return (
23
- env.WATCHER_PORT ||
24
- env.METRO_PORT ||
25
- loadEnvValue('WATCHER_PORT', appRoot) ||
26
- loadEnvValue('METRO_PORT', appRoot) ||
27
- '8081'
28
- );
29
- }
30
-
31
- /** Read WATCHER_PORT from .js.env or env (default: 8081) */
32
- function loadPort() {
33
- return Number.parseInt(resolvePort(), 10);
34
- }
35
-
36
- /** Read IOS_SIMULATOR name from .js.env or env (default: none — accept any device) */
37
- function loadSimulatorName() {
38
- // Explicit empty string in env means "no simulator" — don't fall through to .js.env
39
- if ('IOS_SIMULATOR' in process.env) return process.env.IOS_SIMULATOR;
40
- return loadEnvValue('IOS_SIMULATOR') || '';
41
- }
42
-
43
- /** Read ANDROID_DEVICE from .js.env or env (default: none — accept any device) */
44
- function loadAndroidDevice() {
45
- if ('ANDROID_DEVICE' in process.env) return process.env.ANDROID_DEVICE;
46
- return loadEnvValue('ANDROID_DEVICE') || '';
47
- }
48
-
49
- /**
50
- * Read ANDROID_TARGET_DEVICE_NAME from env — the Metro-compatible model prefix
51
- * resolved from an adb serial by bridge.mjs. Used by target-discovery to select
52
- * the correct Metro CDP target when multiple devices are connected.
53
- *
54
- * Set automatically by the bridge when --device <serial> is used. Users never
55
- * need to set this; pass --device <adb-serial> and the harness maps it internally.
56
- */
57
- function loadAndroidTargetDeviceName() {
58
- return process.env.ANDROID_TARGET_DEVICE_NAME || '';
59
- }
60
-
61
- module.exports = { loadEnvValue, loadPort, resolvePort, loadSimulatorName, loadAndroidDevice, loadAndroidTargetDeviceName };
@@ -1,53 +0,0 @@
1
- 'use strict';
2
-
3
- // Render CDP Runtime.consoleAPICalled args (RemoteObjects) into a log line.
4
- // Primitives carry `value`; objects/arrays do not — a bare console.log(obj)
5
- // arrived as the literal "Object". Hermes ships an inline `preview` (the same
6
- // one React Native DevTools renders in its console), so objects expand from it
7
- // synchronously — no extra CDP round-trip, so the stream never blocks. Depth is
8
- // bounded because previews nest one level via `valuePreview`; beyond that the
9
- // child preview's own description is used.
10
-
11
- const MAX_PREVIEW_DEPTH = 2;
12
-
13
- function formatPropertyValue(prop, depth) {
14
- if (prop.valuePreview && depth < MAX_PREVIEW_DEPTH) {
15
- return formatPreview(prop.valuePreview, depth + 1);
16
- }
17
- if (prop.type === 'string' && prop.value !== undefined) return JSON.stringify(prop.value);
18
- if (prop.value !== undefined) return String(prop.value);
19
- return prop.subtype || prop.type || '';
20
- }
21
-
22
- function formatPreview(preview, depth) {
23
- const properties = Array.isArray(preview.properties) ? preview.properties : [];
24
- const overflow = preview.overflow ? ', …' : '';
25
- if (preview.subtype === 'array') {
26
- return `[${properties.map((p) => formatPropertyValue(p, depth)).join(', ')}${overflow}]`;
27
- }
28
- const body = properties.map((p) => `${p.name}: ${formatPropertyValue(p, depth)}`).join(', ');
29
- // Name a non-plain constructor (Error, Map, custom class) so the class is not lost.
30
- const ctor = preview.description && preview.description !== 'Object' ? `${preview.description} ` : '';
31
- return properties.length > 0 || overflow ? `${ctor}{ ${body}${overflow} }` : `${ctor}{}`;
32
- }
33
-
34
- function formatRemoteObject(a) {
35
- if (!a || typeof a !== 'object') return String(a == null ? '' : a);
36
- // Primitives (number/boolean/string) carry a directly-usable value.
37
- if (a.type !== 'object' && a.type !== 'function' && a.value !== undefined) return String(a.value);
38
- if (a.type === 'undefined') return 'undefined';
39
- if (a.subtype === 'null') return 'null';
40
- if (a.preview) return formatPreview(a.preview, 1);
41
- // Functions, errors, and objects with no preview: the description is the best
42
- // available text (className / Error stack / etc.); fall back to bare value/type.
43
- if (a.description !== undefined) return a.description;
44
- if (a.value !== undefined) return String(a.value);
45
- return a.type || '';
46
- }
47
-
48
- function formatArgs(args, maxLineChars) {
49
- const text = (args || []).map(formatRemoteObject).join(' ');
50
- return maxLineChars && text.length > maxLineChars ? `${text.slice(0, maxLineChars)}…` : text;
51
- }
52
-
53
- module.exports = { formatArgs, formatRemoteObject, formatPreview };
@@ -1,177 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const { WebSocket, WebSocketServer } = require('ws');
5
-
6
- const MAX_FRAME_BYTES = 8 * 1024 * 1024;
7
- const SESSION_TIMEOUT_MS = 10_000;
8
- const EVENT_GATED_DOMAINS = new Set([
9
- 'Debugger',
10
- 'Log',
11
- 'Network',
12
- 'Page',
13
- 'ReactNativeApplication',
14
- 'Runtime',
15
- ]);
16
-
17
- function createDevtoolsProxy({
18
- descriptorPath,
19
- sessions,
20
- sendCommand,
21
- requestDiscovery,
22
- allowedOrigins,
23
- }) {
24
- if (!Array.isArray(allowedOrigins) || allowedOrigins.length === 0) {
25
- throw new Error('DevTools proxy requires at least one allowed Origin');
26
- }
27
- let listeningPort = null;
28
- const clients = new Set();
29
- const server = new WebSocketServer({
30
- host: '127.0.0.1',
31
- port: 0,
32
- maxPayload: MAX_FRAME_BYTES,
33
- });
34
-
35
- async function waitForSession(deviceId) {
36
- const ready = sessions.get(deviceId);
37
- if (ready?.brokerReady) return ready;
38
- requestDiscovery();
39
- const deadline = Date.now() + SESSION_TIMEOUT_MS;
40
- while (Date.now() < deadline) {
41
- await new Promise((resolve) => setTimeout(resolve, 100));
42
- const session = sessions.get(deviceId);
43
- if (session?.brokerReady) return session;
44
- }
45
- throw new Error('Hermes runtime is unavailable or reloading; retry the command');
46
- }
47
-
48
- function writeDescriptor() {
49
- if (!listeningPort) return;
50
- fs.writeFileSync(
51
- descriptorPath,
52
- `${JSON.stringify({ schemaVersion: 1, pid: process.pid, port: listeningPort })}\n`,
53
- { mode: 0o600 },
54
- );
55
- }
56
-
57
- async function forward(client, message) {
58
- if (
59
- !message ||
60
- typeof message !== 'object' ||
61
- !Number.isInteger(message.id) ||
62
- typeof message.method !== 'string'
63
- ) {
64
- return;
65
- }
66
- if (message.method.endsWith('.disable')) {
67
- client.enabled.delete(message.method.replace(/\.disable$/u, '.enable'));
68
- if (client.socket.readyState === WebSocket.OPEN) {
69
- client.socket.send(JSON.stringify({ id: message.id, result: {} }));
70
- }
71
- return;
72
- }
73
- const isEnable = message.method.endsWith('.enable');
74
- if (isEnable) {
75
- client.enabled.set(message.method, message.params || {});
76
- }
77
- try {
78
- const session = await waitForSession(client.deviceId);
79
- const result = await sendCommand(
80
- session,
81
- message.method,
82
- message.params || {},
83
- SESSION_TIMEOUT_MS,
84
- );
85
- if (client.socket.readyState === WebSocket.OPEN) {
86
- client.socket.send(JSON.stringify({ id: message.id, result }));
87
- }
88
- } catch (error) {
89
- if (isEnable) client.enabled.delete(message.method);
90
- if (client.socket.readyState === WebSocket.OPEN) {
91
- client.socket.send(
92
- JSON.stringify({
93
- id: message.id,
94
- error: {
95
- code: -32000,
96
- message: String(error?.message || error).slice(0, 256),
97
- },
98
- }),
99
- );
100
- }
101
- }
102
- }
103
-
104
- server.on('connection', (socket, request) => {
105
- const url = new URL(request.url || '/', 'http://127.0.0.1');
106
- const deviceId = url.searchParams.get('device');
107
- if (
108
- !deviceId ||
109
- !allowedOrigins.includes(request.headers.origin)
110
- ) {
111
- socket.close(1008, 'invalid DevTools proxy Origin or device');
112
- return;
113
- }
114
- for (const client of clients) {
115
- if (client.deviceId === deviceId) {
116
- client.socket.close(1000, 'replaced by a newer DevTools window');
117
- }
118
- }
119
- const client = { socket, deviceId, enabled: new Map() };
120
- clients.add(client);
121
- socket.on('message', (data) => {
122
- let message;
123
- try {
124
- message = JSON.parse(String(data));
125
- } catch {
126
- return;
127
- }
128
- void forward(client, message);
129
- });
130
- const drop = () => clients.delete(client);
131
- socket.on('close', drop);
132
- socket.on('error', drop);
133
- });
134
-
135
- server.on('listening', () => {
136
- const address = server.address();
137
- if (!address || typeof address === 'string') return;
138
- listeningPort = address.port;
139
- writeDescriptor();
140
- });
141
-
142
- return {
143
- onSessionOpen(deviceId, session) {
144
- for (const client of clients) {
145
- if (client.deviceId !== deviceId) continue;
146
- for (const [method, params] of client.enabled) {
147
- void sendCommand(session, method, params, SESSION_TIMEOUT_MS).catch(
148
- () => undefined,
149
- );
150
- }
151
- }
152
- },
153
- onCdpEvent(deviceId, method, params) {
154
- const payload = JSON.stringify({ method, params });
155
- const domain = method.split('.', 1)[0];
156
- for (const client of clients) {
157
- if (
158
- client.deviceId === deviceId &&
159
- client.socket.readyState === WebSocket.OPEN &&
160
- (!EVENT_GATED_DOMAINS.has(domain) ||
161
- client.enabled.has(`${domain}.enable`))
162
- ) {
163
- client.socket.send(payload);
164
- }
165
- }
166
- },
167
- close() {
168
- for (const client of clients) client.socket.close();
169
- server.close();
170
- try {
171
- fs.unlinkSync(descriptorPath);
172
- } catch {}
173
- },
174
- };
175
- }
176
-
177
- module.exports = { createDevtoolsProxy };