@metamask/device-mcp 0.2.0 → 0.3.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.
- package/CHANGELOG.md +21 -1
- package/README.md +55 -2
- package/dist/backends/adb-backend.cjs +12 -5
- package/dist/backends/adb-backend.cjs.map +1 -1
- package/dist/backends/adb-backend.d.cts +8 -2
- package/dist/backends/adb-backend.d.cts.map +1 -1
- package/dist/backends/adb-backend.d.mts +8 -2
- package/dist/backends/adb-backend.d.mts.map +1 -1
- package/dist/backends/adb-backend.mjs +12 -5
- package/dist/backends/adb-backend.mjs.map +1 -1
- package/dist/backends/appium-backend.cjs +16 -7
- package/dist/backends/appium-backend.cjs.map +1 -1
- package/dist/backends/appium-backend.d.cts +8 -2
- package/dist/backends/appium-backend.d.cts.map +1 -1
- package/dist/backends/appium-backend.d.mts +8 -2
- package/dist/backends/appium-backend.d.mts.map +1 -1
- package/dist/backends/appium-backend.mjs +16 -7
- package/dist/backends/appium-backend.mjs.map +1 -1
- package/dist/backends/idb-backend.cjs +12 -5
- package/dist/backends/idb-backend.cjs.map +1 -1
- package/dist/backends/idb-backend.d.cts +8 -2
- package/dist/backends/idb-backend.d.cts.map +1 -1
- package/dist/backends/idb-backend.d.mts +8 -2
- package/dist/backends/idb-backend.d.mts.map +1 -1
- package/dist/backends/idb-backend.mjs +12 -5
- package/dist/backends/idb-backend.mjs.map +1 -1
- package/dist/backends/index.cjs +4 -3
- package/dist/backends/index.cjs.map +1 -1
- package/dist/backends/index.d.cts.map +1 -1
- package/dist/backends/index.d.mts.map +1 -1
- package/dist/backends/index.mjs +4 -3
- package/dist/backends/index.mjs.map +1 -1
- package/dist/backends/types.cjs.map +1 -1
- package/dist/backends/types.d.cts +19 -1
- package/dist/backends/types.d.cts.map +1 -1
- package/dist/backends/types.d.mts +19 -1
- package/dist/backends/types.d.mts.map +1 -1
- package/dist/backends/types.mjs.map +1 -1
- package/dist/hermes/hermes-cdp.cjs +674 -0
- package/dist/hermes/hermes-cdp.cjs.map +1 -0
- package/dist/hermes/hermes-cdp.d.cts +248 -0
- package/dist/hermes/hermes-cdp.d.cts.map +1 -0
- package/dist/hermes/hermes-cdp.d.mts +248 -0
- package/dist/hermes/hermes-cdp.d.mts.map +1 -0
- package/dist/hermes/hermes-cdp.mjs +665 -0
- package/dist/hermes/hermes-cdp.mjs.map +1 -0
- package/dist/hermes/session.cjs +196 -0
- package/dist/hermes/session.cjs.map +1 -0
- package/dist/hermes/session.d.cts +163 -0
- package/dist/hermes/session.d.cts.map +1 -0
- package/dist/hermes/session.d.mts +163 -0
- package/dist/hermes/session.d.mts.map +1 -0
- package/dist/hermes/session.mjs +189 -0
- package/dist/hermes/session.mjs.map +1 -0
- package/dist/index.cjs +16 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +5 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -0
- package/dist/index.mjs.map +1 -1
- package/dist/server.cjs +3 -0
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +4 -1
- package/dist/server.mjs.map +1 -1
- package/dist/tools/hermes-cdp.cjs +102 -0
- package/dist/tools/hermes-cdp.cjs.map +1 -0
- package/dist/tools/hermes-cdp.d.cts +18 -0
- package/dist/tools/hermes-cdp.d.cts.map +1 -0
- package/dist/tools/hermes-cdp.d.mts +18 -0
- package/dist/tools/hermes-cdp.d.mts.map +1 -0
- package/dist/tools/hermes-cdp.mjs +99 -0
- package/dist/tools/hermes-cdp.mjs.map +1 -0
- package/dist/tools/hermes-targets.cjs +127 -0
- package/dist/tools/hermes-targets.cjs.map +1 -0
- package/dist/tools/hermes-targets.d.cts +20 -0
- package/dist/tools/hermes-targets.d.cts.map +1 -0
- package/dist/tools/hermes-targets.d.mts +20 -0
- package/dist/tools/hermes-targets.d.mts.map +1 -0
- package/dist/tools/hermes-targets.mjs +124 -0
- package/dist/tools/hermes-targets.mjs.map +1 -0
- package/dist/tools/index.cjs +5 -1
- package/dist/tools/index.cjs.map +1 -1
- package/dist/tools/index.d.cts +2 -0
- package/dist/tools/index.d.cts.map +1 -1
- package/dist/tools/index.d.mts +2 -0
- package/dist/tools/index.d.mts.map +1 -1
- package/dist/tools/index.mjs +2 -0
- package/dist/tools/index.mjs.map +1 -1
- package/dist/tools/screenshot.cjs +8 -3
- package/dist/tools/screenshot.cjs.map +1 -1
- package/dist/tools/screenshot.d.cts.map +1 -1
- package/dist/tools/screenshot.d.mts.map +1 -1
- package/dist/tools/screenshot.mjs +8 -3
- package/dist/tools/screenshot.mjs.map +1 -1
- package/dist/utils/output-path.cjs +128 -0
- package/dist/utils/output-path.cjs.map +1 -0
- package/dist/utils/output-path.d.cts +41 -0
- package/dist/utils/output-path.d.cts.map +1 -0
- package/dist/utils/output-path.d.mts +41 -0
- package/dist/utils/output-path.d.mts.map +1 -0
- package/dist/utils/output-path.mjs +123 -0
- package/dist/utils/output-path.mjs.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hermes-cdp.mjs","sourceRoot":"","sources":["../../src/hermes/hermes-cdp.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAkGH;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,yBAAyB,CAAC;AAEjE;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,qBAAqB,CAAC;AAEzD;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,yBAAyB,CAAC;AAEjE;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,4BAA4B,CAAC;AAEvE;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AAE7D;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,uBAAuB,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AAI,CAAC,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IAClD,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED;;;;GAIG;AACH,SAAS,WAAW,CAAC,MAAiB;IACpC,IACE,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,UAAU;QAC1C,MAAM,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EACpC,CAAC;QACD,MAAM,CAAC,KAAK,EAAE,CAAC;IACjB,CAAC;AACH,CAAC","sourcesContent":["/**\n * Pure Hermes Chrome DevTools Protocol (CDP) core for `@metamask/device-mcp`.\n *\n * Ported from `@metamask/client-mcp-core`'s `src/tools/hermes-cdp.ts`, decoupled\n * from that repo's `ToolContext`/`ErrorCodes`/`createToolError|Success`. Every\n * function here takes EXPLICIT parameters (port, appId, pin) and returns a\n * discriminated {@link HermesCdpResult} so this module is MCP-free and\n * unit-testable. The tools layer is responsible for resolving session state and\n * for PERSISTING the device pin — this file never imports `HermesSession`.\n *\n * Mechanism: the React Native Hermes runtime connects out to Metro's inspector\n * proxy; Metro exposes debuggable targets over `http://localhost:<metroPort>/json`\n * and a per-target `webSocketDebuggerUrl`. We speak real CDP over that WebSocket\n * using the GLOBAL `WebSocket` (no library) and the global `fetch` for discovery.\n *\n * Five fail-closed safety checks are preserved VERBATIM from the reference:\n * 1. Strict `appId` match (`===`, no substring, no `targets[0]` fallback).\n * 2. `HermesInternal.getRuntimeProperties()` identity probe before the user method.\n * 3. Device pin on `reactNative.logicalDeviceId` (set on first success).\n * 4. Multi-device fail-closed (missing or >1 distinct `logicalDeviceId`).\n * 5. WebSocket URL validation (protocol/hostname/port).\n */\n\n/**\n * Reported capability flags on a Metro Hermes target.\n */\ntype HermesCapabilities = {\n /** Whether the target supports native page reloads (newer RN registrations). */\n nativePageReloads?: boolean;\n /** Whether the target supports native source-code fetching. */\n nativeSourceCodeFetching?: boolean;\n /** Whether the target supports multiple concurrent debuggers. */\n supportsMultipleDebuggers?: boolean;\n};\n\n/**\n * React Native-specific metadata attached to a Metro Hermes target.\n */\ntype HermesReactNative = {\n /** Stable logical device identifier used for session pinning. */\n logicalDeviceId?: string;\n /** Reported capability flags for this target. */\n capabilities?: HermesCapabilities;\n};\n\n/**\n * A debuggable Hermes target as reported by Metro's `/json` (or `/json/list`)\n * discovery endpoint. Shape matches the reference implementation exactly.\n */\nexport type HermesTarget = {\n /** Metro's per-target identifier. */\n id?: string;\n /** Human-readable target title (used to filter the legacy synthetic page). */\n title?: string;\n /** Human-readable target description. */\n description?: string;\n /** The app bundle identifier this target belongs to (strict-matched). */\n appId?: string;\n /** The `ws://` URL used to speak CDP with this target. */\n webSocketDebuggerUrl?: string;\n /** React Native-specific metadata (logical device id + capabilities). */\n reactNative?: HermesReactNative;\n};\n\n/**\n * Discriminated result of a Hermes CDP operation.\n *\n * On success `result` carries the raw CDP `result` payload. On failure `code`\n * is a STABLE string error code (see the `HERMES_*` constants) and `message`\n * is a human-readable diagnostic preserving the reference's wording.\n */\nexport type HermesCdpResult =\n | { ok: true; result: unknown }\n | { ok: false; code: string; message: string };\n\n/**\n * Parameters for {@link runHermesCdp}.\n */\nexport type RunHermesCdpInput = {\n /** The CDP method to invoke (e.g. `Runtime.evaluate`). */\n method: string;\n /** Optional CDP method parameters. */\n params?: Record<string, unknown>;\n /** Per-call timeout in milliseconds for discovery and each CDP round-trip. */\n timeoutMs: number;\n /** The resolved Metro inspector proxy port. */\n metroPort: number;\n /** The expected app bundle identifier (strict-matched against targets). */\n appId: string;\n /** The pinned `logicalDeviceId` for this session, if one has been set. */\n pinnedDeviceId?: string;\n /**\n * Callback invoked with the resolved `logicalDeviceId` on the FIRST\n * successful identity probe so the caller can persist the pin. This file\n * stays pure: it never imports or mutates session state itself.\n */\n onPin?: (logicalDeviceId: string) => void;\n};\n\ntype CdpSuccessResponse = {\n id: number;\n result?: unknown;\n};\n\ntype CdpErrorResponse = {\n id: number;\n error: {\n message?: string;\n code?: number;\n data?: unknown;\n };\n};\n\ntype TargetSelection =\n | { ok: true; target: HermesTarget }\n | { ok: false; code: string; message: string };\n\ntype ProbeResult = { ok: true } | { ok: false; code: string; message: string };\n\n/**\n * No Hermes debug target matched the expected appId (after synthetic-title and\n * pin filtering). Often means Metro is up but the app is not registered.\n */\nexport const HERMES_TARGET_NOT_FOUND = 'HERMES_TARGET_NOT_FOUND';\n\n/**\n * A target was found but could not be verified as the expected Hermes runtime\n * (identity probe failed, missing `logicalDeviceId`, or non-JSON probe payload).\n */\nexport const HERMES_NOT_VERIFIED = 'HERMES_NOT_VERIFIED';\n\n/**\n * Multiple distinct logical devices are registered without a session pin (or a\n * candidate is missing its `logicalDeviceId`); routing would be a guess, so we\n * fail closed.\n */\nexport const HERMES_MULTIPLE_DEVICES = 'HERMES_MULTIPLE_DEVICES';\n\n/**\n * The resolved target's `logicalDeviceId` does not match the session pin.\n */\nexport const HERMES_DEVICE_PIN_MISMATCH = 'HERMES_DEVICE_PIN_MISMATCH';\n\n/**\n * The requested CDP method is in the destructive blocked set.\n */\nexport const HERMES_BLOCKED_METHOD = 'HERMES_BLOCKED_METHOD';\n\n/**\n * The target's `webSocketDebuggerUrl` failed protocol/hostname/port validation.\n */\nexport const HERMES_INVALID_WS_URL = 'HERMES_INVALID_WS_URL';\n\n/**\n * The underlying connection (discovery fetch or WebSocket) failed.\n */\nexport const HERMES_CONNECTION_FAILED = 'HERMES_CONNECTION_FAILED';\n\n/**\n * A discovery, socket-open, or CDP round-trip exceeded the configured timeout.\n */\nexport const HERMES_TIMEOUT = 'HERMES_TIMEOUT';\n\n/**\n * The user's CDP method returned a CDP-level error.\n */\nexport const HERMES_CDP_FAILED = 'HERMES_CDP_FAILED';\n\n/**\n * The global `WebSocket` constructor is unavailable in this Node runtime.\n */\nexport const HERMES_WEBSOCKET_UNAVAILABLE = 'HERMES_WEBSOCKET_UNAVAILABLE';\n\n/**\n * CDP methods blocked for safety. Ported VERBATIM from the reference — do not\n * weaken.\n */\nconst HERMES_BLOCKED_METHODS = new Set([\n 'Runtime.terminateExecution',\n 'Inspector.detached',\n]);\n\nconst DISCOVERY_PATHS = ['/json', '/json/list'];\nconst ALLOWED_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);\n\n/**\n * Title of the synthetic legacy \"Improved Chrome Reloads\" page that Metro\n * registers alongside the real Hermes target. Filtered out during selection.\n * Ported VERBATIM from the reference.\n */\nexport const LEGACY_SYNTHETIC_TITLE =\n 'React Native Experimental (Improved Chrome Reloads)';\n\n/**\n * JavaScript expression evaluated against a candidate target BEFORE the user's\n * method, to verify it is a genuine Hermes runtime. Copied VERBATIM from the\n * reference — do not alter the verification semantics.\n */\nexport const IDENTITY_PROBE_EXPR = `(function () {\n try {\n var hi = typeof HermesInternal !== 'undefined' ? HermesInternal : null;\n var p =\n hi && typeof hi.getRuntimeProperties === 'function'\n ? hi.getRuntimeProperties()\n : null;\n return JSON.stringify({\n isHermes: !!hi,\n ossVersion: p ? p['OSS Release Version'] : null,\n debuggerEnabled: p ? p['Debugger Enabled'] : null,\n });\n } catch (e) {\n return JSON.stringify({ error: String(e) });\n }\n})();`;\n\n/**\n * Orchestrates a single verified Hermes CDP command end to end.\n *\n * Resolves a target from Metro discovery, enforces all five fail-closed safety\n * checks, runs the identity probe, persists the device pin via `onPin` on first\n * success, sends the user's method, and returns the raw CDP `result`. The caller\n * supplies the resolved port/appId/pin and persists the pin — this function is\n * pure with respect to session state.\n *\n * @param input - Method, params, timeout, resolved port/appId/pin, and the pin\n * persistence callback. See {@link RunHermesCdpInput}.\n * @returns A discriminated {@link HermesCdpResult}.\n */\nexport async function runHermesCdp(\n input: RunHermesCdpInput,\n): Promise<HermesCdpResult> {\n if (HERMES_BLOCKED_METHODS.has(input.method)) {\n return {\n ok: false,\n code: HERMES_BLOCKED_METHOD,\n message:\n `CDP method \"${input.method}\" is blocked for safety. ` +\n `Blocked methods: ${[...HERMES_BLOCKED_METHODS].join(', ')}`,\n };\n }\n\n if (typeof WebSocket !== 'function') {\n return {\n ok: false,\n code: HERMES_WEBSOCKET_UNAVAILABLE,\n message:\n 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +\n 'NODE_OPTIONS=\"--experimental-websocket\" (or use Node 22+).',\n };\n }\n\n try {\n const targets = await fetchDiscoveryTargets(\n input.metroPort,\n input.timeoutMs,\n );\n const selection = selectHermesTarget(\n targets,\n input.appId,\n input.pinnedDeviceId,\n );\n if (!selection.ok) {\n return { ok: false, code: selection.code, message: selection.message };\n }\n\n const validation = validateWebSocketUrl(\n selection.target.webSocketDebuggerUrl,\n input.metroPort,\n );\n if (!validation.ok) {\n return {\n ok: false,\n code: HERMES_INVALID_WS_URL,\n message: validation.message,\n };\n }\n\n return await executeVerifiedCdpCommand(\n selection.target,\n input,\n input.pinnedDeviceId,\n input.onPin,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n ok: false,\n code: HERMES_CONNECTION_FAILED,\n message: `Hermes CDP connection failed: ${message}`,\n };\n }\n}\n\n/**\n * Fetches debuggable Hermes targets from Metro, trying `/json` then falling\n * back to `/json/list`. Each attempt is bounded by an `AbortController`\n * timeout. The payload must be an array; non-object entries are filtered out.\n *\n * @param metroPort - The Metro inspector proxy port.\n * @param timeoutMs - Per-attempt timeout in milliseconds.\n * @returns The discovered targets (objects only).\n * @throws The last error encountered if all discovery paths fail.\n */\nexport async function fetchDiscoveryTargets(\n metroPort: number,\n timeoutMs: number,\n): Promise<HermesTarget[]> {\n let lastError: unknown;\n\n for (const path of DISCOVERY_PATHS) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const response = await fetch(`http://localhost:${metroPort}${path}`, {\n signal: controller.signal,\n });\n if (!response.ok) {\n throw new Error(`Metro ${path} returned HTTP ${response.status}`);\n }\n\n const payload: unknown = await response.json();\n if (!Array.isArray(payload)) {\n throw new Error(`Metro ${path} returned a non-array response`);\n }\n\n return payload.filter(isHermesTarget);\n } catch (error) {\n lastError = error;\n } finally {\n clearTimeout(timer);\n }\n }\n\n throw lastError instanceof Error ? lastError : new Error(String(lastError));\n}\n\n/**\n * Narrows an unknown discovery entry to a {@link HermesTarget} (object guard).\n *\n * @param value - A raw entry from the Metro discovery payload.\n * @returns True when `value` is a non-null object.\n */\nfunction isHermesTarget(value: unknown): value is HermesTarget {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Selects the single safe Hermes target for the expected app, applying the\n * fail-closed selection algorithm VERBATIM from the reference:\n *\n * `webSocketDebuggerUrl` present → drop the synthetic legacy title → strict\n * `appId` match (`===`) → pin filter → ambiguity check ({@link hasAmbiguousTarget})\n * → `nativePageReloads` tiebreak → last-in-array.\n *\n * @param targets - All discovered targets.\n * @param expectedAppId - The strict app bundle identifier to match.\n * @param pinnedDeviceId - The session pin, if set, used to filter candidates.\n * @returns The selected target or a classified failure.\n */\nexport function selectHermesTarget(\n targets: HermesTarget[],\n expectedAppId: string,\n pinnedDeviceId: string | undefined,\n): TargetSelection {\n const seenAppIds = [...new Set(targets.map((target) => target.appId))].filter(\n (appId): appId is string => typeof appId === 'string',\n );\n\n let candidates = targets\n .filter((target) => Boolean(target.webSocketDebuggerUrl))\n .filter((target) => target.title !== LEGACY_SYNTHETIC_TITLE)\n .filter((target) => target.appId === expectedAppId);\n\n if (pinnedDeviceId) {\n candidates = candidates.filter(\n (target) => target.reactNative?.logicalDeviceId === pinnedDeviceId,\n );\n }\n\n if (candidates.length === 0) {\n return {\n ok: false,\n code: HERMES_TARGET_NOT_FOUND,\n message: `No Hermes debug target found for appId ${expectedAppId}. Saw appIds: ${JSON.stringify(\n seenAppIds,\n )}`,\n };\n }\n\n if (hasAmbiguousTarget(candidates)) {\n return {\n ok: false,\n code: HERMES_MULTIPLE_DEVICES,\n message: `Ambiguous Hermes target after pin filtering. Candidates: ${candidates\n .map(\n (target) =>\n `${target.id ?? '<unknown>'} (device=${\n target.reactNative?.logicalDeviceId ?? '<missing>'\n })`,\n )\n .join(', ')}`,\n };\n }\n\n // Same-device tiebreak: prefer pages with nativePageReloads (newer RN page\n // registrations) over stale entries left behind after in-app reloads.\n const nativeReloadTargets = candidates.filter(\n (target) => target.reactNative?.capabilities?.nativePageReloads === true,\n );\n if (nativeReloadTargets.length > 0) {\n candidates = nativeReloadTargets;\n }\n\n return { ok: true, target: candidates[candidates.length - 1] };\n}\n\n/**\n * Determines whether a multi-candidate target list is too ambiguous to choose\n * from safely. Returns true when:\n * - any candidate is missing a `reactNative.logicalDeviceId` (we can't route safely), or\n * - candidates resolve to more than one distinct `logicalDeviceId` (multi-device\n * without a session pin — picking any one would silently bind the wrong device).\n *\n * Returns false when all candidates share the same logical device ID. In that\n * case the caller falls through to the \"last-in-array\" tiebreak, matching the\n * React Native convention that the most recent page registration wins (e.g.,\n * stale + fresh page after an in-app reload).\n *\n * @param candidates - Targets remaining after appId/pin/capability filtering.\n * @returns True when the caller must fail closed; false when tiebreak is safe.\n */\nexport function hasAmbiguousTarget(candidates: HermesTarget[]): boolean {\n if (candidates.length <= 1) {\n return false;\n }\n const deviceIds = candidates.map(\n (target) => target.reactNative?.logicalDeviceId,\n );\n // Any candidate missing a logicalDeviceId → can't safely route.\n if (deviceIds.some((id) => !id)) {\n return true;\n }\n // Multiple distinct device IDs → multi-device without pin.\n return new Set(deviceIds).size > 1;\n}\n\n/**\n * Validates a target's `webSocketDebuggerUrl` before connecting. The protocol\n * must be `ws:`, the hostname must be loopback (`localhost`, `127.0.0.1`, `::1`,\n * or `[::1]`), and the port must equal the resolved Metro port. Ported VERBATIM\n * from the reference.\n *\n * @param rawUrl - The candidate `webSocketDebuggerUrl`.\n * @param expectedPort - The resolved Metro port the URL must point at.\n * @returns `{ ok: true }` when valid, otherwise a failure with a message.\n */\nexport function validateWebSocketUrl(\n rawUrl: string | undefined,\n expectedPort: number,\n): { ok: true } | { ok: false; message: string } {\n if (!rawUrl) {\n return { ok: false, message: 'webSocketDebuggerUrl is missing' };\n }\n\n let parsed: URL;\n try {\n parsed = new URL(rawUrl);\n } catch {\n return {\n ok: false,\n message: `webSocketDebuggerUrl is not a valid URL: ${rawUrl}`,\n };\n }\n\n if (parsed.protocol !== 'ws:') {\n return { ok: false, message: `Unexpected protocol '${parsed.protocol}'` };\n }\n if (!ALLOWED_HOSTNAMES.has(parsed.hostname)) {\n return { ok: false, message: `Unexpected hostname '${parsed.hostname}'` };\n }\n if (Number(parsed.port) !== expectedPort) {\n return {\n ok: false,\n message: `Port mismatch: target=${parsed.port} expected=${expectedPort}`,\n };\n }\n\n return { ok: true };\n}\n\n/**\n * Opens the target WebSocket, runs the identity probe, enforces the device pin\n * (persisting it via `onPin` on first success, failing closed on mismatch),\n * sends the user's method, matches the response by `id`, and always closes the\n * socket in a `finally`. Ported faithfully from the reference.\n *\n * @param target - The validated, selected target.\n * @param input - The original {@link RunHermesCdpInput} (method/params/timeout).\n * @param pinnedDeviceId - The session pin, if set.\n * @param onPin - Callback to persist the resolved pin on first success.\n * @returns A discriminated {@link HermesCdpResult}.\n */\nexport async function executeVerifiedCdpCommand(\n target: HermesTarget,\n input: RunHermesCdpInput,\n pinnedDeviceId: string | undefined,\n onPin: ((logicalDeviceId: string) => void) | undefined,\n): Promise<HermesCdpResult> {\n if (!target.webSocketDebuggerUrl) {\n return {\n ok: false,\n code: HERMES_INVALID_WS_URL,\n message: 'Target is missing webSocketDebuggerUrl',\n };\n }\n if (typeof WebSocket !== 'function') {\n return {\n ok: false,\n code: HERMES_WEBSOCKET_UNAVAILABLE,\n message:\n 'Global WebSocket is unavailable. On Node 20 launch device-mcp with ' +\n 'NODE_OPTIONS=\"--experimental-websocket\" (or use Node 22+).',\n };\n }\n\n const socket = new WebSocket(target.webSocketDebuggerUrl);\n let nextId = 1;\n\n try {\n await waitForSocketOpen(socket, input.timeoutMs);\n\n const probe = await runIdentityProbe(socket, input.timeoutMs, nextId);\n nextId += 1;\n if (!probe.ok) {\n return { ok: false, code: probe.code, message: probe.message };\n }\n\n const targetDeviceId = target.reactNative?.logicalDeviceId;\n if (!targetDeviceId) {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: 'Target is missing reactNative.logicalDeviceId',\n };\n }\n if (!pinnedDeviceId) {\n onPin?.(targetDeviceId);\n } else if (pinnedDeviceId !== targetDeviceId) {\n return {\n ok: false,\n code: HERMES_DEVICE_PIN_MISMATCH,\n message: `Hermes target device ${targetDeviceId} does not match session pin ${pinnedDeviceId}`,\n };\n }\n\n const response = await sendUserMethod(socket, input, nextId);\n nextId += 1;\n if (isCdpErrorResponse(response)) {\n return {\n ok: false,\n code: HERMES_CDP_FAILED,\n message: `Hermes CDP \"${input.method}\" failed: ${formatCdpError(\n response,\n )}`,\n };\n }\n\n return { ok: true, result: response.result };\n } finally {\n closeSocket(socket);\n }\n}\n\n/**\n * Runs the {@link IDENTITY_PROBE_EXPR} against an open socket and verifies the\n * response confirms a Hermes runtime. Distinguishes timeout from connection\n * failure and unverified payloads.\n *\n * @param socket - The open target WebSocket.\n * @param timeoutMs - Round-trip timeout in milliseconds.\n * @param id - The CDP message id to use for this probe.\n * @returns A {@link ProbeResult}.\n */\nasync function runIdentityProbe(\n socket: WebSocket,\n timeoutMs: number,\n id: number,\n): Promise<ProbeResult> {\n socket.send(\n JSON.stringify({\n id,\n method: 'Runtime.evaluate',\n params: { expression: IDENTITY_PROBE_EXPR, returnByValue: true },\n }),\n );\n\n let response: CdpSuccessResponse | CdpErrorResponse;\n try {\n response = await waitForCdpResponse(socket, id, timeoutMs);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.includes('timed out')) {\n return {\n ok: false,\n code: HERMES_TIMEOUT,\n message: `Identity probe timed out after ${timeoutMs}ms`,\n };\n }\n return {\n ok: false,\n code: HERMES_CONNECTION_FAILED,\n message: `Hermes CDP connection failed: ${message}`,\n };\n }\n\n if (isCdpErrorResponse(response)) {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: `Identity probe failed: ${formatCdpError(response)}`,\n };\n }\n\n const remoteResult = getProbeRemoteResult(response);\n if (remoteResult.subtype === 'error') {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: 'Identity probe evaluation returned an error subtype',\n };\n }\n if (remoteResult.value === undefined || remoteResult.value === null) {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: 'Identity probe response missing result.value',\n };\n }\n\n const raw =\n typeof remoteResult.value === 'string'\n ? remoteResult.value\n : JSON.stringify(remoteResult.value);\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: `Identity probe returned non-JSON: ${raw}`,\n };\n }\n\n if (!isHermesProbePayload(parsed)) {\n return {\n ok: false,\n code: HERMES_NOT_VERIFIED,\n message: `Identity probe did not verify Hermes runtime: ${raw}`,\n };\n }\n\n return { ok: true };\n}\n\n/**\n * Safely extracts the nested CDP `result.result` (the remote object) from a\n * `Runtime.evaluate` success response.\n *\n * @param response - A CDP success response.\n * @returns The remote object's `subtype`/`value`, or an empty object.\n */\nfunction getProbeRemoteResult(response: CdpSuccessResponse): {\n subtype?: unknown;\n value?: unknown;\n} {\n if (typeof response.result !== 'object' || response.result === null) {\n return {};\n }\n const outer = response.result as Record<string, unknown>;\n if (typeof outer.result !== 'object' || outer.result === null) {\n return {};\n }\n return outer.result;\n}\n\n/**\n * Narrows a parsed probe payload to one confirming a Hermes runtime.\n *\n * @param value - The parsed probe JSON payload.\n * @returns True when `isHermes === true`.\n */\nfunction isHermesProbePayload(value: unknown): value is { isHermes: true } {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as Record<string, unknown>).isHermes === true\n );\n}\n\n/**\n * Sends the user's CDP method over an open, verified socket and awaits the\n * matching response by id.\n *\n * @param socket - The open, verified target WebSocket.\n * @param input - The original input carrying method/params/timeout.\n * @param id - The CDP message id to use.\n * @returns The matching CDP success or error response.\n */\nasync function sendUserMethod(\n socket: WebSocket,\n input: RunHermesCdpInput,\n id: number,\n): Promise<CdpSuccessResponse | CdpErrorResponse> {\n socket.send(\n JSON.stringify({\n id,\n method: input.method,\n params: input.params ?? {},\n }),\n );\n return await waitForCdpResponse(socket, id, input.timeoutMs);\n}\n\n/**\n * Resolves once the socket reaches the OPEN state, rejecting on error or\n * timeout. Listeners are always cleaned up.\n *\n * @param socket - The connecting target WebSocket.\n * @param timeoutMs - Connection timeout in milliseconds.\n * @returns A promise that resolves when the socket is open.\n */\nasync function waitForSocketOpen(\n socket: WebSocket,\n timeoutMs: number,\n): Promise<void> {\n if (socket.readyState === WebSocket.OPEN) {\n return Promise.resolve();\n }\n\n return new Promise((resolve, reject) => {\n let cleanup = (): void => undefined;\n const handleOpen = (): void => {\n cleanup();\n resolve();\n };\n const handleError = (): void => {\n cleanup();\n reject(new Error('WebSocket connection error'));\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`WebSocket connection timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n cleanup = (): void => {\n clearTimeout(timer);\n socket.removeEventListener('open', handleOpen);\n socket.removeEventListener('error', handleError);\n };\n\n socket.addEventListener('open', handleOpen);\n socket.addEventListener('error', handleError);\n });\n}\n\n/**\n * Resolves with the CDP response whose `id` matches, rejecting on socket error,\n * premature close, or timeout. Listeners are always cleaned up.\n *\n * @param socket - The open target WebSocket.\n * @param id - The CDP message id to match.\n * @param timeoutMs - Round-trip timeout in milliseconds.\n * @returns The matching CDP success or error response.\n */\nasync function waitForCdpResponse(\n socket: WebSocket,\n id: number,\n timeoutMs: number,\n): Promise<CdpSuccessResponse | CdpErrorResponse> {\n return new Promise((resolve, reject) => {\n let cleanup = (): void => undefined;\n const handleMessage = (event: MessageEvent): void => {\n try {\n const parsed = parseCdpResponse(event.data);\n if (parsed?.id !== id) {\n return;\n }\n cleanup();\n resolve(parsed);\n } catch (error) {\n cleanup();\n reject(error);\n }\n };\n const handleError = (): void => {\n cleanup();\n reject(new Error('WebSocket message error'));\n };\n const handleClose = (): void => {\n cleanup();\n reject(new Error('WebSocket closed before CDP response'));\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`Hermes CDP call timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n cleanup = (): void => {\n clearTimeout(timer);\n socket.removeEventListener('message', handleMessage);\n socket.removeEventListener('error', handleError);\n socket.removeEventListener('close', handleClose);\n };\n\n socket.addEventListener('message', handleMessage);\n socket.addEventListener('error', handleError);\n socket.addEventListener('close', handleClose);\n });\n}\n\n/**\n * Parses a raw WebSocket frame into a CDP response, returning undefined when it\n * is not an addressable (`id`-bearing) message.\n *\n * @param data - The raw `MessageEvent.data`.\n * @returns A CDP success/error response, or undefined when not addressable.\n * @throws When the frame is not a text frame.\n */\nfunction parseCdpResponse(\n data: MessageEvent['data'],\n): CdpSuccessResponse | CdpErrorResponse | undefined {\n if (typeof data !== 'string') {\n throw new Error('Hermes CDP returned a non-text WebSocket frame');\n }\n\n const parsed: unknown = JSON.parse(data);\n if (typeof parsed !== 'object' || parsed === null) {\n return undefined;\n }\n const candidate = parsed as Record<string, unknown>;\n if (typeof candidate.id !== 'number') {\n return undefined;\n }\n if (isCdpError(candidate.error)) {\n return { id: candidate.id, error: candidate.error };\n }\n return { id: candidate.id, result: candidate.result };\n}\n\n/**\n * Narrows an unknown value to a CDP error object.\n *\n * @param value - The candidate `error` field.\n * @returns True when `value` is a non-null object.\n */\nfunction isCdpError(value: unknown): value is CdpErrorResponse['error'] {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Discriminates a CDP response as an error response.\n *\n * @param response - A CDP success or error response.\n * @returns True when the response carries an `error` field.\n */\nfunction isCdpErrorResponse(\n response: CdpSuccessResponse | CdpErrorResponse,\n): response is CdpErrorResponse {\n return 'error' in response;\n}\n\n/**\n * Formats a CDP error response into a single human-readable line.\n *\n * @param response - The CDP error response.\n * @returns A combined message including code and data when present.\n */\nfunction formatCdpError(response: CdpErrorResponse): string {\n const parts = [response.error.message ?? 'Unknown CDP error'];\n if (typeof response.error.code === 'number') {\n parts.push(`code ${response.error.code}`);\n }\n if (response.error.data !== undefined) {\n parts.push(JSON.stringify(response.error.data));\n }\n return parts.join(' - ');\n}\n\n/**\n * Closes the socket if it is still connecting or open.\n *\n * @param socket - The target WebSocket.\n */\nfunction closeSocket(socket: WebSocket): void {\n if (\n socket.readyState === WebSocket.CONNECTING ||\n socket.readyState === WebSocket.OPEN\n ) {\n socket.close();\n }\n}\n"]}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Standalone state module for Hermes CDP sessions.
|
|
4
|
+
*
|
|
5
|
+
* Holds the resolved Metro inspector proxy port, the expected app bundle ID,
|
|
6
|
+
* and the pinned Hermes `logicalDeviceId`. This module is intentionally
|
|
7
|
+
* INDEPENDENT of `DeviceBackend` — Hermes/Metro access is orthogonal to the
|
|
8
|
+
* idb/adb/Appium UI automation backends, and it stores no live connection
|
|
9
|
+
* (the MVP opens a fresh WebSocket per tool call).
|
|
10
|
+
*
|
|
11
|
+
* Resolution precedence for both port and appId is exactly:
|
|
12
|
+
* per-call param > environment variable > default.
|
|
13
|
+
*/
|
|
14
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
15
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
16
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
17
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
18
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
19
|
+
};
|
|
20
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
21
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
22
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
23
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
24
|
+
};
|
|
25
|
+
var _HermesSession_instances, _HermesSession_metroPort, _HermesSession_expectedAppId, _HermesSession_appIdFromEnv, _HermesSession_pinnedDeviceId, _HermesSession_resolveAppId;
|
|
26
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
27
|
+
exports.HermesSession = exports.DEFAULT_METRO_PORT = exports.DEFAULT_ANDROID_APP_ID = exports.DEFAULT_IOS_APP_ID = void 0;
|
|
28
|
+
exports.defaultAppIdForPlatform = defaultAppIdForPlatform;
|
|
29
|
+
exports.getHermesSession = getHermesSession;
|
|
30
|
+
exports.resetHermesSession = resetHermesSession;
|
|
31
|
+
/** Default MetaMask app bundle ID for iOS (`CFBundleIdentifier`). */
|
|
32
|
+
exports.DEFAULT_IOS_APP_ID = 'io.metamask.MetaMask';
|
|
33
|
+
/** Default MetaMask app bundle ID for Android (`applicationId`). */
|
|
34
|
+
exports.DEFAULT_ANDROID_APP_ID = 'io.metamask';
|
|
35
|
+
/** Default Metro inspector proxy port when none is configured. */
|
|
36
|
+
exports.DEFAULT_METRO_PORT = 8081;
|
|
37
|
+
/**
|
|
38
|
+
* Resolve the platform default app bundle ID.
|
|
39
|
+
*
|
|
40
|
+
* Defaults to the iOS id when the platform is unknown. Agents running against
|
|
41
|
+
* Android should pass `appId` per call or set `HERMES_APP_ID` if they are not
|
|
42
|
+
* using the default Android bundle ID.
|
|
43
|
+
*
|
|
44
|
+
* @param platform - The active platform, if known.
|
|
45
|
+
* @returns The default app bundle ID for the platform.
|
|
46
|
+
*/
|
|
47
|
+
function defaultAppIdForPlatform(platform) {
|
|
48
|
+
return platform === 'android' ? exports.DEFAULT_ANDROID_APP_ID : exports.DEFAULT_IOS_APP_ID;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Parse a Metro port from an environment variable value.
|
|
52
|
+
*
|
|
53
|
+
* @param value - The raw environment variable value (or undefined).
|
|
54
|
+
* @returns The parsed integer port, or undefined when unset/invalid.
|
|
55
|
+
*/
|
|
56
|
+
function parseEnvPort(value) {
|
|
57
|
+
if (value === undefined) {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
const parsed = Number.parseInt(value, 10);
|
|
61
|
+
return Number.isInteger(parsed) ? parsed : undefined;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Holds the Metro port, expected appId, and pinned Hermes deviceId for a
|
|
65
|
+
* process-lifetime Hermes session.
|
|
66
|
+
*
|
|
67
|
+
* The stored port and appId are resolved once at construction time using
|
|
68
|
+
* `param ?? env ?? default` precedence (with `param` being undefined at
|
|
69
|
+
* construction — those are supplied per call to {@link resolve}). The pinned
|
|
70
|
+
* deviceId starts unset and is assigned on the first successful identity probe.
|
|
71
|
+
*/
|
|
72
|
+
class HermesSession {
|
|
73
|
+
constructor(options = {}) {
|
|
74
|
+
_HermesSession_instances.add(this);
|
|
75
|
+
_HermesSession_metroPort.set(this, void 0);
|
|
76
|
+
_HermesSession_expectedAppId.set(this, void 0);
|
|
77
|
+
/**
|
|
78
|
+
* Whether {@link #expectedAppId} came from an explicit source (the
|
|
79
|
+
* `HERMES_APP_ID` env var) rather than the platform fallback. When true, the
|
|
80
|
+
* stored appId is a deliberate override and {@link resolve} must not let a
|
|
81
|
+
* per-call `platform` recompute it; when false, the stored value is only the
|
|
82
|
+
* construction-time platform default and `resolve` may recompute it from the
|
|
83
|
+
* live platform.
|
|
84
|
+
*/
|
|
85
|
+
_HermesSession_appIdFromEnv.set(this, void 0);
|
|
86
|
+
_HermesSession_pinnedDeviceId.set(this, void 0);
|
|
87
|
+
const env = options.env ?? process.env;
|
|
88
|
+
__classPrivateFieldSet(this, _HermesSession_metroPort, parseEnvPort(env.HERMES_METRO_PORT) ?? exports.DEFAULT_METRO_PORT, "f");
|
|
89
|
+
__classPrivateFieldSet(this, _HermesSession_appIdFromEnv, env.HERMES_APP_ID !== undefined, "f");
|
|
90
|
+
__classPrivateFieldSet(this, _HermesSession_expectedAppId, env.HERMES_APP_ID ?? defaultAppIdForPlatform(options.platform), "f");
|
|
91
|
+
__classPrivateFieldSet(this, _HermesSession_pinnedDeviceId, undefined, "f");
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Returns the session-default Metro inspector proxy port.
|
|
95
|
+
*
|
|
96
|
+
* @returns The resolved Metro port (env `HERMES_METRO_PORT`, else 8081).
|
|
97
|
+
*/
|
|
98
|
+
getMetroPort() {
|
|
99
|
+
return __classPrivateFieldGet(this, _HermesSession_metroPort, "f");
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Returns the session-default expected app bundle ID.
|
|
103
|
+
*
|
|
104
|
+
* @returns The resolved app bundle ID (env `HERMES_APP_ID`, else the
|
|
105
|
+
* platform default).
|
|
106
|
+
*/
|
|
107
|
+
getAppId() {
|
|
108
|
+
return __classPrivateFieldGet(this, _HermesSession_expectedAppId, "f");
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Returns the pinned Hermes `logicalDeviceId` for this session, if any.
|
|
112
|
+
*
|
|
113
|
+
* Set on the first successful identity probe via
|
|
114
|
+
* {@link setPinnedHermesDeviceId}. Persists for the lifetime of this
|
|
115
|
+
* instance.
|
|
116
|
+
*
|
|
117
|
+
* @returns The pinned `logicalDeviceId`, or undefined when no pin is set.
|
|
118
|
+
*/
|
|
119
|
+
getPinnedHermesDeviceId() {
|
|
120
|
+
return __classPrivateFieldGet(this, _HermesSession_pinnedDeviceId, "f");
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Pin the Hermes `logicalDeviceId` for this session.
|
|
124
|
+
*
|
|
125
|
+
* Called after a successful identity probe on the first call. Subsequent
|
|
126
|
+
* calls then enforce this pin to prevent target switching mid-session.
|
|
127
|
+
*
|
|
128
|
+
* @param id - The `logicalDeviceId` from Metro's
|
|
129
|
+
* `reactNative.logicalDeviceId` field.
|
|
130
|
+
*/
|
|
131
|
+
setPinnedHermesDeviceId(id) {
|
|
132
|
+
__classPrivateFieldSet(this, _HermesSession_pinnedDeviceId, id, "f");
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Resolve the effective parameters for a single tool call by merging
|
|
136
|
+
* per-call overrides over the stored session defaults.
|
|
137
|
+
*
|
|
138
|
+
* This is PURE with respect to stored state: it never mutates the stored
|
|
139
|
+
* port, appId, or pin. Only {@link setPinnedHermesDeviceId} mutates the pin.
|
|
140
|
+
*
|
|
141
|
+
* Port precedence is `input.metroPort ?? this.getMetroPort()` (which itself
|
|
142
|
+
* already encodes `env ?? default`), mirroring the reference driver's
|
|
143
|
+
* `input.metroPort ?? driver.getMetroPort() ?? 8081`.
|
|
144
|
+
*
|
|
145
|
+
* AppId precedence is `input.appId ?? <HERMES_APP_ID env if set> ??
|
|
146
|
+
* defaultAppIdForPlatform(input.platform) ?? <stored default>`. An explicitly
|
|
147
|
+
* set `HERMES_APP_ID` always WINS over the per-call platform default (env is a
|
|
148
|
+
* deliberate override): in that case the stored appId is returned unchanged.
|
|
149
|
+
* Only when the stored appId is the construction-time platform fallback does
|
|
150
|
+
* a per-call `platform` recompute it — without mutating stored state. When no
|
|
151
|
+
* `platform` is passed this preserves the original iOS-default behavior.
|
|
152
|
+
*
|
|
153
|
+
* @param input - Optional per-call overrides for port, appId, and platform.
|
|
154
|
+
* @returns The effective `{ metroPort, appId, pinnedDeviceId }`.
|
|
155
|
+
*/
|
|
156
|
+
resolve(input = {}) {
|
|
157
|
+
return {
|
|
158
|
+
metroPort: input.metroPort ?? __classPrivateFieldGet(this, _HermesSession_metroPort, "f"),
|
|
159
|
+
appId: input.appId ?? __classPrivateFieldGet(this, _HermesSession_instances, "m", _HermesSession_resolveAppId).call(this, input.platform),
|
|
160
|
+
pinnedDeviceId: __classPrivateFieldGet(this, _HermesSession_pinnedDeviceId, "f"),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
exports.HermesSession = HermesSession;
|
|
165
|
+
_HermesSession_metroPort = new WeakMap(), _HermesSession_expectedAppId = new WeakMap(), _HermesSession_appIdFromEnv = new WeakMap(), _HermesSession_pinnedDeviceId = new WeakMap(), _HermesSession_instances = new WeakSet(), _HermesSession_resolveAppId = function _HermesSession_resolveAppId(platform) {
|
|
166
|
+
if (__classPrivateFieldGet(this, _HermesSession_appIdFromEnv, "f") || platform === undefined) {
|
|
167
|
+
return __classPrivateFieldGet(this, _HermesSession_expectedAppId, "f");
|
|
168
|
+
}
|
|
169
|
+
return defaultAppIdForPlatform(platform);
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* Module-level lazily-created singleton instance.
|
|
173
|
+
*/
|
|
174
|
+
let sessionInstance;
|
|
175
|
+
/**
|
|
176
|
+
* Returns the process-singleton {@link HermesSession}, creating it on first
|
|
177
|
+
* access.
|
|
178
|
+
*
|
|
179
|
+
* @param options - Options applied only when the singleton is first created.
|
|
180
|
+
* @returns The shared `HermesSession` instance.
|
|
181
|
+
*/
|
|
182
|
+
function getHermesSession(options) {
|
|
183
|
+
if (sessionInstance === undefined) {
|
|
184
|
+
sessionInstance = new HermesSession(options);
|
|
185
|
+
}
|
|
186
|
+
return sessionInstance;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Resets the process-singleton {@link HermesSession}.
|
|
190
|
+
*
|
|
191
|
+
* Intended for test isolation so each test can start from a clean session.
|
|
192
|
+
*/
|
|
193
|
+
function resetHermesSession() {
|
|
194
|
+
sessionInstance = undefined;
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=session.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.cjs","sourceRoot":"","sources":["../../src/hermes/session.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;GAWG;;;;;;;;;;;;;;;AA6BH,0DAEC;AA0MD,4CAOC;AAOD,gDAEC;AA/OD,qEAAqE;AACxD,QAAA,kBAAkB,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;;;;;OAKG;IACH,QAAQ;QACN,OAAO,uBAAA,IAAI,oCAAe,CAAC;IAC7B,CAAC;IAED;;;;;;;;OAQG;IACH,uBAAuB;QACrB,OAAO,uBAAA,IAAI,qCAAgB,CAAC;IAC9B,CAAC;IAED;;;;;;;;OAQG;IACH,uBAAuB,CAAC,EAAU;QAChC,uBAAA,IAAI,iCAAmB,EAAE,MAAA,CAAC;IAC5B,CAAC;IAED;;;;;;;;;;;;;;;;;;;;;OAqBG;IACH,OAAO,CAAC,QAAmC,EAAE;QAC3C,OAAO;YACL,SAAS,EAAE,KAAK,CAAC,SAAS,IAAI,uBAAA,IAAI,gCAAW;YAC7C,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,uBAAA,IAAI,6DAAc,MAAlB,IAAI,EAAe,KAAK,CAAC,QAAQ,CAAC;YACxD,cAAc,EAAE,uBAAA,IAAI,qCAAgB;SACrC,CAAC;IACJ,CAAC;CAeF;AArHD,sCAqHC;iSANe,QAAoC;IAChD,IAAI,uBAAA,IAAI,mCAAc,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;QACjD,OAAO,uBAAA,IAAI,oCAAe,CAAC;IAC7B,CAAC;IACD,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC;AAGH;;GAEG;AACH,IAAI,eAA0C,CAAC;AAE/C;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,OAA8B;IAE9B,IAAI,eAAe,KAAK,SAAS,EAAE,CAAC;QAClC,eAAe,GAAG,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC;IAC/C,CAAC;IACD,OAAO,eAAe,CAAC;AACzB,CAAC;AAED;;;;GAIG;AACH,SAAgB,kBAAkB;IAChC,eAAe,GAAG,SAAS,CAAC;AAC9B,CAAC","sourcesContent":["/**\n * Standalone state module for Hermes CDP sessions.\n *\n * Holds the resolved Metro inspector proxy port, the expected app bundle ID,\n * and the pinned Hermes `logicalDeviceId`. This module is intentionally\n * INDEPENDENT of `DeviceBackend` — Hermes/Metro access is orthogonal to the\n * idb/adb/Appium UI automation backends, and it stores no live connection\n * (the MVP opens a fresh WebSocket per tool call).\n *\n * Resolution precedence for both port and appId is exactly:\n * per-call param > environment variable > default.\n */\n\n/**\n * Platform identifier used to pick the default app bundle ID.\n *\n * Kept structurally compatible with the backend's `Platform` type without\n * importing it, so this module stays decoupled from `DeviceBackend`.\n */\nexport type HermesPlatform = 'ios' | 'android';\n\n/** Default MetaMask app bundle ID for iOS (`CFBundleIdentifier`). */\nexport const DEFAULT_IOS_APP_ID = 'io.metamask.MetaMask';\n\n/** Default MetaMask app bundle ID for Android (`applicationId`). */\nexport const DEFAULT_ANDROID_APP_ID = 'io.metamask';\n\n/** Default Metro inspector proxy port when none is configured. */\nexport const DEFAULT_METRO_PORT = 8081;\n\n/**\n * Resolve the platform default app bundle ID.\n *\n * Defaults to the iOS id when the platform is unknown. Agents running against\n * Android should pass `appId` per call or set `HERMES_APP_ID` if they are not\n * using the default Android bundle ID.\n *\n * @param platform - The active platform, if known.\n * @returns The default app bundle ID for the platform.\n */\nexport function defaultAppIdForPlatform(platform?: HermesPlatform): string {\n return platform === 'android' ? DEFAULT_ANDROID_APP_ID : DEFAULT_IOS_APP_ID;\n}\n\n/**\n * Parse a Metro port from an environment variable value.\n *\n * @param value - The raw environment variable value (or undefined).\n * @returns The parsed integer port, or undefined when unset/invalid.\n */\nfunction parseEnvPort(value: string | undefined): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n const parsed = Number.parseInt(value, 10);\n return Number.isInteger(parsed) ? parsed : undefined;\n}\n\n/**\n * Per-call overrides accepted by {@link HermesSession.resolve}.\n *\n * Any field left undefined falls back to the session default (which itself\n * falls back to the relevant environment variable, then the hardcoded default).\n */\nexport type HermesSessionResolveInput = {\n /** Override the Metro inspector proxy port for this call. */\n metroPort?: number;\n /** Override the expected app bundle ID for this call. */\n appId?: string;\n /**\n * The active platform, used to compute the default app bundle ID AT CALL\n * TIME when neither a per-call `appId` nor the `HERMES_APP_ID` env var is set.\n * This lets a session created before a device connects (when the platform is\n * not yet known) still resolve the correct Android default once the backend's\n * live platform becomes `'android'`.\n */\n platform?: HermesPlatform;\n};\n\n/**\n * The effective Hermes session parameters for a single tool call.\n */\nexport type HermesSessionResolved = {\n /** The resolved Metro inspector proxy port. */\n metroPort: number;\n /** The resolved expected app bundle ID. */\n appId: string;\n /** The pinned Hermes `logicalDeviceId`, if one has been set. */\n pinnedDeviceId: string | undefined;\n};\n\n/**\n * Options for constructing a {@link HermesSession}.\n */\nexport type HermesSessionOptions = {\n /** The active platform, used only to pick the default app bundle ID. */\n platform?: HermesPlatform;\n /**\n * Environment source. Defaults to `process.env`. Injectable for tests so\n * resolution precedence can be exercised without mutating the real env.\n */\n env?: NodeJS.ProcessEnv;\n};\n\n/**\n * Holds the Metro port, expected appId, and pinned Hermes deviceId for a\n * process-lifetime Hermes session.\n *\n * The stored port and appId are resolved once at construction time using\n * `param ?? env ?? default` precedence (with `param` being undefined at\n * construction — those are supplied per call to {@link resolve}). The pinned\n * deviceId starts unset and is assigned on the first successful identity probe.\n */\nexport class HermesSession {\n readonly #metroPort: number;\n\n readonly #expectedAppId: string;\n\n /**\n * Whether {@link #expectedAppId} came from an explicit source (the\n * `HERMES_APP_ID` env var) rather than the platform fallback. When true, the\n * stored appId is a deliberate override and {@link resolve} must not let a\n * per-call `platform` recompute it; when false, the stored value is only the\n * construction-time platform default and `resolve` may recompute it from the\n * live platform.\n */\n readonly #appIdFromEnv: boolean;\n\n #pinnedDeviceId: string | undefined;\n\n constructor(options: HermesSessionOptions = {}) {\n const env = options.env ?? process.env;\n\n this.#metroPort = parseEnvPort(env.HERMES_METRO_PORT) ?? DEFAULT_METRO_PORT;\n\n this.#appIdFromEnv = env.HERMES_APP_ID !== undefined;\n this.#expectedAppId =\n env.HERMES_APP_ID ?? defaultAppIdForPlatform(options.platform);\n\n this.#pinnedDeviceId = undefined;\n }\n\n /**\n * Returns the session-default Metro inspector proxy port.\n *\n * @returns The resolved Metro port (env `HERMES_METRO_PORT`, else 8081).\n */\n getMetroPort(): number {\n return this.#metroPort;\n }\n\n /**\n * Returns the session-default expected app bundle ID.\n *\n * @returns The resolved app bundle ID (env `HERMES_APP_ID`, else the\n * platform default).\n */\n getAppId(): string {\n return this.#expectedAppId;\n }\n\n /**\n * Returns the pinned Hermes `logicalDeviceId` for this session, if any.\n *\n * Set on the first successful identity probe via\n * {@link setPinnedHermesDeviceId}. Persists for the lifetime of this\n * instance.\n *\n * @returns The pinned `logicalDeviceId`, or undefined when no pin is set.\n */\n getPinnedHermesDeviceId(): string | undefined {\n return this.#pinnedDeviceId;\n }\n\n /**\n * Pin the Hermes `logicalDeviceId` for this session.\n *\n * Called after a successful identity probe on the first call. Subsequent\n * calls then enforce this pin to prevent target switching mid-session.\n *\n * @param id - The `logicalDeviceId` from Metro's\n * `reactNative.logicalDeviceId` field.\n */\n setPinnedHermesDeviceId(id: string): void {\n this.#pinnedDeviceId = id;\n }\n\n /**\n * Resolve the effective parameters for a single tool call by merging\n * per-call overrides over the stored session defaults.\n *\n * This is PURE with respect to stored state: it never mutates the stored\n * port, appId, or pin. Only {@link setPinnedHermesDeviceId} mutates the pin.\n *\n * Port precedence is `input.metroPort ?? this.getMetroPort()` (which itself\n * already encodes `env ?? default`), mirroring the reference driver's\n * `input.metroPort ?? driver.getMetroPort() ?? 8081`.\n *\n * AppId precedence is `input.appId ?? <HERMES_APP_ID env if set> ??\n * defaultAppIdForPlatform(input.platform) ?? <stored default>`. An explicitly\n * set `HERMES_APP_ID` always WINS over the per-call platform default (env is a\n * deliberate override): in that case the stored appId is returned unchanged.\n * Only when the stored appId is the construction-time platform fallback does\n * a per-call `platform` recompute it — without mutating stored state. When no\n * `platform` is passed this preserves the original iOS-default behavior.\n *\n * @param input - Optional per-call overrides for port, appId, and platform.\n * @returns The effective `{ metroPort, appId, pinnedDeviceId }`.\n */\n resolve(input: HermesSessionResolveInput = {}): HermesSessionResolved {\n return {\n metroPort: input.metroPort ?? this.#metroPort,\n appId: input.appId ?? this.#resolveAppId(input.platform),\n pinnedDeviceId: this.#pinnedDeviceId,\n };\n }\n\n /**\n * Compute the effective default appId for a call, honouring the\n * env-over-platform-default precedence documented on {@link resolve}.\n *\n * @param platform - The live platform passed for this call, if any.\n * @returns The stored env/explicit appId, or the platform default.\n */\n #resolveAppId(platform: HermesPlatform | undefined): string {\n if (this.#appIdFromEnv || platform === undefined) {\n return this.#expectedAppId;\n }\n return defaultAppIdForPlatform(platform);\n }\n}\n\n/**\n * Module-level lazily-created singleton instance.\n */\nlet sessionInstance: HermesSession | undefined;\n\n/**\n * Returns the process-singleton {@link HermesSession}, creating it on first\n * access.\n *\n * @param options - Options applied only when the singleton is first created.\n * @returns The shared `HermesSession` instance.\n */\nexport function getHermesSession(\n options?: HermesSessionOptions,\n): HermesSession {\n if (sessionInstance === undefined) {\n sessionInstance = new HermesSession(options);\n }\n return sessionInstance;\n}\n\n/**\n * Resets the process-singleton {@link HermesSession}.\n *\n * Intended for test isolation so each test can start from a clean session.\n */\nexport function resetHermesSession(): void {\n sessionInstance = undefined;\n}\n"]}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone state module for Hermes CDP sessions.
|
|
3
|
+
*
|
|
4
|
+
* Holds the resolved Metro inspector proxy port, the expected app bundle ID,
|
|
5
|
+
* and the pinned Hermes `logicalDeviceId`. This module is intentionally
|
|
6
|
+
* INDEPENDENT of `DeviceBackend` — Hermes/Metro access is orthogonal to the
|
|
7
|
+
* idb/adb/Appium UI automation backends, and it stores no live connection
|
|
8
|
+
* (the MVP opens a fresh WebSocket per tool call).
|
|
9
|
+
*
|
|
10
|
+
* Resolution precedence for both port and appId is exactly:
|
|
11
|
+
* per-call param > environment variable > default.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Platform identifier used to pick the default app bundle ID.
|
|
15
|
+
*
|
|
16
|
+
* Kept structurally compatible with the backend's `Platform` type without
|
|
17
|
+
* importing it, so this module stays decoupled from `DeviceBackend`.
|
|
18
|
+
*/
|
|
19
|
+
export type HermesPlatform = 'ios' | 'android';
|
|
20
|
+
/** Default MetaMask app bundle ID for iOS (`CFBundleIdentifier`). */
|
|
21
|
+
export declare const DEFAULT_IOS_APP_ID = "io.metamask.MetaMask";
|
|
22
|
+
/** Default MetaMask app bundle ID for Android (`applicationId`). */
|
|
23
|
+
export declare const DEFAULT_ANDROID_APP_ID = "io.metamask";
|
|
24
|
+
/** Default Metro inspector proxy port when none is configured. */
|
|
25
|
+
export declare const DEFAULT_METRO_PORT = 8081;
|
|
26
|
+
/**
|
|
27
|
+
* Resolve the platform default app bundle ID.
|
|
28
|
+
*
|
|
29
|
+
* Defaults to the iOS id when the platform is unknown. Agents running against
|
|
30
|
+
* Android should pass `appId` per call or set `HERMES_APP_ID` if they are not
|
|
31
|
+
* using the default Android bundle ID.
|
|
32
|
+
*
|
|
33
|
+
* @param platform - The active platform, if known.
|
|
34
|
+
* @returns The default app bundle ID for the platform.
|
|
35
|
+
*/
|
|
36
|
+
export declare function defaultAppIdForPlatform(platform?: HermesPlatform): string;
|
|
37
|
+
/**
|
|
38
|
+
* Per-call overrides accepted by {@link HermesSession.resolve}.
|
|
39
|
+
*
|
|
40
|
+
* Any field left undefined falls back to the session default (which itself
|
|
41
|
+
* falls back to the relevant environment variable, then the hardcoded default).
|
|
42
|
+
*/
|
|
43
|
+
export type HermesSessionResolveInput = {
|
|
44
|
+
/** Override the Metro inspector proxy port for this call. */
|
|
45
|
+
metroPort?: number;
|
|
46
|
+
/** Override the expected app bundle ID for this call. */
|
|
47
|
+
appId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* The active platform, used to compute the default app bundle ID AT CALL
|
|
50
|
+
* TIME when neither a per-call `appId` nor the `HERMES_APP_ID` env var is set.
|
|
51
|
+
* This lets a session created before a device connects (when the platform is
|
|
52
|
+
* not yet known) still resolve the correct Android default once the backend's
|
|
53
|
+
* live platform becomes `'android'`.
|
|
54
|
+
*/
|
|
55
|
+
platform?: HermesPlatform;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The effective Hermes session parameters for a single tool call.
|
|
59
|
+
*/
|
|
60
|
+
export type HermesSessionResolved = {
|
|
61
|
+
/** The resolved Metro inspector proxy port. */
|
|
62
|
+
metroPort: number;
|
|
63
|
+
/** The resolved expected app bundle ID. */
|
|
64
|
+
appId: string;
|
|
65
|
+
/** The pinned Hermes `logicalDeviceId`, if one has been set. */
|
|
66
|
+
pinnedDeviceId: string | undefined;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Options for constructing a {@link HermesSession}.
|
|
70
|
+
*/
|
|
71
|
+
export type HermesSessionOptions = {
|
|
72
|
+
/** The active platform, used only to pick the default app bundle ID. */
|
|
73
|
+
platform?: HermesPlatform;
|
|
74
|
+
/**
|
|
75
|
+
* Environment source. Defaults to `process.env`. Injectable for tests so
|
|
76
|
+
* resolution precedence can be exercised without mutating the real env.
|
|
77
|
+
*/
|
|
78
|
+
env?: NodeJS.ProcessEnv;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Holds the Metro port, expected appId, and pinned Hermes deviceId for a
|
|
82
|
+
* process-lifetime Hermes session.
|
|
83
|
+
*
|
|
84
|
+
* The stored port and appId are resolved once at construction time using
|
|
85
|
+
* `param ?? env ?? default` precedence (with `param` being undefined at
|
|
86
|
+
* construction — those are supplied per call to {@link resolve}). The pinned
|
|
87
|
+
* deviceId starts unset and is assigned on the first successful identity probe.
|
|
88
|
+
*/
|
|
89
|
+
export declare class HermesSession {
|
|
90
|
+
#private;
|
|
91
|
+
constructor(options?: HermesSessionOptions);
|
|
92
|
+
/**
|
|
93
|
+
* Returns the session-default Metro inspector proxy port.
|
|
94
|
+
*
|
|
95
|
+
* @returns The resolved Metro port (env `HERMES_METRO_PORT`, else 8081).
|
|
96
|
+
*/
|
|
97
|
+
getMetroPort(): number;
|
|
98
|
+
/**
|
|
99
|
+
* Returns the session-default expected app bundle ID.
|
|
100
|
+
*
|
|
101
|
+
* @returns The resolved app bundle ID (env `HERMES_APP_ID`, else the
|
|
102
|
+
* platform default).
|
|
103
|
+
*/
|
|
104
|
+
getAppId(): string;
|
|
105
|
+
/**
|
|
106
|
+
* Returns the pinned Hermes `logicalDeviceId` for this session, if any.
|
|
107
|
+
*
|
|
108
|
+
* Set on the first successful identity probe via
|
|
109
|
+
* {@link setPinnedHermesDeviceId}. Persists for the lifetime of this
|
|
110
|
+
* instance.
|
|
111
|
+
*
|
|
112
|
+
* @returns The pinned `logicalDeviceId`, or undefined when no pin is set.
|
|
113
|
+
*/
|
|
114
|
+
getPinnedHermesDeviceId(): string | undefined;
|
|
115
|
+
/**
|
|
116
|
+
* Pin the Hermes `logicalDeviceId` for this session.
|
|
117
|
+
*
|
|
118
|
+
* Called after a successful identity probe on the first call. Subsequent
|
|
119
|
+
* calls then enforce this pin to prevent target switching mid-session.
|
|
120
|
+
*
|
|
121
|
+
* @param id - The `logicalDeviceId` from Metro's
|
|
122
|
+
* `reactNative.logicalDeviceId` field.
|
|
123
|
+
*/
|
|
124
|
+
setPinnedHermesDeviceId(id: string): void;
|
|
125
|
+
/**
|
|
126
|
+
* Resolve the effective parameters for a single tool call by merging
|
|
127
|
+
* per-call overrides over the stored session defaults.
|
|
128
|
+
*
|
|
129
|
+
* This is PURE with respect to stored state: it never mutates the stored
|
|
130
|
+
* port, appId, or pin. Only {@link setPinnedHermesDeviceId} mutates the pin.
|
|
131
|
+
*
|
|
132
|
+
* Port precedence is `input.metroPort ?? this.getMetroPort()` (which itself
|
|
133
|
+
* already encodes `env ?? default`), mirroring the reference driver's
|
|
134
|
+
* `input.metroPort ?? driver.getMetroPort() ?? 8081`.
|
|
135
|
+
*
|
|
136
|
+
* AppId precedence is `input.appId ?? <HERMES_APP_ID env if set> ??
|
|
137
|
+
* defaultAppIdForPlatform(input.platform) ?? <stored default>`. An explicitly
|
|
138
|
+
* set `HERMES_APP_ID` always WINS over the per-call platform default (env is a
|
|
139
|
+
* deliberate override): in that case the stored appId is returned unchanged.
|
|
140
|
+
* Only when the stored appId is the construction-time platform fallback does
|
|
141
|
+
* a per-call `platform` recompute it — without mutating stored state. When no
|
|
142
|
+
* `platform` is passed this preserves the original iOS-default behavior.
|
|
143
|
+
*
|
|
144
|
+
* @param input - Optional per-call overrides for port, appId, and platform.
|
|
145
|
+
* @returns The effective `{ metroPort, appId, pinnedDeviceId }`.
|
|
146
|
+
*/
|
|
147
|
+
resolve(input?: HermesSessionResolveInput): HermesSessionResolved;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Returns the process-singleton {@link HermesSession}, creating it on first
|
|
151
|
+
* access.
|
|
152
|
+
*
|
|
153
|
+
* @param options - Options applied only when the singleton is first created.
|
|
154
|
+
* @returns The shared `HermesSession` instance.
|
|
155
|
+
*/
|
|
156
|
+
export declare function getHermesSession(options?: HermesSessionOptions): HermesSession;
|
|
157
|
+
/**
|
|
158
|
+
* Resets the process-singleton {@link HermesSession}.
|
|
159
|
+
*
|
|
160
|
+
* Intended for test isolation so each test can start from a clean session.
|
|
161
|
+
*/
|
|
162
|
+
export declare function resetHermesSession(): void;
|
|
163
|
+
//# sourceMappingURL=session.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.d.cts","sourceRoot":"","sources":["../../src/hermes/session.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GAAG,KAAK,GAAG,SAAS,CAAC;AAE/C,qEAAqE;AACrE,eAAO,MAAM,kBAAkB,yBAAyB,CAAC;AAEzD,oEAAoE;AACpE,eAAO,MAAM,sBAAsB,gBAAgB,CAAC;AAEpD,kEAAkE;AAClE,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAEvC;;;;;;;;;GASG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,CAAC,EAAE,cAAc,GAAG,MAAM,CAEzE;AAgBD;;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