agent-device 0.21.0 → 0.21.1

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 (282) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.apk → agent-device-android-ime-helper-0.21.1.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.1.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.0.manifest.json → agent-device-android-ime-helper-0.21.1.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.apk → agent-device-android-snapshot-helper-0.21.1.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.1.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.0.manifest.json → agent-device-android-snapshot-helper-0.21.1.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/README.md +58 -1
  8. package/apple/snapshot-bridge/SnapshotBridge.m +6 -0
  9. package/apple/snapshot-bridge/SnapshotBridgeCapture.h +25 -0
  10. package/apple/snapshot-bridge/SnapshotBridgeCapture.m +138 -0
  11. package/apple/snapshot-bridge/SnapshotBridgeRuntime.h +1 -0
  12. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +32 -3
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +12 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSelectorMatchPolicy.swift +15 -15
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerSystemSurfaceHostPolicy.swift +72 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift +63 -14
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +668 -82
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Alert.swift +14 -4
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+BlockingSystemModalResolution.swift +39 -4
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +1065 -223
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +290 -0
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Environment.swift +1 -1
  24. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Exceptions.swift +10 -10
  25. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +249 -61
  26. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +101 -42
  27. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +13 -13
  28. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +51 -43
  29. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Navigation.swift +71 -4
  30. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +144 -7
  31. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScreenRecorder.swift +13 -1
  32. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+ScrollGesture.swift +216 -17
  33. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SequenceExecution.swift +206 -22
  34. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +289 -42
  35. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +92 -22
  36. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +617 -122
  37. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotTiming.swift +79 -4
  38. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedCommitDeadline.swift +71 -71
  39. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedGesturePolicy.swift +83 -5
  40. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedTextEntry.swift +67 -67
  41. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +4 -4
  42. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +17 -17
  43. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +30 -30
  44. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryReadiness.swift +31 -31
  45. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputCandidatePolicy.swift +28 -0
  46. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextInputProbe.swift +101 -0
  47. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +19 -19
  48. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Transport.swift +55 -17
  49. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TvRemote.swift +26 -5
  50. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +125 -75
  51. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/RecordingExportSupport.swift +9 -9
  52. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-overlay.swift +9 -9
  53. package/dist/apple/runner/AgentDeviceRunner/RecordingScripts/recording-trim.swift +4 -4
  54. package/dist/src/adapter.js +1 -1
  55. package/dist/src/adb-executor.js +1 -1
  56. package/dist/src/adb-failure.js +1 -1
  57. package/dist/src/agent-browser-process-record.js +1 -1
  58. package/dist/src/agent-browser-provider.js +1 -1
  59. package/dist/src/agent-browser-tool.js +1 -1
  60. package/dist/src/agent-device-client.js +2 -2
  61. package/dist/src/ai-sdk.d.ts +1 -1
  62. package/dist/src/ai-sdk.js +1 -1
  63. package/dist/src/alert-runtime.js +1 -1
  64. package/dist/src/android-input-ownership.js +1 -1
  65. package/dist/src/app-catalog.js +1 -1
  66. package/dist/src/app-deployment-resolution.js +1 -1
  67. package/dist/src/app-inventory-contract.js +1 -1
  68. package/dist/src/app-inventory.js +1 -1
  69. package/dist/src/app-launch.js +2 -2
  70. package/dist/src/app-lifecycle.js +3 -3
  71. package/dist/src/app-lifecycle2.js +1 -1
  72. package/dist/src/app-log-files.js +1 -1
  73. package/dist/src/app-log-runtime2.js +3 -3
  74. package/dist/src/app-resolution.js +1 -1
  75. package/dist/src/apple-runner-platform.js +1 -0
  76. package/dist/src/application-lifecycle-interaction.js +1 -1
  77. package/dist/src/archive.js +1 -1
  78. package/dist/src/artifact-download.js +1 -1
  79. package/dist/src/auth-session.js +1 -1
  80. package/dist/src/auth.js +1 -1
  81. package/dist/src/backend-snapshot-options.js +1 -1
  82. package/dist/src/boot-diagnostics.js +1 -1
  83. package/dist/src/capture.js +1 -1
  84. package/dist/src/cli-config.js +1 -1
  85. package/dist/src/cli-help.js +25 -21
  86. package/dist/src/cli-runner.js +1 -1
  87. package/dist/src/cli.js +4 -4
  88. package/dist/src/click-button.js +1 -1
  89. package/dist/src/client-metro-companion.js +1 -1
  90. package/dist/src/client-metro.js +1 -1
  91. package/dist/src/client-types.d.ts +27 -13
  92. package/dist/src/code-signature-cache.js +1 -1
  93. package/dist/src/code-signature.js +1 -1
  94. package/dist/src/command-schema.js +3 -3
  95. package/dist/src/command-tools.js +2 -2
  96. package/dist/src/command.js +1 -1
  97. package/dist/src/connection-runtime.js +1 -1
  98. package/dist/src/connection.js +3 -3
  99. package/dist/src/contracts.d.ts +1 -1
  100. package/dist/src/contracts.js +1 -1
  101. package/dist/src/daemon-client-lifecycle.js +1 -1
  102. package/dist/src/daemon.js +1 -1
  103. package/dist/src/debug-symbols-facade.js +1 -1
  104. package/dist/src/device-claim-rule.js +1 -1
  105. package/dist/src/device-inventory-context.js +1 -1
  106. package/dist/src/device-rotation.js +1 -1
  107. package/dist/src/device-selection-resolver.js +1 -1
  108. package/dist/src/device-session.js +1 -1
  109. package/dist/src/device2.js +1 -1
  110. package/dist/src/diagnostics.js +1 -1
  111. package/dist/src/dispatch-resolve.js +1 -1
  112. package/dist/src/doctor2.js +1 -1
  113. package/dist/src/error.js +1 -1
  114. package/dist/src/exec.js +1 -1
  115. package/dist/src/file.js +1 -1
  116. package/dist/src/find.js +1 -1
  117. package/dist/src/generic-settle.js +1 -1
  118. package/dist/src/gesture-plan.js +1 -1
  119. package/dist/src/gesture-runtime.js +1 -1
  120. package/dist/src/harmonyos.js +1 -1
  121. package/dist/src/hdc.js +1 -1
  122. package/dist/src/helper.js +2 -2
  123. package/dist/src/human-control-contract.js +1 -1
  124. package/dist/src/human-control.js +1 -1
  125. package/dist/src/index.d.ts +1 -1
  126. package/dist/src/index.js +1 -1
  127. package/dist/src/input-actions.js +1 -1
  128. package/dist/src/input-actions2.js +2 -2
  129. package/dist/src/install-artifact-facade.js +1 -1
  130. package/dist/src/install-source-network-transport.js +1 -1
  131. package/dist/src/install-source2.js +1 -1
  132. package/dist/src/interaction-positionals.js +1 -1
  133. package/dist/src/interaction-ref-policy.js +1 -1
  134. package/dist/src/interaction2.js +1 -1
  135. package/dist/src/interactor.js +5 -5
  136. package/dist/src/interactor2.js +1 -1
  137. package/dist/src/interactors.js +1 -1
  138. package/dist/src/internal/bin.js +1 -1
  139. package/dist/src/internal/daemon.js +2 -2
  140. package/dist/src/internal/png-worker.js +1 -1
  141. package/dist/src/internal/run-script-http-child.js +1 -1
  142. package/dist/src/inventory.js +2 -2
  143. package/dist/src/inventory2.js +1 -1
  144. package/dist/src/inventory3.js +1 -1
  145. package/dist/src/inventory5.js +1 -1
  146. package/dist/src/ios-snapshot-runtime.js +1 -1
  147. package/dist/src/ios-system-surface.js +1 -0
  148. package/dist/src/lease-scope.js +1 -1
  149. package/dist/src/lease.js +1 -1
  150. package/dist/src/limrun-runtime-dependencies.js +1 -1
  151. package/dist/src/limrun.d.ts +1 -1
  152. package/dist/src/linux.js +1 -1
  153. package/dist/src/location-coordinates.js +1 -1
  154. package/dist/src/managed-device-scope.js +1 -1
  155. package/dist/src/mechanics.js +16 -16
  156. package/dist/src/multitouch-support.js +1 -1
  157. package/dist/src/observation.js +1 -1
  158. package/dist/src/open-target-resolution.js +1 -0
  159. package/dist/src/owner-identity.js +3 -3
  160. package/dist/src/parameterized-recorded-fill.js +1 -1
  161. package/dist/src/perf-facade.js +2 -2
  162. package/dist/src/perf-process-identity.js +1 -0
  163. package/dist/src/perf-runtime-operation-builder.js +1 -1
  164. package/dist/src/perf-runtime-plan.js +1 -1
  165. package/dist/src/perf.js +1 -1
  166. package/dist/src/physical-device-control.js +1 -1
  167. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  168. package/dist/src/platform-runtime-app-log-process.js +1 -1
  169. package/dist/src/platform-runtime-host.js +1 -1
  170. package/dist/src/platform-runtime-managed-owner.js +1 -1
  171. package/dist/src/platform-runtime-open-target.js +1 -1
  172. package/dist/src/platform-runtime-operation-host.js +2 -2
  173. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  174. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  175. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  176. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  177. package/dist/src/platform-runtime-unavailable.js +1 -1
  178. package/dist/src/platform-runtime.js +1 -1
  179. package/dist/src/platform-runtime2.js +1 -1
  180. package/dist/src/png-worker-contract.js +1 -1
  181. package/dist/src/prepare-kind.js +1 -1
  182. package/dist/src/provider-device-runtime.js +1 -1
  183. package/dist/src/provider-session-ownership.js +1 -1
  184. package/dist/src/provider-webdriver.js +1 -1
  185. package/dist/src/proxy.js +1 -1
  186. package/dist/src/react-native.js +1 -1
  187. package/dist/src/record-runtime.js +1 -1
  188. package/dist/src/rect-center.js +1 -1
  189. package/dist/src/register-builtins.js +1 -1
  190. package/dist/src/registry.js +37 -36
  191. package/dist/src/remote-config2.js +1 -1
  192. package/dist/src/replay-divergence.js +1 -1
  193. package/dist/src/replay.js +2 -2
  194. package/dist/src/reporting.js +9 -8
  195. package/dist/src/request-admission.js +1 -1
  196. package/dist/src/request-cancel.js +1 -1
  197. package/dist/src/request-runtime-binding.js +1 -1
  198. package/dist/src/retry.js +1 -1
  199. package/dist/src/runner-cache-metadata.js +2 -2
  200. package/dist/src/runner-client.js +1 -1
  201. package/dist/src/runner-disposal.js +1 -1
  202. package/dist/src/runner-operations-facade.js +1 -1
  203. package/dist/src/runner.js +1 -1
  204. package/dist/src/runtime-transport-hints.js +1 -1
  205. package/dist/src/runtime.js +3 -3
  206. package/dist/src/runtime2.js +4 -4
  207. package/dist/src/runtime3.js +1 -1
  208. package/dist/src/runtime4.js +5 -4
  209. package/dist/src/runtime5.js +1 -1
  210. package/dist/src/runtime6.js +1 -1
  211. package/dist/src/runtime7.js +1 -1
  212. package/dist/src/runtime8.js +1 -1
  213. package/dist/src/runtime9.js +1 -1
  214. package/dist/src/screen-recording-live-handle.js +1 -1
  215. package/dist/src/screen-recording-options.js +1 -1
  216. package/dist/src/screen-recording-resource-recovery.js +1 -1
  217. package/dist/src/screenshot-density.js +1 -1
  218. package/dist/src/screenshot-runtime.js +1 -1
  219. package/dist/src/screenshot.js +1 -1
  220. package/dist/src/screenshot3.js +3 -3
  221. package/dist/src/script.js +1 -1
  222. package/dist/src/scroll-command.js +1 -1
  223. package/dist/src/scroll-gesture.js +1 -1
  224. package/dist/src/sdk-batch-runner.js +2 -2
  225. package/dist/src/sdk-batch.js +2 -2
  226. package/dist/src/sdk-contracts.d.ts +44 -1
  227. package/dist/src/sdk-contracts.js +2 -2
  228. package/dist/src/sdk-device.js +1 -1
  229. package/dist/src/sdk-finders.d.ts +1 -1
  230. package/dist/src/sdk-io.js +1 -1
  231. package/dist/src/sdk-remote-config.d.ts +1 -1
  232. package/dist/src/sdk-remote-config.js +1 -1
  233. package/dist/src/sdk-selectors.d.ts +69 -13
  234. package/dist/src/selector-runtime.js +1 -1
  235. package/dist/src/server.js +3 -3
  236. package/dist/src/session-allocation.js +1 -1
  237. package/dist/src/session-observation.js +1 -0
  238. package/dist/src/session-routing.js +1 -1
  239. package/dist/src/session-runtime-admission.js +1 -1
  240. package/dist/src/session-snapshot.js +1 -1
  241. package/dist/src/session-store.js +3 -3
  242. package/dist/src/session-target-evidence.js +1 -1
  243. package/dist/src/session2.js +5 -5
  244. package/dist/src/settings.js +1 -1
  245. package/dist/src/simulator.js +1 -1
  246. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  247. package/dist/src/snapshot-quality-verdict.js +1 -1
  248. package/dist/src/snapshot-runtime-binding.js +1 -1
  249. package/dist/src/snapshot-runtime.js +1 -1
  250. package/dist/src/snapshot-state.js +1 -1
  251. package/dist/src/snapshot2.js +1 -1
  252. package/dist/src/snapshot3.js +1 -1
  253. package/dist/src/snapshot4.js +1 -1
  254. package/dist/src/src.js +1 -1
  255. package/dist/src/src7.js +2 -2
  256. package/dist/src/src8.js +2 -2
  257. package/dist/src/string-enum.js +1 -1
  258. package/dist/src/takeover.js +1 -1
  259. package/dist/src/tool-provider.js +2 -2
  260. package/dist/src/tool-provider2.js +1 -1
  261. package/dist/src/tool-provider3.js +1 -1
  262. package/dist/src/toolchain-probe.js +1 -1
  263. package/dist/src/touch-reference-frame.js +1 -0
  264. package/dist/src/touch-runtime.js +1 -1
  265. package/dist/src/transport.js +1 -1
  266. package/dist/src/tv-remote.js +1 -1
  267. package/dist/src/type-text-runtime.js +1 -1
  268. package/dist/src/update-check.js +1 -1
  269. package/dist/src/verified-file.js +1 -1
  270. package/dist/src/video.js +1 -1
  271. package/dist/src/web.js +1 -1
  272. package/dist/src/web2.js +1 -1
  273. package/dist/src/webdriver-source.js +1 -1
  274. package/dist/src/window-state.js +1 -0
  275. package/package.json +3 -2
  276. package/server.json +2 -2
  277. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.0.apk.sha256 +0 -1
  278. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.0.apk.sha256 +0 -1
  279. package/dist/src/back-mode.js +0 -1
  280. package/dist/src/format.js +0 -2
  281. package/dist/src/platform-runtime-apple-resources.js +0 -1
  282. package/dist/src/runner-selector-query.js +0 -1
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Wt as n,Xt as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o,t as s}from"./touch-runtime.js";import{A as c,D as l,G as u,H as d,I as f,L as p,N as ee,O as te,P as m,R as h,T as g,U as ne,a as re,b as ie,d as ae,g as oe,i as se,j as ce,m as le,s as ue,t as de,v as fe,w as pe,x as me,z as he}from"./alert-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{a as _,n as v}from"./durable-resource.js";import{n as ve}from"./async-lifecycle.js";import{i as ye,r as be}from"./src7.js";import{t as y}from"./screen-recording-live-handle.js";import{t as b}from"./screen-recording-completion.js";import{t as x}from"./screen-recording-options.js";import{t as S}from"./screen-recording-runtime.js";import{i as C}from"./gesture-admission.js";import{t as w}from"./interactor-operation-catalog.js";import{i as T,n as E}from"./perf-runtime-operation-builder.js";import{t as D}from"./app-log-runtime.js";import{n as O,t as k}from"./application-lifecycle-interaction.js";import{randomUUID as A}from"node:crypto";import{setTimeout as j}from"node:timers/promises";const M=Object.freeze({resourceKind:D,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!P(e.outputPath)||!P(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function N(e){return v({resourceKind:D,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:_(M,e.descriptor)})}function P(e){return typeof e==`string`&&e.trim().length>0}function xe(e){return be(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:M,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await Se(e,r);return{resolvePid:async r=>await ye(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>N({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Se(t,n){n.throwIfAborted(),await F(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await F(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function F(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function Ce(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await T(t().sampleMemory(n,e)):E(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const I=Object.freeze({resourceKind:S,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&Ee(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function we(e){let{device:n,owner:r,input:i,descriptor:a}=e;return v({resourceKind:S,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:_(I,a)})}function Te(e){return I.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function Ee(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function De(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function Oe(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await ke({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>Te(e.envelope.descriptor.body)})}async function ke(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);x(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${A()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await R(n,r,c).catch(()=>{}),o.reason):e}B(l,`start`);try{o.throwIfAborted()}catch(e){throw await R(n,r,c).catch(()=>{}),e}let u=Ae(a),d=!1,f=async()=>{d||=(B(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=y(u,{finish:async e=>await je(n,r,e,c,f),forceCleanup:async()=>await R(n,r,c,f)});return Object.freeze({pendingHandle:new ve(p),envelope:we({device:r,owner:i,input:a,descriptor:c})})}function Ae(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function je(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await Pe(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await Me(e,t,r,a);return b(n,{...i,...Ne(i.warning,o)},!1)}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function Me(e,t,n,r){let i=[];return await L(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await L(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function L(e){try{return await e()}catch{return!1}}function Ne(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function Pe(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function R(e,t,n,r=async()=>{B(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await z(r),await z(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await z(async()=>await Fe(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Fe(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function z(e){try{await e();return}catch(e){return e}}function B(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function Ie(t,n){n.throwIfAborted();let{runHarmonyHdc:r}=await import(`./hdc.js`),i=await r(t,[`shell`,`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=Le(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function Le(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}function Re(e){return k({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,binding:O({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const ze=Object.freeze({available:!0}),Be=Object.freeze({available:!1,reason:`unsupported-device-kind`}),V=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function H(e){let t=e.kind===`emulator`||e.kind===`device`?ze:Be;return Object.freeze({deployApp:t,materializeAppSource:V,deployMaterializedApp:V,sendPushNotification:V})}function Ve(e){return H(e.device).deployApp.available?Object.freeze({deployApp:async t=>await He(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function He(t,n,r,i){let a=await Ue(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await U(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await j(1e3,void 0,{signal:i}),await We(t,n,a,i)),{packageName:a,launchTarget:a}}async function Ue(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function We(t,n,r,i){let a=Ge((await U(t,n,[`shell`,`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await U(t,n,[`shell`,`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Ge(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function U(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}const W=n(`harmonyos`),Ke=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`HarmonyOS reads element text from the captured tree only.`}),qe=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on HarmonyOS emulators and physical devices.`}),G=Object.freeze({available:!0}),K=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Je=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`}),Ye=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),q=Object.freeze({available:!0}),Xe=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for HarmonyOS emulators and devices.`}),Ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for HarmonyOS emulators and devices.`}),Qe=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),J=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for HarmonyOS emulators and devices.`}),Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for HarmonyOS emulators and devices.`}),$e=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),et=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`});function tt(e){let t=nt(e),n=rt(e);return a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:K,clearRuntimeHints:K,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Ye,configureProviderPortReverse:Qe})}function nt(e){return e.kind===`emulator`||e.kind===`device`?q:Xe}function rt(e){return e.kind===`emulator`||e.kind===`device`?q:Ze}const it=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on HarmonyOS emulators and physical devices.`}),at=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ot=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:C});function X(e){return e.kind===`emulator`||e.kind===`device`?G:it}function Z(e){return e.kind===`emulator`||e.kind===`device`?G:qe}const Q=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),st=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`}),$=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`});function ct(e){let t=xe(e),n=async e=>{let n=await t.inspectFacts(e),r=H(e),i=De(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?Je:G,networkDump:K,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...d({capture:e.kind===`emulator`||e.kind===`device`?G:J,customActions:$e,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?G:J}),...u({capture:e.kind===`emulator`||e.kind===`device`?G:Y}),...h({findText:J,findSelector:J}),...p({setViewport:et}),...f({focus:Z(e)}),...ee({plan:X(e),directionalFling:X(e),multiTouch:at,targetAuthoredDrag:ot,viewport:X(e)}),...c({scroll:X(e)}),...l({type:Z(e)}),...o({tap:Z(e),tapRef:K,longPress:Z(e),hover:K,hoverRef:K,fill:Z(e),fillRef:K,tapElementSelector:K}),...pe({readTextAtPoint:Ke}),...me({back:Z(e)}),...ie({home:Z(e)}),...ue({appSwitcher:Z(e)}),...re({triggerAppEvent:Q}),...se({setSetting:Z(e)}),...de({read:Q,wait:Q,accept:Q,dismiss:Q}),...fe({orientation:Q}),...oe({tvRemote:Q}),...le({status:st,dismiss:Z(e),enter:Z(e)}),...ae({read:Q,write:Q}),...ge({capture:$,query:$}),..._e({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:G,bootTarget:K,bootTargetHeadless:K,listApps:G,...tt(e),shutdownTarget:K}})};return Object.freeze({owner:W,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async a=>{let o=await t.bind(a),c=await n(a.device),l=c.operations.screenRecordingStart;return Object.freeze({device:o.device,owner:W,facts:c,operations:Object.freeze({...o.operations,...Ve({commands:e.commands,device:a.device,signal:a.scope.signal}),...c.operations.appState.available?{appState:async()=>await Ie(a.device,a.scope.signal)}:{},ensureReady:async()=>({...a.device,booted:!0}),...l.available?Oe({host:e,device:a.device,owner:W,signal:a.scope.signal}):{},...c.operations.captureSnapshot.available?he({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.captureScreenshot.available?ne({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.focusPoint.available?m({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.typeText.available?g({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...ce({device:a.device,signal:a.scope.signal,facts:c.operations,resolveInteractor:e.localInteractors.resolve}),...c.operations.scrollDirection.available?te({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...w({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations}),...r(c.operations.perfFrames,()=>Ce({resolveHost:()=>e.perf.harmony,device:a.device})),...r(c.operations.tapPoint,()=>s({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations,pause:async t=>await e.clock.sleep(t,a.scope.signal)})),listApps:async e=>{a.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:a.scope.signal})).map(e=>({id:e.package,name:e.name}))},...i(Re({host:e.localInteractors,device:a.device,signal:a.scope.signal}),c.operations)}),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{ct as createHarmonyPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Wt as n,Xt as r}from"./sdk-batch.js";import{n as i,t as a}from"./application-lifecycle-runtime.js";import{i as o,t as s}from"./touch-runtime.js";import{A as c,D as l,G as u,H as d,I as f,L as p,N as ee,O as te,P as m,R as h,T as g,U as ne,a as re,b as ie,d as ae,g as oe,i as se,j as ce,m as le,s as ue,t as de,v as fe,w as pe,x as me,z as he}from"./alert-runtime.js";import{n as ge}from"./audio-probe-runtime.js";import{n as _e}from"./perf-runtime.js";import{a as _,n as v}from"./durable-resource.js";import{n as ve}from"./async-lifecycle.js";import{i as ye,r as be}from"./src7.js";import{t as xe}from"./screen-recording-live-handle.js";import{t as y}from"./screen-recording-completion.js";import{t as b}from"./screen-recording-options.js";import{t as x}from"./screen-recording-runtime.js";import{i as S}from"./gesture-admission.js";import{t as C}from"./interactor-operation-catalog.js";import{i as w,n as T}from"./perf-runtime-operation-builder.js";import{t as E}from"./app-log-runtime.js";import{n as D,t as O}from"./application-lifecycle-interaction.js";import{randomUUID as k}from"node:crypto";import{setTimeout as A}from"node:timers/promises";const j=Object.freeze({resourceKind:E,version:1,encode:e=>({...e}),decode:e=>e.transport!==`harmony-hilog`||!N(e.outputPath)||!N(e.pidPath)?{status:`invalid`,message:`Invalid HarmonyOS app-log descriptor`}:{status:`decoded`,descriptor:Object.freeze({transport:`harmony-hilog`,outputPath:e.outputPath,pidPath:e.pidPath})}});function M(e){return v({resourceKind:E,sessionId:e.sessionId,device:{id:e.device.id,family:`harmonyos`,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target}},owner:e.owner,fence:e.fence,lifecycle:`open`,descriptor:_(j,e.descriptor)})}function N(e){return typeof e==`string`&&e.trim().length>0}function Se(e){return be(e,{family:`harmonyos`,backend:`harmonyos`,label:`HarmonyOS`,codec:j,startUnavailableHint:`The selected HarmonyOS transport cannot start a background hilog stream.`,cleanupFailureMessage:`HarmonyOS app-log cleanup did not settle every owned resource`,doctor:async(e,t)=>({backend:`harmonyos`,checks:{},notes:t?[]:[`No app bundle is tracked in this session. Run open <app> first for app-scoped logs.`]}),process:async({host:e,device:t,input:n,signal:r})=>{let i=await Ce(e,r);return{resolvePid:async r=>await ye(e,{executable:i,args:[`-t`,t.id,`shell`,`pidof`,n.appBundleId],allowFailure:!0,timeoutMs:5e3},r),command:e=>({kind:`host`,request:{executable:i,args:[`-t`,t.id,`shell`,`hilog`,`-P`,e],allowFailure:!0}})}},descriptor:({artifacts:e})=>({transport:`harmony-hilog`,...e}),envelope:({input:e,device:t,owner:n,descriptor:r})=>M({sessionId:e.sessionId,device:t,owner:n,fence:e.fence,descriptor:r})})}async function Ce(t,n){n.throwIfAborted(),await P(async()=>await t.toolchains.prepare(`harmonyos`),n),n.throwIfAborted();let r=await P(async()=>await t.commands.which(`hdc`),n);if(n.throwIfAborted(),!r)throw new e(`TOOL_MISSING`,`hdc not found in PATH`,{hint:`Install HarmonyOS Command Line Tools, then add its sdk/default/openharmony/toolchains directory to PATH.`});return r}async function P(e,t){try{return await e()}catch(e){throw t.throwIfAborted(),e}}function we(e){let{resolveHost:t,device:n}=e,r={available:!1,reason:`Dropped-frame sampling is currently available only on Android app sessions and connected iOS device app sessions.`};return Object.freeze({perfFrames:async()=>({metric:r,sampling:r}),perfMemorySample:async({appId:e})=>({metric:e?await w(t().sampleMemory(n,e)):T(`HarmonyOS`,`bundle`),sampling:{method:`hdc-shell-proc-status`,description:`Resident memory snapshot from HarmonyOS /proc/<pid>/status. Values are reported in kilobytes.`,unit:`kB`,topConsumerLimit:1}}),perfMemorySnapshot:async({kind:e})=>({artifact:{available:!1,kind:e??`memgraph`,reason:`Memory snapshot artifacts are not supported on harmonyos.`,hint:`Use perf memory sample where supported, or run the snapshot against Android, iOS simulator, or macOS.`,support:{platform:`harmonyos`,defaultKind:`memgraph`,androidHprof:!1,memgraph:!1,heapprofd:!1}},sampling:{method:`unsupported`,description:`HarmonyOS memory snapshot capture is not available through HDC.`,artifactOnly:!0}})})}const F=Object.freeze({resourceKind:x,version:1,encode:e=>({...e}),decode:e=>e.backend===`harmony-screen-recorder`&&typeof e.fileName==`string`&&De(e.fileName)&&e.remotePath===`/data/local/tmp/${e.fileName}`?{status:`decoded`,descriptor:Object.freeze({backend:`harmony-screen-recorder`,fileName:e.fileName,remotePath:e.remotePath})}:{status:`invalid`,message:`Invalid HarmonyOS screen-recording descriptor`}});function Te(e){let{device:n,owner:r,input:i,descriptor:a}=e;return v({resourceKind:x,sessionId:i.sessionId,device:t(n),owner:r,fence:i.fence,lifecycle:`open`,descriptor:_(F,a)})}function Ee(e){return F.decode(e).status===`decoded`?{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`HarmonyOS recorder ownership cannot be proven after daemon restart; no recorder was stopped.`}:{status:`cleanup-pending`,reason:`manual-recovery-required`}}function De(e){return/^agent-device-recording-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.mp4$/i.test(e)}function Oe(e){return e.kind===`device`?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS recording is supported on physical devices only.`})}function ke(e){let{host:t,device:n,owner:r,signal:i}=e;return Object.freeze({screenRecordingStart:async e=>await Ae({host:t,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`HarmonyOS recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async e=>Ee(e.envelope.descriptor.body)})}async function Ae(t){let{host:n,device:r,owner:i,input:a,signal:o}=t;if(a.scope===`app`)throw new e(`INVALID_ARGS`,`HarmonyOS recording captures the whole physical-device screen; use --scope device or --scope system`);b(a,{scopes:[`device`,`system`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`HarmonyOS recordings do not support ${e.join(`, `)}`),o.throwIfAborted(),await n.screenRecording.outputs.prepare(a.outputPath);let s=`agent-device-recording-${k()}.mp4`,c={backend:`harmony-screen-recorder`,fileName:s,remotePath:`/data/local/tmp/${s}`},l;try{l=await n.screenRecording.harmony.start(r,s,o),o.throwIfAborted()}catch(e){throw o.aborted?(await L(n,r,c).catch(()=>{}),o.reason):e}z(l,`start`);try{o.throwIfAborted()}catch(e){throw await L(n,r,c).catch(()=>{}),e}let u=je(a),d=!1,f=async()=>{d||=(z(await n.screenRecording.harmony.stop(r),`stop`),!0)},p=xe(u,{finish:async e=>await Me(n,r,e,c,f),forceCleanup:async()=>await L(n,r,c,f)});return Object.freeze({pendingHandle:new ve(p),envelope:Te({device:r,owner:i,input:a,descriptor:c})})}function je(e){return Object.freeze({backend:`HarmonyOS ScreenRecorder`,outPath:e.outputPath,...e.clientOutputPath===void 0?{}:{clientOutPath:e.clientOutputPath},startedAt:Date.now(),scope:e.scope,showTouches:!1,recordOnlySession:e.recordOnlySession,...e.activeSessionApp===void 0?{}:{activeSessionApp:e.activeSessionApp},gestureEvents:[]})}async function Me(e,t,n,r,i){await i();let a=await e.screenRecording.harmony.findMedia(t,r.fileName);if(!a)throw Error(`failed to find finalized HarmonyOS recording '${r.fileName}'`);if(!await Fe(e,t,r,a))throw Error(`failed to finalize HarmonyOS recording: ${r.fileName} did not produce a non-empty media file`);try{if((await e.screenRecording.harmony.pull(t,{remotePath:r.remotePath,outputPath:n.outPath})).exitCode!==0)throw Error(`failed to retrieve HarmonyOS recording`);let i=await e.screenRecording.finalize.complete({outputPath:n.outPath,showTouches:!1,gestureEvents:n.gestureEvents,targetLabel:`HarmonyOS recording`}),o=await Ne(e,t,r,a);return y(n,{...i,...Pe(i.warning,o)},!1)}catch(n){throw await e.screenRecording.harmony.remove(t,r.remotePath).catch(()=>{}),n}}async function Ne(e,t,n,r){let i=[];return await I(()=>e.screenRecording.harmony.remove(t,n.remotePath))||i.push(`staging artifact`),await I(()=>e.screenRecording.harmony.removeMedia(t,r))||i.push(`media-library artifact`),i.length===0?void 0:`HarmonyOS recording completed, but cleanup was not confirmed for the ${i.join(` and `)}.`}async function I(e){try{return await e()}catch{return!1}}function Pe(e,t){let n=[e,t].filter(e=>e!==void 0).join(` `);return n.length===0?{}:{warning:n}}async function Fe(e,t,n,r){let i;for(let a=0;a<40;a+=1){if(await e.screenRecording.harmony.remove(t,n.remotePath).catch(()=>{}),await e.screenRecording.harmony.stageMedia(t,{mediaUri:r,remotePath:n.remotePath})){let r=await e.screenRecording.harmony.stagedFileSize(t,n.remotePath);if(r!==void 0&&r>0&&r===i)return!0;i=r!==void 0&&r>0?r:void 0}else i=void 0;a<39&&await e.clock.sleep(250)}return!1}async function L(e,t,n,r=async()=>{z(await e.screenRecording.harmony.stop(t),`stop`)}){let i=[await R(r),await R(async()=>{if(!await e.screenRecording.harmony.remove(t,n.remotePath))throw Error(`HarmonyOS recording staging artifact removal was not confirmed`)}),await R(async()=>await Ie(e,t,n.fileName))].find(e=>e!==void 0);return i===void 0?{status:`cleaned`}:{status:`cleanup-pending`,reason:`transport-failed`,message:i instanceof Error?i.message:`HarmonyOS recording cleanup failed`}}async function Ie(e,t,n){let r=await e.screenRecording.harmony.findMedia(t,n);if(r&&!await e.screenRecording.harmony.removeMedia(t,r))throw Error(`HarmonyOS recording media removal was not confirmed`)}async function R(e){try{await e();return}catch(e){return e}}function z(e,t){if(e.exitCode===0&&e.stdout.includes(`start ability successfully`))return;let n=e.stdout.trim()||e.stderr.trim()||`hdc exit ${e.exitCode}`;throw Error(`failed to ${t} HarmonyOS screen recording: ${n}`)}async function Le(t,n){n.throwIfAborted();let{runHarmonyHdc:r}=await import(`./hdc.js`),i=await r(t,[`shell`,`aa`,`dump`,`-l`],{timeoutMs:15e3,signal:n});n.throwIfAborted();let a=Re(i.stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine the foreground HarmonyOS app`,{hint:`Open an app on the target, then retry appstate.`});return a}function Re(e){let t=e.split(/(?=^\s*Mission ID #)/m);for(let e of t){if(!/\bstate #FOREGROUND\b/.test(e))continue;let t=e.match(/mission name #\[#([^:]+):[^:]*:([^\]]+)]/);if(!t)continue;let[,n,r]=t;if(!(!n||!r))return{package:n,activity:r}}}function ze(e){return O({owner:`HarmonyOS`,openTargetIdentity:`bundle-id`,binding:D({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const Be=Object.freeze({available:!0}),Ve=Object.freeze({available:!1,reason:`unsupported-device-kind`}),B=Object.freeze({available:!1,reason:`unsupported-platform-leaf`});function V(e){let t=e.kind===`emulator`||e.kind===`device`?Be:Ve;return Object.freeze({deployApp:t,materializeAppSource:B,deployMaterializedApp:B,sendPushNotification:B})}function He(e){return V(e.device).deployApp.available?Object.freeze({deployApp:async t=>await Ue(e.commands,e.device,t,e.signal)}):Object.freeze({})}async function Ue(t,n,r,i){let a=await We(t,r.appPath,i)??r.app.trim();if(!a)throw new e(`INVALID_ARGS`,`Could not determine the bundle name from the HAP archive`,{hint:`Pass the HarmonyOS bundle name before the HAP path, or provide a valid HAP containing module.json.`});return await H(t,n,[`install`,`-r`,r.appPath],i,18e4),r.replaceExisting&&(await A(1e3,void 0,{signal:i}),await Ge(t,n,a,i)),{packageName:a,launchTarget:a}}async function We(e,t,n){let r=await e.run({executable:`unzip`,args:[`-p`,t,`module.json`],allowFailure:!0,timeoutMs:15e3},n);if(r.exitCode===0&&r.stdout.trim().length!==0)try{return JSON.parse(r.stdout).app?.bundleName?.trim()||void 0}catch{return}}async function Ge(t,n,r,i){let a=Ke((await H(t,n,[`shell`,`bm`,`dump`,`-n`,r],i)).stdout);if(!a)throw new e(`COMMAND_FAILED`,`Could not determine a launchable ability for ${r}`,{hint:`Check that the HarmonyOS bundle exposes a main ability.`});await H(t,n,[`shell`,`aa`,`start`,`-b`,r,...a.module?[`-m`,a.module]:[],`-a`,a.ability],i)}function Ke(e){let t=e.indexOf(`{`);if(t!==-1)try{let n=JSON.parse(e.slice(t)).hapModuleInfos?.find(e=>e.mainElementName);return n?.mainElementName?{ability:n.mainElementName,...n.moduleName?{module:n.moduleName}:{}}:void 0}catch{return}}async function H(e,t,n,r,i=15e3){return await e.run({executable:`hdc`,args:[`-t`,t.id,...n],timeoutMs:i},r)}const U=n(`harmonyos`),qe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`HarmonyOS reads element text from the captured tree only.`}),Je=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`focus is supported on HarmonyOS emulators and physical devices.`}),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Ye=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`HarmonyOS appstate is supported only for HarmonyOS emulators and devices.`}),Xe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),K=Object.freeze({available:!0}),Ze=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for HarmonyOS emulators and devices.`}),Qe=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for HarmonyOS emulators and devices.`}),$e=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`}),q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`snapshot is supported only for HarmonyOS emulators and devices.`}),J=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`screenshot is supported only for HarmonyOS emulators and devices.`}),et=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),tt=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`viewport resizes web targets only (--platform web).`});function nt(e){let t=rt(e),n=it(e);return a({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:G,clearRuntimeHints:G,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:Xe,configureProviderPortReverse:$e})}function rt(e){return e.kind===`emulator`||e.kind===`device`?K:Ze}function it(e){return e.kind===`emulator`||e.kind===`device`?K:Qe}const Y=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`Gestures are supported on HarmonyOS emulators and physical devices.`}),at=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ot=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:S});function X(e){return e.kind===`emulator`||e.kind===`device`?W:Y}function Z(e){return e.kind===`emulator`||e.kind===`device`?W:Je}const Q=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),st=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`keyboard status/get is not available through the public HarmonyOS HDC API; use keyboard dismiss or enter`}),$=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`});function ct(e){let t=Se(e),n=async e=>{let n=await t.inspectFacts(e),r=V(e),i=Oe(e);return Object.freeze({device:n.device,operations:{...n.operations,...r,appState:e.kind===`simulator`?Ye:W,networkDump:G,screenRecordingStart:i,screenRecordingReattach:i,screenRecordingCleanup:i,...d({capture:e.kind===`emulator`||e.kind===`device`?W:q,customActions:et,withoutActiveApp:e.kind===`emulator`||e.kind===`device`?W:q}),...u({capture:e.kind===`emulator`||e.kind===`device`?W:J}),...h({findText:q}),...p({setViewport:tt}),...f({focus:Z(e)}),...ee({unsupported:Y,plan:X(e),directionalFling:X(e),multiTouch:at,targetAuthoredDrag:ot,viewport:X(e)}),...c({scroll:X(e)}),...l({type:Z(e)}),...o({unsupported:G,tap:Z(e),longPress:Z(e),fill:Z(e)}),...pe({readTextAtPoint:qe}),...me({back:Z(e)}),...ie({home:Z(e)}),...ue({appSwitcher:Z(e)}),...re({triggerAppEvent:Q}),...se({setSetting:Z(e)}),...de({read:Q,wait:Q,accept:Q,dismiss:Q}),...fe({orientation:Q}),...oe({tvRemote:Q}),...le({unsupported:Q,status:st,dismiss:Z(e),enter:Z(e)}),...ae({unsupported:Q}),...ge({capture:$,query:$}),..._e({frames:Z(e),memorySample:Z(e),memorySnapshot:Z(e),nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:G,bootTargetHeadless:G,listApps:W,...nt(e),shutdownTarget:G}})};return Object.freeze({owner:U,ownsDevice:e=>e.platform===`harmonyos`,inspectFacts:n,bind:async a=>{let o=await t.bind(a),c=await n(a.device),l=c.operations.screenRecordingStart;return Object.freeze({device:o.device,owner:U,facts:c,operations:Object.freeze({...o.operations,...He({commands:e.commands,device:a.device,signal:a.scope.signal}),...c.operations.appState.available?{appState:async()=>await Le(a.device,a.scope.signal)}:{},ensureReady:async()=>({...a.device,booted:!0}),...l.available?ke({host:e,device:a.device,owner:U,signal:a.scope.signal}):{},...c.operations.captureSnapshot.available?he({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.captureScreenshot.available?ne({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.focusPoint.available?m({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...c.operations.typeText.available?g({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...ce({device:a.device,signal:a.scope.signal,facts:c.operations,resolveInteractor:e.localInteractors.resolve}),...c.operations.scrollDirection.available?te({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve}):{},...C({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations}),...r(c.operations.perfFrames,()=>we({resolveHost:()=>e.perf.harmony,device:a.device})),...r(c.operations.tapPoint,()=>s({device:a.device,signal:a.scope.signal,resolveInteractor:e.localInteractors.resolve,facts:c.operations,pause:async t=>await e.clock.sleep(t,a.scope.signal)})),listApps:async e=>{a.scope.signal.throwIfAborted();let{listHarmonyApps:t}=await import(`./app-lifecycle2.js`);return(await t(e.device,e.filter,{signal:a.scope.signal})).map(e=>({id:e.package,name:e.name}))},...i(ze({host:e.localInteractors,device:a.device,signal:a.scope.signal}),c.operations)}),[Symbol.asyncDispose]:async()=>await o[Symbol.asyncDispose]()})},shutdown:async()=>await t.shutdown()})}export{ct as createHarmonyPlatformRuntime};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{Wt as t,Yt as n}from"./sdk-batch.js";import{n as r,t as i}from"./application-lifecycle-runtime.js";import{i as a}from"./touch-runtime.js";import{A as o,D as s,G as c,H as ee,I as l,N as u,V as d,b as f,d as p,w as m,x as h}from"./alert-runtime.js";import{r as g}from"./platform-runtime-unavailable.js";import{i as _}from"./gesture-admission.js";import{t as v}from"./local-interactor-operation-set.js";import{n as y,t as b}from"./application-lifecycle-interaction.js";function x(e){return b({owner:`Linux`,openTargetIdentity:`app-name`,binding:y({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const S=Object.freeze({available:!0}),C=t(`linux`),w=$(`unsupported-platform-leaf`),T=$(`unsupported-device-kind`),E=$(`unsupported-device-kind`,`focus is supported only for the Linux desktop device.`),D=$(`unsupported-device-kind`,`type is supported only for the Linux desktop device.`),O=$(`unsupported-device-kind`,`Gestures are supported only for the Linux desktop device.`),k=$(`unsupported-device-kind`,`scroll is supported only for the Linux desktop device.`),A=$(`unsupported-platform-leaf`),j=$(`unsupported-platform-leaf`),M=$(`unsupported-platform-leaf`,_),N=$(`unsupported-platform-leaf`),P=$(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),F=$(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),I=$(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),L=$(`unsupported-device-kind`,`open is supported only for the Linux desktop device.`),R=$(`unsupported-device-kind`,`close is supported only for the Linux desktop device.`),z=$(`unsupported-device-kind`,`snapshot is supported only for the Linux desktop device.`),B=$(`unsupported-device-kind`,`screenshot is supported only for the Linux desktop device.`),V=$(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),H=$(`unsupported-device-kind`,`back is supported only for the Linux desktop device.`),U=$(`unsupported-device-kind`,`home is supported only for the Linux desktop device.`),W=$(`unsupported-device-kind`,`clipboard is supported only for the Linux desktop device.`),G=w,K=$(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function q(t){return Object.freeze({owner:C,ownsDevice:e=>e.platform===`linux`,inspectFacts:async e=>Y(e),bind:async i=>{if(i.intent.kind===`exact-owner`&&!n(i.intent.owner,C))throw new e(`UNSUPPORTED_OPERATION`,`Linux runtime owner identity does not match`);if(i.device.platform!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`Linux runtime cannot bind this device`);let a=Y(i.device),o=x({host:t.localInteractors,device:i.device,signal:i.scope.signal});return Object.freeze({device:i.device,owner:C,facts:a,operations:Object.freeze({...r(o,a.operations),...a.operations.captureSnapshot.available?Q(t,i):{},...J(t,i,a)}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function J(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return v({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}function Y(e){let t=e.kind===`device`?S:L,n=e.kind===`device`?S:R,r=g(e,C,{appLog:w,network:w,screenshot:B,snapshot:z,viewport:w,focus:E,gesture:O,scroll:k,typeText:D,touch:E,elementText:T,back:H,home:U,orientation:G,tvRemote:G,readClipboard:W,writeClipboard:W,appSwitcher:G,triggerAppEvent:G,setSetting:G,readAlert:G,awaitAlert:G,acceptAlert:G,dismissAlert:G,keyboardStatus:G,keyboardDismiss:G,keyboardEnter:G,audioProbeCapture:K,audioProbeQuery:K,perf:G,readiness:w,lifecycle:i({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:P,clearRuntimeHints:P,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:F,configureProviderPortReverse:I})});return Object.freeze({device:r.device,operations:{...r.operations,...ee({capture:X(e,z),customActions:V,withoutActiveApp:X(e,z)}),...c({capture:X(e,B)}),...l({focus:X(e,E)}),...u({plan:X(e,O),directionalFling:A,multiTouch:j,targetAuthoredDrag:M,viewport:N}),...o({scroll:X(e,k)}),...s({type:X(e,D)}),...Z(e),...m({readTextAtPoint:X(e,T)}),...h({back:X(e,H)}),...f({home:X(e,U)}),...p({read:X(e,W),write:X(e,W)})}})}function X(e,t){return e.kind===`device`?S:t}function Z(e){let t=e.kind===`device`?S:E;return a({tap:t,tapRef:w,longPress:t,hover:w,hoverRef:w,fill:t,fillRef:w,tapElementSelector:w})}function Q(e,t){let n=async n=>await e.snapshot.captureSurface(t.device,n.options,d(t.scope.signal,n));return Object.freeze({captureSnapshot:n,captureSnapshotWithCustomActions:n,captureSnapshotWithoutActiveApp:n})}function $(e,t){return Object.freeze(t===void 0?{available:!1,reason:e}:{available:!1,reason:e,hint:t})}export{q as createLinuxPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{Wt as t,Yt as n}from"./sdk-batch.js";import{n as r,t as i}from"./application-lifecycle-runtime.js";import{i as a}from"./touch-runtime.js";import{A as o,D as s,G as c,H as ee,I as l,N as u,V as d,b as f,d as p,w as m,x as h}from"./alert-runtime.js";import{r as g}from"./platform-runtime-unavailable.js";import{i as _}from"./gesture-admission.js";import{t as v}from"./local-interactor-operation-set.js";import{n as y,t as b}from"./application-lifecycle-interaction.js";function x(e){return b({owner:`Linux`,openTargetIdentity:`app-name`,binding:y({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const S=Object.freeze({available:!0}),C=t(`linux`),w=$(`unsupported-platform-leaf`),T=$(`unsupported-device-kind`),E=$(`unsupported-device-kind`,`focus is supported only for the Linux desktop device.`),D=$(`unsupported-device-kind`,`type is supported only for the Linux desktop device.`),O=$(`unsupported-device-kind`,`Gestures are supported only for the Linux desktop device.`),k=$(`unsupported-device-kind`,`scroll is supported only for the Linux desktop device.`),A=$(`unsupported-platform-leaf`),j=$(`unsupported-platform-leaf`),M=$(`unsupported-platform-leaf`,_),N=$(`unsupported-platform-leaf`),P=$(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),F=$(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),I=$(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),L=$(`unsupported-device-kind`,`open is supported only for the Linux desktop device.`),R=$(`unsupported-device-kind`,`close is supported only for the Linux desktop device.`),z=$(`unsupported-device-kind`,`snapshot is supported only for the Linux desktop device.`),B=$(`unsupported-device-kind`,`screenshot is supported only for the Linux desktop device.`),V=$(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),H=$(`unsupported-device-kind`,`back is supported only for the Linux desktop device.`),U=$(`unsupported-device-kind`,`home is supported only for the Linux desktop device.`),W=$(`unsupported-device-kind`,`clipboard is supported only for the Linux desktop device.`),G=w,K=$(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function q(t){return Object.freeze({owner:C,ownsDevice:e=>e.platform===`linux`,inspectFacts:async e=>Y(e),bind:async i=>{if(i.intent.kind===`exact-owner`&&!n(i.intent.owner,C))throw new e(`UNSUPPORTED_OPERATION`,`Linux runtime owner identity does not match`);if(i.device.platform!==`linux`)throw new e(`UNSUPPORTED_PLATFORM`,`Linux runtime cannot bind this device`);let a=Y(i.device),o=x({host:t.localInteractors,device:i.device,signal:i.scope.signal});return Object.freeze({device:i.device,owner:C,facts:a,operations:Object.freeze({...r(o,a.operations),...a.operations.captureSnapshot.available?Q(t,i):{},...J(t,i,a)}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}function J(e,t,n){let r={device:t.device,signal:t.scope.signal,resolveInteractor:e.localInteractors.resolve};return v({...r,facts:n.operations,pause:async n=>await e.clock.sleep(n,t.scope.signal)})}function Y(e){let t=e.kind===`device`?S:L,n=e.kind===`device`?S:R,r=g(e,C,{appLog:w,network:w,screenshot:B,snapshot:z,viewport:w,focus:E,gesture:O,scroll:k,typeText:D,touch:E,elementText:T,back:H,home:U,orientation:G,tvRemote:G,clipboard:W,appSwitcher:G,triggerAppEvent:G,setSetting:G,readAlert:G,awaitAlert:G,acceptAlert:G,dismissAlert:G,keyboard:G,audioProbeCapture:K,audioProbeQuery:K,perf:G,readiness:w,lifecycle:i({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:P,clearRuntimeHints:P,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:F,configureProviderPortReverse:I})});return Object.freeze({device:r.device,operations:{...r.operations,...ee({capture:X(e,z),customActions:V,withoutActiveApp:X(e,z)}),...c({capture:X(e,B)}),...l({focus:X(e,E)}),...u({unsupported:O,plan:X(e,O),directionalFling:A,multiTouch:j,targetAuthoredDrag:M,viewport:N}),...o({scroll:X(e,k)}),...s({type:X(e,D)}),...Z(e),...m({readTextAtPoint:X(e,T)}),...h({back:X(e,H)}),...f({home:X(e,U)}),...p({unsupported:W,read:X(e,W),write:X(e,W)})}})}function X(e,t){return e.kind===`device`?S:t}function Z(e){let t=e.kind===`device`?S:E;return a({unsupported:w,tap:t,longPress:t,fill:t})}function Q(e,t){let n=async n=>await e.snapshot.captureSurface(t.device,n.options,d(t.scope.signal,n));return Object.freeze({captureSnapshot:n,captureSnapshotWithCustomActions:n,captureSnapshotWithoutActiveApp:n})}function $(e,t){return Object.freeze(t===void 0?{available:!1,reason:e}:{available:!1,reason:e,hint:t})}export{q as createLinuxPlatformRuntime};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{Wt as t,Yt as n}from"./sdk-batch.js";import{n as r,t as i}from"./application-lifecycle-runtime.js";import{N as a,b as o,g as s,x as c}from"./alert-runtime.js";import{r as l}from"./platform-runtime-unavailable.js";import{i as u}from"./gesture-admission.js";import{t as d}from"./interactor-operation-catalog.js";import{n as f,t as p}from"./application-lifecycle-interaction.js";function m(e){return p({owner:`Vega`,openTargetIdentity:`app-name`,binding:f({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const h=t(`vega`),g=Object.freeze({available:!0}),_=U(`unsupported-platform-leaf`),v=U(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),y=U(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),b=U(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),x=U(`unsupported-device-kind`,`open currently supports only Vega Virtual Devices.`),S=U(`unsupported-device-kind`,`close currently supports only Vega Virtual Devices.`);function C(t){return Object.freeze({owner:h,ownsDevice:e=>e.platform===`vega`,inspectFacts:async e=>H(e),bind:async i=>{if(i.intent.kind===`exact-owner`&&!n(i.intent.owner,h))throw new e(`UNSUPPORTED_OPERATION`,`Vega runtime owner identity does not match`);if(i.device.platform!==`vega`)throw new e(`UNSUPPORTED_PLATFORM`,`Vega runtime cannot bind this device`);let a=H(i.device),o=m({host:t.localInteractors,device:i.device,signal:i.scope.signal});return Object.freeze({device:i.device,owner:h,facts:a,operations:Object.freeze({...r(o,a.operations),...d({device:i.device,signal:i.scope.signal,resolveInteractor:t.localInteractors.resolve,facts:a.operations})}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}const w=U(`unsupported-platform-leaf`,`screenshot is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),T=U(`unsupported-platform-leaf`,`focus is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),E=U(`unsupported-platform-leaf`,`type is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),D=U(`unsupported-platform-leaf`,`Gestures are not supported on Vega OS: the Vega runtime exposes remote navigation only.`),O=U(`unsupported-platform-leaf`,`scroll is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),k=U(`unsupported-platform-leaf`),A=U(`unsupported-platform-leaf`,u),j=U(`unsupported-platform-leaf`,`orientation is not supported on Vega OS.`),M=U(`unsupported-platform-leaf`,`keyboard is not supported on Vega OS.`),N=U(`unsupported-platform-leaf`,`alert is not supported on Vega OS.`),P=U(`unsupported-platform-leaf`,`settings is not supported on Vega OS.`),F=U(`unsupported-platform-leaf`,`trigger-app-event is not supported on Vega OS.`),I=U(`unsupported-platform-leaf`,`app-switcher is not supported on Vega OS.`),L=U(`unsupported-platform-leaf`,`clipboard is not supported on Vega OS.`),R=U(`unsupported-device-kind`,`back currently supports only Vega Virtual Devices.`),z=U(`unsupported-device-kind`,`home currently supports only Vega Virtual Devices.`),B=U(`unsupported-device-kind`,`tv-remote currently supports only Vega Virtual Devices.`),V=U(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function H(e){let t=e.kind===`emulator`&&e.target===`tv`,n=t?g:x,r=t?g:S,u=l(e,h,{appLog:_,network:_,screenshot:w,snapshot:_,viewport:_,focus:T,gesture:D,scroll:O,typeText:E,touch:_,elementText:_,back:R,home:z,orientation:j,tvRemote:B,readClipboard:L,writeClipboard:L,appSwitcher:I,triggerAppEvent:F,setSetting:P,readAlert:N,awaitAlert:N,acceptAlert:N,dismissAlert:N,keyboardStatus:M,keyboardDismiss:M,keyboardEnter:M,audioProbeCapture:V,audioProbeQuery:V,perf:_,readiness:_,lifecycle:i({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:v,clearRuntimeHints:v,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:y,configureProviderPortReverse:b})});return Object.freeze({device:u.device,operations:{...u.operations,...c({back:t?g:R}),...o({home:t?g:z}),...s({tvRemote:t?g:B}),...a({plan:D,directionalFling:D,multiTouch:k,targetAuthoredDrag:A,viewport:D})}})}function U(e,t){let n={available:!1,reason:e,...t===void 0?{}:{hint:t}};return Object.freeze(n)}export{C as createVegaPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{Wt as t,Yt as n}from"./sdk-batch.js";import{n as r,t as i}from"./application-lifecycle-runtime.js";import{N as a,b as o,g as s,x as c}from"./alert-runtime.js";import{r as l}from"./platform-runtime-unavailable.js";import{i as u}from"./gesture-admission.js";import{t as d}from"./interactor-operation-catalog.js";import{n as f,t as p}from"./application-lifecycle-interaction.js";function m(e){return p({owner:`Vega`,openTargetIdentity:`app-name`,binding:f({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const h=t(`vega`),g=Object.freeze({available:!0}),_=U(`unsupported-platform-leaf`),v=U(`unsupported-platform-leaf`,`Runtime hints are supported only for local iOS-family simulators and Android devices.`),y=U(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),b=U(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`),x=U(`unsupported-device-kind`,`open currently supports only Vega Virtual Devices.`),S=U(`unsupported-device-kind`,`close currently supports only Vega Virtual Devices.`);function C(t){return Object.freeze({owner:h,ownsDevice:e=>e.platform===`vega`,inspectFacts:async e=>H(e),bind:async i=>{if(i.intent.kind===`exact-owner`&&!n(i.intent.owner,h))throw new e(`UNSUPPORTED_OPERATION`,`Vega runtime owner identity does not match`);if(i.device.platform!==`vega`)throw new e(`UNSUPPORTED_PLATFORM`,`Vega runtime cannot bind this device`);let a=H(i.device),o=m({host:t.localInteractors,device:i.device,signal:i.scope.signal});return Object.freeze({device:i.device,owner:h,facts:a,operations:Object.freeze({...r(o,a.operations),...d({device:i.device,signal:i.scope.signal,resolveInteractor:t.localInteractors.resolve,facts:a.operations})}),[Symbol.asyncDispose]:async()=>void 0})},shutdown:async()=>void 0})}const w=U(`unsupported-platform-leaf`,`screenshot is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),T=U(`unsupported-platform-leaf`,`focus is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),E=U(`unsupported-platform-leaf`,`type is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),D=U(`unsupported-platform-leaf`,`Gestures are not supported on Vega OS: the Vega runtime exposes remote navigation only.`),O=U(`unsupported-platform-leaf`,`scroll is not supported on Vega OS: the Vega runtime exposes remote navigation only.`),k=U(`unsupported-platform-leaf`),A=U(`unsupported-platform-leaf`,u),j=U(`unsupported-platform-leaf`,`orientation is not supported on Vega OS.`),M=U(`unsupported-platform-leaf`,`keyboard is not supported on Vega OS.`),N=U(`unsupported-platform-leaf`,`alert is not supported on Vega OS.`),P=U(`unsupported-platform-leaf`,`settings is not supported on Vega OS.`),F=U(`unsupported-platform-leaf`,`trigger-app-event is not supported on Vega OS.`),I=U(`unsupported-platform-leaf`,`app-switcher is not supported on Vega OS.`),L=U(`unsupported-platform-leaf`,`clipboard is not supported on Vega OS.`),R=U(`unsupported-device-kind`,`back currently supports only Vega Virtual Devices.`),z=U(`unsupported-device-kind`,`home currently supports only Vega Virtual Devices.`),B=U(`unsupported-device-kind`,`tv-remote currently supports only Vega Virtual Devices.`),V=U(`unsupported-platform-leaf`,`audio is supported for web browser sessions, macOS sessions, iOS simulators, and Android emulators on macOS hosts`);function H(e){let t=e.kind===`emulator`&&e.target===`tv`,n=t?g:x,r=t?g:S,u=l(e,h,{appLog:_,network:_,screenshot:w,snapshot:_,viewport:_,focus:T,gesture:D,scroll:O,typeText:E,touch:_,elementText:_,back:R,home:z,orientation:j,tvRemote:B,clipboard:L,appSwitcher:I,triggerAppEvent:F,setSetting:P,readAlert:N,awaitAlert:N,acceptAlert:N,dismissAlert:N,keyboard:M,audioProbeCapture:V,audioProbeQuery:V,perf:_,readiness:_,lifecycle:i({resolveOpenTarget:n,prepareApplicationOpen:n,openApplication:n,applyRuntimeHints:v,clearRuntimeHints:v,closeApplication:r,finalizeApplicationClose:r,prepareAppleRunner:y,configureProviderPortReverse:b})});return Object.freeze({device:u.device,operations:{...u.operations,...c({back:t?g:R}),...o({home:t?g:z}),...s({tvRemote:t?g:B}),...a({unsupported:D,multiTouch:k,targetAuthoredDrag:A})}})}function U(e,t){let n={available:!1,reason:e,...t===void 0?{}:{hint:t}};return Object.freeze(n)}export{C as createVegaPlatformRuntime};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Wt as n,Xt as r,Yt as i}from"./sdk-batch.js";import{n as a,t as o}from"./application-lifecycle-runtime.js";import{i as s,t as c}from"./touch-runtime.js";import{A as l,D as u,G as d,H as f,I as ee,L as te,N as p,O as m,P as h,R as g,T as _,U as ne,a as v,b as y,d as re,g as ie,i as ae,m as oe,s as se,t as b,v as x,w as S,x as C,z as w}from"./alert-runtime.js";import{n as T}from"./audio-probe-runtime.js";import{n as E}from"./perf-runtime.js";import{a as D,n as O}from"./durable-resource.js";import{n as k}from"./async-lifecycle.js";import"./src7.js";import{t as A}from"./screen-recording-live-handle.js";import{t as j}from"./screen-recording-completion.js";import{t as M}from"./screen-recording-options.js";import{t as N}from"./screen-recording-runtime.js";import{i as P}from"./gesture-admission.js";import{n as F,t as I}from"./application-lifecycle-interaction.js";const L=Object.freeze({resourceKind:N,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function R(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await z({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>B()}}:{available:!1,operations:{}}}async function z(n){let{host:r,transport:i,device:a,owner:o,input:s,signal:c}=n;if(s.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!s.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);M(s,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),c.throwIfAborted(),await r.screenRecording.outputs.prepare(s.outputPath);let l=!1;try{await i.start(s.outputPath,c),l=!0,c.throwIfAborted()}catch(e){throw l&&await i.stop().catch(()=>{}),c.throwIfAborted(),e}let u=!1,d=async()=>{u||=(await i.stop(),!0)},f=A({backend:`agent-browser`,outPath:s.outputPath,...s.clientOutputPath===void 0?{}:{clientOutPath:s.clientOutputPath},startedAt:Date.now(),scope:s.scope,showTouches:!1,recordOnlySession:s.recordOnlySession,...s.activeSessionApp===void 0?{}:{activeSessionApp:s.activeSessionApp},gestureEvents:[]},{finish:async e=>{await d();let t=await r.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`});return j(e,t,!1)},forceCleanup:async()=>{try{return await d(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new k(f),envelope:O({resourceKind:N,sessionId:s.sessionId,device:t(a),owner:o,fence:s.fence,lifecycle:`open`,descriptor:D(L,{backend:`agent-browser`,outputPath:s.outputPath})})})}function B(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}function V(e){return I({owner:`web`,openTargetIdentity:`app-name`,binding:F({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const H=n(`web`),U=Object.freeze({available:!0}),W=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Web targets read element text from the captured tree only.`}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),K=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`}),ce=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),q=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),le=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`apps is not supported on web targets.`}),ue=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),J=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),de=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),fe=Object.freeze({available:!1,reason:`owner-capability-missing`}),pe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio on web sessions is the stateless page probe; host capture is a macOS-host operation.`});function Y(e,t){return typeof e==`function`?t:fe}function X(e,t){return e?U:t}const Z=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),me=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:P}),Q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for web browser devices.`}),he=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for web browser devices.`}),ge=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`});function _e(e){let t=ve(e),n=ye(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:q,clearRuntimeHints:q,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:de,configureProviderPortReverse:ge})}function ve(e){return e.kind===`device`?U:Q}function ye(e){return e.kind===`device`?U:he}function be(t){return Object.freeze({owner:H,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let n=await t.networkTransports.resolve(e),r=await R({host:t,device:e,owner:H,signal:new AbortController().signal}),i=e.kind===`device`?await t.localInteractors.resolve(e,{}):void 0;return $(e,n,r.available,i)},bind:async n=>{if(n.intent.kind===`exact-owner`&&!i(n.intent.owner,H))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(n.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${n.device.platform}`);let r=await t.networkTransports.resolve(n.device),a=await R({host:t,device:n.device,owner:H,signal:n.scope.signal}),o=n.device.kind===`device`?await t.localInteractors.resolve(n.device,{signal:n.scope.signal}):void 0;return xe(t,n.device,n.scope.signal,r,a,$(n.device,r,a.available,o))},shutdown:async()=>void 0})}function xe(t,n,i,o,s,l){let u=o.dump,d={...u?{networkDump:async e=>{let t=await u({maxEntries:e.maxEntries,include:e.include},i);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?w({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?ne({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?h({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?_({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...r(l.operations.tapPoint,()=>c({device:n,signal:i,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,i)})),...l.operations.scrollDirection.available?m({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async r=>{i.throwIfAborted();let a=await t.localInteractors.resolve(n,{signal:i});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(r.width,r.height),i.throwIfAborted()}}:{},...r(l.operations.audioProbeQuery,()=>({audioProbeQuery:async r=>{let i=await t.audioProbe.web.resolve(n);if(i===void 0)throw new e(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);return await i.probe(r)}})),...a(V({host:t.localInteractors,device:n,signal:i}),l.operations)};return Object.freeze({device:n,owner:H,facts:l,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,r){let i=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`}),a=X(e.kind===`device`,Q);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:G,appLogDoctor:G,appLogStart:G,appLogReattach:G,appLogCleanup:G,appState:ue,networkDump:X(!!t.dump,i),screenRecordingStart:X(n,K),screenRecordingReattach:X(n,K),screenRecordingCleanup:X(n,K),...f({capture:a,customActions:ce,withoutActiveApp:a}),...g({findText:Q,findSelector:Q}),...d({capture:a}),...ee({focus:a}),...u({type:a}),...s({tap:a,tapRef:Y(r?.tapRef,a),longPress:q,hover:Y(r?.hover,a),hoverRef:Y(r?.hoverRef,a),fill:a,fillRef:Y(r?.fillRef,a),tapElementSelector:q}),...l({scroll:a}),...p({plan:Z,directionalFling:Z,multiTouch:Z,targetAuthoredDrag:me,viewport:Z}),...te({setViewport:a}),...S({readTextAtPoint:W}),...C({back:J}),...y({home:J}),...x({orientation:J}),...ie({tvRemote:J}),...oe({status:J,dismiss:J,enter:J}),...re({read:J,write:J}),...T({capture:pe,query:U}),...E({frames:J,memorySample:J,memorySnapshot:J,nativeCapture:J,profileReport:J}),...se({appSwitcher:J}),...v({triggerAppEvent:J}),...ae({setSetting:J}),...b({read:J,wait:J,accept:J,dismiss:J}),ensureReady:q,bootTarget:q,bootTargetHeadless:q,listApps:le,deployApp:q,materializeAppSource:q,deployMaterializedApp:q,sendPushNotification:q,shutdownTarget:q,..._e(e)}})}export{be as createWebPlatformRuntime};
1
+ import{C as e}from"./sdk-contracts.js";import{w as t}from"./sdk-device.js";import{Wt as n,Xt as r,Yt as i}from"./sdk-batch.js";import{n as a,t as o}from"./application-lifecycle-runtime.js";import{i as s,t as c}from"./touch-runtime.js";import{A as l,D as u,G as d,H as f,I as p,L as m,N as ee,O as te,P as ne,R as re,T as ie,U as h,a as g,b as _,d as v,g as ae,i as y,m as oe,s as b,t as x,v as S,w as C,x as w,z as T}from"./alert-runtime.js";import{n as E}from"./audio-probe-runtime.js";import{n as D}from"./perf-runtime.js";import{a as O,n as k}from"./durable-resource.js";import{n as A}from"./async-lifecycle.js";import"./src7.js";import{t as j}from"./screen-recording-live-handle.js";import{t as M}from"./screen-recording-completion.js";import{t as N}from"./screen-recording-options.js";import{t as P}from"./screen-recording-runtime.js";import{i as F}from"./gesture-admission.js";import{n as I,t as L}from"./application-lifecycle-interaction.js";const R=Object.freeze({resourceKind:P,version:1,encode:e=>({...e}),decode:e=>e.backend===`agent-browser`&&typeof e.outputPath==`string`?{status:`decoded`,descriptor:Object.freeze({backend:`agent-browser`,outputPath:e.outputPath})}:{status:`invalid`,message:`Invalid web screen-recording descriptor`}});async function z(e){let{host:t,device:n,owner:r,signal:i}=e,a=await t.screenRecording.web.resolve(n);return a?{available:!0,operations:{screenRecordingStart:async e=>await B({host:t,transport:a,device:n,owner:r,input:e,signal:i}),screenRecordingReattach:async()=>({status:`unreattachable`,reason:`transport-not-reattachable`,message:`Web recordings cannot be reattached after daemon restart.`}),screenRecordingCleanup:async()=>V()}}:{available:!1,operations:{}}}async function B(n){let{host:r,transport:i,device:a,owner:o,input:s,signal:c}=n;if(s.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!s.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`);N(s,{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`),c.throwIfAborted(),await r.screenRecording.outputs.prepare(s.outputPath);let l=!1;try{await i.start(s.outputPath,c),l=!0,c.throwIfAborted()}catch(e){throw l&&await i.stop().catch(()=>{}),c.throwIfAborted(),e}let u=!1,d=async()=>{u||=(await i.stop(),!0)},f=j({backend:`agent-browser`,outPath:s.outputPath,...s.clientOutputPath===void 0?{}:{clientOutPath:s.clientOutputPath},startedAt:Date.now(),scope:s.scope,showTouches:!1,recordOnlySession:s.recordOnlySession,...s.activeSessionApp===void 0?{}:{activeSessionApp:s.activeSessionApp},gestureEvents:[]},{finish:async e=>{await d();let t=await r.screenRecording.finalize.complete({outputPath:e.outPath,showTouches:!1,gestureEvents:e.gestureEvents,targetLabel:`web recording`});return M(e,t,!1)},forceCleanup:async()=>{try{return await d(),{status:`cleaned`}}catch(e){return{status:`cleanup-pending`,reason:`transport-failed`,message:e instanceof Error?e.message:`Web recording cleanup failed`}}}});return Object.freeze({pendingHandle:new A(f),envelope:k({resourceKind:P,sessionId:s.sessionId,device:t(a),owner:o,fence:s.fence,lifecycle:`open`,descriptor:O(R,{backend:`agent-browser`,outputPath:s.outputPath})})})}function V(){return{status:`cleanup-pending`,reason:`manual-recovery-required`,message:`Web recordings cannot be cleaned after daemon restart.`}}function H(e){return L({owner:`web`,openTargetIdentity:`app-name`,binding:I({device:e.device,signal:e.signal,resolveInteractor:e.host.resolve})})}const U=n(`web`),W=Object.freeze({available:!0}),G=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Web targets read element text from the captured tree only.`}),K=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),q=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`record is not supported by this web provider`}),se=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Re-run without --actions, or target an iOS simulator.`}),J=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ce=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`apps is not supported on web targets.`}),le=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),Y=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),ue=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`Apple runner preparation is supported only for Apple targets.`}),de=Object.freeze({available:!1,reason:`owner-capability-missing`}),fe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`audio on web sessions is the stateless page probe; host capture is a macOS-host operation.`});function X(e,t){return typeof e==`function`?t:de}function Z(e,t){return e?W:t}const pe=Object.freeze({available:!1,reason:`unsupported-platform-leaf`}),me=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:F}),Q=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`open is supported only for web browser devices.`}),he=Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`close is supported only for web browser devices.`}),ge=Object.freeze({available:!1,reason:`unsupported-provider-mode`,hint:`Port reverse is supported only by an owning provider runtime.`});function _e(e){let t=ve(e),n=ye(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:J,clearRuntimeHints:J,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:ue,configureProviderPortReverse:ge})}function ve(e){return e.kind===`device`?W:Q}function ye(e){return e.kind===`device`?W:he}function be(t){return Object.freeze({owner:U,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let n=await t.networkTransports.resolve(e),r=await z({host:t,device:e,owner:U,signal:new AbortController().signal}),i=e.kind===`device`?await t.localInteractors.resolve(e,{}):void 0;return $(e,n,r.available,i)},bind:async n=>{if(n.intent.kind===`exact-owner`&&!i(n.intent.owner,U))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(n.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${n.device.platform}`);let r=await t.networkTransports.resolve(n.device),a=await z({host:t,device:n.device,owner:U,signal:n.scope.signal}),o=n.device.kind===`device`?await t.localInteractors.resolve(n.device,{signal:n.scope.signal}):void 0;return xe(t,n.device,n.scope.signal,r,a,$(n.device,r,a.available,o))},shutdown:async()=>void 0})}function xe(t,n,i,o,s,l){let u=o.dump,d={...u?{networkDump:async e=>{let t=await u({maxEntries:e.maxEntries,include:e.include},i);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?T({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?h({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?ne({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?ie({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...r(l.operations.tapPoint,()=>c({device:n,signal:i,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,i)})),...l.operations.scrollDirection.available?te({device:n,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async r=>{i.throwIfAborted();let a=await t.localInteractors.resolve(n,{signal:i});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(r.width,r.height),i.throwIfAborted()}}:{},...r(l.operations.audioProbeQuery,()=>({audioProbeQuery:async r=>{let i=await t.audioProbe.web.resolve(n);if(i===void 0)throw new e(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);return await i.probe(r)}})),...a(H({host:t.localInteractors,device:n,signal:i}),l.operations)};return Object.freeze({device:n,owner:U,facts:l,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,r){let i=Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`network is not supported by this web provider`}),a=Z(e.kind===`device`,Q);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:K,appLogDoctor:K,appLogStart:K,appLogReattach:K,appLogCleanup:K,appState:le,networkDump:Z(!!t.dump,i),screenRecordingStart:Z(n,q),screenRecordingReattach:Z(n,q),screenRecordingCleanup:Z(n,q),...f({capture:a,customActions:se,withoutActiveApp:a}),...re({findText:Q}),...d({capture:a}),...p({focus:a}),...u({type:a}),...s({unsupported:J,tap:a,tapRef:X(r?.tapRef,a),longPress:J,hover:X(r?.hover,a),hoverRef:X(r?.hoverRef,a),fill:a,fillRef:X(r?.fillRef,a)}),...l({scroll:a}),...ee({unsupported:pe,targetAuthoredDrag:me}),...m({setViewport:a}),...C({readTextAtPoint:G}),...w({back:Y}),..._({home:Y}),...S({orientation:Y}),...ae({tvRemote:Y}),...oe({unsupported:Y}),...v({unsupported:Y}),...E({capture:fe,query:W}),...D({frames:Y,memorySample:Y,memorySnapshot:Y,nativeCapture:Y,profileReport:Y}),...b({appSwitcher:Y}),...g({triggerAppEvent:Y}),...y({setSetting:Y}),...x({read:Y,wait:Y,accept:Y,dismiss:Y}),ensureReady:J,bootTarget:J,bootTargetHeadless:J,listApps:ce,deployApp:J,materializeAppSource:J,deployMaterializedApp:J,sendPushNotification:J,shutdownTarget:J,..._e(e)}})}export{be as createWebPlatformRuntime};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{t}from"./durable-resource.js";function n(e,t){let n=r(e),a,o,s,c=()=>a??=t.finish(n),l=()=>o??=a?a.then(async e=>e.status===`completed`?{status:`cleaned`}:await t.forceCleanup(n),async()=>await t.forceCleanup(n)):t.forceCleanup(n);return Object.freeze({inspect:()=>n,appendGestureEvents:e=>{e.length===0||a||o||(n=r({...n,gestureEvents:[...n.gestureEvents,...e]}))},setTouchReferenceFrame:e=>{a||o||(n=r({...n,...e?{touchReferenceFrame:e}:{}}))},setRunnerSessionId:e=>{a||o||e.trim().length===0||(n=r({...n,runnerSessionId:e}))},invalidate:e=>{a||o||n.invalidatedReason||(n=r({...n,invalidatedReason:e}))},finish:c,forceCleanup:l,[Symbol.asyncDispose]:async()=>{s??=l().then(i),await s}})}function r(e){return Object.freeze({...e,gestureEvents:Object.freeze([...e.gestureEvents])})}function i(n){if(!t(n))throw new e(`COMMAND_FAILED`,n.message??`Screen recording cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:n.reason===`ownership-fence-lost`?`Use the current recording owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}export{n as t};
1
+ import{C as e}from"./sdk-contracts.js";import{t}from"./durable-resource.js";function n(e,t){let n=r(e),a,o,s,c=()=>a??=t.finish(n),l=()=>o??=a?a.then(async e=>e.status===`completed`?{status:`cleaned`}:await t.forceCleanup(n),async()=>await t.forceCleanup(n)):t.forceCleanup(n);return Object.freeze({inspect:()=>n,appendGestureEvents:e=>{e.length===0||a||o||(n=r({...n,gestureEvents:[...n.gestureEvents,...e]}))},setTouchReferenceFrame:e=>{a||o||(n=r({...n,...e?{touchReferenceFrame:e}:{}}))},setRunnerSessionId:e=>{a||o||e.trim().length===0||(n=r({...n,runnerSessionId:e}))},invalidate:e=>{a||o||n.invalidatedReason||(n=r({...n,invalidatedReason:e}))},finish:c,forceCleanup:l,[Symbol.asyncDispose]:async()=>{s??=l().then(i),await s}})}function r(e){return Object.freeze({...e,gestureEvents:Object.freeze([...e.gestureEvents])})}function i(n){if(!t(n))throw new e(`COMMAND_FAILED`,n.message??`Screen recording cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:n.reason===`ownership-fence-lost`?`Use the current recording owner or recovery record before retrying cleanup.`:`Keep the recovery record and retry cleanup through the exact runtime owner.`})}export{n as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";function t(t,r,i){let a=n(t,r);if(a.length>0)throw new e(`INVALID_ARGS`,i(a))}function n(e,t){return Object.freeze([...t.scopes.includes(e.scope)?[]:[`--scope`],...t.fps||e.fps===void 0?[]:[`--fps`],...t.exportQuality||e.exportQuality===void 0?[]:[`--quality`],...t.hideTouches||!e.hideTouchesRequested?[]:[`--hide-touches`]])}export{t};
1
+ import{C as e}from"./sdk-contracts.js";function t(t,r,i){let a=n(t,r);if(a.length>0)throw new e(`INVALID_ARGS`,i(a))}function n(e,t){return Object.freeze([...t.scopes.includes(e.scope)?[]:[`--scope`],...t.fps||e.fps===void 0?[]:[`--fps`],...t.exportQuality||e.exportQuality===void 0?[]:[`--quality`],...t.hideTouches||!e.hideTouchesRequested?[]:[`--hide-touches`]])}export{t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{D as t,T as n,w as r}from"./sdk-device.js";import{D as i,Jt as a,Kt as o}from"./sdk-batch.js";import{r as s}from"./diagnostics.js";import{E as c}from"./owner-identity.js";import{i as l}from"./verified-file.js";import"./file.js";import"./diagnostics2.js";import{r as u}from"./session-paths.js";import{i as d,n as f,t as p}from"./durable-resource.js";import{t as m}from"./screen-recording-runtime.js";import h from"node:path";import g from"node:fs";import ee from"node:crypto";function _(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function v(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{let i=ce(ae(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,{handle:a,envelope:i}))}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=r.kind!==`pending`||ie(e,t,n),o=re(e,t,n,await y(t,r));t.reportUndurableCleanup(t.device,!a&&o.cleanupError===void 0||o.confirmed?{confirmed:!0}:{confirmed:!1,reason:o.cleanupError instanceof Error?o.cleanupError.message:`The durable cleanup transition could not be confirmed`}),o.cleanupError!==void 0&&x(e,t,i,o.cleanupError)}function re(e,t,n,r){try{return{confirmed:se(e,n,t.fence,r),cleanupError:r}}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.sessionName,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:r??n}}}async function y(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ie(e,t,n){try{return e.store.write(n,b(e,t,t.envelope.descriptor)),!0}catch(r){try{return e.store.write(n,b(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.sessionName,descriptorError:r instanceof Error?r.message:String(r),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function b(e,t,n){return f({resourceKind:e.resourceKind,sessionId:t.sessionName,device:r(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function ae(t,n){let r=d(n.envelope);if(r.status===`decoded`&&oe(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${_(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function oe(e,n,i){return e.resourceKind===i&&e.sessionId===n.sessionName&&t(e.device,r(n.device))&&a(e.owner)===a(n.owner)&&e.fence.token===n.fence.token&&e.fence.generation===n.fence.generation&&e.lifecycle===`open`}function se(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function x(e,t,n,r){s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.sessionName,primaryError:n instanceof Error?n.message:String(n),cleanupError:r instanceof Error?r.message:String(r)}})}function ce(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function S(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new w(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=ue(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>le(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function le(e,t,n){try{t.reattached.status===`active`&&await C(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await C(e,t.control,`late_control_cleanup_failed`,n)}}async function ue(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await C(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await C(e,n,`late_control_cleanup_failed`,t)}throw t}}async function C(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var w=class extends Error{deadlineMs;constructor(e,t){super(`${_(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const T=new Map;async function E(e){return await de(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw O(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!D(t.envelope.fence,e.expected))throw O(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function D(e,t){return e.token===t.token&&e.generation===t.generation}async function de(e,t){let n=T.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);T.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),T.get(e)===a&&T.delete(e)}}function O(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function fe(t,n,r){let i=t.sessionSlot.read(n.session);if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await k(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r});return M(t,n),e}catch(e){let i=t.store.read(r);throw i.status===`decoded`&&i.envelope.lifecycle===`completed`&&M(t,n),e}}async function k(e,t){return await E({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{R(n);let r;try{r=await t.handle.finish()}catch(r){throw await A(e,n,t,r),r}if(r.status===`completed`)return L(e,n,r),r.result;L(e,n,r);let i=I(e,r);throw await A(e,n,t,i),i}})}async function A(e,t,n,r){let i;try{i=await n.handle.forceCleanup()}catch(i){j(e,n,r,i,pe(t,i));return}try{P(t,i)}catch(t){j(e,n,r,i.status===`cleanup-pending`?i.message??i.reason:`cleanup returned ${i.status}`,t);return}p(i)||j(e,n,r,i.message)}function pe(e,t){try{P(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:N(t)});return}catch(e){return e}}function j(e,t,n,r,i){s({level:`error`,phase:`${e.resourceKind.replaceAll(`-`,`_`)}_finish_cleanup_failed`,data:{resourcePath:t.resourcePath,finishError:N(n),cleanupError:r===void 0?`cleanup could not be confirmed`:N(r),...i===void 0?{}:{transitionError:N(i)}}})}function M(e,t){t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0))}function N(e){return e instanceof Error?e.message:String(e)}async function me(e,t){let n=e.sessionSlot.read(t.session);n&&(F(e,await E({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{R(e);let t=await n.handle.forceCleanup();return P(e,t),t}})),t.sessionStore&&t.sessionName&&t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0)))}function P(e,t){e.transition(p(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:p(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function F(e,t){if(!p(t))throw I(e,t)}function I(t,n){return new e(`COMMAND_FAILED`,n.message??`${_(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function L(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}P(t,n)}function R(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function z(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await B(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function B(e,t){let n=he(e,t);if(n.status!==`recoverable`)return n.status;try{return await ge(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return U(e,n instanceof w?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof w?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function he(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return U(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return h.resolve(t)===h.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(U(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function ge(e,t,n,r){return await _e(e,t,n,await S({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>U(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function _e(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{ve(e);let t=await i.forceCleanup();return P(e,t),t}});return p(a)}case`completed`:return await V(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await V(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!H(r.reattached.reason))return U(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>P(e,i)}),p(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function V(e,t,n,r){await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function ve(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function H(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function U(e,t,n,r){let i={phase:`${v(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:r};e.onDiagnostic?e.onDiagnostic(i):s({level:`warn`,phase:i.phase,data:{resourcePath:n,...r}})}async function ye(t,n){let r=t.store.read(n.resourcePath);if(r.status!==`decoded`||r.envelope.lifecycle!==`open`)throw W(t,r.status);let i=r.envelope,a=await S({displayName:t.displayName,envelope:i,scope:n.scope,deadlineMs:n.deadlineMs??5e3,acquireControl:n.acquireControl,onLateCleanupFailure:(e,r,i)=>n.scope.diagnostics.emit({level:`error`,phase:`${v(t.resourceKind)}_recovery_${e}`,data:{resourcePath:n.resourcePath,error:G(r),primaryError:G(i)}})});try{switch(a.reattached.status){case`active`:return await k(t,{handle:a.reattached.handle,fence:i.fence,resourcePath:n.resourcePath});case`completed`:{let e=a.reattached.result;return await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async n=>{L(t,n,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${_(t.displayName)} is missing`,{reason:`resource-missing`,hint:t.messages.cleanupPendingHint});case`unreattachable`:if(H(a.reattached.reason)){let e=await a.control.cleanup(i);await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async t=>P(t,e)}),F(t,e)}throw new e(`COMMAND_FAILED`,a.reattached.message??`${_(t.displayName)} cannot be reattached`,{reason:a.reattached.reason,hint:t.messages.cleanupPendingHint})}}finally{await a.control[Symbol.asyncDispose]()}}function W(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${_(t.displayName)} recovery record is not open`)}function G(e){return e instanceof Error?e.message:String(e)}function K(e){xe(e.fileName);let t=t=>h.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=l(t),n===void 0)return{status:`missing`};r=JSON.parse(g.readFileSync(n,`utf8`))}catch(t){return J(t)?{status:`missing`}:q(Ce(t,e.displayName))}finally{n!==void 0&&g.closeSync(n)}return be(d(r),e.resourceKind)},write(e,t){let n=h.dirname(e);g.mkdirSync(n,{recursive:!0}),c({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=g.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(h.join(e,n.name))).filter(Se).sort()}})}function be(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:q(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function xe(e){if(e.length===0||h.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function Se(e){try{return g.lstatSync(e),!0}catch(e){return!J(e)}}function q(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function J(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Ce(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function we(e,t){t.admissionLedger.assertStartAllowed(t.device),Te(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function Te(t,i,a){let o=n(r(a));for(let r of t.store.list(h.dirname(h.dirname(i)))){let a=t.store.read(r);if(a.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${_(Y(t.displayName))} ${t.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===i||n(a.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${_(Y(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function Y(e){return/^[aeiou]/i.test(e)?`an`:`a`}function X(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>h.join(t.sessionsDir,u(e)),...t});return Object.freeze({store:e.store,createNextFence(t){return we(e,t)},adoptStarted(n){return te(e,{...n,reportUndurableCleanup:(e,t)=>{t.confirmed?n.admissionLedger.clearUndurableCleanup(e):n.admissionLedger.blockUndurableCleanup(e,t.reason)}},t(n.sessionStore,n.sessionName))},finishLive(n){return fe(e,n,t(n.sessionStore,n.sessionName))},finishRecovered(t){return ye(e,t)},forceCleanupLive(t){return me(e,t)},recoverAll(e){return z(n(e))},recoverOne(e,t){return B(n(e),t)}})}const Z=X({resourceKind:`screen-recording`,displayName:`screen recording`,store:K({resourceKind:m,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),sessionSlot:{read:e=>e.screenRecording,replace:(e,t)=>({...e,screenRecording:t})},completionMetadata:e=>({backend:e.backend,outputPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession}),messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Ee(e){return Z.adoptStarted(e)}function De(e){return Z.finishLive(e)}function Oe(e){return Z.finishRecovered(e)}async function Q(e){let t;try{return t=await e.gateway.bind({device:ke(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function ke(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}function Ae(e){return Z.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await je(e.gateway,t,n)},e.resourcePath)}async function je(e,t,n){return await Q({gateway:e,envelope:t,scope:n,create:e=>$({runtime:o(e,i),dispose:async()=>await e[Symbol.asyncDispose]()})})}function $(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}export{De as a,X as c,Ee as i,K as l,Ae as n,Oe as o,Q as r,Z as s,$ as t};
1
+ import{C as e}from"./sdk-contracts.js";import{D as t,T as n,w as r}from"./sdk-device.js";import{D as i,Jt as a,Kt as o}from"./sdk-batch.js";import{r as s}from"./diagnostics.js";import{E as c}from"./owner-identity.js";import{i as l}from"./verified-file.js";import"./file.js";import"./diagnostics2.js";import{r as u}from"./session-paths.js";import{i as d,n as f,t as p}from"./durable-resource.js";import{t as m}from"./screen-recording-runtime.js";import h from"node:path";import g from"node:fs";import ee from"node:crypto";function _(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function v(e){return e.replaceAll(`-`,`_`)}async function te(e,t,n){let r={kind:`pending`};try{let i=ce(ae(e,t),`active`);e.store.write(n,i),r={kind:`persisted`},t.throwIfCanceled();let a=t.pendingHandle.transfer();r={kind:`transferred`,handle:a},t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,{handle:a,envelope:i}))}catch(i){throw await ne(e,t,n,r,i),i}}async function ne(e,t,n,r,i){let a=r.kind!==`pending`||ie(e,t,n),o=re(e,t,n,await y(t,r));t.reportUndurableCleanup(t.device,!a&&o.cleanupError===void 0||o.confirmed?{confirmed:!0}:{confirmed:!1,reason:o.cleanupError instanceof Error?o.cleanupError.message:`The durable cleanup transition could not be confirmed`}),o.cleanupError!==void 0&&x(e,t,i,o.cleanupError)}function re(e,t,n,r){try{return{confirmed:se(e,n,t.fence,r),cleanupError:r}}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_transition_failed`,data:{session:t.sessionName,transitionError:n instanceof Error?n.message:String(n)}}),{confirmed:!1,cleanupError:r??n}}}async function y(e,t){try{t.kind===`transferred`?await t.handle[Symbol.asyncDispose]():await e.pendingHandle[Symbol.asyncDispose]();return}catch(e){return e}}function ie(e,t,n){try{return e.store.write(n,b(e,t,t.envelope.descriptor)),!0}catch(r){try{return e.store.write(n,b(e,t,{version:0,body:{reason:`runtime-contract-invalid`}})),!0}catch(n){return s({level:`error`,phase:`${v(e.resourceKind)}_runtime_contract_tombstone_failed`,data:{session:t.sessionName,descriptorError:r instanceof Error?r.message:String(r),persistenceError:n instanceof Error?n.message:String(n)}}),!1}}}function b(e,t,n){return f({resourceKind:e.resourceKind,sessionId:t.sessionName,device:r(t.device),owner:t.owner,fence:t.fence,lifecycle:`open`,descriptor:n,metadata:{phase:`runtime-contract-invalid`,runtimeContractInvalid:!0}})}function ae(t,n){let r=d(n.envelope);if(r.status===`decoded`&&oe(r.envelope,n,t.resourceKind))return r.envelope;throw new e(`COMMAND_FAILED`,`${_(t.displayName)} runtime returned an incoherent durable envelope`,{reason:`runtime-contract-invalid`,hint:`Retain the runtime diagnostics and report the selected device and owner.`})}function oe(e,n,i){return e.resourceKind===i&&e.sessionId===n.sessionName&&t(e.device,r(n.device))&&a(e.owner)===a(n.owner)&&e.fence.token===n.fence.token&&e.fence.generation===n.fence.generation&&e.lifecycle===`open`}function se(e,t,n,r){let i=e.store.read(t);return i.status!==`decoded`||i.envelope.fence.token!==n.token||i.envelope.fence.generation!==n.generation?!1:(e.store.write(t,{...i.envelope,lifecycle:r===void 0?`completed`:`open`,metadata:{...i.envelope.metadata??{},phase:r===void 0?`completed`:`cleanup-pending`,cleanupStatus:r===void 0?`cleaned`:`cleanup-pending`}}),!0)}function x(e,t,n,r){s({level:`error`,phase:`${v(e.resourceKind)}_pending_adoption_cleanup_failed`,data:{session:t.sessionName,primaryError:n instanceof Error?n.message:String(n),cleanupError:r instanceof Error?r.message:String(r)}})}function ce(e,t){return Object.freeze({...e,lifecycle:`open`,metadata:{...e.metadata??{},phase:t}})}async function S(e){e.scope.signal.throwIfAborted();let t=new AbortController,n={...e.scope,signal:AbortSignal.any([e.scope.signal,t.signal])},r=()=>{},i=new Promise((e,t)=>{r=t}),a=()=>{},o=new Promise((t,n)=>{let r=()=>{try{e.scope.signal.throwIfAborted()}catch(e){n(e)}};if(e.scope.signal.aborted){r();return}e.scope.signal.addEventListener(`abort`,r,{once:!0}),a=()=>e.scope.signal.removeEventListener(`abort`,r)}),s=setTimeout(()=>{let n=new w(e.displayName,e.deadlineMs);t.abort(n),r(n)},e.deadlineMs);s.unref?.();let c=ue(e,n),l,u=c.then(e=>(l??={kind:`acquisition`},e),e=>{throw l??={kind:`acquisition-error`},e}),d=i.catch(e=>{throw l??={kind:`deadline`,error:e},e}),f=o.catch(e=>{throw l??={kind:`cancellation`,error:e},e});try{return await Promise.race([u,d,f])}finally{if(clearTimeout(s),a(),l?.kind===`deadline`||l?.kind===`cancellation`){let t=l.error;c.then(n=>le(e,n,t),()=>{}).catch(()=>{})}else c.catch(()=>{})}}async function le(e,t,n){try{t.reattached.status===`active`&&await C(e,t.reattached.handle,`late_handle_cleanup_failed`,n)}finally{await C(e,t.control,`late_control_cleanup_failed`,n)}}async function ue(e,t){let n,r;try{return n=await e.acquireControl(e.envelope,t),t.signal.throwIfAborted(),r=await n.reattach(e.envelope),t.signal.throwIfAborted(),{control:n,reattached:r}}catch(t){try{r?.status===`active`&&await C(e,r.handle,`late_handle_cleanup_failed`,t)}finally{n&&await C(e,n,`late_control_cleanup_failed`,t)}throw t}}async function C(e,t,n,r){try{await t[Symbol.asyncDispose]()}catch(t){e.onLateCleanupFailure(n,t,r)}}var w=class extends Error{deadlineMs;constructor(e,t){super(`${_(e)} recovery exceeded its ${t}ms deadline`),this.name=`DurableCaptureRecoveryDeadlineError`,this.deadlineMs=t}};const T=new Map;async function E(e){return await de(e.resourcePath,async()=>{let t=e.store.read(e.resourcePath);if(t.status!==`decoded`)throw O(e.store,t.status===`missing`?`${e.store.displayName} resource record is missing`:`${e.store.displayName} resource record is unreattachable: ${t.message}`);if(!D(t.envelope.fence,e.expected))throw O(e.store,`${e.store.displayName} resource ownership fence was lost`);let n=t.envelope;return await e.run({get envelope(){return n},transition(t,r={}){return n=Object.freeze({...n,lifecycle:t,...r.descriptor===void 0?{}:{descriptor:r.descriptor},...r.metadata===void 0?{}:{metadata:r.metadata}}),e.store.write(e.resourcePath,n),n}})})}function D(e,t){return e.token===t.token&&e.generation===t.generation}async function de(e,t){let n=T.get(e)??Promise.resolve(),r,i=new Promise(e=>{r=e}),a=n.catch(()=>{}).then(()=>i);T.set(e,a),await n.catch(()=>{});try{return await t()}finally{r(),T.get(e)===a&&T.delete(e)}}function O(t,n){return new e(`COMMAND_FAILED`,n,{reason:`ownership-fence-lost`,retriable:!1,hint:`Use the current ${t.displayName.toLowerCase()} resource owner or retain the recovery record for manual recovery.`})}async function fe(t,n,r){let i=t.sessionSlot.read(n.session);if(!i)throw new e(`INVALID_ARGS`,t.messages.noActive);try{let e=await k(t,{handle:i.handle,fence:i.envelope.fence,resourcePath:r});return M(t,n),e}catch(e){let i=t.store.read(r);throw i.status===`decoded`&&i.envelope.lifecycle===`completed`&&M(t,n),e}}async function k(e,t){return await E({store:e.store,resourcePath:t.resourcePath,expected:t.fence,run:async n=>{R(n);let r;try{r=await t.handle.finish()}catch(r){throw await A(e,n,t,r),r}if(r.status===`completed`)return L(e,n,r),r.result;L(e,n,r);let i=I(e,r);throw await A(e,n,t,i),i}})}async function A(e,t,n,r){let i;try{i=await n.handle.forceCleanup()}catch(i){j(e,n,r,i,pe(t,i));return}try{P(t,i)}catch(t){j(e,n,r,i.status===`cleanup-pending`?i.message??i.reason:`cleanup returned ${i.status}`,t);return}p(i)||j(e,n,r,i.message)}function pe(e,t){try{P(e,{status:`cleanup-pending`,reason:`cleanup-unconfirmed`,message:N(t)});return}catch(e){return e}}function j(e,t,n,r,i){s({level:`error`,phase:`${e.resourceKind.replaceAll(`-`,`_`)}_finish_cleanup_failed`,data:{resourcePath:t.resourcePath,finishError:N(n),cleanupError:r===void 0?`cleanup could not be confirmed`:N(r),...i===void 0?{}:{transitionError:N(i)}}})}function M(e,t){t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0))}function N(e){return e instanceof Error?e.message:String(e)}async function me(e,t){let n=e.sessionSlot.read(t.session);n&&(F(e,await E({store:e.store,resourcePath:t.resourcePath,expected:n.envelope.fence,run:async e=>{R(e);let t=await n.handle.forceCleanup();return P(e,t),t}})),t.sessionStore&&t.sessionName&&t.sessionStore.set(t.sessionName,e.sessionSlot.replace(t.session,void 0)))}function P(e,t){e.transition(p(t)?`completed`:`open`,{metadata:{...e.envelope.metadata??{},phase:p(t)?`completed`:`cleanup-pending`,cleanupStatus:t.status,...t.status===`cleanup-pending`?{cleanupPendingReason:t.reason,...t.message?{cleanupPendingMessage:t.message}:{}}:{}}})}function F(e,t){if(!p(t))throw I(e,t)}function I(t,n){return new e(`COMMAND_FAILED`,n.message??`${_(t.displayName)} cleanup could not be confirmed`,{reason:n.reason,retriable:n.reason!==`ownership-fence-lost`,hint:t.messages.cleanupPendingHint})}function L(e,t,n){if(n.status===`completed`){t.transition(`completed`,{metadata:{...t.envelope.metadata??{},...e.completionMetadata(n.result),phase:`completed`}});return}P(t,n)}function R(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}async function z(e){let t=e.definition.store.list(e.sessionsDir),n=[];for(let r of t)n.push(await B(e,r));return{scanned:t.length,recovered:n.filter(e=>e===`recovered`).length,retained:n.filter(e=>e===`retained`).length}}async function B(e,t){let n=he(e,t);if(n.status!==`recoverable`)return n.status;try{return await ge(e,t,n.envelope,e.perRecordDeadlineMs??5e3)?`recovered`:`retained`}catch(n){return U(e,n instanceof w?`timed_out`:`failed`,t,{error:n instanceof Error?n.message:String(n),...n instanceof w?{deadlineMs:n.deadlineMs}:{}}),`retained`}}function he(e,t){let n=e.definition.store.read(t);if(n.status===`unreattachable`)return U(e,`record_unreattachable`,t,{reason:n.reason,message:n.message,version:n.version}),{status:`retained`};if(n.status===`missing`||n.envelope.lifecycle===`completed`)return{status:`ignored`};let r=e.definition.store.resolvePath(e.resolveSessionDir(n.envelope.sessionId));return h.resolve(t)===h.resolve(r)?{status:`recoverable`,envelope:n.envelope}:(U(e,`session_path_mismatch`,t,{envelopeSessionId:n.envelope.sessionId,canonicalPath:r}),{status:`retained`})}async function ge(e,t,n,r){return await _e(e,t,n,await S({displayName:e.definition.displayName,envelope:n,scope:e.scope,deadlineMs:r,acquireControl:e.acquireControl,onLateCleanupFailure:(n,r,i)=>U(e,n,t,{error:r instanceof Error?r.message:String(r),primaryError:i instanceof Error?i.message:String(i)})}))}async function _e(e,t,n,r){try{switch(r.reattached.status){case`active`:{let i=r.reattached.handle,a=await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{ve(e);let t=await i.forceCleanup();return P(e,t),t}});return p(a)}case`completed`:return await V(e,t,n,{...e.definition.completionMetadata(r.reattached.result)}),!0;case`missing`:return await V(e,t,n,{recoveryStatus:`already-missing`}),!0;case`unreattachable`:{if(!H(r.reattached.reason))return U(e,`retained`,t,{reason:r.reattached.reason,message:r.reattached.message}),!1;let i=await r.control.cleanup(n);return await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>P(e,i)}),p(i)}}}finally{await r.control[Symbol.asyncDispose]()}}async function V(e,t,n,r){await E({store:e.definition.store,resourcePath:t,expected:n.fence,run:async e=>{e.transition(`completed`,{metadata:{...e.envelope.metadata??{},phase:`completed`,...r}})}})}function ve(e){e.transition(`open`,{metadata:{...e.envelope.metadata??{},phase:`completing`}})}function H(e){switch(e){case`descriptor-invalid`:case`descriptor-version-unsupported`:case`ownership-fence-lost`:return!1;case`owner-unavailable`:case`transport-not-reattachable`:return!0}}function U(e,t,n,r){let i={phase:`${v(e.definition.resourceKind)}_recovery_${t}`,resourcePath:n,data:r};e.onDiagnostic?e.onDiagnostic(i):s({level:`warn`,phase:i.phase,data:{resourcePath:n,...r}})}async function ye(t,n){let r=t.store.read(n.resourcePath);if(r.status!==`decoded`||r.envelope.lifecycle!==`open`)throw W(t,r.status);let i=r.envelope,a=await S({displayName:t.displayName,envelope:i,scope:n.scope,deadlineMs:n.deadlineMs??5e3,acquireControl:n.acquireControl,onLateCleanupFailure:(e,r,i)=>n.scope.diagnostics.emit({level:`error`,phase:`${v(t.resourceKind)}_recovery_${e}`,data:{resourcePath:n.resourcePath,error:G(r),primaryError:G(i)}})});try{switch(a.reattached.status){case`active`:return await k(t,{handle:a.reattached.handle,fence:i.fence,resourcePath:n.resourcePath});case`completed`:{let e=a.reattached.result;return await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async n=>{L(t,n,{status:`completed`,result:e,alreadyCompleted:!0})}}),e}case`missing`:throw new e(`COMMAND_FAILED`,`${_(t.displayName)} is missing`,{reason:`resource-missing`,hint:t.messages.cleanupPendingHint});case`unreattachable`:if(H(a.reattached.reason)){let e=await a.control.cleanup(i);await E({store:t.store,resourcePath:n.resourcePath,expected:i.fence,run:async t=>P(t,e)}),F(t,e)}throw new e(`COMMAND_FAILED`,a.reattached.message??`${_(t.displayName)} cannot be reattached`,{reason:a.reattached.reason,hint:t.messages.cleanupPendingHint})}}finally{await a.control[Symbol.asyncDispose]()}}function W(t,n){return new e(`INVALID_ARGS`,n===`missing`?t.messages.noActive:`${_(t.displayName)} recovery record is not open`)}function G(e){return e instanceof Error?e.message:String(e)}function K(e){xe(e.fileName);let t=t=>h.join(t,e.fileName);return Object.freeze({resourceKind:e.resourceKind,displayName:e.displayName,resolvePath:t,read(t){let n,r;try{if(n=l(t),n===void 0)return{status:`missing`};r=JSON.parse(g.readFileSync(n,`utf8`))}catch(t){return J(t)?{status:`missing`}:q(Ce(t,e.displayName))}finally{n!==void 0&&g.closeSync(n)}return be(d(r),e.resourceKind)},write(e,t){let n=h.dirname(e);g.mkdirSync(n,{recursive:!0}),c({destination:e,contents:`${JSON.stringify(t)}\n`})},list(e){let n;try{n=g.readdirSync(e,{withFileTypes:!0})}catch{return[]}return n.filter(e=>e.isDirectory()).map(n=>t(h.join(e,n.name))).filter(Se).sort()}})}function be(e,t){return e.status===`decoded`?e.envelope.resourceKind===t?{status:`decoded`,envelope:e.envelope}:q(`Expected ${t} resource record, received ${e.envelope.resourceKind}`):e}function xe(e){if(e.length===0||h.basename(e)!==e)throw TypeError(`Durable capture resource fileName must be one file name`)}function Se(e){try{return g.lstatSync(e),!0}catch(e){return!J(e)}}function q(e){return{status:`unreattachable`,reason:`descriptor-invalid`,message:e}}function J(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function Ce(e,t){return e instanceof Error?e.message:`${t} resource record is invalid`}function we(e,t){t.admissionLedger.assertStartAllowed(t.device),Te(e,t.resourcePath,t.device);let n=e.store.read(t.resourcePath);return Object.freeze({token:ee.randomUUID(),generation:n.status===`decoded`?n.envelope.fence.generation+1:1})}function Te(t,i,a){let o=n(r(a));for(let r of t.store.list(h.dirname(h.dirname(i)))){let a=t.store.read(r);if(a.status===`unreattachable`)throw new e(`COMMAND_FAILED`,`${_(Y(t.displayName))} ${t.displayName} recovery record is unreattachable: ${a.message}`,{reason:a.reason,retriable:!1,hint:`Retain the corrupt or future-version ${t.displayName} manifest for manual recovery; no replacement capture is safe.`});if(a.status===`decoded`&&a.envelope.lifecycle!==`completed`&&(r===i||n(a.envelope.device)===o))throw new e(`COMMAND_FAILED`,`${_(Y(t.displayName))} ${t.displayName} resource for this device has not reached a confirmed terminal state`,{reason:`cleanup-unconfirmed`,hint:`Retry exact-owner cleanup using the existing ${t.displayName} manifest before starting a replacement.`})}}function Y(e){return/^[aeiou]/i.test(e)?`an`:`a`}function X(e){let t=(t,n)=>e.store.resolvePath(t.resolveSessionDir(n)),n=t=>({definition:e,resolveSessionDir:e=>h.join(t.sessionsDir,u(e)),...t});return Object.freeze({store:e.store,createNextFence(t){return we(e,t)},adoptStarted(n){return te(e,{...n,reportUndurableCleanup:(e,t)=>{t.confirmed?n.admissionLedger.clearUndurableCleanup(e):n.admissionLedger.blockUndurableCleanup(e,t.reason)}},t(n.sessionStore,n.sessionName))},finishLive(n){return fe(e,n,t(n.sessionStore,n.sessionName))},finishRecovered(t){return ye(e,t)},forceCleanupLive(t){return me(e,t)},recoverAll(e){return z(n(e))},recoverOne(e,t){return B(n(e),t)}})}const Z=X({resourceKind:`screen-recording`,displayName:`screen recording`,store:K({resourceKind:m,fileName:`screen-recording.resource.json`,displayName:`screen recording`}),sessionSlot:{read:e=>e.screenRecording,replace:(e,t)=>({...e,screenRecording:t})},completionMetadata:e=>({backend:e.backend,outputPath:e.outPath,startedAt:e.startedAt,completedAt:e.completedAt,scope:e.scope,showTouches:e.showTouches,recordOnlySession:e.recordOnlySession}),messages:{noActive:`no active recording`,cleanupPendingHint:`Keep screen-recording.resource.json and retry stop through its exact runtime owner.`}});function Ee(e){return Z.adoptStarted(e)}function De(e){return Z.finishLive(e)}function Oe(e){return Z.finishRecovered(e)}async function Q(e){let t;try{return t=await e.gateway.bind({device:ke(e.envelope),intent:{kind:`exact-owner`,owner:e.envelope.owner,fence:e.envelope.fence},scope:e.scope}),e.scope.signal.throwIfAborted(),e.create(t)}catch(e){throw t&&await t[Symbol.asyncDispose](),e}}function ke(e){return{platform:e.device.family,id:e.device.id,name:e.device.id,kind:e.device.kind,...e.device.target===void 0?{}:{target:e.device.target},...e.device.appleOs===void 0?{}:{appleOs:e.device.appleOs},...e.device.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.device.iosPhysicalDeviceBackend}}}function Ae(e){return Z.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await je(e.gateway,t,n)},e.resourcePath)}async function je(e,t,n){return await Q({gateway:e,envelope:t,scope:n,create:e=>$({runtime:o(e,i),dispose:async()=>await e[Symbol.asyncDispose]()})})}function $(e){return Object.freeze({reattach:async t=>await e.runtime.operations.screenRecordingReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.screenRecordingCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}export{De as a,X as c,Ee as i,K as l,Ae as n,Oe as o,Q as r,Z as s,$ as t};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{promises as n}from"node:fs";async function r(t){let r=await n.open(t,`r`);try{let t=Buffer.alloc(24),{bytesRead:n}=await r.read(t,0,t.length,0);if(n<t.length||t.toString(`ascii`,12,16)!==`IHDR`)throw new e(`COMMAND_FAILED`,`Screenshot file is not a valid PNG`);return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}finally{await r.close()}}function i(t,n){if(!(n===void 0||c(t)))throw new e(`UNSUPPORTED_OPERATION`,`--pixel-density is currently supported only on iOS-family simulators`)}function a(e,t,n){let r=s(n);if(t!==r)return{width:Math.max(1,Math.round(e.width/t*r)),height:Math.max(1,Math.round(e.height/t*r))}}async function o(e){let t=c(e.device),n;try{n=await r(e.path)}catch(e){if(t)throw e;return{}}let i={width:n.width,height:n.height};if(!t||e.scale!==void 0&&e.scale!==1)return i;let a=s(e.requestedPixelDensity);return{...i,logicalWidth:Math.round(n.width/a),logicalHeight:Math.round(n.height/a),pixelDensity:a}}function s(e){return e??1}function c(e){return t(e)&&e.kind===`simulator`}export{r as i,a as n,o as r,i as t};
1
+ import{C as e}from"./sdk-contracts.js";import{l as t}from"./sdk-device.js";import{promises as n}from"node:fs";async function r(t){let r=await n.open(t,`r`);try{let t=Buffer.alloc(24),{bytesRead:n}=await r.read(t,0,t.length,0);if(n<t.length||t.toString(`ascii`,12,16)!==`IHDR`)throw new e(`COMMAND_FAILED`,`Screenshot file is not a valid PNG`);return{width:t.readUInt32BE(16),height:t.readUInt32BE(20)}}finally{await r.close()}}function i(t,n){if(!(n===void 0||c(t)))throw new e(`UNSUPPORTED_OPERATION`,`--pixel-density is currently supported only on iOS-family simulators`)}function a(e,t,n){let r=s(n);if(t!==r)return{width:Math.max(1,Math.round(e.width/t*r)),height:Math.max(1,Math.round(e.height/t*r))}}async function o(e){let t=c(e.device),n;try{n=await r(e.path)}catch(e){if(t)throw e;return{}}let i={width:n.width,height:n.height};if(!t||e.scale!==void 0&&e.scale!==1)return i;let a=s(e.requestedPixelDensity);return{...i,logicalWidth:Math.round(n.width/a),logicalHeight:Math.round(n.height/a),pixelDensity:a}}function s(e){return e??1}function c(e){return t(e)&&e.kind===`simulator`}export{r as i,a as n,o as r,i as t};
@@ -1 +1 @@
1
- import{d as e,y as t}from"./sdk-contracts.js";import{f as n,i as r,l as i,u as a}from"./capture.js";import{S as o,l as s,v as c}from"./sdk-device.js";import{Ar as l,Hr as u,Mt as d,Nr as f,Rr as p,Tr as m,Vr as h,b as g,jr as _,l as ee,ln as te,u as ne,v as re}from"./sdk-batch.js";import{t as ie}from"./session-store.js";import{E as ae,n as oe,p as se,t as ce,y as le}from"./runtime.js";import{t as v}from"./snapshot-state.js";import{i as y}from"./request-runtime-binding.js";import{c as b,i as ue,o as de,p as x}from"./session-snapshot.js";import{a as fe}from"./png-worker-contract.js";import{c as S,l as C}from"./snapshot-quality-verdict.js";import{i as pe,r as me,t as he}from"./screenshot-density.js";import{a as ge,i as _e,n as ve,t as ye}from"./session-runtime-admission.js";import w from"node:path";import{promises as T}from"node:fs";import E from"node:os";const D=ee(ne),be=Ie(D);function xe(e){return A(e)?.route??`generic`}function Se(e){return A(e)?.sessionKind}function Ce(e){return A(e)?.leaseAdmissionExempt===!0}function we(e){return A(e)?.selectorValidationExempt!==!0}function O(e){return A(e)?.sessionExecutionLockExempt!==!0}function k(e){return A(e)?.replayScopedAction===!0}function Te(e){return A(e)?.allowInvalidRecording!==!0}function Ee(e){return A(e)?.saveScriptFlagOwner===!0}function De(){return D.filter(e=>e.saveScriptFlagOwner===!0).map(e=>e.command).sort()}function Oe(e){return A(e)?.lockPolicySelectorOverride===!0}function ke(e){return A(e)?.androidBlockingDialogGuard===!0}function Ae(e){if(e.command===`human_control`||e.command===`lease_heartbeat`)return!1;let t=g(e);return t===void 0?Se(e.command)!==`observability`&&re(e.command)!==`observe`:t!==`observes-app`}function je(e){return A(e.command)?.preferExplicitDeviceOverExistingSession===!0}function Me(e){let t=A(e.command)?.allowSessionlessDefaultDevice;return typeof t==`function`&&t(e)}function Ne(e){return A(e.command)?.sessionlessLeaseAdmissionExemption?.(e)}function Pe(e){let t=A(e.command)?.refFrameEffect;return typeof t==`function`?t(e):t}function Fe(e,t){return t.hasExistingSession?je(e)&&t.hasExplicitDeviceIdentity?`explicit-device`:`existing-session`:Le(e)?`skip`:t.hasDeviceSelectionInput?`explicit-device`:Me(e)?`sessionless-default-device`:`skip`}function A(e){return be.descriptorsByCommand.get(e)}function Ie(e){let t=new Map;for(let n of e){if(t.has(n.command))throw Error(`Duplicate daemon command descriptor: ${n.command}`);t.set(n.command,n)}return{descriptorsByCommand:t}}function Le(e){let t=A(e.command);if(t?.route===`lease`)return!0;let n=t?.skipSessionlessProviderDevice;return typeof n==`function`&&n(e)}const j=r.pendingPixelIdentityEvidence,Re=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:j},{target:`macos-app-window`,status:`rejected`,rejectionReason:j},{target:`ios-physical`,status:`rejected`,rejectionReason:j},{target:`macos-helper`,status:`rejected`,rejectionReason:j},{target:`web`,status:`rejected`,rejectionReason:j},{target:`linux`,status:`rejected`,rejectionReason:j},{target:`tvos`,status:`rejected`,rejectionReason:j},{target:`harmonyos`,status:`rejected`,rejectionReason:j},{target:`vega`,status:`rejected`,rejectionReason:j}];function ze(e,t){switch(e.platform){case`apple`:return Be(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function Be(e,t){let n=o(e);switch(n){case`ios`:case`ipados`:return e.kind===`device`?`ios-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return Ve(t);case`watchos`:case`visionos`:throw M(n)}}function Ve(e){return e===`app`||e===`frontmost-app`?`macos-app-window`:`macos-helper`}function M(e,n){return new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${e} targets`,{reason:r.targetNotAccepted,...n?{rejectionReason:n}:{}})}function He(e){if(e.overlayRefs||e.fullscreen)throw new t(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:r.frameMismatch});try{te(e.cropOn)}catch{throw new t(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:r.selectorInvalid})}let n=ze(e.device,e.surface),i=Re.find(e=>e.target===n);if(!i||i.status===`rejected`)throw M(n,i?.status===`rejected`?i.rejectionReason:void 0)}async function Ue(e,n){if(!We(n))throw new t(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await S(await T.readFile(e),`screenshot`);if(n.x+n.width>r.width||n.y+n.height>r.height)throw new t(`INVALID_ARGS`,`Screenshot crop box ${n.width}x${n.height} at (${n.x}, ${n.y}) exceeds the ${r.width}x${r.height} image`);(n.x!==0||n.y!==0||n.width!==r.width||n.height!==r.height)&&await T.writeFile(e,await C(Ge(r,n)))}function We(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function Ge(e,t){let n=new fe.PNG({width:t.width,height:t.height});for(let r=0;r<t.height;r+=1){let i=((r+t.y)*e.width+t.x)*4;e.data.copy(n.data,r*n.width*4,i,i+t.width*4)}return n}function Ke(e){switch(e){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${e??`unknown`}"`,{reason:r.targetNotAccepted})}}function N(e,t,n,r,i){if(e===`device-pixels`||t===null)return Xe(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function qe(e,t,n){let r=Math.max(e.x,0),i=Math.max(e.y,0),a=Math.min(e.x+e.width,t),o=Math.min(e.y+e.height,n);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function P(e){let t=null;for(let n of e)!m(n)||!p(n.rect)||(!t||h(n.rect)>h(t))&&(t=n.rect);return t||Je(e.filter(e=>p(e.rect)&&!Ye(e)))}function Je(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)p(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Ye(e){return _(e.type??``)===`image`&&!l(e.label)}function Xe(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Ze=`${r.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Qe(e){return e?.partialIntersection?[Ze]:[]}async function $e(e){let{device:n,session:i,surface:a,cropOn:o,screenshotPath:s,logPath:c,dispatchContext:l}=e,u={snapshotInteractiveOnly:!1},d=await b({device:n,session:i,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:a},execution:x(l)})}),f=v(d,u);if(f.snapshotQuality?.state===`sparse`)throw new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:r.captureUnreadable});let p=await et(f.nodes,o,f.truncated,n),m=await pe(s),h=N(Ke(f.backend),P(f.nodes),p.rect,m.width,m.height),g=qe(h,m.width,m.height);if(g===null)throw new t(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:r.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await Ue(s,g),{partialIntersection:_}}async function et(e,n,i,a){let o=await se(le.cropTarget,e,n,{platform:c(a)});if(o.kind===`ambiguous`)throw new t(`COMMAND_FAILED`,`--crop-on matched ${o.matchedNodes.length} nodes and must resolve to one`,{reason:r.targetAmbiguous,candidates:o.matchedNodes.map(e=>e.label??e.ref),matches:o.matchedNodes.length});if(o.kind===`none`)throw i?new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:r.captureIncomplete}):new t(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:r.targetNotFound,hint:`find ${n} list`});return o.node}function F(e){return!!(e&&e.width>0&&e.height>0)}function I(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(n,e)):t}function L(e){return e.width*e.height}function tt(e){let t=e[0];if(t===void 0)throw Error(`unionRects requires at least one rect`);let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}const nt=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function rt(e,t,n){if(e.backend!==`android`||!n.hittable||!F(n.rect)||m(n))return!1;let r=_(n.type??``);return!(nt.some(e=>r.includes(e))||t&&L(n.rect)>L(t)*.25)}function it(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:at(e,t,r)}function at(e,t,n){let r=e.rect,i=ot(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function ot(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&ct(t,e,i)&&st(t,n)&&F(t.rect)&&u(r,t.rect)).map(e=>e.rect);return a.length<2?null:tt(a)}function st(e,t){let n=_(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function ct(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const lt=[255,59,48,255],ut=[255,214,10,255],dt=[0,0,0,255],ft={e:[`01110`,`10000`,`11110`,`10000`,`10000`,`10001`,`01110`],0:[`01110`,`10001`,`10011`,`10101`,`11001`,`10001`,`01110`],1:[`00100`,`01100`,`00100`,`00100`,`00100`,`00100`,`01110`],2:[`01110`,`10001`,`00001`,`00010`,`00100`,`01000`,`11111`],3:[`11110`,`00001`,`00001`,`01110`,`00001`,`00001`,`11110`],4:[`00010`,`00110`,`01010`,`10010`,`11111`,`00010`,`00010`],5:[`11111`,`10000`,`10000`,`11110`,`00001`,`00001`,`11110`],6:[`01110`,`10000`,`10000`,`11110`,`10001`,`10001`,`01110`],7:[`11111`,`00001`,`00010`,`00100`,`01000`,`01000`,`01000`],8:[`01110`,`10001`,`10001`,`01110`,`10001`,`10001`,`01110`],9:[`01110`,`10001`,`10001`,`01111`,`00001`,`00001`,`01110`]};function pt(e,t){mt(e,t.overlayRect,lt,2),ht(e,t.overlayRect,t.ref)}function mt(e,t,n,r){for(let i=0;i<r;i+=1)R(e,t.x,t.x+t.width-1,t.y+i,n),R(e,t.x,t.x+t.width-1,t.y+t.height-1-i,n),z(e,t.x+i,t.y,t.y+t.height-1,n),z(e,t.x+t.width-1-i,t.y,t.y+t.height-1,n)}function ht(e,t,n){let r=6+n.length*5+Math.max(0,n.length-1)*1,i=I(t.x,0,Math.max(0,e.width-r)),a=t.y-11-2,o=a>=0?a:I(t.y+2,0,Math.max(0,e.height-11));_t(e,i,o,r,11,ut),gt(e,i+3,o+2,n,dt)}function gt(e,t,n,r,i){let a=t;for(let t of r.toLowerCase()){let r=ft[t];if(r)for(let t=0;t<r.length;t+=1)for(let o=0;o<r[t].length;o+=1)r[t][o]===`1`&&B(e,a+o,n+t,i);a+=6}}function _t(e,t,n,r,i,a){for(let o=0;o<i;o+=1)for(let i=0;i<r;i+=1)B(e,t+i,n+o,a)}function R(e,t,n,r,i){for(let a=t;a<=n;a+=1)B(e,a,r,i)}function z(e,t,n,r,i){for(let a=n;a<=r;a+=1)B(e,t,a,i)}function B(e,t,n,r){if(t<0||n<0||t>=e.width||n>=e.height)return;let i=(e.width*n+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}const vt=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await T.readFile(e.screenshotPath),n=await S(t,`screenshot`),r=yt(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)pt(n,e);return await T.writeFile(e.screenshotPath,await C(n)),r}function yt(t,n,r,i={}){let a=P(t.nodes),o=new Map;for(let e of t.nodes){if(!St(t,a,e))continue;let i=Ct(t.nodes,e);if(!i?.rect||!F(i.rect))continue;let s=wt(e,i,t.nodes),c=Tt(e,i,s),l=H(t,a,xt(t,i,t.nodes),n,r);if(!F(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return bt(t,a,o,n,r),Et([...o.values()]).sort(It).slice(0,i.maxRefs??24).sort(J).map(t=>({ref:t.ref,label:t.label,rect:t.rect,overlayRect:t.overlayRect,center:e(t.overlayRect)}))}function bt(e,t,n,r,i){let a=ae(e.nodes).primaryAction;if(!a?.ref||!a.rect||!F(a.rect))return;let o=H(e,t,a.rect,r,i);if(!F(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function xt(e,t,n){return e.backend===`android`?it(t,n,U,e=>!!q(e))??t.rect:t.rect}function St(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return rt(e,t,n)?!0:U(n)?r:r&&Dt(n)}function Ct(e,t){return[W(t)?t:null,f(e,t,W),t.hittable?t:null,f(e,t,e=>e.hittable===!0)].find(Ot)??null}function wt(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:kt(t,n)||q(t)}function Tt(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),l(t.value)&&(r+=1),r}function Et(e){let t=[];for(let n of e.sort((e,t)=>L(e.overlayRect)-L(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(u(e.overlayRect,n.overlayRect)||u(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}L(n.overlayRect)<L(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Ft(N(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>_(e??``)).join(` `);return vt.some(e=>t.includes(e))}function W(e){return U(e)&&!m(e)}function Dt(e){let t=_(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ot(e){return!!(e?.rect&&F(e.rect)&&!m(e))}function G(e){return l(e)?!Mt(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Nt(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function kt(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!At(r,e,t))continue;let i=q(r);if(!i)continue;let a=jt(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function At(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function jt(e){let t=0;return _(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Mt(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Nt(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Pt(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Ft(e,t,n){let r=I(e.x,0,Math.max(0,t-1)),i=I(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:I(e.width,1,a),height:I(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Pt(e.ref,t.ref):r}function It(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=d({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ye({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await X(e.bindDevice,n)}:{ok:!1,response:Rt(t.kind,n.operation,n.fact)}}async function X(e,t){let n=ve(e),{device:r,plan:i}=ge(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:Z(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:Z(e),captureSnapshot:Lt(e)})}}}function Z(e){return async t=>await e.operations.captureScreenshot(t)}function Lt(e){return async t=>await e.operations.captureSnapshot(t)}function Rt(e,t,n){return t===`captureScreenshot`?_e(`screenshot`,n):e===`capture-with-crop-on`?y(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):y(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}async function zt(e){let{req:n,session:r}=e,a=i(`screenshot`,n.flags);if(a)throw new t(`INVALID_ARGS`,a);he(r.device,n.flags?.screenshotPixelDensity);let o=Wt(n),s=typeof n.flags?.screenshotCropOn==`string`&&n.flags.screenshotCropOn.length>0?n.flags.screenshotCropOn:void 0;s!==void 0&&He({device:r.device,surface:r.surface,cropOn:s,overlayRefs:n.flags?.overlayRefs===!0,fullscreen:n.flags?.screenshotFullscreen===!0});let c=await Y({device:r.device,overlayRefs:n.flags?.overlayRefs===!0,cropOn:s,inspectFacts:e.inspectFacts,bindDevice:e.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]};return{ok:!0,recorded:o.recorded,execute:async e=>await Bt({session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Q(e){let{session:t,sessionName:r,outPath:i,dispatchContext:a}=e;return await ce({backend:Gt(e),artifacts:Kt(),sessions:de({sessionName:r,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:oe()}).capture.screenshot({session:r,requestId:a.requestId,appBundleId:t.appBundleId,...n(a),surface:t.surface,...i?{out:{kind:`path`,path:i}}:{}})}function $(e){return x(e)}async function Bt(e){let{session:t,runtime:n,flags:r}=e,i=Vt({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await Ht({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await me({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function Vt(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function Ht(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await Ut({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function Ut(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await b({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:$(n)})}),a=v(i,r);return ue(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function Wt(e){let t=e.positionals??[],n=e.flags??{},r=t=>t===void 0?void 0:ie.expandHome(t,e.meta?.cwd),i=r(t[0]),a=r(n.out);return{outPath:i??a,recorded:{positionals:i?[i,...t.slice(1)]:t,flags:a?{...n,out:a}:n}}}function Gt(e){let{session:t,dispatchContext:r,captureScreenshot:i,crop:o}=e;return{platform:c(t.device),captureScreenshot:async(e,c,l)=>{let u=n({...r,...a(l)});if(await i({outPath:c,options:{appBundleId:r.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:l?.surface,skipIosSimulatorBootCheck:r.skipIosSimulatorBootCheck??(s(t.device)&&t.device.kind===`simulator`),captureBackend:r.screenshotCaptureBackend},execution:$(r)}),o){let e=await $e({device:t.device,session:t,surface:t.surface,cropOn:o.cropOn,screenshotPath:c,logPath:o.logPath,dispatchContext:r,captureSnapshot:o.captureSnapshot});o.run.warnings.push(...Qe(e))}}}}function Kt(){return{resolveInput:async()=>{throw new t(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await T.mkdtemp(w.join(E.tmpdir(),`agent-device-screenshot-`)),n=w.join(t,`screenshot.png`)),await T.mkdir(w.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await T.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await T.mkdtemp(w.join(E.tmpdir(),`${e.prefix}-`));return{path:w.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await T.rm(t,{recursive:!0,force:!0})}}}}}export{ke as _,V as a,xe as c,De as d,Ee as f,Te as g,Ne as h,Y as i,Ae as l,Pe as m,zt as n,Oe as o,Fe as p,$ as r,k as s,Q as t,Ce as u,O as v,we as y};
1
+ import{C as e,p as t}from"./sdk-contracts.js";import{c as n,d as r,l as i,r as a}from"./capture.js";import{S as o,l as s,v as c}from"./sdk-device.js";import{Ar as l,Hr as u,Mt as d,Nr as f,Rr as p,Tr as m,Vr as h,b as g,jr as _,l as ee,ln as te,u as ne,v as re}from"./sdk-batch.js";import{t as ie}from"./session-store.js";import{C as ae,d as oe,g as se,n as ce,t as le}from"./runtime.js";import{t as v}from"./snapshot-state.js";import{i as y}from"./request-runtime-binding.js";import{c as b,i as ue,o as de,p as x}from"./session-snapshot.js";import{a as fe}from"./png-worker-contract.js";import{c as S,l as C}from"./snapshot-quality-verdict.js";import{i as pe,r as me,t as he}from"./screenshot-density.js";import{a as ge,i as _e,n as ve,t as ye}from"./session-runtime-admission.js";import w from"node:path";import{promises as T}from"node:fs";import E from"node:os";const D=ee(ne),be=Ie(D);function xe(e){return A(e)?.route??`generic`}function Se(e){return A(e)?.sessionKind}function Ce(e){return A(e)?.leaseAdmissionExempt===!0}function we(e){return A(e)?.selectorValidationExempt!==!0}function O(e){return A(e)?.sessionExecutionLockExempt!==!0}function k(e){return A(e)?.replayScopedAction===!0}function Te(e){return A(e)?.allowInvalidRecording!==!0}function Ee(e){return A(e)?.saveScriptFlagOwner===!0}function De(){return D.filter(e=>e.saveScriptFlagOwner===!0).map(e=>e.command).sort()}function Oe(e){return A(e)?.lockPolicySelectorOverride===!0}function ke(e){return A(e)?.androidBlockingDialogGuard===!0}function Ae(e){if(e.command===`human_control`||e.command===`lease_heartbeat`)return!1;let t=g(e);return t===void 0?Se(e.command)!==`observability`&&re(e.command)!==`observe`:t!==`observes-app`}function je(e){return A(e.command)?.preferExplicitDeviceOverExistingSession===!0}function Me(e){let t=A(e.command)?.allowSessionlessDefaultDevice;return typeof t==`function`&&t(e)}function Ne(e){return A(e.command)?.sessionlessLeaseAdmissionExemption?.(e)}function Pe(e){let t=A(e.command)?.refFrameEffect;return typeof t==`function`?t(e):t}function Fe(e,t){return t.hasExistingSession?je(e)&&t.hasExplicitDeviceIdentity?`explicit-device`:`existing-session`:Le(e)?`skip`:t.hasDeviceSelectionInput?`explicit-device`:Me(e)?`sessionless-default-device`:`skip`}function A(e){return be.descriptorsByCommand.get(e)}function Ie(e){let t=new Map;for(let n of e){if(t.has(n.command))throw Error(`Duplicate daemon command descriptor: ${n.command}`);t.set(n.command,n)}return{descriptorsByCommand:t}}function Le(e){let t=A(e.command);if(t?.route===`lease`)return!0;let n=t?.skipSessionlessProviderDevice;return typeof n==`function`&&n(e)}const j=a.pendingPixelIdentityEvidence,Re=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:j},{target:`macos-app-window`,status:`rejected`,rejectionReason:j},{target:`ios-physical`,status:`rejected`,rejectionReason:j},{target:`macos-helper`,status:`rejected`,rejectionReason:j},{target:`web`,status:`rejected`,rejectionReason:j},{target:`linux`,status:`rejected`,rejectionReason:j},{target:`tvos`,status:`rejected`,rejectionReason:j},{target:`harmonyos`,status:`rejected`,rejectionReason:j},{target:`vega`,status:`rejected`,rejectionReason:j}];function ze(e,t){switch(e.platform){case`apple`:return Be(e,t);case`android`:return e.kind===`device`?`android-device`:`android-emulator`;case`harmonyos`:return`harmonyos`;case`vega`:return`vega`;case`linux`:return`linux`;case`web`:return`web`}}function Be(e,t){let n=o(e);switch(n){case`ios`:case`ipados`:return e.kind===`device`?`ios-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return Ve(t);case`watchos`:case`visionos`:throw M(n)}}function Ve(e){return e===`app`||e===`frontmost-app`?`macos-app-window`:`macos-helper`}function M(t,n){return new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${t} targets`,{reason:a.targetNotAccepted,...n?{rejectionReason:n}:{}})}function He(t){if(t.overlayRefs||t.fullscreen)throw new e(`INVALID_ARGS`,`--crop-on cannot be combined with --overlay-refs or --fullscreen: both move the captured frame away from the snapshot viewport the crop is measured against`,{reason:a.frameMismatch});try{te(t.cropOn)}catch{throw new e(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:a.selectorInvalid})}let n=ze(t.device,t.surface),r=Re.find(e=>e.target===n);if(!r||r.status===`rejected`)throw M(n,r?.status===`rejected`?r.rejectionReason:void 0)}async function Ue(t,n){if(!We(n))throw new e(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await S(await T.readFile(t),`screenshot`);if(n.x+n.width>r.width||n.y+n.height>r.height)throw new e(`INVALID_ARGS`,`Screenshot crop box ${n.width}x${n.height} at (${n.x}, ${n.y}) exceeds the ${r.width}x${r.height} image`);(n.x!==0||n.y!==0||n.width!==r.width||n.height!==r.height)&&await T.writeFile(t,await C(Ge(r,n)))}function We(e){return Number.isInteger(e.x)&&e.x>=0&&Number.isInteger(e.y)&&e.y>=0&&Number.isInteger(e.width)&&e.width>0&&Number.isInteger(e.height)&&e.height>0}function Ge(e,t){let n=new fe.PNG({width:t.width,height:t.height});for(let r=0;r<t.height;r+=1){let i=((r+t.y)*e.width+t.x)*4;e.data.copy(n.data,r*n.width*4,i,i+t.width*4)}return n}function Ke(t){switch(t){case`android`:return`device-pixels`;case`xctest`:case`macos-helper`:return`viewport-points`;default:throw new e(`UNSUPPORTED_OPERATION`,`screenshot --crop-on does not accept snapshot backend "${t??`unknown`}"`,{reason:a.targetNotAccepted})}}function N(e,t,n,r,i){if(e===`device-pixels`||t===null)return Xe(n);let a=r/t.width,o=i/t.height;return{x:Math.round((n.x-t.x)*a),y:Math.round((n.y-t.y)*o),width:Math.round(n.width*a),height:Math.round(n.height*o)}}function qe(e,t,n){let r=Math.max(e.x,0),i=Math.max(e.y,0),a=Math.min(e.x+e.width,t),o=Math.min(e.y+e.height,n);return a<=r||o<=i?null:{x:r,y:i,width:a-r,height:o-i}}function P(e){let t=null;for(let n of e)!m(n)||!p(n.rect)||(!t||h(n.rect)>h(t))&&(t=n.rect);return t||Je(e.filter(e=>p(e.rect)&&!Ye(e)))}function Je(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)p(a.rect)&&(t=Math.min(t,a.rect.x),n=Math.min(n,a.rect.y),r=Math.max(r,a.rect.x+a.rect.width),i=Math.max(i,a.rect.y+a.rect.height));return!Number.isFinite(t)||!Number.isFinite(n)||r<=t||i<=n?null:{x:t,y:n,width:r-t,height:i-n}}function Ye(e){return _(e.type??``)===`image`&&!l(e.label)}function Xe(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const Ze=`${a.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Qe(e){return e?.partialIntersection?[Ze]:[]}async function $e(t){let{device:n,session:r,surface:i,cropOn:o,screenshotPath:s,logPath:c,dispatchContext:l}=t,u={snapshotInteractiveOnly:!1},d=await b({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await t.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:x(l)})}),f=v(d,u);if(f.snapshotQuality?.state===`sparse`)throw new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was sparse and cannot be read as the screen`,{reason:a.captureUnreadable});let p=await et(f.nodes,o,f.truncated,n),m=await pe(s),h=N(Ke(f.backend),P(f.nodes),p.rect,m.width,m.height),g=qe(h,m.width,m.height);if(g===null)throw new e(`COMMAND_FAILED`,`the frame resolved by --crop-on occupies no pixel of the capture`,{reason:a.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await Ue(s,g),{partialIntersection:_}}async function et(t,n,r,i){let o=await oe(se.cropTarget,t,n,{platform:c(i)});if(o.kind===`ambiguous`)throw new e(`COMMAND_FAILED`,`--crop-on matched ${o.matchedNodes.length} nodes and must resolve to one`,{reason:a.targetAmbiguous,candidates:o.matchedNodes.map(e=>e.label??e.ref),matches:o.matchedNodes.length});if(o.kind===`none`)throw r?new e(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:a.captureIncomplete}):new e(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:a.targetNotFound,hint:`find ${n} list`});return o.node}function F(e){return!!(e&&e.width>0&&e.height>0)}function I(e,t,n){return Number.isFinite(e)?Math.max(t,Math.min(n,e)):t}function L(e){return e.width*e.height}function tt(e){let t=e[0];if(t===void 0)throw Error(`unionRects requires at least one rect`);let n=t.x,r=t.y,i=t.x+t.width,a=t.y+t.height;for(let t of e.slice(1))n=Math.min(n,t.x),r=Math.min(r,t.y),i=Math.max(i,t.x+t.width),a=Math.max(a,t.y+t.height);return{x:n,y:r,width:i-n,height:a-r}}const nt=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function rt(e,t,n){if(e.backend!==`android`||!n.hittable||!F(n.rect)||m(n))return!1;let r=_(n.type??``);return!(nt.some(e=>r.includes(e))||t&&L(n.rect)>L(t)*.25)}function it(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:at(e,t,r)}function at(e,t,n){let r=e.rect,i=ot(e,t,n);if(!i)return null;let a=i.y-r.y,o=r.y+r.height-(i.y+i.height);if(a<0||o<0||Math.abs(o-a)<16)return null;let s=Math.min(a,o),c=Math.round(i.y-s),l=Math.round(i.height+s*2);return l<=0||l>=r.height?null:{x:r.x,y:c,width:r.width,height:l}}function ot(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&ct(t,e,i)&&st(t,n)&&F(t.rect)&&u(r,t.rect)).map(e=>e.rect);return a.length<2?null:tt(a)}function st(e,t){let n=_(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function ct(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n.get(r.parentIndex);if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}const lt=[255,59,48,255],ut=[255,214,10,255],dt=[0,0,0,255],ft={e:[`01110`,`10000`,`11110`,`10000`,`10000`,`10001`,`01110`],0:[`01110`,`10001`,`10011`,`10101`,`11001`,`10001`,`01110`],1:[`00100`,`01100`,`00100`,`00100`,`00100`,`00100`,`01110`],2:[`01110`,`10001`,`00001`,`00010`,`00100`,`01000`,`11111`],3:[`11110`,`00001`,`00001`,`01110`,`00001`,`00001`,`11110`],4:[`00010`,`00110`,`01010`,`10010`,`11111`,`00010`,`00010`],5:[`11111`,`10000`,`10000`,`11110`,`00001`,`00001`,`11110`],6:[`01110`,`10000`,`10000`,`11110`,`10001`,`10001`,`01110`],7:[`11111`,`00001`,`00010`,`00100`,`01000`,`01000`,`01000`],8:[`01110`,`10001`,`10001`,`01110`,`10001`,`10001`,`01110`],9:[`01110`,`10001`,`10001`,`01111`,`00001`,`00001`,`01110`]};function pt(e,t){mt(e,t.overlayRect,lt,2),ht(e,t.overlayRect,t.ref)}function mt(e,t,n,r){for(let i=0;i<r;i+=1)R(e,t.x,t.x+t.width-1,t.y+i,n),R(e,t.x,t.x+t.width-1,t.y+t.height-1-i,n),z(e,t.x+i,t.y,t.y+t.height-1,n),z(e,t.x+t.width-1-i,t.y,t.y+t.height-1,n)}function ht(e,t,n){let r=6+n.length*5+Math.max(0,n.length-1)*1,i=I(t.x,0,Math.max(0,e.width-r)),a=t.y-11-2,o=a>=0?a:I(t.y+2,0,Math.max(0,e.height-11));_t(e,i,o,r,11,ut),gt(e,i+3,o+2,n,dt)}function gt(e,t,n,r,i){let a=t;for(let t of r.toLowerCase()){let r=ft[t];if(r)for(let t=0;t<r.length;t+=1)for(let o=0;o<r[t].length;o+=1)r[t][o]===`1`&&B(e,a+o,n+t,i);a+=6}}function _t(e,t,n,r,i,a){for(let o=0;o<i;o+=1)for(let i=0;i<r;i+=1)B(e,t+i,n+o,a)}function R(e,t,n,r,i){for(let a=t;a<=n;a+=1)B(e,a,r,i)}function z(e,t,n,r,i){for(let a=n;a<=r;a+=1)B(e,t,a,i)}function B(e,t,n,r){if(t<0||n<0||t>=e.width||n>=e.height)return;let i=(e.width*n+t)*4;e.data[i]=r[0],e.data[i+1]=r[1],e.data[i+2]=r[2],e.data[i+3]=r[3]}const vt=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await T.readFile(e.screenshotPath),n=await S(t,`screenshot`),r=yt(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)pt(n,e);return await T.writeFile(e.screenshotPath,await C(n)),r}function yt(e,n,r,i={}){let a=P(e.nodes),o=new Map;for(let t of e.nodes){if(!St(e,a,t))continue;let i=Ct(e.nodes,t);if(!i?.rect||!F(i.rect))continue;let s=wt(t,i,e.nodes),c=Tt(t,i,s),l=H(e,a,xt(e,i,e.nodes),n,r);if(!F(l))continue;let u=o.get(i.ref);(!u||c>u.score)&&o.set(i.ref,{ref:i.ref,label:s,rect:i.rect,overlayRect:l,score:c})}return bt(e,a,o,n,r),Et([...o.values()]).sort(It).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:t(e.overlayRect)}))}function bt(e,t,n,r,i){let a=ae(e.nodes).primaryAction;if(!a?.ref||!a.rect||!F(a.rect))return;let o=H(e,t,a.rect,r,i);if(!F(o))return;let s={ref:a.ref,label:a.label,rect:a.rect,overlayRect:o,score:100},c=n.get(a.ref);n.set(a.ref,c?{...c,score:Math.max(c.score,s.score)}:s)}function xt(e,t,n){return e.backend===`android`?it(t,n,U,e=>!!q(e))??t.rect:t.rect}function St(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return rt(e,t,n)?!0:U(n)?r:r&&Dt(n)}function Ct(e,t){return[W(t)?t:null,f(e,t,W),t.hittable?t:null,f(e,t,e=>e.hittable===!0)].find(Ot)??null}function wt(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:kt(t,n)||q(t)}function Tt(e,t,n){let r=0;return e.ref===t.ref&&(r+=4),t.hittable&&(r+=3),U(t)&&(r+=3),U(e)&&(r+=2),n&&(r+=2),K(t.identifier)&&(r+=1),l(t.value)&&(r+=1),r}function Et(e){let t=[];for(let n of e.sort((e,t)=>L(e.overlayRect)-L(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(u(e.overlayRect,n.overlayRect)||u(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}L(n.overlayRect)<L(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Ft(N(e.backend===`android`?`device-pixels`:`viewport-points`,t,n,r,i),r,i)}function U(e){let t=[e.type,e.role,e.subrole].map(e=>_(e??``)).join(` `);return vt.some(e=>t.includes(e))}function W(e){return U(e)&&!m(e)}function Dt(e){let t=_(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ot(e){return!!(e?.rect&&F(e.rect)&&!m(e))}function G(e){return l(e)?!Mt(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Nt(e)}function q(e){let t=[e.label,e.value].find(G);if(t)return t.trim();if(K(e.identifier))return e.identifier.trim()}function kt(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!At(r,e,t))continue;let i=q(r);if(!i)continue;let a=jt(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function At(e,t,n){let r=e;for(;r.parentIndex!==void 0;){let e=n[r.parentIndex];if(!e)return!1;if(e.ref===t.ref)return!0;r=e}return!1}function jt(e){let t=0;return _(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Mt(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Nt(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Pt(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Ft(e,t,n){let r=I(e.x,0,Math.max(0,t-1)),i=I(e.y,0,Math.max(0,n-1)),a=Math.max(1,t-r),o=Math.max(1,n-i);return{x:r,y:i,width:I(e.width,1,a),height:I(e.height,1,o)}}function J(e,t){let n=e.overlayRect.y-t.overlayRect.y;if(n!==0)return n;let r=e.overlayRect.x-t.overlayRect.x;return r===0?Pt(e.ref,t.ref):r}function It(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function Y(e){let t=d({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ye({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await X(e.bindDevice,n)}:{ok:!1,response:Rt(t.kind,n.operation,n.fact)}}async function X(e,t){let n=ve(e),{device:r,plan:i}=ge(t);switch(i.kind){case`capture`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:Z(e)})}case`capture-with-overlay-refs`:case`capture-with-crop-on`:{let e=await n(r,i.use);return Object.freeze({captureScreenshot:Z(e),captureSnapshot:Lt(e)})}}}function Z(e){return async t=>await e.operations.captureScreenshot(t)}function Lt(e){return async t=>await e.operations.captureSnapshot(t)}function Rt(e,t,n){return t===`captureScreenshot`?_e(`screenshot`,n):e===`capture-with-crop-on`?y(`UNSUPPORTED_OPERATION`,`--crop-on crops the capture to a selector frame using a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --crop-on.`}):y(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:n.available?void 0:n.reason},{hint:(n.available?void 0:n.hint)??`Re-run screenshot without --overlay-refs.`})}async function zt(t){let{req:r,session:i}=t,a=n(`screenshot`,r.flags);if(a)throw new e(`INVALID_ARGS`,a);he(i.device,r.flags?.screenshotPixelDensity);let o=Wt(r),s=typeof r.flags?.screenshotCropOn==`string`&&r.flags.screenshotCropOn.length>0?r.flags.screenshotCropOn:void 0;s!==void 0&&He({device:i.device,surface:i.surface,cropOn:s,overlayRefs:r.flags?.overlayRefs===!0,fullscreen:r.flags?.screenshotFullscreen===!0});let c=await Y({device:i.device,overlayRefs:r.flags?.overlayRefs===!0,cropOn:s,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]};return{ok:!0,recorded:o.recorded,execute:async e=>await Bt({session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:o.outPath,runtime:l,cropOn:s,cropRun:u})}}async function Q(e){let{session:t,sessionName:n,outPath:i,dispatchContext:a}=e;return await le({backend:Gt(e),artifacts:Kt(),sessions:de({sessionName:n,getSession:()=>t,recordOptions:{includeSnapshot:!1},setRecord:()=>{}}),policy:ce()}).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...r(a),surface:t.surface,...i?{out:{kind:`path`,path:i}}:{}})}function $(e){return x(e)}async function Bt(e){let{session:t,runtime:n,flags:r}=e,i=Vt({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({session:t,sessionName:e.sessionName,outPath:e.outPath,dispatchContext:e.dispatchContext,captureScreenshot:n.captureScreenshot,...i?{crop:i}:{}}),o=[...a.warnings??[],...i?.run?.warnings??[]];return{...a,...o.length>0?{warnings:o}:{},...await Ht({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await me({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function Vt(e){let{cropOn:t,captureSnapshot:n,cropRun:r}=e;if(t!==void 0&&n!==void 0&&r!==void 0)return{cropOn:t,captureSnapshot:n,run:r,logPath:e.logPath}}async function Ht(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await Ut({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function Ut(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await b({device:t.device,session:t,flags:r,logPath:e.logPath,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:t.appBundleId,interactiveOnly:!0,surface:t.surface},execution:$(n)})}),a=v(i,r);return ue(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function Wt(e){let t=e.positionals??[],n=e.flags??{},r=t=>t===void 0?void 0:ie.expandHome(t,e.meta?.cwd),i=r(t[0]),a=r(n.out);return{outPath:i??a,recorded:{positionals:i?[i,...t.slice(1)]:t,flags:a?{...n,out:a}:n}}}function Gt(e){let{session:t,dispatchContext:n,captureScreenshot:a,crop:o}=e;return{platform:c(t.device),captureScreenshot:async(e,c,l)=>{let u=r({...n,...i(l)});if(await a({outPath:c,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:l?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(s(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:$(n)}),o){let e=await $e({device:t.device,session:t,surface:t.surface,cropOn:o.cropOn,screenshotPath:c,logPath:o.logPath,dispatchContext:n,captureSnapshot:o.captureSnapshot});o.run.warnings.push(...Qe(e))}}}}function Kt(){return{resolveInput:async()=>{throw new e(`UNSUPPORTED_OPERATION`,`screenshot does not resolve input artifacts`)},reserveOutput:async e=>{let t,n;return e?.kind===`path`?n=e.path:(t=await T.mkdtemp(w.join(E.tmpdir(),`agent-device-screenshot-`)),n=w.join(t,`screenshot.png`)),await T.mkdir(w.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await T.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await T.mkdtemp(w.join(E.tmpdir(),`${e.prefix}-`));return{path:w.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await T.rm(t,{recursive:!0,force:!0})}}}}}export{ke as _,V as a,xe as c,De as d,Ee as f,Te as g,Ne as h,Y as i,Ae as l,Pe as m,zt as n,Oe as o,Fe as p,$ as r,k as s,Q as t,Ce as u,O as v,we as y};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";import{h as t}from"./host-file.js";import{runHarmonyHdc as n}from"./hdc.js";import{randomUUID as r}from"node:crypto";async function i(i,a){let o=`/data/local/tmp/agent-device-screen-${r()}.jpeg`;try{await n(i,[`shell`,`snapshot_display`,`-f`,o],{timeoutMs:15e3}),await n(i,[`file`,`recv`,o,a],{timeoutMs:15e3});let r=await t(a);if(r.length<3||r[0]!==255||r[1]!==216||r[2]!==255)throw new e(`COMMAND_FAILED`,`HarmonyOS screenshot is not a JPEG file`)}finally{await n(i,[`shell`,`rm`,`-f`,o],{allowFailure:!0}).catch(()=>{})}}export{i as screenshotHarmony};
1
+ import{C as e}from"./sdk-contracts.js";import{h as t}from"./host-file.js";import{runHarmonyHdc as n}from"./hdc.js";import{randomUUID as r}from"node:crypto";async function i(i,a){let o=`/data/local/tmp/agent-device-screen-${r()}.jpeg`;try{await n(i,[`shell`,`snapshot_display`,`-f`,o],{timeoutMs:15e3}),await n(i,[`file`,`recv`,o,a],{timeoutMs:15e3});let r=await t(a);if(r.length<3||r[0]!==255||r[1]!==216||r[2]!==255)throw new e(`COMMAND_FAILED`,`HarmonyOS screenshot is not a JPEG file`)}finally{await n(i,[`shell`,`rm`,`-f`,o],{allowFailure:!0}).catch(()=>{})}}export{i as screenshotHarmony};
@@ -1,5 +1,5 @@
1
- import{a as e,y as t}from"./sdk-contracts.js";import{l as n}from"./registry.js";import{n as r}from"./path-resolution.js";import"./file.js";import{n as i}from"./screenshot-result.js";import{t as a}from"./shared.js";import{t as o}from"./cli-runner.js";import{n as s,t as c}from"./color.js";import l from"node:path";function u(e){let t=e.baselineInitialized===!0,r=e.summary??{},i=v(r.additions),a=v(r.removals),o=v(r.unchanged),l=s(),u=n(e),d=u.length>0?`${u.join(`
1
+ import{C as e,a as t}from"./sdk-contracts.js";import{u as n}from"./registry.js";import{n as r}from"./path-resolution.js";import"./file.js";import{n as i}from"./screenshot-result.js";import{t as a}from"./shared.js";import{t as o}from"./cli-runner.js";import{n as s,t as c}from"./color.js";import l from"node:path";function u(e){let t=e.baselineInitialized===!0,r=e.summary??{},i=v(r.additions),a=v(r.removals),o=v(r.unchanged),l=s(),u=n(e),d=u.length>0?`${u.join(`
2
2
  `)}\n`:``;if(t)return`${d}Baseline initialized (${o} lines).\n`;let f=y(Array.isArray(e.lines)?e.lines:[],1).map(e=>{let t=typeof e.text==`string`?e.text:``;if(e.kind===`added`){let e=t.startsWith(` `)?`+${t}`:`+ ${t}`;return l?c(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return l?c(e,`red`):e}return l?c(t,`dim`):t}),p=f.length>0?`${f.join(`
3
3
  `)}\n`:``;return l?`${d}${p}${[`${c(String(i),`green`)} additions`,`${c(String(a),`red`)} removals`,`${c(String(o),`dim`)} unchanged`].join(`, `)}\n`:`${d}${p}${i} additions, ${a} removals, ${o} unchanged\n`}function d(e){let t=s(),n=e.match===!0,r=e.dimensionMismatch,i=[];return i.push(...f(e,t)),i.push(...p(e,n,t)),!n&&!r&&(i.push(...m(e,t)),i.push(...h(e,t))),`${i.join(`
4
- `)}\n`}function f(e,t){if(e.match===!0)return[`${t?c(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?c(`✗`,`red`):`✗`;if(n){let e=n.expected,t=n.actual;return[`${r} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let i=v(e.differentPixels),a=v(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?c(o,`red`):o}`]}function p(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=_(e.diffPath),i=n?c(`Diff image:`,`dim`):`Diff image:`,a=n?c(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=_(e.currentOverlayPath),i=n?c(`Current overlay:`,`dim`):`Current overlay:`,a=n?c(t,`green`):t,o=v(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function m(e,t){let n=v(e.differentPixels),r=v(e.totalPixels);return[` ${t?c(String(n),`red`):String(n)} different / ${r} total pixels`]}function h(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${b(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...g(e));return r}function g(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff`],i=e.currentOverlayMatches?.[0];if(i){let e=i.label?` "${i.label}"`:``;r.push(` overlaps @${i.ref}${e}, ${i.regionCoveragePercentage}% of region`)}return r}function _(e){let t=process.cwd(),n=l.relative(t,e);return n===``||!n.startsWith(`..`)&&!l.isAbsolute(n)?n===``?`.`:`.${l.sep}${n}`:e}function v(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function y(e,t){if(e.length===0)return e;let n=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>e.kind===`added`||e.kind===`removed`).map(e=>e.index);if(n.length===0)return e;let r=Array(e.length).fill(!1);for(let i of n){let n=Math.max(0,i-t),a=Math.min(e.length-1,i+t);for(let e=n;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])}function b(e,t){return t?c(e,`dim`):e}const x=async({positionals:t,flags:n,client:r})=>{let s=await o({client:r,command:`screenshot`,positionals:t,flags:n});if(e(n.responseLevel))return await a(n,s,()=>JSON.stringify(s,null,2)),!0;let c=i(s);return await a(n,c,()=>{let e=s.overlayRefs?`Annotated ${s.overlayRefs.length} refs onto ${s.path}`:w(s),t=s.warnings??[];return t.length>0?[e,...t].join(`
5
- `):e}),!0},S=async({positionals:e,flags:n,client:i})=>{if(e[0]===`snapshot`){let t=await o({client:i,command:`diff`,positionals:e,flags:n});return await a(n,t,()=>u(t)),!0}if(e[0]!==`screenshot`)return!1;let s=n.baseline;if(!s||typeof s!=`string`)throw new t(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let c=r(s),l=typeof n.out==`string`?r(n.out):void 0,f=e[1];if(e.length>2)throw new t(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:p,localCommandPolicy:m},{createLocalArtifactAdapter:h}]=await Promise.all([import(`./runtime.js`).then(e=>e.r),import(`./sdk-io.js`).then(e=>e.n)]),g=await p({backend:C(i,n),artifacts:h(),sessions:{get:e=>({name:e}),set:()=>{}},policy:m()}).capture.diffScreenshot({session:n.session,baseline:{kind:`path`,path:c},current:f?{kind:`path`,path:r(f)}:{kind:`live`},...l?{out:{kind:`path`,path:l}}:{},threshold:E(n.threshold),overlayRefs:n.overlayRefs,normalizeStatusBar:n.screenshotNormalizeStatusBar,surface:n.surface});return await a(n,g,()=>d(g)),!0};function C(e,t){return{platform:T(t),captureScreenshot:async(t,n,r)=>{let a=await e.capture.screenshot({path:n,session:t.session,overlayRefs:r?.overlayRefs,pixelDensity:r?.pixelDensity,fullscreen:r?.fullscreen,normalizeStatusBar:r?.normalizeStatusBar,stabilize:r?.stabilize,surface:r?.surface});return i(a)}}}function w(e){if(typeof e.width!=`number`||typeof e.height!=`number`)return e.path;let t=typeof e.pixelDensity==`number`?` @${e.pixelDensity}x`:``;return`${e.path} (${e.width}x${e.height}${t})`}function T(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function E(e){if(e!=null&&e!==``)return Number(e)}export{S as diffCommand,x as screenshotCommand};
4
+ `)}\n`}function f(e,t){if(e.match===!0)return[`${t?c(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?c(`✗`,`red`):`✗`;if(n){let e=n.expected,t=n.actual;return[`${r} Screenshots have different dimensions: expected ${e?.width}x${e?.height}, got ${t?.width}x${t?.height}`]}let i=v(e.differentPixels),a=v(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?c(o,`red`):o}`]}function p(e,t,n){if(t)return[];let r=[];if(e.diffPath){let t=_(e.diffPath),i=n?c(`Diff image:`,`dim`):`Diff image:`,a=n?c(t,`green`):t;r.push(` ${i} ${a}`)}if(e.currentOverlayPath){let t=_(e.currentOverlayPath),i=n?c(`Current overlay:`,`dim`):`Current overlay:`,a=n?c(t,`green`):t,o=v(e.currentOverlayRefCount),s=o>0?` (${o} refs)`:``;r.push(` ${i} ${a}${s}`)}return r}function m(e,t){let n=v(e.differentPixels),r=v(e.totalPixels);return[` ${t?c(String(n),`red`):String(n)} different / ${r} total pixels`]}function h(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${b(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(...g(e));return r}function g(e){let t=e.shareOfDiffPercentage===0&&e.differentPixels>0?`<0.01`:String(e.shareOfDiffPercentage),n=e.rect,r=[` ${e.index}. x=${n.x} y=${n.y} ${n.width}x${n.height}, ${t}% of diff`],i=e.currentOverlayMatches?.[0];if(i){let e=i.label?` "${i.label}"`:``;r.push(` overlaps @${i.ref}${e}, ${i.regionCoveragePercentage}% of region`)}return r}function _(e){let t=process.cwd(),n=l.relative(t,e);return n===``||!n.startsWith(`..`)&&!l.isAbsolute(n)?n===``?`.`:`.${l.sep}${n}`:e}function v(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function y(e,t){if(e.length===0)return e;let n=e.map((e,t)=>({index:t,kind:e.kind})).filter(e=>e.kind===`added`||e.kind===`removed`).map(e=>e.index);if(n.length===0)return e;let r=Array(e.length).fill(!1);for(let i of n){let n=Math.max(0,i-t),a=Math.min(e.length-1,i+t);for(let e=n;e<=a;e+=1)r[e]=!0}return e.filter((e,t)=>r[t])}function b(e,t){return t?c(e,`dim`):e}const x=async({positionals:e,flags:n,client:r})=>{let s=await o({client:r,command:`screenshot`,positionals:e,flags:n});if(t(n.responseLevel))return await a(n,s,()=>JSON.stringify(s,null,2)),!0;let c=i(s);return await a(n,c,()=>{let e=s.overlayRefs?`Annotated ${s.overlayRefs.length} refs onto ${s.path}`:w(s),t=s.warnings??[];return t.length>0?[e,...t].join(`
5
+ `):e}),!0},S=async({positionals:t,flags:n,client:i})=>{if(t[0]===`snapshot`){let e=await o({client:i,command:`diff`,positionals:t,flags:n});return await a(n,e,()=>u(e)),!0}if(t[0]!==`screenshot`)return!1;let s=n.baseline;if(!s||typeof s!=`string`)throw new e(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let c=r(s),l=typeof n.out==`string`?r(n.out):void 0,f=t[1];if(t.length>2)throw new e(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:p,localCommandPolicy:m},{createLocalArtifactAdapter:h}]=await Promise.all([import(`./runtime.js`).then(e=>e.r),import(`./sdk-io.js`).then(e=>e.n)]),g=await p({backend:C(i,n),artifacts:h(),sessions:{get:e=>({name:e}),set:()=>{}},policy:m()}).capture.diffScreenshot({session:n.session,baseline:{kind:`path`,path:c},current:f?{kind:`path`,path:r(f)}:{kind:`live`},...l?{out:{kind:`path`,path:l}}:{},threshold:E(n.threshold),overlayRefs:n.overlayRefs,normalizeStatusBar:n.screenshotNormalizeStatusBar,surface:n.surface});return await a(n,g,()=>d(g)),!0};function C(e,t){return{platform:T(t),captureScreenshot:async(t,n,r)=>{let a=await e.capture.screenshot({path:n,session:t.session,overlayRefs:r?.overlayRefs,pixelDensity:r?.pixelDensity,fullscreen:r?.fullscreen,normalizeStatusBar:r?.normalizeStatusBar,stabilize:r?.stabilize,surface:r?.surface});return i(a)}}}function w(e){if(typeof e.width!=`number`||typeof e.height!=`number`)return e.path;let t=typeof e.pixelDensity==`number`?` @${e.pixelDensity}x`:``;return`${e.path} (${e.width}x${e.height}${t})`}function T(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function E(e){if(e!=null&&e!==``)return Number(e)}export{S as diffCommand,x as screenshotCommand};
@@ -1 +1 @@
1
- import{_ as e,y as t}from"./sdk-contracts.js";import{c as n,s as r,t as i}from"./capture.js";import{f as a}from"./sdk-batch-runner.js";import{r as o}from"./sdk-device.js";import{Xn as s,Yn as c}from"./sdk-batch.js";import{r as l}from"./recording-export-quality.js";import{a as u,t as d}from"./scroll-gesture.js";import{t as f}from"./gesture-plan-types.js";const p=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`,`drag`];function m(e){let n=g(e),r=x(n,`kind`,p);if(r===`pan`)return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),pointerCount:a(n,`pointerCount`,{min:1,max:2}),durationMs:h(n)};if(r===`drag`)return ee(n);if(n.pointerCount!==void 0)throw new t(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(n.durationMs!==void 0)throw new t(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:x(n,`direction`,d),origin:_(n,`origin`),distance:a(n,`distance`,{min:0})}}if(r===`swipe`){if(n.durationMs!==void 0)throw new t(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:x(n,`preset`,u)}}if(r===`pinch`)return{kind:r,scale:y(n,`scale`),origin:v(n,`origin`)};if(r===`rotate`){if(n.velocity!==void 0)throw new t(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:y(n,`degrees`),origin:v(n,`origin`)}}return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),scale:y(n,`scale`),degrees:y(n,`degrees`),durationMs:h(n)}}function ee(e){let n=a(e,`sourceHoldMs`,{min:1,max:1e4}),r=a(e,`moveMs`,{min:16,max:1e4}),i=a(e,`destinationHoldMs`,{min:0,max:1e4});if((n??800)+(r??500)+(i??0)>1e4)throw new t(`INVALID_ARGS`,`gesture drag total duration must be at most ${f}`);return{kind:`drag`,source:b(e,`source`),destination:b(e,`destination`),sourceHoldMs:n,moveMs:r,destinationHoldMs:i}}function h(e){let n=a(e,`durationMs`);if(n!==void 0){if(n<16||n>1e4)throw new t(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${f}.`);return n}}function g(e){if(!e||typeof e!=`object`||Array.isArray(e))throw new t(`INVALID_ARGS`,`gesture requires structured object input`);return e}function _(e,t){let n=g(e[t]);return{x:y(n,`x`),y:y(n,`y`)}}function v(e,t){return e[t]===void 0?void 0:_(e,t)}function y(e,n){let r=e[n];if(typeof r!=`number`||!Number.isFinite(r))throw new t(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function b(e,n){let r=e[n];if(typeof r!=`string`||r.trim().length===0)throw new t(`INVALID_ARGS`,`Expected ${n} to be a non-empty string.`);return r.trim()}function x(e,n,r){let i=e[n];if(typeof i!=`string`||!r.includes(i))throw new t(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const S={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:te}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`},"gesture drag":{max:5,usage:`gesture drag accepts at most 5 arguments: source destination [sourceHoldMs] [moveMs] [destinationHoldMs]`}};function te(e,t){let[n,r,i,a,o]=e,s=C(n,i),c=C(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function C(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function w(e,t){let n=S[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!T(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function T(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ne(e){if(!(!e||typeof e!=`object`||Array.isArray(e))&&e.durationMs!==void 0)throw new t(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function E(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function D(e,n){let r=w(e,n);if(r)throw new t(`INVALID_ARGS`,E(r))}function re(e,t,n){let r=ie(e,t);return r?E(r,n):void 0}function ie(e,t){if(e===`swipe`)return w(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(S,n))return w(n,t.slice(1))}function O(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function k(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{D(`gesture pan`,r);let{origin:e,delta:i}=O(r);return m({kind:n,origin:e,delta:i,pointerCount:t,durationMs:A(r[4])})}case`fling`:return D(`gesture fling`,r),m({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:A(r[3])});case`swipe`:return D(`gesture swipe`,r),m({kind:n,preset:r[0]});case`pinch`:return D(`gesture pinch`,r),m({kind:n,scale:Number(r[0]),origin:j(r[1],r[2])});case`rotate`:return D(`gesture rotate`,r),m({kind:n,degrees:Number(r[0]),origin:j(r[1],r[2])});case`transform`:{D(`gesture transform`,r);let{origin:e,delta:t}=O(r);return m({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:A(r[6])})}case`drag`:return D(`gesture drag`,r),m({kind:n,source:r[0],destination:r[1],sourceHoldMs:A(r[2]),moveMs:A(r[3]),destinationHoldMs:A(r[4])});default:return m({kind:n})}}function ae(e){if(e[0]!==`drag`)return;let t=k(e);return t.kind===`drag`?t:void 0}function oe(e){switch(e.kind){case`pan`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return M([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return M([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?M([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs]);case`drag`:return[e.kind,e.source,e.destination,String(e.sourceHoldMs??800),String(e.moveMs??500),String(e.destinationHoldMs??0)]}}function se(e,t={}){return D(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function ce(e){switch(e.kind){case`pan`:return{gesture:{intent:`pan`,origin:e.origin,delta:e.delta,pointerCount:e.pointerCount,durationMs:e.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:e.direction,origin:e.origin,distance:e.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:e.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:e.origin,scale:e.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:e.origin,degrees:e.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:e.origin,delta:e.delta,scale:e.scale,degrees:e.degrees,durationMs:e.durationMs}};case`drag`:throw new t(`INVALID_ARGS`,`gesture drag targets must be resolved before coordinate normalization`)}}function le(e){return e.kind===`drag`?{intent:`drag`,source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}:ce(e).gesture}function ue(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function A(e){return e===void 0?void 0:Number(e)}function j(e,n){if(e===void 0!=(n===void 0))throw new t(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return e===void 0?void 0:{x:Number(e),y:Number(n)}}function M(e){return e.filter(e=>e!==void 0).map(String)}const de={ios:!0,android:!0,harmonyos:!0};function N(e){return typeof e==`string`&&Object.hasOwn(de,e)}function P(t){return t.startsWith(`@`)?e(t)?.base??t:t}const F=/^-?\d+(\.\d+)?$/,fe=/^[^\s"\\]+$/,pe=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),me=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),he=new Map([[`--pointer-count`,`pointerCount`]]),ge=new Map([[`--delay-ms`,`delayMs`]]);function I(e){return e===`click`||e===`press`}function L(e){return I(e)||e===`longpress`||e===`hover`}function R(e){return e===`type`||e===`fill`}function z(e){return H(e,_e)}function B(e){return JSON.stringify(e)}function V(e){return H(e,U)}function H(e,t){return t(e)?e:B(e)}function _e(e){return U(e)&&e.startsWith(`@`)||F.test(e)}function U(e){return fe.test(e)}const ve=new Set([`fill`,`type`]);function ye(e){if(!ve.has(e.command)){let t=(e.positionals??[]).map(e=>z(e));return[e.command,...t].join(` `)}let t=be(e).map(e=>z(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function be(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&F.test(n)&&F.test(t[1]??``)?[n,t[1]]:[n]}function W(e,t){let n=t.flags??{};if(I(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}R(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function G(e,t){t&&(N(t.platform)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,V(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,V(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,V(t.launchUrl)))}function xe(e,t){let[n,...r]=t.positionals??[];n&&e.push(V(n));for(let t of r)e.push(z(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function Se(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,z(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Ce(e,t){for(let n of t.positionals??[])e.push(z(n));let n=t.flags?.screenshotCropOn;typeof n==`string`&&n.length>0&&e.push(`--crop-on`,V(n)),r(e,t.flags)}function we(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(V(t));G(e,t.flags)}function Te(e,t){for(let n of t.positionals??[])e.push(z(t.command===`wait`?P(n):n));W(e,t)}function K(e,t){let n=[],r={},i=I(e)?pe:e===`swipe`?me:e===`gesture`?he:R(e)?ge:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(I(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(I(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=J(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function q(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;N(e)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=J(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function J(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function Ee(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function De(e,t){for(let n of t.positionals??[])e.push(z(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),G(e,t.runtime)}function Oe(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=q(t);return{positionals:r.positionals,flags:n,runtime:ke(r.flags)?r.flags:void 0}}function ke(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const Y=/^[A-Z_][A-Z0-9_]*$/,Ae=new Set(o.filter(e=>e!==`web`)),je=new Set([`mobile`,`tv`,`desktop`]);function Me(e){let n=[],r=[],i=e.split(/\r?\n/),a=!1,o,l=(e,n,r)=>{let i=e.kind===`multiple`?`targets-v1`:`target-v1`;throw new t(`INVALID_ARGS`,`${i} annotation on line ${e.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[e,u]of i.entries()){let i=u.trim();if(i.length===0){o&&l(o,e,`is blank`);continue}if(i.startsWith(`#`)){let t=c(i);if(t.kind===`v1`){o&&l(o,e,`is another target annotation`),o={kind:`multiple`,evidence:t.evidence,line:e+1};continue}let n=s(i);if(n.kind===`v1`){o&&l(o,e,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:e+1};continue}o&&l(o,e,`is a comment`);continue}if(X(i)){if(o&&l(o,e,`is an env directive`),a)throw new t(`INVALID_ARGS`,`env directives must precede all actions (line ${e+1}).`);continue}let d=Le(u);if(!d){o&&l(o,e,`did not parse as an action`);continue}let f=re(d.command,d.positionals??[],`line ${e+1}`);if(f)throw new t(`INVALID_ARGS`,f);o&&=(o.kind===`single`?d.targetEvidence=o.evidence:d.targetEvidences=o.evidence,void 0),n.push(d),r.push(e+1),a=!0}if(o){let e=o.kind===`multiple`?`targets-v1`:`target-v1`;throw new t(`INVALID_ARGS`,`${e} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`)}return{actions:n,actionLines:r}}function Ne(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(X(t)){Ie(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&Ae.has(e)&&Z(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&je.has(e)&&Z(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&Z(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&Z(n,`retries`,Math.floor(e))}}return n}function X(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function Pe(e,n){let r=e.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new t(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!Y.test(a))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new t(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:Fe(r.slice(i+1),n)}}function Fe(e,n){if(e.length===0)return``;if(e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t!=`string`)throw Error(`not a string literal`);return t}catch{throw new t(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return e}function Ie(e,n,r){let{key:i,value:a}=Pe(n,r),o=e.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new t(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,e.env=o}function Z(e,n,r){let i=e[n];if(i!==void 0){let e=i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`;throw new t(`INVALID_ARGS`,e)}e[n]=r}function Le(e){let r=e.trim();if(r.length===0||r.startsWith(`#`))return null;let[a,...o]=Re(r);if(a===void 0||a===`context`)return null;let s={ts:Date.now(),command:a,positionals:[],flags:{}};if(a===`snapshot`){s.positionals=[];for(let e=0;e<o.length;e+=1){let t=o[e];if(t===`-i`){s.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){s.flags.snapshotRaw=!0;continue}if(t===`--force-full`){s.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<o.length){let t=Number(o[e+1]);Number.isFinite(t)&&t>=0&&(s.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<o.length){s.flags.snapshotScope=o[e+1],e+=1;continue}if(t===`--backend`&&e+1<o.length){e+=1;continue}}}return s}if(a===`open`){let e=Oe(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s.runtime=e.runtime,s}if(a===`runtime`){let e=q(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s}if(I(a)){let e=K(a,o);Object.assign(s.flags,e.flags);let t=e.positionals[0];if(t===void 0)return s;if(t.startsWith(`@`))return s.positionals=[P(t)],e.positionals[1]&&(s.result={refLabel:e.positionals[1]}),s;let n=e.positionals[0],r=e.positionals[1];return $(n)&&$(r)&&e.positionals.length>=2?(s.positionals=[n,r],s):(s.positionals=[e.positionals.join(` `)],s)}if(a===`fill`){let e=K(a,o);if(Object.assign(s.flags,e.flags),!Q(e.positionals))return s.positionals=e.positionals,s;let[t,n,...r]=e.positionals;if($(t)&&$(n))return s.positionals=[t,n,r.join(` `)],s;let[i,c,...l]=e.positionals;if(i.startsWith(`@`)){let e=P(i);return l.length>0?(s.positionals=[e,l.join(` `)],s.result={refLabel:c},s):(s.positionals=[e,c],s)}return s.positionals=[i,[c,...l].join(` `)],s}if(a===`get`){let e=o[0],t=o[1];return e===void 0||t===void 0?(s.positionals=o,s):t.startsWith(`@`)?(s.positionals=[e,P(t)],o[2]&&(s.result={refLabel:o[2]}),s):(s.positionals=[e,o.slice(1).join(` `)],s)}if(a===`swipe`||a===`type`||a===`gesture`){let e=K(a,o);return Object.assign(s.flags,e.flags),s.positionals=e.positionals,s}if(a===`record`){let e=[];for(let n=0;n<o.length;n+=1){let r=o[n];if(r===i.cliToken)throw new t(`INVALID_ARGS`,i.migration.record);if(r===`--hide-touches`){s.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<o.length){let e=Number(o[n+1]);Number.isFinite(e)&&(s.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<o.length){let e=o[n+1],t=l(e);t!==void 0&&(s.flags.quality=t),n+=1;continue}e.push(r)}return s.positionals=e,s}if(a===`screenshot`){let e=[];for(let t=0;t<o.length;t+=1){let r=o[t],i=n({args:o,index:t,flags:s.flags});if(i.handled){t=i.nextIndex;continue}e.push(r)}return s.positionals=e,s}return s.positionals=a===`wait`||a===`longpress`||a===`hover`?o.map(e=>P(e)):o,s}function Q(e){return e.length>=2}function $(e){return e?!Number.isNaN(Number(e)):!1}function Re(e){let t=[],n=0;for(;n<e.length&&(n=ze(e,n),!(n>=e.length));){let r=e[n]===`"`?Be(e,n):Ve(e,n);t.push(r.value),n=r.nextCursor}return t}function ze(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Be(e,n){let r=n+1,i=!1,a=r;for(;a<e.length;a+=1){let t=e.charAt(a);if(t===`"`&&!i)break;if(i){i=!1;continue}i=t===`\\`}if(a>=e.length)throw new t(`INVALID_ARGS`,`Invalid replay script line: ${e}`);let o=e.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new t(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${e}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function Ve(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}export{ue as C,m as E,le as S,p as T,P as _,Ee as a,k as b,we as c,Se as d,ye as f,L as g,I as h,De as i,Ce as l,B as m,Me as n,Te as o,z as p,Ne as r,xe as s,Y as t,W as u,ne as v,se as w,oe as x,ae as y};
1
+ import{C as e,x as t}from"./sdk-contracts.js";import{o as n,s as r,t as i}from"./capture.js";import{f as a}from"./sdk-batch-runner.js";import{r as o}from"./sdk-device.js";import{Xn as s,Yn as c}from"./sdk-batch.js";import{r as l}from"./recording-export-quality.js";import{n as u,o as d}from"./scroll-gesture.js";import{t as f}from"./gesture-plan-types.js";const p=[`pan`,`fling`,`swipe`,`pinch`,`rotate`,`transform`,`drag`];function m(t){let n=g(t),r=x(n,`kind`,p);if(r===`pan`)return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),pointerCount:a(n,`pointerCount`,{min:1,max:2}),durationMs:h(n)};if(r===`drag`)return ee(n);if(n.pointerCount!==void 0)throw new e(`INVALID_ARGS`,`pointerCount is supported only for gesture pan`);if(r===`fling`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture fling does not accept durationMs; use gesture pan for timed movement`);return{kind:r,direction:x(n,`direction`,u),origin:_(n,`origin`),distance:a(n,`distance`,{min:0})}}if(r===`swipe`){if(n.durationMs!==void 0)throw new e(`INVALID_ARGS`,`gesture swipe does not accept durationMs; use gesture pan for timed movement`);return{kind:r,preset:x(n,`preset`,d)}}if(r===`pinch`)return{kind:r,scale:y(n,`scale`),origin:v(n,`origin`)};if(r===`rotate`){if(n.velocity!==void 0)throw new e(`INVALID_ARGS`,`gesture rotate does not accept velocity; rotation pacing derives from degrees`);return{kind:r,degrees:y(n,`degrees`),origin:v(n,`origin`)}}return{kind:r,origin:_(n,`origin`),delta:_(n,`delta`),scale:y(n,`scale`),degrees:y(n,`degrees`),durationMs:h(n)}}function ee(t){let n=a(t,`sourceHoldMs`,{min:1,max:1e4}),r=a(t,`moveMs`,{min:16,max:1e4}),i=a(t,`destinationHoldMs`,{min:0,max:1e4});if((n??800)+(r??500)+(i??0)>1e4)throw new e(`INVALID_ARGS`,`gesture drag total duration must be at most ${f}`);return{kind:`drag`,source:b(t,`source`),destination:b(t,`destination`),sourceHoldMs:n,moveMs:r,destinationHoldMs:i}}function h(t){let n=a(t,`durationMs`);if(n!==void 0){if(n<16||n>1e4)throw new e(`INVALID_ARGS`,`Expected durationMs to be an integer between 16 and ${f}.`);return n}}function g(t){if(!t||typeof t!=`object`||Array.isArray(t))throw new e(`INVALID_ARGS`,`gesture requires structured object input`);return t}function _(e,t){let n=g(e[t]);return{x:y(n,`x`),y:y(n,`y`)}}function v(e,t){return e[t]===void 0?void 0:_(e,t)}function y(t,n){let r=t[n];if(typeof r!=`number`||!Number.isFinite(r))throw new e(`INVALID_ARGS`,`Expected ${n} to be a finite number.`);return r}function b(t,n){let r=t[n];if(typeof r!=`string`||r.trim().length===0)throw new e(`INVALID_ARGS`,`Expected ${n} to be a non-empty string.`);return r.trim()}function x(t,n,r){let i=t[n];if(typeof i!=`string`||!r.includes(i))throw new e(`INVALID_ARGS`,`Expected ${n} to be one of: ${r.join(`, `)}.`);return i}const S={swipe:{max:4,usage:`swipe accepts 4 arguments: x1 y1 x2 y2`,retired:{positional:`durationMs`,migrate:te}},"gesture pan":{max:5,usage:`gesture pan accepts at most 5 arguments: x y dx dy [durationMs]`},"gesture fling":{max:4,usage:`gesture fling accepts at most 4 arguments: direction x y [distance]`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture swipe":{max:1,usage:`gesture swipe accepts 1 argument: preset`,retired:{positional:`durationMs`,migrate:(e,t)=>`use "${t}", or gesture pan for timed movement.`}},"gesture pinch":{max:3,usage:`gesture pinch accepts at most 3 arguments: scale [x] [y]`},"gesture rotate":{max:3,usage:`gesture rotate accepts at most 3 arguments: degrees [x] [y]`,retired:{positional:`velocity`,migrate:(e,t)=>`use "${t}"; rotation pacing derives from degrees.`}},"gesture transform":{max:7,usage:`gesture transform accepts at most 7 arguments: x y dx dy scale degrees [durationMs]`},"gesture drag":{max:5,usage:`gesture drag accepts at most 5 arguments: source destination [sourceHoldMs] [moveMs] [destinationHoldMs]`}};function te(e,t){let[n,r,i,a,o]=e,s=C(n,i),c=C(r,a);return s===void 0||c===void 0?`use "gesture pan x1 y1 dx dy durationMs" for the same timed drag, or "${t}" for a default-duration swipe.`:`use "gesture pan ${n} ${r} ${s} ${c} ${o}" for the same timed drag, or "${t}" for a default-duration swipe.`}function C(e,t){let n=Number(t)-Number(e);return Number.isFinite(n)?n:void 0}function w(e,t){let n=S[e];if(t.length<=n.max)return;let r=n.retired;if(!r||t.length!==n.max+1||!T(t[n.max]))return{usage:n.usage};let i=`${e} ${t.slice(0,n.max).join(` `)}`;return{usage:n.usage,migration:`The trailing ${r.positional} positional was removed: ${r.migrate(t,i)}`}}function T(e){return e===void 0||e.trim().length===0?!1:e.startsWith("${")||Number.isFinite(Number(e))}function ne(t){if(!(!t||typeof t!=`object`||Array.isArray(t))&&t.durationMs!==void 0)throw new e(`INVALID_ARGS`,`swipe does not accept durationMs; use gesture pan for timed movement`)}function E(e,t){let n=t?`${e.usage} (${t})`:e.usage;return e.migration?`${n}. ${e.migration}`:`${n}.`}function D(t,n){let r=w(t,n);if(r)throw new e(`INVALID_ARGS`,E(r))}function re(e,t,n){let r=ie(e,t);return r?E(r,n):void 0}function ie(e,t){if(e===`swipe`)return w(`swipe`,t);if(e!==`gesture`)return;let n=`gesture ${t[0]}`;if(Object.hasOwn(S,n))return w(n,t.slice(1))}function O(e){return{origin:{x:Number(e[0]),y:Number(e[1])},delta:{x:Number(e[2]),y:Number(e[3])}}}function k(e,t){let n=e[0],r=e.slice(1);switch(n){case`pan`:{D(`gesture pan`,r);let{origin:e,delta:i}=O(r);return m({kind:n,origin:e,delta:i,pointerCount:t,durationMs:A(r[4])})}case`fling`:return D(`gesture fling`,r),m({kind:n,direction:r[0],origin:{x:Number(r[1]),y:Number(r[2])},distance:A(r[3])});case`swipe`:return D(`gesture swipe`,r),m({kind:n,preset:r[0]});case`pinch`:return D(`gesture pinch`,r),m({kind:n,scale:Number(r[0]),origin:j(r[1],r[2])});case`rotate`:return D(`gesture rotate`,r),m({kind:n,degrees:Number(r[0]),origin:j(r[1],r[2])});case`transform`:{D(`gesture transform`,r);let{origin:e,delta:t}=O(r);return m({kind:n,origin:e,delta:t,scale:Number(r[4]),degrees:Number(r[5]),durationMs:A(r[6])})}case`drag`:return D(`gesture drag`,r),m({kind:n,source:r[0],destination:r[1],sourceHoldMs:A(r[2]),moveMs:A(r[3]),destinationHoldMs:A(r[4])});default:return m({kind:n})}}function ae(e){if(e[0]!==`drag`)return;let t=k(e);return t.kind===`drag`?t:void 0}function oe(e){switch(e.kind){case`pan`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.durationMs]);case`fling`:return M([e.kind,e.direction,e.origin.x,e.origin.y,e.distance]);case`swipe`:return[e.kind,e.preset];case`pinch`:return M([e.kind,e.scale,e.origin?.x,e.origin?.y]);case`rotate`:return e.origin?M([e.kind,e.degrees,e.origin.x,e.origin.y]):[e.kind,String(e.degrees)];case`transform`:return M([e.kind,e.origin.x,e.origin.y,e.delta.x,e.delta.y,e.scale,e.degrees,e.durationMs]);case`drag`:return[e.kind,e.source,e.destination,String(e.sourceHoldMs??800),String(e.moveMs??500),String(e.destinationHoldMs??0)]}}function se(e,t={}){return D(`swipe`,e),{from:{x:Number(e[0]),y:Number(e[1])},to:{x:Number(e[2]),y:Number(e[3])},...t.count===void 0?{}:{count:t.count},...t.pauseMs===void 0?{}:{pauseMs:t.pauseMs},...t.pattern===void 0?{}:{pattern:t.pattern}}}function ce(t){switch(t.kind){case`pan`:return{gesture:{intent:`pan`,origin:t.origin,delta:t.delta,pointerCount:t.pointerCount,durationMs:t.durationMs}};case`fling`:return{gesture:{intent:`fling`,direction:t.direction,origin:t.origin,distance:t.distance}};case`swipe`:return{gesture:{intent:`fling`,preset:t.preset}};case`pinch`:return{gesture:{intent:`pinch`,origin:t.origin,scale:t.scale}};case`rotate`:return{gesture:{intent:`rotate`,origin:t.origin,degrees:t.degrees}};case`transform`:return{gesture:{intent:`transform`,origin:t.origin,delta:t.delta,scale:t.scale,degrees:t.degrees,durationMs:t.durationMs}};case`drag`:throw new e(`INVALID_ARGS`,`gesture drag targets must be resolved before coordinate normalization`)}}function le(e){return e.kind===`drag`?{intent:`drag`,source:e.source,destination:e.destination,sourceHoldMs:e.sourceHoldMs,moveMs:e.moveMs,destinationHoldMs:e.destinationHoldMs}:ce(e).gesture}function ue(e){return{gesture:{intent:`fling`,from:e.from,to:e.to}}}function A(e){return e===void 0?void 0:Number(e)}function j(t,n){if(t===void 0!=(n===void 0))throw new e(`INVALID_ARGS`,`gesture origin requires both x and y coordinates`);return t===void 0?void 0:{x:Number(t),y:Number(n)}}function M(e){return e.filter(e=>e!==void 0).map(String)}const de={ios:!0,android:!0,harmonyos:!0};function N(e){return typeof e==`string`&&Object.hasOwn(de,e)}function P(e){return e.startsWith(`@`)?t(e)?.base??e:e}const F=/^-?\d+(\.\d+)?$/,fe=/^[^\s"\\]+$/,pe=new Map([[`--count`,`count`],[`--interval-ms`,`intervalMs`],[`--hold-ms`,`holdMs`],[`--jitter-px`,`jitterPx`]]),me=new Map([[`--count`,`count`],[`--pause-ms`,`pauseMs`]]),he=new Map([[`--pointer-count`,`pointerCount`]]),ge=new Map([[`--delay-ms`,`delayMs`]]);function I(e){return e===`click`||e===`press`}function L(e){return I(e)||e===`longpress`||e===`hover`}function R(e){return e===`type`||e===`fill`}function z(e){return H(e,_e)}function B(e){return JSON.stringify(e)}function V(e){return H(e,U)}function H(e,t){return t(e)?e:B(e)}function _e(e){return U(e)&&e.startsWith(`@`)||F.test(e)}function U(e){return fe.test(e)}const ve=new Set([`fill`,`type`]);function ye(e){if(!ve.has(e.command)){let t=(e.positionals??[]).map(e=>z(e));return[e.command,...t].join(` `)}let t=be(e).map(e=>z(e)).join(` `);return[e.command,t,`<text>`].filter(e=>e.length>0).join(` `)}function be(e){if(e.command===`type`)return[];let t=e.positionals??[],n=t[0];return n===void 0?[]:n.startsWith(`@`)?[n]:t.length>=3&&F.test(n)&&F.test(t[1]??``)?[n,t[1]]:[n]}function W(e,t){let n=t.flags??{};if(I(t.command)){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.intervalMs==`number`&&e.push(`--interval-ms`,String(n.intervalMs)),typeof n.holdMs==`number`&&e.push(`--hold-ms`,String(n.holdMs)),typeof n.jitterPx==`number`&&e.push(`--jitter-px`,String(n.jitterPx)),n.doubleTap===!0&&e.push(`--double-tap`);let t=n.clickButton;t&&t!==`primary`&&e.push(`--button`,t);return}if(t.command===`swipe`){typeof n.count==`number`&&e.push(`--count`,String(n.count)),typeof n.pauseMs==`number`&&e.push(`--pause-ms`,String(n.pauseMs)),(n.pattern===`one-way`||n.pattern===`ping-pong`)&&e.push(`--pattern`,n.pattern);return}if(t.command===`gesture`){typeof n.pointerCount==`number`&&e.push(`--pointer-count`,String(n.pointerCount));return}R(t.command)&&typeof n.delayMs==`number`&&e.push(`--delay-ms`,String(n.delayMs))}function G(e,t){t&&(N(t.platform)&&e.push(`--platform`,t.platform),typeof t.metroHost==`string`&&t.metroHost.length>0&&e.push(`--metro-host`,V(t.metroHost)),typeof t.metroPort==`number`&&e.push(`--metro-port`,String(t.metroPort)),typeof t.bundleUrl==`string`&&t.bundleUrl.length>0&&e.push(`--bundle-url`,V(t.bundleUrl)),typeof t.launchUrl==`string`&&t.launchUrl.length>0&&e.push(`--launch-url`,V(t.launchUrl)))}function xe(e,t){let[n,...r]=t.positionals??[];n&&e.push(V(n));for(let t of r)e.push(z(t));typeof t.flags?.fps==`number`&&e.push(`--fps`,String(t.flags.fps)),(typeof t.flags?.quality==`number`||typeof t.flags?.quality==`string`)&&e.push(`--quality`,String(t.flags.quality)),t.flags?.hideTouches&&e.push(`--hide-touches`)}function Se(e,t){t.flags?.snapshotInteractiveOnly&&e.push(`-i`),typeof t.flags?.snapshotDepth==`number`&&e.push(`-d`,String(t.flags.snapshotDepth)),t.flags?.snapshotScope&&e.push(`-s`,z(t.flags.snapshotScope)),t.flags?.snapshotRaw&&e.push(`--raw`)}function Ce(e,t){for(let n of t.positionals??[])e.push(z(n));let r=t.flags?.screenshotCropOn;typeof r==`string`&&r.length>0&&e.push(`--crop-on`,V(r)),n(e,t.flags)}function we(e,t,n={}){let r=t.positionals??[],i=n.includeAllPositionals?r:r.slice(0,1);for(let t of i)e.push(V(t));G(e,t.flags)}function Te(e,t){for(let n of t.positionals??[])e.push(z(t.command===`wait`?P(n):n));W(e,t)}function K(e,t){let n=[],r={},i=I(e)?pe:e===`swipe`?me:e===`gesture`?he:R(e)?ge:void 0;for(let a=0;a<t.length;a+=1){let o=t[a];if(I(e)&&o===`--double-tap`){r.doubleTap=!0;continue}let s=t[a+1];if(I(e)&&o===`--button`&&s!==void 0){let e=s;(e===`primary`||e===`secondary`||e===`middle`)&&(r.clickButton=e),a+=1;continue}let c=i?.get(o);if(c&&s!==void 0){let e=J(s);if(e!==null){r[c]=e,a+=1;continue}}if(e===`swipe`&&o===`--pattern`&&s!==void 0){let e=s;(e===`one-way`||e===`ping-pong`)&&(r.pattern=e),a+=1;continue}n.push(o)}return{positionals:n,flags:r}}function q(e){let t=[],n={};for(let r=0;r<e.length;r+=1){let i=e[r],a=e[r+1];if(i===`--platform`&&a!==void 0){let e=a;N(e)&&(n.platform=e),r+=1;continue}if(i===`--metro-host`&&a!==void 0){n.metroHost=a,r+=1;continue}if(i===`--metro-port`&&a!==void 0){let e=J(a);e!==null&&(n.metroPort=e),r+=1;continue}if(i===`--bundle-url`&&a!==void 0){n.bundleUrl=a,r+=1;continue}if(i===`--launch-url`&&a!==void 0){n.launchUrl=a,r+=1;continue}t.push(i)}return{positionals:t,flags:n}}function J(e){if(!e)return null;let t=Number(e);return!Number.isFinite(t)||t<0?null:Math.floor(t)}function Ee(e){let t;for(let n of e){if(n.command===`runtime`&&typeof n.flags.platform==`string`){t=n.flags.platform;continue}if(n.command===`open`)return n.runtime?.platform??t}return t}function De(e,t){for(let n of t.positionals??[])e.push(z(n));t.flags?.relaunch&&e.push(`--relaunch`),t.flags?.testIme===!0?e.push(`--test-ime`):t.flags?.testIme===!1&&e.push(`--no-test-ime`),G(e,t.runtime)}function Oe(e){let t=[],n={};for(let r of e){if(r===`--relaunch`){n.relaunch=!0;continue}if(r===`--test-ime`){n.testIme=!0;continue}if(r===`--no-test-ime`){n.testIme=!1;continue}t.push(r)}let r=q(t);return{positionals:r.positionals,flags:n,runtime:ke(r.flags)?r.flags:void 0}}function ke(e){return!!(e.platform||e.metroHost||e.metroPort!==void 0||e.bundleUrl||e.launchUrl)}const Y=/^[A-Z_][A-Z0-9_]*$/,Ae=new Set(o.filter(e=>e!==`web`)),je=new Set([`mobile`,`tv`,`desktop`]);function Me(t){let n=[],r=[],i=t.split(/\r?\n/),a=!1,o,l=(t,n,r)=>{let i=t.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${i} annotation on line ${t.line} must be immediately followed by its action line (line ${n+1} ${r}).`)};for(let[t,u]of i.entries()){let i=u.trim();if(i.length===0){o&&l(o,t,`is blank`);continue}if(i.startsWith(`#`)){let e=c(i);if(e.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`multiple`,evidence:e.evidence,line:t+1};continue}let n=s(i);if(n.kind===`v1`){o&&l(o,t,`is another target annotation`),o={kind:`single`,evidence:n.evidence,line:t+1};continue}o&&l(o,t,`is a comment`);continue}if(X(i)){if(o&&l(o,t,`is an env directive`),a)throw new e(`INVALID_ARGS`,`env directives must precede all actions (line ${t+1}).`);continue}let d=Le(u);if(!d){o&&l(o,t,`did not parse as an action`);continue}let f=re(d.command,d.positionals??[],`line ${t+1}`);if(f)throw new e(`INVALID_ARGS`,f);o&&=(o.kind===`single`?d.targetEvidence=o.evidence:d.targetEvidences=o.evidence,void 0),n.push(d),r.push(t+1),a=!0}if(o){let t=o.kind===`multiple`?`targets-v1`:`target-v1`;throw new e(`INVALID_ARGS`,`${t} annotation on line ${o.line} must be immediately followed by its action line (end of script reached).`)}return{actions:n,actionLines:r}}function Ne(e){let t=e.split(/\r?\n/),n={};for(let[e,r]of t.entries()){let t=r.trim();if(t.length===0||t.startsWith(`#`))continue;if(X(t)){Ie(n,t,e+1);continue}if(!t.startsWith(`context `))break;let i=t.match(/(?:^|\s)platform=([^\s]+)/);if(i){let e=i[1];e&&Ae.has(e)&&Z(n,`platform`,e)}let a=t.match(/(?:^|\s)target=([^\s]+)/);if(a){let e=a[1];e&&je.has(e)&&Z(n,`target`,e)}let o=t.match(/(?:^|\s)timeout=(\d+)/);if(o){let e=Number(o[1]);Number.isFinite(e)&&e>=1&&Z(n,`timeoutMs`,Math.floor(e))}let s=t.match(/(?:^|\s)retries=(\d+)/);if(s){let e=Number(s[1]);Number.isFinite(e)&&e>=0&&Z(n,`retries`,Math.floor(e))}}return n}function X(e){return e===`env`||e.startsWith(`env `)||e.startsWith(`env `)}function Pe(t,n){let r=t.slice(3).replace(/^[\s]+/,``),i=r.indexOf(`=`);if(i<=0)throw new e(`INVALID_ARGS`,`Invalid env directive on line ${n}: expected "env KEY=VALUE".`);let a=r.slice(0,i);if(!Y.test(a))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: keys must be uppercase letters, digits, and underscores (e.g. APP_ID).`);if(a.startsWith(`AD_`))throw new e(`INVALID_ARGS`,`Invalid env key "${a}" on line ${n}: the AD_* namespace is reserved for built-in variables. Rename ${a} to avoid the AD_ prefix.`);return{key:a,value:Fe(r.slice(i+1),n)}}function Fe(t,n){if(t.length===0)return``;if(t.startsWith(`"`))try{let e=JSON.parse(t);if(typeof e!=`string`)throw Error(`not a string literal`);return e}catch{throw new e(`INVALID_ARGS`,`Invalid quoted env value on line ${n}.`)}return t}function Ie(t,n,r){let{key:i,value:a}=Pe(n,r),o=t.env??{};if(Object.prototype.hasOwnProperty.call(o,i))throw new e(`INVALID_ARGS`,`Duplicate env directive "${i}" on line ${r}.`);o[i]=a,t.env=o}function Z(t,n,r){let i=t[n];if(i!==void 0){let t=i===r?`Duplicate replay test metadata "${n}" in context header.`:`Conflicting replay test metadata "${n}" in context header: ${String(i)} vs ${String(r)}.`;throw new e(`INVALID_ARGS`,t)}t[n]=r}function Le(t){let n=t.trim();if(n.length===0||n.startsWith(`#`))return null;let[a,...o]=Re(n);if(a===void 0||a===`context`)return null;let s={ts:Date.now(),command:a,positionals:[],flags:{}};if(a===`snapshot`){s.positionals=[];for(let e=0;e<o.length;e+=1){let t=o[e];if(t===`-i`){s.flags.snapshotInteractiveOnly=!0;continue}if(t!==`-c`){if(t===`--raw`){s.flags.snapshotRaw=!0;continue}if(t===`--force-full`){s.flags.snapshotForceFull=!0;continue}if((t===`-d`||t===`--depth`)&&e+1<o.length){let t=Number(o[e+1]);Number.isFinite(t)&&t>=0&&(s.flags.snapshotDepth=Math.floor(t)),e+=1;continue}if((t===`-s`||t===`--scope`)&&e+1<o.length){s.flags.snapshotScope=o[e+1],e+=1;continue}if(t===`--backend`&&e+1<o.length){e+=1;continue}}}return s}if(a===`open`){let e=Oe(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s.runtime=e.runtime,s}if(a===`runtime`){let e=q(o);return s.positionals=e.positionals,Object.assign(s.flags,e.flags),s}if(I(a)){let e=K(a,o);Object.assign(s.flags,e.flags);let t=e.positionals[0];if(t===void 0)return s;if(t.startsWith(`@`))return s.positionals=[P(t)],e.positionals[1]&&(s.result={refLabel:e.positionals[1]}),s;let n=e.positionals[0],r=e.positionals[1];return $(n)&&$(r)&&e.positionals.length>=2?(s.positionals=[n,r],s):(s.positionals=[e.positionals.join(` `)],s)}if(a===`fill`){let e=K(a,o);if(Object.assign(s.flags,e.flags),!Q(e.positionals))return s.positionals=e.positionals,s;let[t,n,...r]=e.positionals;if($(t)&&$(n))return s.positionals=[t,n,r.join(` `)],s;let[i,c,...l]=e.positionals;if(i.startsWith(`@`)){let e=P(i);return l.length>0?(s.positionals=[e,l.join(` `)],s.result={refLabel:c},s):(s.positionals=[e,c],s)}return s.positionals=[i,[c,...l].join(` `)],s}if(a===`get`){let e=o[0],t=o[1];return e===void 0||t===void 0?(s.positionals=o,s):t.startsWith(`@`)?(s.positionals=[e,P(t)],o[2]&&(s.result={refLabel:o[2]}),s):(s.positionals=[e,o.slice(1).join(` `)],s)}if(a===`swipe`||a===`type`||a===`gesture`){let e=K(a,o);return Object.assign(s.flags,e.flags),s.positionals=e.positionals,s}if(a===`record`){let t=[];for(let n=0;n<o.length;n+=1){let r=o[n];if(r===i.cliToken)throw new e(`INVALID_ARGS`,i.migration.record);if(r===`--hide-touches`){s.flags.hideTouches=!0;continue}if(r===`--fps`&&n+1<o.length){let e=Number(o[n+1]);Number.isFinite(e)&&(s.flags.fps=Math.floor(e)),n+=1;continue}if(r===`--quality`&&n+1<o.length){let e=o[n+1],t=l(e);t!==void 0&&(s.flags.quality=t),n+=1;continue}t.push(r)}return s.positionals=t,s}if(a===`screenshot`){let e=[];for(let t=0;t<o.length;t+=1){let n=o[t],i=r({args:o,index:t,flags:s.flags});if(i.handled){t=i.nextIndex;continue}e.push(n)}return s.positionals=e,s}return s.positionals=a===`wait`||a===`longpress`||a===`hover`?o.map(e=>P(e)):o,s}function Q(e){return e.length>=2}function $(e){return e?!Number.isNaN(Number(e)):!1}function Re(e){let t=[],n=0;for(;n<e.length&&(n=ze(e,n),!(n>=e.length));){let r=e[n]===`"`?Be(e,n):Ve(e,n);t.push(r.value),n=r.nextCursor}return t}function ze(e,t){let n=t;for(;n<e.length&&/\s/.test(e.charAt(n));)n+=1;return n}function Be(t,n){let r=n+1,i=!1,a=r;for(;a<t.length;a+=1){let e=t.charAt(a);if(e===`"`&&!i)break;if(i){i=!1;continue}i=e===`\\`}if(a>=t.length)throw new e(`INVALID_ARGS`,`Invalid replay script line: ${t}`);let o=t.slice(n,a+1),s;try{s=JSON.parse(o)}catch{throw new e(`INVALID_ARGS`,`Invalid quoted value ${o} in replay script line: ${t}`,{hint:`Quoted replay values are JSON strings: escape backslashes, quotes, tabs, and newlines (\\\\, \\", \\t, \\n).`})}return{value:s,nextCursor:a+1}}function Ve(e,t){let n=t;for(;n<e.length&&!/\s/.test(e.charAt(n));)n+=1;return{value:e.slice(t,n),nextCursor:n}}export{ue as C,m as E,le as S,p as T,P as _,Ee as a,k as b,we as c,Se as d,ye as f,L as g,I as h,De as i,Ce as l,B as m,Me as n,Te as o,z as p,Ne as r,xe as s,Y as t,W as u,ne as v,se as w,oe as x,ae as y};
@@ -1 +1 @@
1
- import{y as e}from"./sdk-contracts.js";const t=1e4,n=.65;function r(e,t){return{...e,releaseBehavior:t===void 0?`controlled`:`inertial`}}function i(t,n=`scroll accepts either a relative amount or --pixels, not both`){if(t.amount!==void 0&&t.pixels!==void 0)throw new e(`INVALID_ARGS`,n)}function a(t,n={}){if(t===void 0)return;let r=n.field??`scroll durationMs`,i=n.max??1e4,a=n.invalidMessage??`${r} must be a non-negative integer`;if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e(`INVALID_ARGS`,a);if(t>i)throw new e(`INVALID_ARGS`,`${r} must be a non-negative integer at most ${i}`);return t}function o(e){return typeof e?.durationMs==`number`?e.durationMs:void 0}export{a,o as i,t as n,r as o,i as r,n as t};
1
+ import{C as e}from"./sdk-contracts.js";const t=1e4,n=.65;function r(e,t){return{...e,releaseBehavior:t===void 0?`controlled`:`inertial`}}function i(t,n=`scroll accepts either a relative amount or --pixels, not both`){if(t.amount!==void 0&&t.pixels!==void 0)throw new e(`INVALID_ARGS`,n)}function a(t){if(t.until!==void 0&&t.edge!==void 0)throw new e(`INVALID_ARGS`,`scroll ${t.edge} already scrolls to the ${t.edge} edge and cannot take --until`,{hint:`Use scroll ${t.edge===`bottom`?`down`:`up`} --until <selector> to stop at the target, or scroll ${t.edge} to reach the edge.`})}function o(t,n={}){if(t===void 0)return;let r=n.field??`scroll durationMs`,i=n.max??1e4,a=n.invalidMessage??`${r} must be a non-negative integer`;if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new e(`INVALID_ARGS`,a);if(t>i)throw new e(`INVALID_ARGS`,`${r} must be a non-negative integer at most ${i}`);return t}function s(e){return typeof e?.pixels==`number`?e.pixels:void 0}function c(e){return typeof e?.durationMs==`number`?e.durationMs:void 0}export{c as a,r as c,a as i,t as n,s as o,i as r,o as s,n as t};