agent-device 0.21.29 → 0.21.30

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 (177) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.apk → agent-device-android-ime-helper-0.21.30.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.30.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.29.manifest.json → agent-device-android-ime-helper-0.21.30.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.30.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.29.manifest.json → agent-device-android-snapshot-helper-0.21.30.manifest.json} +7 -7
  7. package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/AudioProbe.swift +4 -2
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +2 -1
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +12 -0
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +25 -0
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +8 -1
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +9 -6
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +3 -0
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SynthesizedInteraction.swift +35 -9
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +44 -26
  16. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +20 -1
  17. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +4 -3
  18. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationProjection.swift +4 -2
  19. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotVisibilityFold.swift +20 -2
  20. package/dist/src/adapter.js +1 -1
  21. package/dist/src/agent-browser-lifecycle.js +1 -1
  22. package/dist/src/agent-browser-process-record.js +1 -1
  23. package/dist/src/agent-browser-provider.js +1 -1
  24. package/dist/src/agent-device-client.js +1 -1
  25. package/dist/src/alert2.js +1 -1
  26. package/dist/src/android.js +1 -1
  27. package/dist/src/app-lifecycle.js +1 -1
  28. package/dist/src/app-log-runtime2.js +3 -3
  29. package/dist/src/auth.js +1 -1
  30. package/dist/src/automation-helper.js +1 -1
  31. package/dist/src/back-mode.js +1 -1
  32. package/dist/src/cli-config.js +1 -1
  33. package/dist/src/cli-help.js +13 -10
  34. package/dist/src/cli.js +3 -3
  35. package/dist/src/client-types.d.ts +82 -13
  36. package/dist/src/cloud-artifacts.d.ts +99 -3
  37. package/dist/src/command-metadata.js +42 -42
  38. package/dist/src/composed-inventory-gateways.js +1 -1
  39. package/dist/src/connection-runtime.js +1 -1
  40. package/dist/src/connection.js +1 -1
  41. package/dist/src/contract.d.ts +2 -2
  42. package/dist/src/contracts.d.ts +1 -1
  43. package/dist/src/daemon-client-ensure.js +1 -1
  44. package/dist/src/daemon-client-ensuring.js +1 -1
  45. package/dist/src/daemon-client-lease-beat.js +1 -1
  46. package/dist/src/daemon-client-lifecycle.js +1 -1
  47. package/dist/src/daemon-client.js +2 -2
  48. package/dist/src/daemon-lifecycle-errors.js +1 -1
  49. package/dist/src/daemon-registration-owner.js +3 -3
  50. package/dist/src/daemon-registration.js +1 -1
  51. package/dist/src/daemon-resolution.js +1 -1
  52. package/dist/src/daemon-shutdown-report.js +1 -1
  53. package/dist/src/daemon-startup-diagnostics.js +1 -1
  54. package/dist/src/daemon.js +3 -3
  55. package/dist/src/device-claim-recovery.js +1 -1
  56. package/dist/src/durable-capture-resource.js +1 -1
  57. package/dist/src/durable-resource.js +1 -1
  58. package/dist/src/ended-lease.js +1 -1
  59. package/dist/src/find.js +1 -1
  60. package/dist/src/finders.js +1 -1
  61. package/dist/src/gesture-plan-types.d.ts +14 -4
  62. package/dist/src/gesture-plan.js +1 -1
  63. package/dist/src/gesture-runtime.js +1 -1
  64. package/dist/src/host4.js +1 -1
  65. package/dist/src/index.d.ts +3 -3
  66. package/dist/src/input-actions.js +1 -1
  67. package/dist/src/input-actions2.js +1 -1
  68. package/dist/src/interaction-positionals.js +1 -1
  69. package/dist/src/interaction.js +1 -1
  70. package/dist/src/interaction2.js +1 -1
  71. package/dist/src/interactor-operation-catalog.js +1 -1
  72. package/dist/src/interactor.js +5 -5
  73. package/dist/src/interactor3.js +1 -1
  74. package/dist/src/interactor4.js +1 -1
  75. package/dist/src/internal/bin.js +1 -1
  76. package/dist/src/internal/daemon.js +1 -1
  77. package/dist/src/internal/png-worker.js +1 -1
  78. package/dist/src/inventory6.js +1 -1
  79. package/dist/src/ios-node-interpretation.js +1 -1
  80. package/dist/src/ios-snapshot-acquisition.js +1 -1
  81. package/dist/src/ios-snapshot-engine.js +1 -1
  82. package/dist/src/ios-snapshot-runtime.js +1 -1
  83. package/dist/src/keyboard-occlusion.js +1 -1
  84. package/dist/src/launch-confirmation.js +1 -1
  85. package/dist/src/lease-context.js +1 -1
  86. package/dist/src/lease-registry-scope.js +1 -1
  87. package/dist/src/lease.js +1 -1
  88. package/dist/src/local-interactor-operation-set.js +1 -1
  89. package/dist/src/mechanics.js +12 -12
  90. package/dist/src/metro-session-hints.js +1 -1
  91. package/dist/src/mobile-snapshot-semantics.js +1 -1
  92. package/dist/src/observability.js +1 -1
  93. package/dist/src/observation.js +1 -1
  94. package/dist/src/parameterized-recorded-fill.js +1 -1
  95. package/dist/src/perf-facade.js +1 -1
  96. package/dist/src/platform-runtime-operation-host.js +1 -1
  97. package/dist/src/platform-runtime-unavailable.js +1 -1
  98. package/dist/src/platform-runtime.js +1 -1
  99. package/dist/src/platform-runtime2.js +1 -1
  100. package/dist/src/plugins2.js +1 -1
  101. package/dist/src/png-resize.js +1 -1
  102. package/dist/src/png-worker-client.js +1 -1
  103. package/dist/src/png-worker-contract.js +1 -1
  104. package/dist/src/provider-device-runtime.d.ts +20 -1
  105. package/dist/src/provider-plugin.d.ts +1 -1
  106. package/dist/src/react-native-overlay2.js +1 -1
  107. package/dist/src/record-runtime.js +1 -1
  108. package/dist/src/replay-maestro-backend.js +3 -3
  109. package/dist/src/replay-script-selection.js +1 -1
  110. package/dist/src/replay.d.ts +1 -1
  111. package/dist/src/request-runtime-binding.js +1 -1
  112. package/dist/src/result-serialization.js +1 -1
  113. package/dist/src/runner-error-classification.js +1 -1
  114. package/dist/src/runtime-admission.js +1 -1
  115. package/dist/src/runtime-deployment.js +1 -1
  116. package/dist/src/runtime-factory.js +1 -1
  117. package/dist/src/runtime-session.js +1 -1
  118. package/dist/src/runtime.js +5 -5
  119. package/dist/src/runtime10.js +2 -2
  120. package/dist/src/runtime3.js +5 -5
  121. package/dist/src/runtime5.js +1 -1
  122. package/dist/src/runtime6.js +1 -1
  123. package/dist/src/runtime7.js +1 -1
  124. package/dist/src/runtime8.js +1 -1
  125. package/dist/src/runtime9.js +2 -2
  126. package/dist/src/screenshot-image-size.js +1 -0
  127. package/dist/src/screenshot-image.js +1 -1
  128. package/dist/src/screenshot-runtime.js +1 -1
  129. package/dist/src/screenshot3.js +2 -2
  130. package/dist/src/sdk-batch.js +1 -1
  131. package/dist/src/sdk-contracts.d.ts +7 -1
  132. package/dist/src/sdk-finders.js +1 -1
  133. package/dist/src/sdk-selectors.d.ts +1 -1
  134. package/dist/src/sdk-selectors.js +1 -1
  135. package/dist/src/selection.js +0 -0
  136. package/dist/src/selector-pipeline-policy.js +1 -1
  137. package/dist/src/selector-runtime.js +1 -1
  138. package/dist/src/selectors.js +1 -1
  139. package/dist/src/server-startup.js +1 -1
  140. package/dist/src/session-replay-vars.js +1 -1
  141. package/dist/src/session-store.js +2 -2
  142. package/dist/src/session.js +1 -1
  143. package/dist/src/session2.js +5 -5
  144. package/dist/src/settle-observation-capture.js +1 -1
  145. package/dist/src/snapshot-capture-annotations.js +1 -1
  146. package/dist/src/snapshot-chrome.js +1 -1
  147. package/dist/src/snapshot-desktop-projection.js +1 -1
  148. package/dist/src/snapshot-helper-install.js +7 -5
  149. package/dist/src/snapshot-node-lookup.js +1 -1
  150. package/dist/src/snapshot-occlusion.js +1 -1
  151. package/dist/src/snapshot-runtime-binding.js +1 -1
  152. package/dist/src/snapshot-runtime-capture-input.js +1 -1
  153. package/dist/src/snapshot-runtime.js +1 -1
  154. package/dist/src/snapshot-state.js +1 -1
  155. package/dist/src/snapshot.js +1 -1
  156. package/dist/src/src.js +1 -1
  157. package/dist/src/src3.js +1 -1
  158. package/dist/src/src4.js +1 -1
  159. package/dist/src/tap-keyboard-occlusion.js +1 -1
  160. package/dist/src/target-evidence-tree.js +1 -1
  161. package/dist/src/target-evidence.js +1 -1
  162. package/dist/src/telephony-runtime.js +1 -1
  163. package/dist/src/text-entry-focus.js +1 -1
  164. package/dist/src/touch-reference-frame.js +1 -1
  165. package/dist/src/touch-runtime2.js +1 -1
  166. package/dist/src/tree.js +1 -1
  167. package/dist/src/tv-remote-runtime.js +1 -1
  168. package/dist/src/tv-remote.js +2 -2
  169. package/dist/src/type-text-runtime.js +1 -1
  170. package/dist/src/video.js +1 -1
  171. package/dist/src/webdriver-source.js +1 -1
  172. package/package.json +1 -1
  173. package/server.json +2 -2
  174. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.29.apk.sha256 +0 -1
  175. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk +0 -0
  176. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.29.apk.sha256 +0 -1
  177. package/dist/src/daemon-client-lifecycle-request.js +0 -1
@@ -1 +1 @@
1
- import{R as e}from"./sdk-contracts.js";import{Zt as t,in as n,nn as r,rn 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{r as l}from"./gesture-admission.js";import{B as u,D as d,F as f,G as p,H as m,J as h,K as g,L as _,M as ee,N as te,O as ne,S as re,T as ie,X as v,_ as y,b,g as x,j as S,l as C,o as w,p as T,r as E,w as D,z as O}from"./tv-remote-runtime.js";import{r as k,u as A}from"./application-lifecycle-interaction.js";import{n as j,r as M,t as N}from"./screen-recording-transport.js";async function P(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=>(F(e),await N({host:t,device:n,owner:r,input:e,signal:i,transport:{backend:`agent-browser`,targetLabel:`web recording`,start:async t=>await a.start(e.outputPath,t),stop:async()=>await a.stop()},support:{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},unsupported:e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`})),screenRecordingReattach:async()=>M(`Web recordings cannot be reattached after daemon restart.`),screenRecordingCleanup:async()=>j(`Web recordings cannot be cleaned after daemon restart.`)}}:{available:!1,operations:{}}}function F(t){if(t.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!t.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`)}const I=t(`web`),L=Object.freeze({available:!0}),ae=i(`unsupported-platform-leaf`,`Web targets read element text from the captured tree only.`),R=i(`unsupported-platform-leaf`),z=i(`owner-capability-missing`,`record is not supported by this web provider`),B=i(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),V=i(`unsupported-platform-leaf`),H=i(`unsupported-platform-leaf`,`apps is not supported on web targets.`),U=i(`unsupported-platform-leaf`),W=i(`unsupported-platform-leaf`),G=i(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),K=i(`owner-capability-missing`),q=i(`unsupported-platform-leaf`,`A web click is one immediate pointer press; the browser backend has no timed hold.`),J=i(`unsupported-platform-leaf`,`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:K}function X(e,t){return e?L:t}const oe=i(`unsupported-platform-leaf`),se=i(`unsupported-platform-leaf`,l),Z=i(`unsupported-device-kind`,`open is supported only for web browser devices.`),ce=i(`unsupported-device-kind`,`close is supported only for web browser devices.`),le=i(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`);function ue(e){let t=Q(e),n=de(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:V,clearRuntimeHints:V,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:G,configureProviderPortReverse:le})}function Q(e){return e.kind===`device`?L:Z}function de(e){return e.kind===`device`?L:ce}function fe(t){return Object.freeze({owner:I,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let n=await t.networkTransports.resolve(e),r=await P({host:t,device:e,owner:I,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`&&!r(n.intent.owner,I))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 i=await t.networkTransports.resolve(n.device),a=await P({host:t,device:n.device,owner:I,signal:n.scope.signal}),o=n.device.kind===`device`?await t.localInteractors.resolve(n.device,{signal:n.scope.signal}):void 0;return pe(t,n.device,n.scope.signal,i,a,$(n.device,i,a.available,o))},shutdown:async()=>void 0})}function pe(t,r,i,o,s,l){let d=o.dump,f={...d?{networkDump:async e=>{let t=await d({maxEntries:e.maxEntries,include:e.include},i);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?ne({device:r,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?te({device:r,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?g({device:r,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?ie({device:r,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...n(l.operations.tapPoint,()=>c({device:r,signal:i,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,i)})),...l.operations.scrollDirection.available?u({device:r,signal:i,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async n=>{i.throwIfAborted();let a=await t.localInteractors.resolve(r,{signal:i});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(n.width,n.height),i.throwIfAborted()}}:{},...n(l.operations.audioProbeQuery,()=>({audioProbeQuery:async n=>{let i=await t.audioProbe.web.resolve(r);if(i===void 0)throw new e(`UNSUPPORTED_OPERATION`,`audio is not supported by this web provider`);return await i.probe(n)}})),...a(k({owner:`web`,openTargetIdentity:`app-name`,host:t.localInteractors,device:r,signal:i}),l.operations)};return Object.freeze({device:r,owner:I,facts:l,operations:Object.freeze(f),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,r){let a=i(`owner-capability-missing`,`network is not supported by this web provider`),o=X(e.kind===`device`,Z);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:R,appLogDoctor:R,appLogStart:R,appLogReattach:R,appLogCleanup:R,appState:U,networkDump:X(!!t.dump,a),screenRecordingStart:X(n,z),screenRecordingReattach:X(n,z),screenRecordingCleanup:X(n,z),...S({capture:o,customActions:B,withoutActiveApp:o}),...ee({findText:Z,querySelector:Z}),...f({capture:o}),...h({focus:o}),...d({type:o}),...s({unsupported:V,tap:o,tapRef:Y(r?.tapRef,o),longPress:q,hover:Y(r?.hover,o),hoverRef:Y(r?.hoverRef,o),fill:o,fillRef:Y(r?.fillRef,o)}),...m({scroll:o}),...p({unsupported:oe,targetAuthoredDrag:se}),...D({setViewport:o}),...v({readTextAtPoint:ae}),...re({back:W}),...w({orientation:W}),...E({tvRemote:W}),...C({unsupported:W}),...T({unsupported:W}),...O({capture:J,query:L}),..._({frames:W,memorySample:W,memorySnapshot:W,nativeCapture:W,profileReport:W}),...x({unsupported:W}),setFoldPose:W,sendTelephonyEvent:W,...y({triggerAppEvent:W}),...A({target:W,unsupported:W,write:{}}),...b({read:W,wait:W,accept:W,dismiss:W}),ensureReady:V,bootTarget:V,bootTargetHeadless:V,listApps:H,deployApp:V,materializeAppSource:V,deployMaterializedApp:V,sendPushNotification:V,uninstallApp:V,shutdownTarget:V,...ue(e)}})}export{fe as createWebPlatformRuntime};
1
+ import{R as e}from"./sdk-contracts.js";import{an as t,en as n,on as r,sn 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{r as l}from"./gesture-admission.js";import{B as u,C as d,E as f,I as p,K as m,M as h,N as g,O as _,P as ee,R as te,T as ne,U as re,V as ie,Y as v,Z as y,_ as b,k as x,l as S,o as C,p as w,q as T,r as E,v as D,x as O}from"./tv-remote-runtime.js";import{r as k,u as A}from"./application-lifecycle-interaction.js";import{n as j,r as M,t as N}from"./screen-recording-transport.js";async function P(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=>(F(e),await N({host:t,device:n,owner:r,input:e,signal:i,transport:{backend:`agent-browser`,targetLabel:`web recording`,start:async t=>await a.start(e.outputPath,t),stop:async()=>await a.stop()},support:{scopes:[`app`],fps:!1,exportQuality:!1,hideTouches:!1},unsupported:e=>`web recordings do not support ${e.join(`, `)}; agent-browser records WebM directly`})),screenRecordingReattach:async()=>M(`Web recordings cannot be reattached after daemon restart.`),screenRecordingCleanup:async()=>j(`Web recordings cannot be cleaned after daemon restart.`)}}:{available:!1,operations:{}}}function F(t){if(t.recordOnlySession)throw new e(`INVALID_ARGS`,`record on web requires an active browser session; run open <url> --platform web first`);if(!t.outputPath.toLowerCase().endsWith(`.webm`))throw new e(`INVALID_ARGS`,`web recordings require a .webm output path; agent-browser records WebM directly`)}const I=n(`web`),L=Object.freeze({available:!0}),ae=r(`unsupported-platform-leaf`,`Web targets read element text from the captured tree only.`),R=r(`unsupported-platform-leaf`),z=r(`owner-capability-missing`,`record is not supported by this web provider`),B=r(`unsupported-platform-leaf`,`Re-run without --actions, or target an iOS simulator.`),V=r(`unsupported-platform-leaf`),H=r(`unsupported-platform-leaf`,`apps is not supported on web targets.`),U=r(`unsupported-platform-leaf`),W=r(`unsupported-platform-leaf`),G=r(`unsupported-platform-leaf`,`Apple runner preparation is supported only for Apple targets.`),K=r(`owner-capability-missing`),q=r(`unsupported-platform-leaf`,`A web click is one immediate pointer press; the browser backend has no timed hold.`),J=r(`unsupported-platform-leaf`,`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:K}function X(e,t){return e?L:t}const oe=r(`unsupported-platform-leaf`),se=r(`unsupported-platform-leaf`,l),Z=r(`unsupported-device-kind`,`open is supported only for web browser devices.`),ce=r(`unsupported-device-kind`,`close is supported only for web browser devices.`),le=r(`unsupported-provider-mode`,`Port reverse is supported only by an owning provider runtime.`);function ue(e){let t=Q(e),n=de(e);return o({resolveOpenTarget:t,prepareApplicationOpen:t,openApplication:t,applyRuntimeHints:V,clearRuntimeHints:V,closeApplication:n,finalizeApplicationClose:n,prepareAppleRunner:G,configureProviderPortReverse:le})}function Q(e){return e.kind===`device`?L:Z}function de(e){return e.kind===`device`?L:ce}function fe(n){return Object.freeze({owner:I,ownsDevice:e=>e.platform===`web`,inspectFacts:async e=>{let t=await n.networkTransports.resolve(e),r=await P({host:n,device:e,owner:I,signal:new AbortController().signal}),i=e.kind===`device`?await n.localInteractors.resolve(e,{}):void 0;return $(e,t,r.available,i)},bind:async r=>{if(r.intent.kind===`exact-owner`&&!t(r.intent.owner,I))throw new e(`UNSUPPORTED_OPERATION`,`Web runtime owner identity does not match`);if(r.device.platform!==`web`)throw new e(`UNSUPPORTED_PLATFORM`,`Web runtime owner cannot bind ${r.device.platform}`);let i=await n.networkTransports.resolve(r.device),a=await P({host:n,device:r.device,owner:I,signal:r.scope.signal}),o=r.device.kind===`device`?await n.localInteractors.resolve(r.device,{signal:r.scope.signal}):void 0;return pe(n,r.device,r.scope.signal,i,a,$(r.device,i,a.available,o))},shutdown:async()=>void 0})}function pe(t,n,r,o,s,l){let u=o.dump,d={...u?{networkDump:async e=>{let t=await u({maxEntries:e.maxEntries,include:e.include},r);return Object.freeze({source:`provider`,...t})}}:{},...s.operations,...l.operations.captureSnapshot.available?x({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.captureScreenshot.available?ee({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.focusPoint.available?T({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.typeText.available?f({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...i(l.operations.tapPoint,()=>c({device:n,signal:r,resolveInteractor:t.localInteractors.resolve,facts:l.operations,pause:async e=>await t.clock.sleep(e,r)})),...l.operations.scrollDirection.available?ie({device:n,signal:r,resolveInteractor:t.localInteractors.resolve}):{},...l.operations.setViewport.available?{setViewport:async i=>{r.throwIfAborted();let a=await t.localInteractors.resolve(n,{signal:r});if(!a.setViewport)throw new e(`UNSUPPORTED_OPERATION`,`viewport is not supported by the bound web interactor`);await a.setViewport(i.width,i.height),r.throwIfAborted()}}:{},...i(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(k({owner:`web`,openTargetIdentity:`app-name`,host:t.localInteractors,device:n,signal:r}),l.operations)};return Object.freeze({device:n,owner:I,facts:l,operations:Object.freeze(d),[Symbol.asyncDispose]:async()=>void 0})}function $(e,t,n,i){let a=r(`owner-capability-missing`,`network is not supported by this web provider`),o=X(e.kind===`device`,Z);return Object.freeze({device:{family:`web`,kind:e.kind,...e.target===void 0?{}:{target:e.target},providerMode:t.mode},operations:{appLogInspect:R,appLogDoctor:R,appLogStart:R,appLogReattach:R,appLogCleanup:R,appState:U,networkDump:X(!!t.dump,a),screenRecordingStart:X(n,z),screenRecordingReattach:X(n,z),screenRecordingCleanup:X(n,z),...h({capture:o,customActions:B,withoutActiveApp:o}),...g({findText:Z,querySelector:Z}),...p({capture:o}),...v({focus:o}),..._({type:o}),...s({unsupported:V,tap:o,tapRef:Y(i?.tapRef,o),longPress:q,hover:Y(i?.hover,o),hoverRef:Y(i?.hoverRef,o),fill:o,fillRef:Y(i?.fillRef,o)}),...re({scroll:o}),...m({unsupported:oe,targetAuthoredDrag:se}),...ne({setViewport:o}),...y({readTextAtPoint:ae}),...d({back:W}),...C({orientation:W}),...E({tvRemote:W}),...S({unsupported:W}),...w({unsupported:W}),...u({capture:J,query:L}),...te({frames:W,memorySample:W,memorySnapshot:W,nativeCapture:W,profileReport:W}),...b({unsupported:W}),setFoldPose:W,sendTelephonyEvent:W,...D({triggerAppEvent:W}),...A({target:W,unsupported:W,write:{}}),...O({read:W,wait:W,accept:W,dismiss:W}),ensureReady:V,bootTarget:V,bootTargetHeadless:V,listApps:H,deployApp:V,materializeAppSource:V,deployMaterializedApp:V,sendPushNotification:V,uninstallApp:V,shutdownTarget:V,...ue(e)}})}export{fe as createWebPlatformRuntime};
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime.js";import{R as t,q as n}from"./sdk-contracts.js";import{C as r,S as i,it as a}from"./tv-remote.js";import{s as o}from"./sdk-device.js";import{$t as s,ai as c}from"./sdk-batch.js";import{a as l}from"./sdk-remote-config.js";import{a as u,i as ee,o as d,r as te,s as ne,t as re}from"./runtime-deployment.js";import f from"node:fs";import p from"node:path";import ie,{readFile as m,stat as h}from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function _(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function ae(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(e,r){try{await r()}catch(r){e instanceof t&&(e.details={...e.details,cleanupError:n(r)})}}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function oe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function se(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function ce(e,t){let n=new URL(e);return n.pathname=`${se(n.pathname)}/${t}`,n}function le(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ue(e,n,r){if(!(await h(e).catch(()=>void 0))?.isFile())throw new t(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(n,new Blob([await m(e)]),p.basename(e)),i}async function de(e,n,r){let i=await fetch(n.endpoint,{method:`POST`,headers:{...y(n.clientVersion),Authorization:x(n.auth)},body:e,signal:r}),a=await C(i),o=n.readAppReference(a)?.trim();if(!i.ok||!o)throw new t(`COMMAND_FAILED`,`${n.service} app upload failed.`,{status:i.status,response:a});return o}function fe(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function pe(e){let{app:n}=e,r=e.parseReference(n);if(r!==void 0)return r;if(/^https?:\/\//i.test(n))return n;let i=p.isAbsolute(n)?n:p.resolve(me(e),n);if(!f.existsSync(i))throw new t(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:n});return await e.uploadFile(i,e.signal)}function me(e){if(e.cwd!==void 0)return e.cwd;throw new t(`INVALID_ARGS`,`${e.service} --provider-app ${e.app} is a relative path and the request names no working directory; pass an absolute path.`,{providerApp:e.app,reason:`provider_app_cwd_missing`})}const S=15e3;async function he(e,n){let{service:r,unauthorizedHint:i,networkHint:a}=n.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...y(n.clientVersion),...n.auth?{Authorization:x(n.auth)}:{}},signal:AbortSignal.timeout(S)});if(!a.ok){let e=a.status===401||a.status===403;throw new t(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await C(a);if(s===void 0)throw new t(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof t?e:new t(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function ge(e,n){let r,i;try{r=await fetch(e,{headers:{...y(n.clientVersion),Authorization:x(n.auth)},signal:AbortSignal.timeout(S)}),i=await C(r)}catch(e){throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{hint:`Check network access to the ${n.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{status:r.status,response:i});return a}async function C(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function _e(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function ve(e,n){let r=l.find(e=>e===n);if(r)return r;throw new t(`INVALID_ARGS`,`Invalid ${e.flag} value: ${n}.`,{hint:`Use ${l.join(`|`)}.`,flag:e.flag,capability:e.capability})}function w(e,n){if(e)return e;throw new t(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function T(e,n){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new t(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function E(e,n,r){let i=D(e,n);if(i)return i;throw new t(`INVALID_ARGS`,r)}function D(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function O(e,n,r){let i=e[n];if(i?.trim())return i;throw new t(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function k(e,n){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new t(`INVALID_ARGS`,`connect ${n} requires --platform ios|android.`)}function A(e,n,r){if(e?.trim())return e;throw new t(`INVALID_ARGS`,`connect ${n} requires ${r}.`)}function j(e,n,r){let i=p.resolve(n,e);if(f.statSync(i,{throwIfNoEntry:!1})?.isFile())return i;throw new t(`INVALID_ARGS`,`${r} app file not found: ${i}`)}const M=`webdriver_request_timeout`;function N(e){return e instanceof t&&e.details?.reason===M}function P(e){return{dispatched:e}}const F=`webdriver_connect_refused`,I=`webdriver_request_interrupted`,ye=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function be(e){return e instanceof t&&e.details?.reason===F}const xe=new Set([`GET`,`HEAD`]),Se=Object.freeze({});var Ce=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=le(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??xe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Te(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?De(s):{};if(a)return{status:o,value:Ee(c)};let l=Oe(o,c);throw U(l)&&H(z,{method:e,path:t,status:o,code:V(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(oe(t),this.endpoint),o=n===void 0&&e===`POST`?Se:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw L(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw L(e,l,`response`)}}};function L(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Me(r,i,a,e):n===`request`&&we(e)?Ne(r,i,e):n===`response`||e instanceof TypeError?Pe(r,i,e):e}function we(e){let t=R(e,0);return t.length>0&&t.every(e=>ye.has(e))}function R(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...R(r,t+1),...i.flatMap(e=>R(e,t+1))]}function Te(e,t,n,r){return!r?.aborted&&Fe(e)&&t<n}function Ee(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function De(e){try{return JSON.parse(e)}catch(n){throw new t(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},n)}}function Oe(e,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return je(e,n)?new t(`COMMAND_FAILED`,i,{...B(),status:e,response:n}):new t(`COMMAND_FAILED`,i,{status:e,response:n,...e>=500?P(`unknown`):{}})}const z=`webdriver_route_unsupported`;function B(){return{reason:z,...P(`no`)}}const ke=new Set([`unknown command`,`unknown method`]),Ae=new Set([404,405,501]);function je(e,t){let n=V(t);return n===void 0?Ae.has(e):ke.has(n.toLowerCase())}function V(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function H(e,t){import(`./diagnostics.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function U(e){return e instanceof t&&e.details?.reason===z}function Me(e,n,r,i){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} timed out after ${r}ms.`,{reason:M,method:e,path:n,timeoutMs:r,...P(`unknown`)},i instanceof Error?i:void 0)}function Ne(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} could not reach the driver.`,{reason:F,method:e,path:n,...P(`no`)},r instanceof Error?r:void 0)}function Pe(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} lost its connection to the driver.`,{reason:I,method:e,path:n,...P(`unknown`)},r instanceof Error?r:void 0)}function Fe(e){if(N(e)||be(e)||e instanceof t&&e.details?.reason===I)return!0;if(e instanceof t){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Ie=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ce(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Re(await this.requestValue(`POST`,`/session`,{capabilities:Le(e)},{timeoutMs:Be(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!U(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});H(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e,t){let n;try{n=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}})}catch(e){if(U(e))return`unsupported`;throw e}return typeof n==`boolean`?n:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=ze(await this.sessionRequest(`GET`,`/element/active`,void 0,K(t)))}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,K(t));return{id:n,rect:W(e)}}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(e){let n=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(e){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ie.writeFile(e,Buffer.from(n,`base64`))}async windowRect(e){return W(await this.sessionRequest(`GET`,`/window/rect`,void 0,e))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new t(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function W(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=e,r={x:G(n,`x`),y:G(n,`y`),width:G(n,`width`),height:G(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function G(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Le(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Re(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=e,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new t(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}function ze(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function K(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:q(e)}}function Be(e,t){return t===void 0?e:Math.min(e,q(t))}function q(e){return Math.max(0,e-Date.now())}function J(e){return e instanceof t&&Ve(e).toLowerCase()===`no such element`}function Ve(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function Y(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function He(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e,`android`).nodes)}async function Ue(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e).nodes)}function X(e){let t=e.flatMap(e=>We(e)&&Ge(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function We(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ge(e){return!!e&&e.width>=50&&e.height>=50}async function Ke(e,n,r){let i=[];for(let t of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await qe(e,t,r);return}catch(e){if(!U(e))throw e;i.push({transport:t,error:e instanceof Error?e.message:String(e)})}throw new t(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...B(),hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}async function qe(e,t,n){if(t===`rotation`){await e.setRotation(r(n));return}await e.setOrientation(i(n))}const Z=1500;function Je(e){return new Promise(t=>setTimeout(t,e))}function Q(e,n,r){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function $(e,n){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:e,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ye(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Xe(e){return new Ze(e.client,e.backend,e.capabilities,e.targetId)}var Ze=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new t(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(e,n);let o=await this.awaitTextEntryReadiness(a,e,n);return await this.type(r),{backend:`webdriver`,x:e,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),i=a({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...i,x1:i.x1+r.x,y1:i.y1+r.y,x2:i.x2+r.x,y2:i.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:i.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport($e(e)),await this.client.performActions(e.pointers.map(e=>Y(`gesture-pointer-${e.pointerId}`,Qe(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=this.backend===`android`?await this.readAndroidSnapshotViewport(e):void 0,n=await this.readSource(e);e?.throwIfAborted();let r=await this.readSnapshotKeyboardVisibility(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(n,this.targetId,r)}let{parseWebDriverAndroidSnapshotNodes:i}=await import(`./webdriver-android-source.js`),{acquireProviderKeyboard:a}=await import(`./tap-keyboard-occlusion.js`).then(e=>e.i),o=i(n),s=t===void 0?void 0:await this.readAndroidSnapshotViewport(e),c=t!==void 0&&s!==void 0&&t.width===s.width&&t.height===s.height?t:void 0;return{backend:`android`,producer:`appium-source`,...a({nodes:o,viewport:null,visibility:r}),...c===void 0?{}:{viewport:c}}}async readAndroidSnapshotViewport(e){try{let t=await this.client.windowRect({timeoutMs:500,retryAttempts:0,...e===void 0?{}:{signal:e}});return c(t)}catch{e?.throwIfAborted();return}}async readSnapshotKeyboardVisibility(e){try{let t=await this.client.isKeyboardShown(500,e);return e?.throwIfAborted(),t}catch{return e?.throwIfAborted(),`failed`}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw N(e)?et(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Ke(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
2
- `);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(Z);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new t(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ye(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw Q(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw $(t,n);if(r)throw Q(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw Q(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(Z),this.client.activeElement(Z)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(Z,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Je(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([Y(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ue(e):He(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){u(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new t(`UNSUPPORTED_OPERATION`,ne(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function Qe(e){let n=e[0];if(!n)throw new t(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function $e(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`}}function et(e){return new t(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}var tt=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;let{rejectRefusedProviderProfileFields:n}=await import(`./provider-profile-fields.js`).then(e=>e.t);if(n(t?.flags,this.options.profileFields),this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let r=await this.prepareSession(e,t),i=new Ie({clientVersion:this.options.clientVersion,endpoint:r.endpoint,auth:r.auth,headers:r.headers,requestPolicy:this.options.requestPolicy}),a=await this.createSessionWithPreparedCleanup(i,r,e,t),o=this.deviceForLease(e,r),s=r.providerSessionId??a.sessionId,c=d({provider:this.options.provider,platform:r.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:o,client:i,prepared:r,capabilities:c,webDriverSessionId:a.sessionId,providerSessionId:s,interactor:Xe({client:i,backend:te(r.platform),capabilities:c,targetId:o.id})})),this.ownedDeviceIds.add(o.id),{provider:this.options.provider,deviceId:o.id,sessionId:a.sessionId,providerSessionId:s,capabilities:c,...r.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=N(e)?nt(e,this.options.provider,n,t):e;throw await b(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:ee(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...o(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let t=[],r;try{await e.client.deleteSession()}catch(e){t.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:n(e)})}try{r=await e.prepared.cleanup?.()}catch(e){t.push({code:`PROVIDER_CLEANUP_FAILED`,message:n(e)})}return{cleanup:r,warnings:t}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return v({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function nt(e,n,r,i){let a=e.details?.timeoutMs;return new t(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}var rt=e({createCloudWebDriverRuntime:()=>it});function it(e){return new at(e)}var at=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=s(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new tt(e),this.deployment=re({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};export{pe as _,ge as a,_ as b,D as c,k as d,O as f,T as g,w as h,fe as i,b as l,ve as m,ue as n,he as o,E as p,ce as r,de as s,rt as t,A as u,j as v,ae as x,_e as y};
1
+ import{r as e}from"./rolldown-runtime.js";import{R as t,q as n}from"./sdk-contracts.js";import{O as r,ct as i,k as a}from"./tv-remote.js";import{s as o}from"./sdk-device.js";import{ci as s,nn as c}from"./sdk-batch.js";import{a as l}from"./sdk-remote-config.js";import{a as u,i as ee,o as d,r as te,s as ne,t as re}from"./runtime-deployment.js";import f from"node:fs";import p from"node:path";import ie,{readFile as m,stat as h}from"node:fs/promises";import{setTimeout as g}from"node:timers/promises";function _(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:e.artifacts.length>0?`ready`:`pending`,cloudArtifacts:e.artifacts,...e.artifacts.length>0?{}:{message:e.pendingMessage}}}function v(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function ae(e,t,n,r,i,a){let o=n[r],s=typeof o==`string`?o.trim():``;if(s.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:s,availability:`ready`}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function b(e,r){try{await r()}catch(r){e instanceof t&&(e.details={...e.details,cleanupError:n(r)})}}function x(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function oe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function se(e){let t=e.length-1;for(;t>=0&&e.charCodeAt(t)===47;)--t;return t===e.length-1?e:e.slice(0,t+1)}function ce(e,t){let n=new URL(e);return n.pathname=`${se(n.pathname)}/${t}`,n}function le(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}async function ue(e,n,r){if(!(await h(e).catch(()=>void 0))?.isFile())throw new t(`INVALID_ARGS`,`${r.service} can only upload a regular app file: ${e}`,{provider:r.provider,appPath:e,hint:`Use an existing .ipa, .apk, or .aab file, or a .zip of the iOS simulator .app bundle.`});let i=new FormData;return i.set(n,new Blob([await m(e)]),p.basename(e)),i}async function de(e,n,r){let i=await fetch(n.endpoint,{method:`POST`,headers:{...y(n.clientVersion),Authorization:x(n.auth)},body:e,signal:r}),a=await C(i),o=n.readAppReference(a)?.trim();if(!i.ok||!o)throw new t(`COMMAND_FAILED`,`${n.service} app upload failed.`,{status:i.status,response:a});return o}function fe(e){return async({appPath:t,options:n,signal:r})=>({appReference:await e(t,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}async function pe(e){let{app:n}=e,r=e.parseReference(n);if(r!==void 0)return r;if(/^https?:\/\//i.test(n))return n;let i=p.isAbsolute(n)?n:p.resolve(me(e),n);if(!f.existsSync(i))throw new t(`INVALID_ARGS`,`${e.service} --provider-app must be ${e.referenceLabel}, URL, or existing local app path.`,{providerApp:n});return await e.uploadFile(i,e.signal)}function me(e){if(e.cwd!==void 0)return e.cwd;throw new t(`INVALID_ARGS`,`${e.service} --provider-app ${e.app} is a relative path and the request names no working directory; pass an absolute path.`,{providerApp:e.app,reason:`provider_app_cwd_missing`})}const S=15e3;async function he(e,n){let{service:r,unauthorizedHint:i,networkHint:a}=n.hints,o=`Retry connect or check the ${r} service status.`;try{let a=await fetch(e,{headers:{...y(n.clientVersion),...n.auth?{Authorization:x(n.auth)}:{}},signal:AbortSignal.timeout(S)});if(!a.ok){let e=a.status===401||a.status===403;throw new t(e?`UNAUTHORIZED`:`COMMAND_FAILED`,`${r} rejected connection verification.`,{status:a.status,hint:e?i:o})}let s=await C(a);if(s===void 0)throw new t(`COMMAND_FAILED`,`${r} connection verification answer was not JSON.`,{status:a.status,hint:o});return s}catch(e){throw e instanceof t?e:new t(`COMMAND_FAILED`,`${r} connection verification failed.`,{hint:a},e)}}async function ge(e,n){let r,i;try{r=await fetch(e,{headers:{...y(n.clientVersion),Authorization:x(n.auth)},signal:AbortSignal.timeout(S)}),i=await C(r)}catch(e){throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{hint:`Check network access to the ${n.service} API, then retry.`},e)}let a=i&&typeof i==`object`&&!Array.isArray(i)?i:void 0;if(!r.ok||!a)throw new t(`COMMAND_FAILED`,`${n.service} session details lookup failed.`,{status:r.status,response:i});return a}async function C(e){let t=await e.text();if(t.length!==0)try{return JSON.parse(t)}catch{return}}function _e(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function ve(e,n){let r=l.find(e=>e===n);if(r)return r;throw new t(`INVALID_ARGS`,`Invalid ${e.flag} value: ${n}.`,{hint:`Use ${l.join(`|`)}.`,flag:e.flag,capability:e.capability})}function w(e,n){if(e)return e;throw new t(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function T(e,n){let r=e.flags?.platform;if(r===`android`||r===`ios`)return r;throw new t(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function E(e,n,r){let i=D(e,n);if(i)return i;throw new t(`INVALID_ARGS`,r)}function D(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function O(e,n,r){let i=e[n];if(i?.trim())return i;throw new t(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function k(e,n){if(e.platform===`android`||e.platform===`ios`)return e.platform;throw new t(`INVALID_ARGS`,`connect ${n} requires --platform ios|android.`)}function A(e,n,r){if(e?.trim())return e;throw new t(`INVALID_ARGS`,`connect ${n} requires ${r}.`)}function j(e,n,r){let i=p.resolve(n,e);if(f.statSync(i,{throwIfNoEntry:!1})?.isFile())return i;throw new t(`INVALID_ARGS`,`${r} app file not found: ${i}`)}const M=`webdriver_request_timeout`;function N(e){return e instanceof t&&e.details?.reason===M}function P(e){return{dispatched:e}}const F=`webdriver_connect_refused`,I=`webdriver_request_interrupted`,ye=new Set([`ECONNREFUSED`,`ENOTFOUND`,`EAI_AGAIN`,`EHOSTUNREACH`,`ENETUNREACH`,`UND_ERR_CONNECT_TIMEOUT`]);function be(e){return e instanceof t&&e.details?.reason===F}const xe=new Set([`GET`,`HEAD`]),Se=Object.freeze({});var Ce=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=le(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:x(e.auth)}:{},...e.headers},this.requestPolicy={timeoutMs:e.requestPolicy?.timeoutMs??3e4,retryAttempts:e.requestPolicy?.retryAttempts??1,retryDelayMs:e.requestPolicy?.retryDelayMs??250}}async requestValue(e,t,n,r){return(await this.request(e,t,n,r)).value}async request(e,t,n,r){let i=r?.idempotent??xe.has(e);return await this.requestWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??(i?this.requestPolicy.retryAttempts:0),timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!Te(e,a,r.retryAttempts,r.signal))throw e;await g(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?De(s):{};if(a)return{status:o,value:Ee(c)};let l=Oe(o,c);throw U(l)&&H(z,{method:e,path:t,status:o,code:V(c)??null}),l}async fetchWebDriver(e,t,n,r,i){let a=new URL(oe(t),this.endpoint),o=n===void 0&&e===`POST`?Se:n,s=AbortSignal.timeout(r),c=i?AbortSignal.any([i,s]):s,l={method:e,path:t,timeoutMs:r,timeoutSignal:s,requestSignal:i},u;try{u=await fetch(a,{method:e,headers:{Accept:`application/json`,...o===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:o===void 0?void 0:JSON.stringify(o),signal:c})}catch(e){throw L(e,l,`request`)}try{return{ok:u.ok,status:u.status,text:await u.text()}}catch(e){throw L(e,l,`response`)}}};function L(e,t,n){let{method:r,path:i,timeoutMs:a,timeoutSignal:o,requestSignal:s}=t;return s?.aborted?e:o.aborted?Me(r,i,a,e):n===`request`&&we(e)?Ne(r,i,e):n===`response`||e instanceof TypeError?Pe(r,i,e):e}function we(e){let t=R(e,0);return t.length>0&&t.every(e=>ye.has(e))}function R(e,t){if(t>4||!e||typeof e!=`object`)return[];let{code:n,cause:r}=e,i=e instanceof AggregateError?e.errors:[];return[...typeof n==`string`?[n]:[],...R(r,t+1),...i.flatMap(e=>R(e,t+1))]}function Te(e,t,n,r){return!r?.aborted&&Fe(e)&&t<n}function Ee(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function De(e){try{return JSON.parse(e)}catch(n){throw new t(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:e},n)}}function Oe(e,n){let r=n&&typeof n==`object`&&`value`in n?n.value:n,i=r&&typeof r==`object`&&typeof r.message==`string`?r.message:`WebDriver request failed with HTTP ${e}.`;return je(e,n)?new t(`COMMAND_FAILED`,i,{...B(),status:e,response:n}):new t(`COMMAND_FAILED`,i,{status:e,response:n,...e>=500?P(`unknown`):{}})}const z=`webdriver_route_unsupported`;function B(){return{reason:z,...P(`no`)}}const ke=new Set([`unknown command`,`unknown method`]),Ae=new Set([404,405,501]);function je(e,t){let n=V(t);return n===void 0?Ae.has(e):ke.has(n.toLowerCase())}function V(e){let t=e&&typeof e==`object`&&`value`in e?e.value:void 0,n=t&&typeof t==`object`?t.error:void 0;return typeof n==`string`?n:void 0}function H(e,t){import(`./diagnostics.js`).then(e=>e.t).then(({emitDiagnostic:n})=>n({level:`debug`,phase:e,data:t})).catch(()=>void 0)}function U(e){return e instanceof t&&e.details?.reason===z}function Me(e,n,r,i){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} timed out after ${r}ms.`,{reason:M,method:e,path:n,timeoutMs:r,...P(`unknown`)},i instanceof Error?i:void 0)}function Ne(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} could not reach the driver.`,{reason:F,method:e,path:n,...P(`no`)},r instanceof Error?r:void 0)}function Pe(e,n,r){return new t(`COMMAND_FAILED`,`WebDriver ${e} ${n} lost its connection to the driver.`,{reason:I,method:e,path:n,...P(`unknown`)},r instanceof Error?r:void 0)}function Fe(e){if(N(e)||be(e)||e instanceof t&&e.details?.reason===I)return!0;if(e instanceof t){let t=e.details?.status;return typeof t==`number`&&t>=500}return!1}var Ie=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new Ce(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=Re(await this.requestValue(`POST`,`/session`,{capabilities:Le(e)},{timeoutMs:Be(this.sessionCreateTimeoutMs,t?.deadline)}));return this.sessionId=n.sessionId,n}async deleteSession(){let e=this.requireSessionId();await this.requestValue(`DELETE`,`/session/${e}`),this.sessionId=void 0}async installApp(e,t){await this.sessionRequest(`POST`,`/appium/device/install_app`,{appPath:e},{signal:t})}async activateApp(e){await this.appRouteWithSibling(`/appium/device/activate_app`,`mobile: activateApp`,e)}async terminateApp(e){await this.appRouteWithSibling(`/appium/device/terminate_app`,`mobile: terminateApp`,e)}async appRouteWithSibling(e,t,n){try{await this.sessionRequest(`POST`,e,{appId:n})}catch(r){if(!U(r))throw r;let{status:i}=await this.transport.request(`POST`,`/session/${this.requireSessionId()}/execute/sync`,{script:t,args:[{appId:n,bundleId:n}]});H(`webdriver_route_fallback`,{from:e,to:t,status:i})}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`)}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`)}async isKeyboardShown(e,t){let n;try{n=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}})}catch(e){if(U(e))return`unsupported`;throw e}return typeof n==`boolean`?n:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=ze(await this.sessionRequest(`GET`,`/element/active`,void 0,K(t)))}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,K(t));return{id:n,rect:W(e)}}catch(e){if(U(e))return`unsupported`;if(J(e))return`none`;throw e}}async back(){await this.sessionRequest(`POST`,`/back`)}async setRotation(e){await this.sessionRequest(`POST`,`/rotation`,{x:0,y:0,z:e})}async setOrientation(e){await this.sessionRequest(`POST`,`/orientation`,{orientation:e})}async source(e){let n=await this.sessionRequest(`GET`,`/source`,void 0,e);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(e){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new t(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await ie.writeFile(e,Buffer.from(n,`base64`))}async windowRect(e){return W(await this.sessionRequest(`GET`,`/window/rect`,void 0,e))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}async executeReadScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t},{idempotent:!0})}async sessionRequest(e,t,n,r){let i=this.requireSessionId();return await this.requestValue(e,`/session/${i}${t}`,n,r)}requireSessionId(){if(!this.sessionId)throw new t(`SESSION_NOT_FOUND`,`WebDriver session has not been created yet.`);return this.sessionId}async requestValue(e,t,n,r){return await this.transport.requestValue(e,t,n,r)}};function W(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=e,r={x:G(n,`x`),y:G(n,`y`),width:G(n,`width`),height:G(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new t(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function G(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Le(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function Re(e){if(!e||typeof e!=`object`)throw new t(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=e,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new t(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}function ze(e){if(!e||typeof e!=`object`)return;let t=e,n=t[`element-6066-11e4-a52e-4f735466cecf`]??t.ELEMENT;return typeof n==`string`&&n.length>0?n:void 0}function K(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:q(e)}}function Be(e,t){return t===void 0?e:Math.min(e,q(t))}function q(e){return Math.max(0,e-Date.now())}function J(e){return e instanceof t&&Ve(e).toLowerCase()===`no such element`}function Ve(e){let t=e.details?.response,n=t&&typeof t==`object`?t.value:void 0,r=n&&typeof n==`object`?n.error:void 0;return typeof r==`string`?r:``}function Y(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function He(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e,`android`).nodes)}async function Ue(e){let{parseWebDriverSourceFacts:t}=await import(`./webdriver-source.js`);return X(t(e).nodes)}function X(e){let t=e.flatMap(e=>We(e)&&Ge(e.rect)?[e.rect]:[]).sort((e,t)=>t.width*t.height-e.width*e.height)[0];return t?{x:t.x,y:t.y,width:t.width,height:t.height}:void 0}function We(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Ge(e){return!!e&&e.width>=50&&e.height>=50}async function Ke(e,n,r){let i=[];for(let t of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await qe(e,t,r);return}catch(e){if(!U(e))throw e;i.push({transport:t,error:e instanceof Error?e.message:String(e)})}throw new t(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{...B(),hint:`The provider driver rejected both orientation endpoints. Set the orientation as a session capability instead, for example connect --provider-device-orientation portrait.`,rotation:r,attempts:i})}async function qe(e,t,n){if(t===`rotation`){await e.setRotation(a(n));return}await e.setOrientation(r(n))}const Z=1500;function Je(e){return new Promise(t=>setTimeout(t,e))}function Q(e,n,r){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:e,y:n,hint:`The tap most likely missed the field. Re-check the target with snapshot -i and fill the element it reports, rather than retrying the same coordinates.`})}function $(e,n){return new t(`COMMAND_FAILED`,`fill tapped (${e}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:e,y:n,hint:`This provider cannot confirm a field took focus. Use press <target> followed by type <text> to enter it anyway, accepting that nothing witnesses which field receives the keys.`})}function Ye(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function Xe(e){return new Ze(e.client,e.backend,e.capabilities,e.targetId)}var Ze=class{client;backend;capabilities;targetId;constructor(e,t,n,r){this.client=e,this.backend=t,this.capabilities=n,this.targetId=r}async open(e,t){if(t?.url){await this.client.executeScript(`mobile: deepLink`,[{url:t.url,package:e}]);return}let n=t?.appBundleId??e;n&&await this.client.activateApp(n)}async openDevice(){await this.client.executeScript(`mobile: activateApp`,[{}])}async close(e){e&&await this.client.terminateApp(e)}async tap(e,t){return this.requireSupport(`tap`),await this.pointerGesture(`tap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async doubleTap(e,t){return this.requireSupport(`doubleTap`),await this.pointerGesture(`doubleTap`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0},{type:`pause`,duration:80},{type:`pointerDown`,button:0},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t}}async swipe(e,t,n,r,i=400){return this.requireSupport(`swipe`),await this.pointerGesture(`swipe`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pointerMove`,duration:i,x:n,y:r},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x1:e,y1:t,x2:n,y2:r,durationMs:i}}async longPress(e,t,n=600){return this.requireSupport(`longPress`),await this.pointerGesture(`longPress`,[{type:`pointerMove`,duration:0,x:e,y:t},{type:`pointerDown`,button:0},{type:`pause`,duration:n},{type:`pointerUp`,button:0}]),{backend:`webdriver`,x:e,y:t,durationMs:n}}async focus(e,t){return await this.tap(e,t)}async type(e){this.requireSupport(`type`),await this.client.sendKeys(e)}async fill(e,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new t(`UNSUPPORTED_OPERATION`,`fill with empty text (clear field) is not supported on the webdriver backend`,{hint:`Use a visible clear/reset control in the app, or fill the field with the intended replacement text directly.`});let a=await this.readTextEntryState();await this.tap(e,n);let o=await this.awaitTextEntryReadiness(a,e,n);return await this.type(r),{backend:`webdriver`,x:e,y:n,text:r,textEntryReadiness:o}}async scroll(e,t){this.requireSupport(`scroll`);let n=t?.durationMs??350;await this.client.hideKeyboard().catch(()=>void 0);let r=await this.scrollGestureFrame(),a=i({direction:e,amount:t?.amount,pixels:t?.pixels,referenceWidth:r.width,referenceHeight:r.height}),o={...a,x1:a.x1+r.x,y1:a.y1+r.y,x2:a.x2+r.x,y2:a.y2+r.y};return await this.swipe(o.x1,o.y1,o.x2,o.y2,n),{backend:`webdriver`,...o,distance:a.pixels,durationMs:n}}async gestureViewport(){return await this.scrollGestureFrame()}async performGesture(e){return this.requireSupport($e(e)),await this.client.performActions(e.pointers.map(e=>Y(`gesture-pointer-${e.pointerId}`,Qe(e.samples)))),await this.client.releaseActions().catch(()=>void 0),{backend:`webdriver-w3c-actions`}}async screenshot(e,t){this.requireSupport(`screenshot`),await this.client.screenshot(e)}async snapshot(e){return this.requireSupport(`snapshot`),await this.captureSource(e?.signal)}async captureSource(e){let t=this.backend===`android`?await this.readAndroidSnapshotViewport(e):void 0,n=await this.readSource(e);e?.throwIfAborted();let r=await this.readSnapshotKeyboardVisibility(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(n,this.targetId,r)}let{parseWebDriverAndroidSnapshotNodes:i}=await import(`./webdriver-android-source.js`),{acquireProviderKeyboard:a}=await import(`./tap-keyboard-occlusion.js`).then(e=>e.i),o=i(n),s=t===void 0?void 0:await this.readAndroidSnapshotViewport(e),c=t!==void 0&&s!==void 0&&t.width===s.width&&t.height===s.height?t:void 0;return{backend:`android`,producer:`appium-source`,...a({nodes:o,viewport:null,visibility:r}),...c===void 0?{}:{viewport:c}}}async readAndroidSnapshotViewport(e){try{let t=await this.client.windowRect({timeoutMs:500,retryAttempts:0,...e===void 0?{}:{signal:e}});return s(t)}catch{e?.throwIfAborted();return}}async readSnapshotKeyboardVisibility(e){try{let t=await this.client.isKeyboardShown(500,e);return e?.throwIfAborted(),t}catch{return e?.throwIfAborted(),`failed`}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw N(e)?et(e):e}}async back(e){this.requireSupport(`back`),await this.client.back()}async home(){this.requireSupport(`home`),await this.client.executeScript(`mobile: pressButton`,[{name:`home`}])}async setOrientation(e){this.requireSupport(`orientation`),await Ke(this.client,this.backend,e)}async appSwitcher(){this.requireSupport(`appSwitcher`),await this.client.executeScript(`mobile: pressButton`,[{name:`appSwitch`}])}async volumeUp(){this.requireSupport(`volumeUp`),await this.pressVolumeKey(24,`volumeup`)}async volumeDown(){this.requireSupport(`volumeDown`),await this.pressVolumeKey(25,`volumedown`)}async pressVolumeKey(e,t){if(this.backend===`android`){await this.client.executeScript(`mobile: pressKey`,[{keycode:e}]);return}await this.client.executeScript(`mobile: pressButton`,[{name:t}])}async power(){this.requireSupport(`power`),await this.client.executeScript(`mobile: pressKey`,[{keycode:26}])}async tvRemote(e,t){this.unsupported(`tvRemote`)}async keyboardStatus(){return this.requireSupport(`keyboard`),{kind:`ime-probe`,visible:await this.keyboardVisible()}}async keyboardDismiss(){this.requireSupport(`keyboard`);let e=await this.keyboardVisibility();if(e===!1)return this.dismissResult({wasVisible:e,visible:!1,dismissed:!1});await this.client.hideKeyboard();let t=await this.keyboardVisibilityAfterMutation();return this.dismissResult({...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t,dismissed:e===!0&&!t}})}dismissResult(e){return this.backend===`android`?{kind:`ime-probe`,...e}:{kind:`mechanism`,mechanism:`appium-hide-keyboard`,...e}}async keyboardEnter(){if(this.requireSupport(`keyboard`),this.backend===`android`)return await this.client.executeScript(`mobile: pressKey`,[{keycode:66}]),{kind:`android-acknowledged`};let e=await this.keyboardVisibility();await this.client.sendKeys(`
2
+ `);let t=await this.keyboardVisibilityAfterMutation();return{kind:`visibility-echo`,...e===void 0?{}:{wasVisible:e},...t===void 0?{}:{visible:t}}}async keyboardVisibilityAfterMutation(){try{return await this.keyboardVisibility()}catch{return}}async keyboardVisibility(){let e=await this.client.isKeyboardShown(Z);return e===`unsupported`?void 0:e}async keyboardVisible(){let e=await this.keyboardVisibility();if(e===void 0)throw new t(`UNSUPPORTED_OPERATION`,`This driver does not implement the keyboard visibility route.`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`keyboard`});return e}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeReadScript(`mobile: getClipboard`,[{}]);return typeof e==`string`?e:``}async writeClipboard(e){this.requireSupport(`clipboard.write`),await this.client.executeScript(`mobile: setClipboard`,[{content:e}])}async setSetting(e,t,n,r){this.unsupported(`settings`)}async awaitTextEntryReadiness(e,t,n){let r=e.keyboard,i=Date.now()+2e3,a=e.focusedElementId,o=await this.pollWithinBudget(i,async e=>{let r=await this.client.activeElement(e);return r===`unsupported`?`abandon`:r===`none`?`retry`:r.id!==a||Ye(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw Q(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw $(t,n);if(r)throw Q(t,n,`the keyboard was already up and this driver cannot report which field holds focus, so the text was not sent`);if(await this.pollWithinBudget(i,async e=>await this.client.isKeyboardShown(e)===!0?`satisfied`:`retry`)===`satisfied`)return`keyboard-shown`;throw Q(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(Z),this.client.activeElement(Z)]);return{keyboard:e,focusedElementId:t===`none`||t===`unsupported`?void 0:t.id}}async pollWithinBudget(e,t){let n=!1,r;for(;;){let i=e-Date.now();if(i<=0)break;try{let e=await t(Math.min(Z,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await Je(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([Y(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ue(e):He(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){u(this.capabilities,e)||this.unsupported(e)}unsupported(e){throw new t(`UNSUPPORTED_OPERATION`,ne(this.capabilities,e),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:e})}};function Qe(e){let n=e[0];if(!n)throw new t(`INVALID_ARGS`,`WebDriver gesture pointer requires samples`);let r=[{type:`pointerMove`,duration:0,x:n.point.x,y:n.point.y},{type:`pointerDown`,button:0}];for(let t=1;t<e.length;t+=1){let n=e[t-1],i=e[t];r.push({type:`pointerMove`,duration:i.offsetMs-n.offsetMs,x:i.point.x,y:i.point.y})}return r.push({type:`pointerUp`,button:0}),r}function $e(e){if(e.topology===`single`)return`swipe`;switch(e.intent){case`pan`:case`transform`:return`transformGesture`;case`pinch`:return`pinch`;case`rotate`:return`rotateGesture`;case`tap`:return`tapGesture`}}function et(e){return new t(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...e.details,hint:`A screen that never goes idle (looping video, live ticker, continuous animation) gives the driver no moment to read the UI tree. This read has the transport's own budget and does not grow with --timeout; take a screenshot, or drive the screen from refs an earlier snapshot already captured.`},e)}var tt=class{sessionsByLeaseId=new Map;ownedDeviceIds=new Set;releasedProviderSessionIdsByLeaseId=new Map;options;constructor(e){this.options=e}ownsDevice(e){return this.ownedDeviceIds.has(e.id)}findSessionForDevice(e){return[...this.sessionsByLeaseId.values()].find(t=>t.device.id===e.id)}findSessionForLease(e){return this.sessionsByLeaseId.get(e)}getInteractor(e){return this.findSessionForDevice(e)?.interactor}heartbeat(e){if(e.leaseProvider===this.options.provider&&this.sessionsByLeaseId.has(e.leaseId))return{provider:this.options.provider}}async allocate(e,t){if(e.leaseProvider!==this.options.provider)return;let{rejectRefusedProviderProfileFields:n}=await import(`./provider-profile-fields.js`).then(e=>e.t);if(n(t?.flags,this.options.profileFields),this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let r=await this.prepareSession(e,t),i=new Ie({clientVersion:this.options.clientVersion,endpoint:r.endpoint,auth:r.auth,headers:r.headers,requestPolicy:this.options.requestPolicy}),a=await this.createSessionWithPreparedCleanup(i,r,e,t),o=this.deviceForLease(e,r),s=r.providerSessionId??a.sessionId,c=d({provider:this.options.provider,platform:r.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:o,client:i,prepared:r,capabilities:c,webDriverSessionId:a.sessionId,providerSessionId:s,interactor:Xe({client:i,backend:te(r.platform),capabilities:c,targetId:o.id})})),this.ownedDeviceIds.add(o.id),{provider:this.options.provider,deviceId:o.id,sessionId:a.sessionId,providerSessionId:s,capabilities:c,...r.providerData}}async release(e){if(e.leaseProvider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId);if(!t)return;this.sessionsByLeaseId.delete(e.leaseId),this.releasedProviderSessionIdsByLeaseId.set(e.leaseId,t.providerSessionId);let n=await this.closeSession(t),r=await this.safeListArtifacts(t);return{provider:this.options.provider,providerSessionId:t.providerSessionId,...n.cleanup,...n.warnings.length>0?{warnings:n.warnings}:{},...r?{cloudArtifacts:r}:{}}}async listCloudArtifacts(e){if(e.provider!==this.options.provider)return;let t=this.sessionsByLeaseId.get(e.leaseId??``);return t?await this.listActiveCloudArtifacts(t,e.providerSessionId):await this.listReleasedCloudArtifacts(e)}async listActiveCloudArtifacts(e,t){if(!(t&&t!==e.providerSessionId))return await this.safeListArtifacts(e)}async listReleasedCloudArtifacts(e){let t=this.releasedProviderSessionIdsByLeaseId.get(e.leaseId??``);if(!(!t||!this.options.listArtifacts)&&!(e.providerSessionId&&e.providerSessionId!==t))return await this.options.listArtifacts({provider:this.options.provider,providerSessionId:t})}async shutdown(){await Promise.allSettled([...this.sessionsByLeaseId.values()].map(async e=>await this.closeSession(e))),this.sessionsByLeaseId.clear(),this.ownedDeviceIds.clear()}async createSessionWithPreparedCleanup(e,t,n,r){try{return await e.createSession(t.webdriverCapabilities,{deadline:r?.deadline})}catch(e){let r=N(e)?nt(e,this.options.provider,n,t):e;throw await b(r,()=>t.cleanup?.()),r}}async prepareSession(e,t){let n=this.baseSessionForLease(e);return this.options.prepareSession?await this.options.prepareSession({lease:e,req:t,base:n}):n}baseSessionForLease(e){let t=typeof this.options.webdriverCapabilities==`function`?this.options.webdriverCapabilities(e):this.options.webdriverCapabilities??{};return{provider:this.options.provider,endpoint:this.options.endpoint,platform:this.options.platform,deviceName:this.options.deviceName,auth:this.options.auth,headers:this.options.headers,webdriverCapabilities:ee(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...o(t.platform),...t.platform===`ios`?{appleOs:`ios`}:{},id:t.deviceId??this.options.deviceId?.(e)??`${this.options.provider}:${t.platform}:${e.leaseId}`,name:t.deviceName,kind:`device`,target:`mobile`,booted:!0}}async closeSession(e){let t=[],r;try{await e.client.deleteSession()}catch(e){t.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:n(e)})}try{r=await e.prepared.cleanup?.()}catch(e){t.push({code:`PROVIDER_CLEANUP_FAILED`,message:n(e)})}return{cleanup:r,warnings:t}}async safeListArtifacts(e){let t=e.prepared.listArtifacts??this.options.listArtifacts;if(t)try{return await t({provider:this.options.provider,lease:e.lease,device:e.device,webDriverSessionId:e.webDriverSessionId,providerSessionId:e.providerSessionId})}catch(t){return v({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function nt(e,n,r,i){let a=e.details?.timeoutMs;return new t(`COMMAND_FAILED`,`${n} did not create the WebDriver session within ${String(a)}ms.`,{reason:`provider_session_create_timeout`,provider:n,leaseId:r.leaseId,runId:r.runId,timeoutMs:a,...i.providerSessionId?{providerSessionId:i.providerSessionId}:{},hint:`${n} may still finish creating the session after agent-device stopped waiting, and that session would keep billing until the provider reaps it. Before retrying, check ${n} for a running session created for lease ${r.leaseId} (run ${r.runId}) and stop it.`},e)}var rt=e({createCloudWebDriverRuntime:()=>it});function it(e){return new at(e)}var at=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=c(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new tt(e),this.deployment=re({provider:e.provider,uploadApp:e.uploadApp,findSessionForDevice:e=>this.sessions.findSessionForDevice(e)}),this.platformRuntimeModule=Object.freeze({owner:this.owner,loadRuntime:async e=>await this.loadRuntime(e)}),this.leaseLifecycle={allocate:async(e,t)=>await this.sessions.allocate(e,t),heartbeat:async e=>this.sessions.heartbeat(e),release:async e=>await this.sessions.release(e)},this.cloudArtifacts={listCloudArtifacts:async e=>await this.sessions.listCloudArtifacts(e)},this.deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider)return null;if(!e.leaseId)return[];let t=this.sessions.findSessionForLease(e.leaseId);return t?[t.device]:[]}}async loadRuntime(e){let{createWebDriverPlatformRuntimeOwner:t}=await import(`./platform-runtime.js`);return t({host:e,owner:this.owner,ownsDevice:e=>this.ownsDevice(e),isSessionActive:e=>this.sessions.findSessionForDevice(e)!==void 0,deployment:this.deployment,capabilities:this.capabilities,snapshotAvailable:this.capabilities.operations.snapshot.support!==`unsupported`,screenshotAvailable:this.capabilities.operations.screenshot.support!==`unsupported`,getInteractor:e=>this.getInteractor(e)})}ownsDevice(e){return this.sessions.ownsDevice(e)}getInteractor(e){return this.sessions.getInteractor(e)}async installApp(e,t,n,r){return await this.deployment.installApp(e,t,n,r)}async installInstallablePath(e,t,n){return await this.deployment.installInstallablePath(e,t,n)}async shutdown(){await this.sessions.shutdown()}};export{pe as _,ge as a,_ as b,D as c,k as d,O as f,T as g,w as h,fe as i,b as l,ve as m,ue as n,he as o,E as p,ce as r,de as s,rt as t,A as u,j as v,ae as x,_e as y};
@@ -0,0 +1 @@
1
+ import{R as e}from"./sdk-contracts.js";import{a as t}from"./png-worker-contract.js";function n(e,n,a){a==null||a<=0||(t(e)?r(e,n,a):e[0]===255&&e[1]===216&&i(e,n,a))}function r(e,t,n){let r=8;for(;r+16<=e.length;){let i=e.readUInt32BE(r),a=e.toString(`ascii`,r+4,r+8);if(a===`IHDR`&&i>=8&&o(e.readUInt32BE(r+8),e.readUInt32BE(r+12),t,n),a===`IEND`)return;r+=i+12}}function i(e,t,n){for(let{marker:r,offset:i,length:s}of a(e))[192,193,194].includes(r)&&s>=8&&o(e.readUInt16BE(i+5),e.readUInt16BE(i+3),t,n)}function*a(e){let t=2;for(;t+3<e.length&&e[t]===255;){for(;e[t]===255;)t+=1;let n=e[t++];if(n===218||n===217||t+2>e.length)return;let r=e.readUInt16BE(t);if(r<2||t+r>e.length)return;yield{marker:n,offset:t,length:r},t+=r}}function o(t,n,r,i){let a=t*n;if(!Number.isSafeInteger(a)||a<1||i!=null&&i>0&&a>i)throw new e(`INVALID_ARGS`,`${r} is ${a} pixels, which exceeds the configured maxImagePixels limit of ${i}`)}export{n as validateScreenshotImagePixels,o as validateScreenshotPixels};
@@ -1 +1 @@
1
- import{t as e}from"./rolldown-runtime.js";import{R as t}from"./sdk-contracts.js";import{a as n,i as r,o as i}from"./png-worker-contract.js";var a=e(((e,t)=>{function n(e){var n=Math.floor,r=Array(64),i=Array(64),a=Array(64),o=Array(64),s,c,l,u,d=Array(65535),f=Array(65535),p=Array(64),m=Array(64),h=[],g=0,_=7,v=Array(64),y=Array(64),b=Array(64),x=Array(256),S=Array(2048),C,w=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],T=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],E=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],O=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],k=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],j=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],M=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function N(e){for(var t=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],s=0;s<64;s++){var c=n((t[s]*e+50)/100);c<1?c=1:c>255&&(c=255),r[w[s]]=c}for(var l=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],u=0;u<64;u++){var d=n((l[u]*e+50)/100);d<1?d=1:d>255&&(d=255),i[w[u]]=d}for(var f=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],p=0,m=0;m<8;m++)for(var h=0;h<8;h++)a[p]=1/(r[w[p]]*f[m]*f[h]*8),o[p]=1/(i[w[p]]*f[m]*f[h]*8),p++}function P(e,t){for(var n=0,r=0,i=[],a=1;a<=16;a++){for(var o=1;o<=e[a];o++)i[t[r]]=[],i[t[r]][0]=n,i[t[r]][1]=a,r++,n++;n*=2}return i}function F(){s=P(T,E),c=P(k,A),l=P(D,O),u=P(j,M)}function I(){for(var e=1,t=2,n=1;n<=15;n++){for(var r=e;r<t;r++)f[32767+r]=n,d[32767+r]=[],d[32767+r][1]=n,d[32767+r][0]=r;for(var i=-(t-1);i<=-e;i++)f[32767+i]=n,d[32767+i]=[],d[32767+i][1]=n,d[32767+i][0]=t-1+i;e<<=1,t<<=1}}function L(){for(var e=0;e<256;e++)S[e]=19595*e,S[e+256>>0]=38470*e,S[e+512>>0]=7471*e+32768,S[e+768>>0]=-11059*e,S[e+1024>>0]=-21709*e,S[e+1280>>0]=32768*e+8421375,S[e+1536>>0]=-27439*e,S[e+1792>>0]=-5329*e}function R(e){for(var t=e[0],n=e[1]-1;n>=0;)t&1<<n&&(g|=1<<_),n--,_--,_<0&&(g==255?(z(255),z(0)):z(g),_=7,g=0)}function z(e){h.push(e)}function B(e){z(e>>8&255),z(e&255)}function V(e,t){var n,r,i,a,o,s,c,l,u=0,d,f=8,m=64;for(d=0;d<f;++d){n=e[u],r=e[u+1],i=e[u+2],a=e[u+3],o=e[u+4],s=e[u+5],c=e[u+6],l=e[u+7];var h=n+l,g=n-l,_=r+c,v=r-c,y=i+s,b=i-s,x=a+o,S=a-o,C=h+x,w=h-x,T=_+y,E=_-y;e[u]=C+T,e[u+4]=C-T;var D=(E+w)*.707106781;e[u+2]=w+D,e[u+6]=w-D,C=S+b,T=b+v,E=v+g;var O=(C-E)*.382683433,k=.5411961*C+O,A=1.306562965*E+O,j=T*.707106781,M=g+j,N=g-j;e[u+5]=N+k,e[u+3]=N-k,e[u+1]=M+A,e[u+7]=M-A,u+=8}for(u=0,d=0;d<f;++d){n=e[u],r=e[u+8],i=e[u+16],a=e[u+24],o=e[u+32],s=e[u+40],c=e[u+48],l=e[u+56];var P=n+l,F=n-l,I=r+c,L=r-c,R=i+s,z=i-s,B=a+o,V=a-o,H=P+B,U=P-B,W=I+R,G=I-R;e[u]=H+W,e[u+32]=H-W;var K=(G+U)*.707106781;e[u+16]=U+K,e[u+48]=U-K,H=V+z,W=z+L,G=L+F;var q=(H-G)*.382683433,J=.5411961*H+q,Y=1.306562965*G+q,X=W*.707106781,Z=F+X,Q=F-X;e[u+40]=Q+J,e[u+24]=Q-J,e[u+8]=Z+Y,e[u+56]=Z-Y,u++}var $;for(d=0;d<m;++d)$=e[d]*t[d],p[d]=$>0?$+.5|0:$-.5|0;return p}function H(){B(65504),B(16),z(74),z(70),z(73),z(70),z(0),z(1),z(1),z(0),B(1),B(1),z(0),z(0)}function U(e){if(e){B(65505),e[0]===69&&e[1]===120&&e[2]===105&&e[3]===102?B(e.length+2):(B(e.length+5+2),z(69),z(120),z(105),z(102),z(0));for(var t=0;t<e.length;t++)z(e[t])}}function W(e,t){B(65472),B(17),z(8),B(t),B(e),z(3),z(1),z(17),z(0),z(2),z(17),z(1),z(3),z(17),z(1)}function G(){B(65499),B(132),z(0);for(var e=0;e<64;e++)z(r[e]);z(1);for(var t=0;t<64;t++)z(i[t])}function K(){B(65476),B(418),z(0);for(var e=0;e<16;e++)z(T[e+1]);for(var t=0;t<=11;t++)z(E[t]);z(16);for(var n=0;n<16;n++)z(D[n+1]);for(var r=0;r<=161;r++)z(O[r]);z(1);for(var i=0;i<16;i++)z(k[i+1]);for(var a=0;a<=11;a++)z(A[a]);z(17);for(var o=0;o<16;o++)z(j[o+1]);for(var s=0;s<=161;s++)z(M[s])}function q(e){e!==void 0&&e.constructor===Array&&e.forEach(e=>{if(typeof e==`string`){B(65534);var t=e.length;B(t+2);var n;for(n=0;n<t;n++)z(e.charCodeAt(n))}})}function J(){B(65498),B(12),z(3),z(1),z(0),z(2),z(17),z(3),z(17),z(0),z(63),z(0)}function Y(e,t,n,r,i){for(var a=i[0],o=i[240],s,c=16,l=63,u=64,p=V(e,t),h=0;h<u;++h)m[w[h]]=p[h];var g=m[0]-n;n=m[0],g==0?R(r[0]):(s=32767+g,R(r[f[s]]),R(d[s]));for(var _=63;_>0&&m[_]==0;_--);if(_==0)return R(a),n;for(var v=1,y;v<=_;){for(var b=v;m[v]==0&&v<=_;++v);var x=v-b;if(x>=c){y=x>>4;for(var S=1;S<=y;++S)R(o);x&=15}s=32767+m[v],R(i[(x<<4)+f[s]]),R(d[s]),v++}return _!=l&&R(a),n}function X(){for(var e=String.fromCharCode,t=0;t<256;t++)x[t]=e(t)}this.encode=function(e,n){new Date().getTime(),n&&Z(n),h=[],g=0,_=7,B(65496),H(),q(e.comments),U(e.exifBuffer),G(),W(e.width,e.height),K(),J();var r=0,i=0,d=0;g=0,_=7,this.encode.displayName=`_encode_`;var f=e.data,p=e.width,m=e.height,x=p*4;p*3;for(var C,w=0,T,E,D,O,k,A,j,M;w<m;){for(C=0;C<x;){for(O=x*w+C,k=O,A=-1,j=0,M=0;M<64;M++)j=M>>3,A=(M&7)*4,k=O+j*x+A,w+j>=m&&(k-=x*(w+1+j-m)),C+A>=x&&(k-=C+A-x+4),T=f[k++],E=f[k++],D=f[k++],v[M]=(S[T]+S[E+256>>0]+S[D+512>>0]>>16)-128,y[M]=(S[T+768>>0]+S[E+1024>>0]+S[D+1280>>0]>>16)-128,b[M]=(S[T+1280>>0]+S[E+1536>>0]+S[D+1792>>0]>>16)-128;r=Y(v,a,r,s,l),i=Y(y,o,i,c,u),d=Y(b,o,d,c,u),C+=32}w+=8}if(_>=0){var N=[];N[1]=_+1,N[0]=(1<<_+1)-1,R(N)}return B(65497),t===void 0?new Uint8Array(h):Buffer.from(h)};function Z(e){if(e<=0&&(e=1),e>100&&(e=100),C!=e){var t=0;t=Math.floor(e<50?5e3/e:200-e*2),N(t),C=e}}function Q(){var t=new Date().getTime();e||=50,X(),F(),I(),L(),Z(e),new Date().getTime()-t}Q()}t===void 0?typeof window<`u`&&(window[`jpeg-js`]=window[`jpeg-js`]||{},window[`jpeg-js`].encode=r):t.exports=r;function r(e,t){return t===void 0&&(t=50),{data:new n(t).encode(e,t),width:e.width,height:e.height}}})),o=e(((e,t)=>{var n=(function(){var e=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,n=799,r=3406,i=2276,a=1567,o=3784,s=5793,c=2896;function l(){}function u(e,t){for(var n=0,r=[],i,a,o=16;o>0&&!e[o-1];)o--;r.push({children:[],index:0});var s=r[0],c;for(i=0;i<o;i++){for(a=0;a<e[i];a++){for(s=r.pop(),s.children[s.index]=t[n];s.index>0;){if(r.length===0)throw Error(`Could not recreate Huffman Table`);s=r.pop()}for(s.index++,r.push(s);r.length<=i;)r.push(c={children:[],index:0}),s.children[s.index]=c.children,s=c;n++}i+1<o&&(r.push(c={children:[],index:0}),s.children[s.index]=c.children,s=c)}return r[0].children}function d(t,n,r,i,a,o,s,c,l,u){r.precision,r.samplesPerLine,r.scanLines;var d=r.mcusPerLine,f=r.progressive;r.maxH,r.maxV;var p=n,m=0,h=0;function g(){if(h>0)return h--,m>>h&1;if(m=t[n++],m==255){var e=t[n++];if(e)throw Error(`unexpected marker: `+(m<<8|e).toString(16))}return h=7,m>>>7}function _(e){for(var t=e,n;(n=g())!==null;){if(t=t[n],typeof t==`number`)return t;if(typeof t!=`object`)throw Error(`invalid huffman sequence`)}return null}function v(e){for(var t=0;e>0;){var n=g();if(n===null)return;t=t<<1|n,e--}return t}function y(e){var t=v(e);return t>=1<<e-1?t:t+(-1<<e)+1}function b(t,n){var r=_(t.huffmanTableDC),i=r===0?0:y(r);n[0]=t.pred+=i;for(var a=1;a<64;){var o=_(t.huffmanTableAC),s=o&15,c=o>>4;if(s===0){if(c<15)break;a+=16;continue}a+=c;var l=e[a];n[l]=y(s),a++}}function x(e,t){var n=_(e.huffmanTableDC),r=n===0?0:y(n)<<l;t[0]=e.pred+=r}function S(e,t){t[0]|=g()<<l}var C=0;function w(t,n){if(C>0){C--;return}for(var r=o,i=s;r<=i;){var a=_(t.huffmanTableAC),c=a&15,u=a>>4;if(c===0){if(u<15){C=v(u)+(1<<u)-1;break}r+=16;continue}r+=u;var d=e[r];n[d]=y(c)*(1<<l),r++}}var T=0,E;function D(t,n){for(var r=o,i=s,a=0;r<=i;){var c=e[r],u=n[c]<0?-1:1;switch(T){case 0:var d=_(t.huffmanTableAC),f=d&15,a=d>>4;if(f===0)a<15?(C=v(a)+(1<<a),T=4):(a=16,T=1);else{if(f!==1)throw Error(`invalid ACn encoding`);E=y(f),T=a?2:3}continue;case 1:case 2:n[c]?n[c]+=(g()<<l)*u:(a--,a===0&&(T=T==2?3:0));break;case 3:n[c]?n[c]+=(g()<<l)*u:(n[c]=E<<l,T=0);break;case 4:n[c]&&(n[c]+=(g()<<l)*u)}r++}T===4&&(C--,C===0&&(T=0))}function O(e,t,n,r,i){var a=n/d|0,o=n%d,s=a*e.v+r,c=o*e.h+i;e.blocks[s]===void 0&&u.tolerantDecoding||t(e,e.blocks[s][c])}function k(e,t,n){var r=n/e.blocksPerLine|0,i=n%e.blocksPerLine;e.blocks[r]===void 0&&u.tolerantDecoding||t(e,e.blocks[r][i])}var A=i.length,j,M,N,P,F,I=f?o===0?c===0?x:S:c===0?w:D:b,L=0,R,z=A==1?i[0].blocksPerLine*i[0].blocksPerColumn:d*r.mcusPerColumn;a||=z;for(var B,V;L<z;){for(M=0;M<A;M++)i[M].pred=0;if(C=0,A==1)for(j=i[0],F=0;F<a;F++)k(j,I,L),L++;else for(F=0;F<a;F++){for(M=0;M<A;M++)for(j=i[M],B=j.h,V=j.v,N=0;N<V;N++)for(P=0;P<B;P++)O(j,I,L,N,P);if(L++,L===z)break}if(L===z)do{if(t[n]===255&&t[n+1]!==0)break;n+=1}while(n<t.length-2);if(h=0,R=t[n]<<8|t[n+1],R<65280)throw Error(`marker was not found`);if(R>=65488&&R<=65495)n+=2;else break}return n-p}function f(e,l){var u=[],d=l.blocksPerLine,f=l.blocksPerColumn,p=d<<3,m=new Int32Array(64),h=new Uint8Array(64);function _(e,u,d){var f=l.quantizationTable,p,m,h,g,_,v,y,b,x,S=d,C;for(C=0;C<64;C++)S[C]=e[C]*f[C];for(C=0;C<8;++C){var w=8*C;if(S[1+w]==0&&S[2+w]==0&&S[3+w]==0&&S[4+w]==0&&S[5+w]==0&&S[6+w]==0&&S[7+w]==0){x=s*S[0+w]+512>>10,S[0+w]=x,S[1+w]=x,S[2+w]=x,S[3+w]=x,S[4+w]=x,S[5+w]=x,S[6+w]=x,S[7+w]=x;continue}p=s*S[0+w]+128>>8,m=s*S[4+w]+128>>8,h=S[2+w],g=S[6+w],_=c*(S[1+w]-S[7+w])+128>>8,b=c*(S[1+w]+S[7+w])+128>>8,v=S[3+w]<<4,y=S[5+w]<<4,x=p-m+1>>1,p=p+m+1>>1,m=x,x=h*o+g*a+128>>8,h=h*a-g*o+128>>8,g=x,x=_-y+1>>1,_=_+y+1>>1,y=x,x=b+v+1>>1,v=b-v+1>>1,b=x,x=p-g+1>>1,p=p+g+1>>1,g=x,x=m-h+1>>1,m=m+h+1>>1,h=x,x=_*i+b*r+2048>>12,_=_*r-b*i+2048>>12,b=x,x=v*n+y*t+2048>>12,v=v*t-y*n+2048>>12,y=x,S[0+w]=p+b,S[7+w]=p-b,S[1+w]=m+y,S[6+w]=m-y,S[2+w]=h+v,S[5+w]=h-v,S[3+w]=g+_,S[4+w]=g-_}for(C=0;C<8;++C){var T=C;if(S[8+T]==0&&S[16+T]==0&&S[24+T]==0&&S[32+T]==0&&S[40+T]==0&&S[48+T]==0&&S[56+T]==0){x=s*d[C+0]+8192>>14,S[0+T]=x,S[8+T]=x,S[16+T]=x,S[24+T]=x,S[32+T]=x,S[40+T]=x,S[48+T]=x,S[56+T]=x;continue}p=s*S[0+T]+2048>>12,m=s*S[32+T]+2048>>12,h=S[16+T],g=S[48+T],_=c*(S[8+T]-S[56+T])+2048>>12,b=c*(S[8+T]+S[56+T])+2048>>12,v=S[24+T],y=S[40+T],x=p-m+1>>1,p=p+m+1>>1,m=x,x=h*o+g*a+2048>>12,h=h*a-g*o+2048>>12,g=x,x=_-y+1>>1,_=_+y+1>>1,y=x,x=b+v+1>>1,v=b-v+1>>1,b=x,x=p-g+1>>1,p=p+g+1>>1,g=x,x=m-h+1>>1,m=m+h+1>>1,h=x,x=_*i+b*r+2048>>12,_=_*r-b*i+2048>>12,b=x,x=v*n+y*t+2048>>12,v=v*t-y*n+2048>>12,y=x,S[0+T]=p+b,S[56+T]=p-b,S[8+T]=m+y,S[48+T]=m-y,S[16+T]=h+v,S[40+T]=h-v,S[24+T]=g+_,S[32+T]=g-_}for(C=0;C<64;++C){var E=128+(S[C]+8>>4);u[C]=E<0?0:E>255?255:E}}g(p*f*8);for(var v,y,b=0;b<f;b++){var x=b<<3;for(v=0;v<8;v++)u.push(new Uint8Array(p));for(var S=0;S<d;S++){_(l.blocks[b][S],h,m);var C=0,w=S<<3;for(y=0;y<8;y++){var T=u[x+y];for(v=0;v<8;v++)T[w+v]=h[C++]}}}return u}function p(e){return e<0?0:e>255?255:e}l.prototype={load:function(e){var t=new XMLHttpRequest;t.open(`GET`,e,!0),t.responseType=`arraybuffer`,t.onload=(function(){var e=new Uint8Array(t.response||t.mozResponseArrayBuffer);this.parse(e),this.onload&&this.onload()}).bind(this),t.send(null)},parse:function(t){var n=this.opts.maxResolutionInMP*1e3*1e3,r=0;t.length;function i(){var e=t[r]<<8|t[r+1];return r+=2,e}function a(){var e=i(),n=t.subarray(r,r+e-2);return r+=n.length,n}function o(e){var t=1,n=1,r,i;for(i in e.components)e.components.hasOwnProperty(i)&&(r=e.components[i],t<r.h&&(t=r.h),n<r.v&&(n=r.v));var a=Math.ceil(e.samplesPerLine/8/t),o=Math.ceil(e.scanLines/8/n);for(i in e.components)if(e.components.hasOwnProperty(i)){r=e.components[i];var s=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/t),c=Math.ceil(Math.ceil(e.scanLines/8)*r.v/n),l=a*r.h,u=o*r.v,d=u*l,f=[];g(d*256);for(var p=0;p<u;p++){for(var m=[],h=0;h<l;h++)m.push(new Int32Array(64));f.push(m)}r.blocksPerLine=s,r.blocksPerColumn=c,r.blocks=f}e.maxH=t,e.maxV=n,e.mcusPerLine=a,e.mcusPerColumn=o}var s=null,c=null,l,p,m=[],h=[],_=[],v=[],y=i(),b=-1;if(this.comments=[],y!=65496)throw Error(`SOI not found`);for(y=i();y!=65497;){var x,S;switch(y){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var C=a();if(y===65534){var w=String.fromCharCode.apply(null,C);this.comments.push(w)}y===65504&&C[0]===74&&C[1]===70&&C[2]===73&&C[3]===70&&C[4]===0&&(s={version:{major:C[5],minor:C[6]},densityUnits:C[7],xDensity:C[8]<<8|C[9],yDensity:C[10]<<8|C[11],thumbWidth:C[12],thumbHeight:C[13],thumbData:C.subarray(14,14+3*C[12]*C[13])}),y===65505&&C[0]===69&&C[1]===120&&C[2]===105&&C[3]===102&&C[4]===0&&(this.exifBuffer=C.subarray(5,C.length)),y===65518&&C[0]===65&&C[1]===100&&C[2]===111&&C[3]===98&&C[4]===101&&C[5]===0&&(c={version:C[6],flags0:C[7]<<8|C[8],flags1:C[9]<<8|C[10],transformCode:C[11]});break;case 65499:for(var T=i()+r-2;r<T;){var E=t[r++];g(256);var D=new Int32Array(64);if(!(E>>4))for(S=0;S<64;S++){var O=e[S];D[O]=t[r++]}else if(E>>4==1)for(S=0;S<64;S++){var O=e[S];D[O]=i()}else throw Error(`DQT: invalid table spec`);m[E&15]=D}break;case 65472:case 65473:case 65474:i(),l={},l.extended=y===65473,l.progressive=y===65474,l.precision=t[r++],l.scanLines=i(),l.samplesPerLine=i(),l.components={},l.componentsOrder=[];var k=l.scanLines*l.samplesPerLine;if(k>n){var A=Math.ceil((k-n)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${A}MP`)}var j=t[r++],M;for(x=0;x<j;x++){M=t[r];var N=t[r+1]>>4,P=t[r+1]&15,F=t[r+2];if(N<=0||P<=0)throw Error(`Invalid sampling factor, expected values above 0`);l.componentsOrder.push(M),l.components[M]={h:N,v:P,quantizationIdx:F},r+=3}o(l),h.push(l);break;case 65476:var I=i();for(x=2;x<I;){var L=t[r++],R=new Uint8Array(16),z=0;for(S=0;S<16;S++,r++)z+=R[S]=t[r];g(16+z);var B=new Uint8Array(z);for(S=0;S<z;S++,r++)B[S]=t[r];x+=17+z,(L>>4?_:v)[L&15]=u(R,B)}break;case 65501:i(),p=i();break;case 65500:i(),i();break;case 65498:i();var V=t[r++],H=[],U;for(x=0;x<V;x++){U=l.components[t[r++]];var W=t[r++];U.huffmanTableDC=v[W>>4],U.huffmanTableAC=_[W&15],H.push(U)}var G=t[r++],K=t[r++],q=t[r++],J=d(t,r,l,H,p,G,K,q>>4,q&15,this.opts);r+=J;break;case 65535:t[r]!==255&&r--;break;default:if(t[r-3]==255&&t[r-2]>=192&&t[r-2]<=254){r-=3;break}if(y===224||y==225){if(b!==-1)throw Error(`first unknown JPEG marker at offset ${b.toString(16)}, second unknown JPEG marker ${y.toString(16)} at offset ${(r-1).toString(16)}`);b=r-1;let e=i();if(t[r+e-2]===255){r+=e-2;break}}throw Error(`unknown JPEG marker `+y.toString(16))}y=i()}if(h.length!=1)throw Error(`only single frame JPEGs supported`);for(var x=0;x<h.length;x++){var Y=h[x].components;for(var S in Y)Y[S].quantizationTable=m[Y[S].quantizationIdx],delete Y[S].quantizationIdx}this.width=l.samplesPerLine,this.height=l.scanLines,this.jfif=s,this.adobe=c,this.components=[];for(var x=0;x<l.componentsOrder.length;x++){var U=l.components[l.componentsOrder[x]];this.components.push({lines:f(l,U),scaleX:U.h/l.maxH,scaleY:U.v/l.maxV})}},getData:function(e,t){var n=this.width/e,r=this.height/t,i,a,o,s,c,l,u,d,f,m,h=0,_,v,y,b,x,S,C,w,T,E,D,O=e*t*this.components.length;g(O);var k=new Uint8Array(O);switch(this.components.length){case 1:for(i=this.components[0],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],f=0;f<e;f++)_=c[0|f*i.scaleX*n],k[h++]=_;break;case 2:for(i=this.components[0],a=this.components[1],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],f=0;f<e;f++)_=c[0|f*i.scaleX*n],k[h++]=_,_=l[0|f*a.scaleX*n],k[h++]=_;break;case 3:for(D=!0,this.adobe&&this.adobe.transformCode?D=!0:this.opts.colorTransform!==void 0&&(D=!!this.opts.colorTransform),i=this.components[0],a=this.components[1],o=this.components[2],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],u=o.lines[0|m*o.scaleY*r],f=0;f<e;f++)D?(_=c[0|f*i.scaleX*n],v=l[0|f*a.scaleX*n],y=u[0|f*o.scaleX*n],w=p(_+1.402*(y-128)),T=p(_-.3441363*(v-128)-.71413636*(y-128)),E=p(_+1.772*(v-128))):(w=c[0|f*i.scaleX*n],T=l[0|f*a.scaleX*n],E=u[0|f*o.scaleX*n]),k[h++]=w,k[h++]=T,k[h++]=E;break;case 4:if(!this.adobe)throw Error(`Unsupported color mode (4 components)`);for(D=!1,this.adobe&&this.adobe.transformCode?D=!0:this.opts.colorTransform!==void 0&&(D=!!this.opts.colorTransform),i=this.components[0],a=this.components[1],o=this.components[2],s=this.components[3],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],u=o.lines[0|m*o.scaleY*r],d=s.lines[0|m*s.scaleY*r],f=0;f<e;f++)D?(_=c[0|f*i.scaleX*n],v=l[0|f*a.scaleX*n],y=u[0|f*o.scaleX*n],b=d[0|f*s.scaleX*n],x=255-p(_+1.402*(y-128)),S=255-p(_-.3441363*(v-128)-.71413636*(y-128)),C=255-p(_+1.772*(v-128))):(x=c[0|f*i.scaleX*n],S=l[0|f*a.scaleX*n],C=u[0|f*o.scaleX*n],b=d[0|f*s.scaleX*n]),k[h++]=255-x,k[h++]=255-S,k[h++]=255-C,k[h++]=255-b;break;default:throw Error(`Unsupported color mode`)}return k},copyToImageData:function(e,t){var n=e.width,r=e.height,i=e.data,a=this.getData(n,r),o=0,s=0,c,l,u,d,f,m,h,g,_;switch(this.components.length){case 1:for(l=0;l<r;l++)for(c=0;c<n;c++)u=a[o++],i[s++]=u,i[s++]=u,i[s++]=u,t&&(i[s++]=255);break;case 3:for(l=0;l<r;l++)for(c=0;c<n;c++)h=a[o++],g=a[o++],_=a[o++],i[s++]=h,i[s++]=g,i[s++]=_,t&&(i[s++]=255);break;case 4:for(l=0;l<r;l++)for(c=0;c<n;c++)f=a[o++],m=a[o++],u=a[o++],d=a[o++],h=255-p(f*(1-d/255)+d),g=255-p(m*(1-d/255)+d),_=255-p(u*(1-d/255)+d),i[s++]=h,i[s++]=g,i[s++]=_,t&&(i[s++]=255);break;default:throw Error(`Unsupported color mode`)}}};var m=0,h=0;function g(e=0){var t=m+e;if(t>h){var n=Math.ceil((t-h)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${n}MB`)}m=t}return l.resetMaxMemoryUsage=function(e){m=0,h=e},l.getBytesAllocated=function(){return m},l.requestMemoryAllocation=g,l})();t===void 0?typeof window<`u`&&(window[`jpeg-js`]=window[`jpeg-js`]||{},window[`jpeg-js`].decode=r):t.exports=r;function r(e,t={}){var r={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512,...t},i=new Uint8Array(e),a=new n;a.opts=r,n.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),a.parse(i);var o=r.formatAsRGBA?4:3,s=a.width*a.height*o;try{n.requestMemoryAllocation(s);var c={width:a.width,height:a.height,exifBuffer:a.exifBuffer,data:r.useTArray?new Uint8Array(s):Buffer.alloc(s)};a.comments.length>0&&(c.comments=a.comments)}catch(e){throw e instanceof RangeError?Error(`Could not allocate enough memory for the image. Required: `+s):e instanceof ReferenceError&&e.message===`Buffer is not defined`?Error(`Buffer is not globally defined in this environment. Consider setting useTArray to true`):e}return a.copyToImageData(c,r.formatAsRGBA),c}})),s=e(((e,t)=>{t.exports={encode:a(),decode:o()}}))();const c=Buffer.from([255,216,255]);function l(e){if(n(e))return`png`;if(e.subarray(0,c.length).equals(c))return`jpeg`}function u(e,t){let n=l(e);if(n===`png`)return r(e,t);if(n===`jpeg`)return f(e,t);throw p(t,e)}function d(e,t){let n=l(e);if(n===`png`)return e;if(n===`jpeg`)return i.PNG.sync.write(f(e,t));throw p(t,e)}function f(e,n){try{let t=(0,s.decode)(e,{useTArray:!0,formatAsRGBA:!0}),n=new i.PNG({width:t.width,height:t.height});return n.data=Buffer.from(t.data.buffer,t.data.byteOffset,t.data.byteLength),n}catch(e){throw new t(`COMMAND_FAILED`,`Failed to decode ${n} as JPEG`,{label:n,reason:e instanceof Error?e.message:String(e)})}}function p(e,n){return new t(`COMMAND_FAILED`,`${e} is neither PNG nor JPEG`,{label:e,leadingBytes:n.subarray(0,4).toString(`hex`)})}export{u as decodeScreenshotImage,d as transcodeScreenshotToPng};
1
+ import{t as e}from"./rolldown-runtime.js";import{R as t}from"./sdk-contracts.js";import{a as n,i as r,o as i}from"./png-worker-contract.js";import{validateScreenshotImagePixels as a}from"./screenshot-image-size.js";var o=e(((e,t)=>{function n(e){var n=Math.floor,r=Array(64),i=Array(64),a=Array(64),o=Array(64),s,c,l,u,d=Array(65535),f=Array(65535),p=Array(64),m=Array(64),h=[],g=0,_=7,v=Array(64),y=Array(64),b=Array(64),x=Array(256),S=Array(2048),C,w=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],T=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],E=[0,1,2,3,4,5,6,7,8,9,10,11],D=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],O=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],k=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],A=[0,1,2,3,4,5,6,7,8,9,10,11],j=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],M=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function N(e){for(var t=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],s=0;s<64;s++){var c=n((t[s]*e+50)/100);c<1?c=1:c>255&&(c=255),r[w[s]]=c}for(var l=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],u=0;u<64;u++){var d=n((l[u]*e+50)/100);d<1?d=1:d>255&&(d=255),i[w[u]]=d}for(var f=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],p=0,m=0;m<8;m++)for(var h=0;h<8;h++)a[p]=1/(r[w[p]]*f[m]*f[h]*8),o[p]=1/(i[w[p]]*f[m]*f[h]*8),p++}function P(e,t){for(var n=0,r=0,i=[],a=1;a<=16;a++){for(var o=1;o<=e[a];o++)i[t[r]]=[],i[t[r]][0]=n,i[t[r]][1]=a,r++,n++;n*=2}return i}function F(){s=P(T,E),c=P(k,A),l=P(D,O),u=P(j,M)}function I(){for(var e=1,t=2,n=1;n<=15;n++){for(var r=e;r<t;r++)f[32767+r]=n,d[32767+r]=[],d[32767+r][1]=n,d[32767+r][0]=r;for(var i=-(t-1);i<=-e;i++)f[32767+i]=n,d[32767+i]=[],d[32767+i][1]=n,d[32767+i][0]=t-1+i;e<<=1,t<<=1}}function L(){for(var e=0;e<256;e++)S[e]=19595*e,S[e+256>>0]=38470*e,S[e+512>>0]=7471*e+32768,S[e+768>>0]=-11059*e,S[e+1024>>0]=-21709*e,S[e+1280>>0]=32768*e+8421375,S[e+1536>>0]=-27439*e,S[e+1792>>0]=-5329*e}function R(e){for(var t=e[0],n=e[1]-1;n>=0;)t&1<<n&&(g|=1<<_),n--,_--,_<0&&(g==255?(z(255),z(0)):z(g),_=7,g=0)}function z(e){h.push(e)}function B(e){z(e>>8&255),z(e&255)}function V(e,t){var n,r,i,a,o,s,c,l,u=0,d,f=8,m=64;for(d=0;d<f;++d){n=e[u],r=e[u+1],i=e[u+2],a=e[u+3],o=e[u+4],s=e[u+5],c=e[u+6],l=e[u+7];var h=n+l,g=n-l,_=r+c,v=r-c,y=i+s,b=i-s,x=a+o,S=a-o,C=h+x,w=h-x,T=_+y,E=_-y;e[u]=C+T,e[u+4]=C-T;var D=(E+w)*.707106781;e[u+2]=w+D,e[u+6]=w-D,C=S+b,T=b+v,E=v+g;var O=(C-E)*.382683433,k=.5411961*C+O,A=1.306562965*E+O,j=T*.707106781,M=g+j,N=g-j;e[u+5]=N+k,e[u+3]=N-k,e[u+1]=M+A,e[u+7]=M-A,u+=8}for(u=0,d=0;d<f;++d){n=e[u],r=e[u+8],i=e[u+16],a=e[u+24],o=e[u+32],s=e[u+40],c=e[u+48],l=e[u+56];var P=n+l,F=n-l,I=r+c,L=r-c,R=i+s,z=i-s,B=a+o,V=a-o,H=P+B,U=P-B,W=I+R,G=I-R;e[u]=H+W,e[u+32]=H-W;var K=(G+U)*.707106781;e[u+16]=U+K,e[u+48]=U-K,H=V+z,W=z+L,G=L+F;var q=(H-G)*.382683433,J=.5411961*H+q,Y=1.306562965*G+q,X=W*.707106781,Z=F+X,Q=F-X;e[u+40]=Q+J,e[u+24]=Q-J,e[u+8]=Z+Y,e[u+56]=Z-Y,u++}var $;for(d=0;d<m;++d)$=e[d]*t[d],p[d]=$>0?$+.5|0:$-.5|0;return p}function H(){B(65504),B(16),z(74),z(70),z(73),z(70),z(0),z(1),z(1),z(0),B(1),B(1),z(0),z(0)}function U(e){if(e){B(65505),e[0]===69&&e[1]===120&&e[2]===105&&e[3]===102?B(e.length+2):(B(e.length+5+2),z(69),z(120),z(105),z(102),z(0));for(var t=0;t<e.length;t++)z(e[t])}}function W(e,t){B(65472),B(17),z(8),B(t),B(e),z(3),z(1),z(17),z(0),z(2),z(17),z(1),z(3),z(17),z(1)}function G(){B(65499),B(132),z(0);for(var e=0;e<64;e++)z(r[e]);z(1);for(var t=0;t<64;t++)z(i[t])}function K(){B(65476),B(418),z(0);for(var e=0;e<16;e++)z(T[e+1]);for(var t=0;t<=11;t++)z(E[t]);z(16);for(var n=0;n<16;n++)z(D[n+1]);for(var r=0;r<=161;r++)z(O[r]);z(1);for(var i=0;i<16;i++)z(k[i+1]);for(var a=0;a<=11;a++)z(A[a]);z(17);for(var o=0;o<16;o++)z(j[o+1]);for(var s=0;s<=161;s++)z(M[s])}function q(e){e!==void 0&&e.constructor===Array&&e.forEach(e=>{if(typeof e==`string`){B(65534);var t=e.length;B(t+2);var n;for(n=0;n<t;n++)z(e.charCodeAt(n))}})}function J(){B(65498),B(12),z(3),z(1),z(0),z(2),z(17),z(3),z(17),z(0),z(63),z(0)}function Y(e,t,n,r,i){for(var a=i[0],o=i[240],s,c=16,l=63,u=64,p=V(e,t),h=0;h<u;++h)m[w[h]]=p[h];var g=m[0]-n;n=m[0],g==0?R(r[0]):(s=32767+g,R(r[f[s]]),R(d[s]));for(var _=63;_>0&&m[_]==0;_--);if(_==0)return R(a),n;for(var v=1,y;v<=_;){for(var b=v;m[v]==0&&v<=_;++v);var x=v-b;if(x>=c){y=x>>4;for(var S=1;S<=y;++S)R(o);x&=15}s=32767+m[v],R(i[(x<<4)+f[s]]),R(d[s]),v++}return _!=l&&R(a),n}function X(){for(var e=String.fromCharCode,t=0;t<256;t++)x[t]=e(t)}this.encode=function(e,n){new Date().getTime(),n&&Z(n),h=[],g=0,_=7,B(65496),H(),q(e.comments),U(e.exifBuffer),G(),W(e.width,e.height),K(),J();var r=0,i=0,d=0;g=0,_=7,this.encode.displayName=`_encode_`;var f=e.data,p=e.width,m=e.height,x=p*4;p*3;for(var C,w=0,T,E,D,O,k,A,j,M;w<m;){for(C=0;C<x;){for(O=x*w+C,k=O,A=-1,j=0,M=0;M<64;M++)j=M>>3,A=(M&7)*4,k=O+j*x+A,w+j>=m&&(k-=x*(w+1+j-m)),C+A>=x&&(k-=C+A-x+4),T=f[k++],E=f[k++],D=f[k++],v[M]=(S[T]+S[E+256>>0]+S[D+512>>0]>>16)-128,y[M]=(S[T+768>>0]+S[E+1024>>0]+S[D+1280>>0]>>16)-128,b[M]=(S[T+1280>>0]+S[E+1536>>0]+S[D+1792>>0]>>16)-128;r=Y(v,a,r,s,l),i=Y(y,o,i,c,u),d=Y(b,o,d,c,u),C+=32}w+=8}if(_>=0){var N=[];N[1]=_+1,N[0]=(1<<_+1)-1,R(N)}return B(65497),t===void 0?new Uint8Array(h):Buffer.from(h)};function Z(e){if(e<=0&&(e=1),e>100&&(e=100),C!=e){var t=0;t=Math.floor(e<50?5e3/e:200-e*2),N(t),C=e}}function Q(){var t=new Date().getTime();e||=50,X(),F(),I(),L(),Z(e),new Date().getTime()-t}Q()}t===void 0?typeof window<`u`&&(window[`jpeg-js`]=window[`jpeg-js`]||{},window[`jpeg-js`].encode=r):t.exports=r;function r(e,t){return t===void 0&&(t=50),{data:new n(t).encode(e,t),width:e.width,height:e.height}}})),s=e(((e,t)=>{var n=(function(){var e=new Int32Array([0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]),t=4017,n=799,r=3406,i=2276,a=1567,o=3784,s=5793,c=2896;function l(){}function u(e,t){for(var n=0,r=[],i,a,o=16;o>0&&!e[o-1];)o--;r.push({children:[],index:0});var s=r[0],c;for(i=0;i<o;i++){for(a=0;a<e[i];a++){for(s=r.pop(),s.children[s.index]=t[n];s.index>0;){if(r.length===0)throw Error(`Could not recreate Huffman Table`);s=r.pop()}for(s.index++,r.push(s);r.length<=i;)r.push(c={children:[],index:0}),s.children[s.index]=c.children,s=c;n++}i+1<o&&(r.push(c={children:[],index:0}),s.children[s.index]=c.children,s=c)}return r[0].children}function d(t,n,r,i,a,o,s,c,l,u){r.precision,r.samplesPerLine,r.scanLines;var d=r.mcusPerLine,f=r.progressive;r.maxH,r.maxV;var p=n,m=0,h=0;function g(){if(h>0)return h--,m>>h&1;if(m=t[n++],m==255){var e=t[n++];if(e)throw Error(`unexpected marker: `+(m<<8|e).toString(16))}return h=7,m>>>7}function _(e){for(var t=e,n;(n=g())!==null;){if(t=t[n],typeof t==`number`)return t;if(typeof t!=`object`)throw Error(`invalid huffman sequence`)}return null}function v(e){for(var t=0;e>0;){var n=g();if(n===null)return;t=t<<1|n,e--}return t}function y(e){var t=v(e);return t>=1<<e-1?t:t+(-1<<e)+1}function b(t,n){var r=_(t.huffmanTableDC),i=r===0?0:y(r);n[0]=t.pred+=i;for(var a=1;a<64;){var o=_(t.huffmanTableAC),s=o&15,c=o>>4;if(s===0){if(c<15)break;a+=16;continue}a+=c;var l=e[a];n[l]=y(s),a++}}function x(e,t){var n=_(e.huffmanTableDC),r=n===0?0:y(n)<<l;t[0]=e.pred+=r}function S(e,t){t[0]|=g()<<l}var C=0;function w(t,n){if(C>0){C--;return}for(var r=o,i=s;r<=i;){var a=_(t.huffmanTableAC),c=a&15,u=a>>4;if(c===0){if(u<15){C=v(u)+(1<<u)-1;break}r+=16;continue}r+=u;var d=e[r];n[d]=y(c)*(1<<l),r++}}var T=0,E;function D(t,n){for(var r=o,i=s,a=0;r<=i;){var c=e[r],u=n[c]<0?-1:1;switch(T){case 0:var d=_(t.huffmanTableAC),f=d&15,a=d>>4;if(f===0)a<15?(C=v(a)+(1<<a),T=4):(a=16,T=1);else{if(f!==1)throw Error(`invalid ACn encoding`);E=y(f),T=a?2:3}continue;case 1:case 2:n[c]?n[c]+=(g()<<l)*u:(a--,a===0&&(T=T==2?3:0));break;case 3:n[c]?n[c]+=(g()<<l)*u:(n[c]=E<<l,T=0);break;case 4:n[c]&&(n[c]+=(g()<<l)*u)}r++}T===4&&(C--,C===0&&(T=0))}function O(e,t,n,r,i){var a=n/d|0,o=n%d,s=a*e.v+r,c=o*e.h+i;e.blocks[s]===void 0&&u.tolerantDecoding||t(e,e.blocks[s][c])}function k(e,t,n){var r=n/e.blocksPerLine|0,i=n%e.blocksPerLine;e.blocks[r]===void 0&&u.tolerantDecoding||t(e,e.blocks[r][i])}var A=i.length,j,M,N,P,F,I=f?o===0?c===0?x:S:c===0?w:D:b,L=0,R,z=A==1?i[0].blocksPerLine*i[0].blocksPerColumn:d*r.mcusPerColumn;a||=z;for(var B,V;L<z;){for(M=0;M<A;M++)i[M].pred=0;if(C=0,A==1)for(j=i[0],F=0;F<a;F++)k(j,I,L),L++;else for(F=0;F<a;F++){for(M=0;M<A;M++)for(j=i[M],B=j.h,V=j.v,N=0;N<V;N++)for(P=0;P<B;P++)O(j,I,L,N,P);if(L++,L===z)break}if(L===z)do{if(t[n]===255&&t[n+1]!==0)break;n+=1}while(n<t.length-2);if(h=0,R=t[n]<<8|t[n+1],R<65280)throw Error(`marker was not found`);if(R>=65488&&R<=65495)n+=2;else break}return n-p}function f(e,l){var u=[],d=l.blocksPerLine,f=l.blocksPerColumn,p=d<<3,m=new Int32Array(64),h=new Uint8Array(64);function _(e,u,d){var f=l.quantizationTable,p,m,h,g,_,v,y,b,x,S=d,C;for(C=0;C<64;C++)S[C]=e[C]*f[C];for(C=0;C<8;++C){var w=8*C;if(S[1+w]==0&&S[2+w]==0&&S[3+w]==0&&S[4+w]==0&&S[5+w]==0&&S[6+w]==0&&S[7+w]==0){x=s*S[0+w]+512>>10,S[0+w]=x,S[1+w]=x,S[2+w]=x,S[3+w]=x,S[4+w]=x,S[5+w]=x,S[6+w]=x,S[7+w]=x;continue}p=s*S[0+w]+128>>8,m=s*S[4+w]+128>>8,h=S[2+w],g=S[6+w],_=c*(S[1+w]-S[7+w])+128>>8,b=c*(S[1+w]+S[7+w])+128>>8,v=S[3+w]<<4,y=S[5+w]<<4,x=p-m+1>>1,p=p+m+1>>1,m=x,x=h*o+g*a+128>>8,h=h*a-g*o+128>>8,g=x,x=_-y+1>>1,_=_+y+1>>1,y=x,x=b+v+1>>1,v=b-v+1>>1,b=x,x=p-g+1>>1,p=p+g+1>>1,g=x,x=m-h+1>>1,m=m+h+1>>1,h=x,x=_*i+b*r+2048>>12,_=_*r-b*i+2048>>12,b=x,x=v*n+y*t+2048>>12,v=v*t-y*n+2048>>12,y=x,S[0+w]=p+b,S[7+w]=p-b,S[1+w]=m+y,S[6+w]=m-y,S[2+w]=h+v,S[5+w]=h-v,S[3+w]=g+_,S[4+w]=g-_}for(C=0;C<8;++C){var T=C;if(S[8+T]==0&&S[16+T]==0&&S[24+T]==0&&S[32+T]==0&&S[40+T]==0&&S[48+T]==0&&S[56+T]==0){x=s*d[C+0]+8192>>14,S[0+T]=x,S[8+T]=x,S[16+T]=x,S[24+T]=x,S[32+T]=x,S[40+T]=x,S[48+T]=x,S[56+T]=x;continue}p=s*S[0+T]+2048>>12,m=s*S[32+T]+2048>>12,h=S[16+T],g=S[48+T],_=c*(S[8+T]-S[56+T])+2048>>12,b=c*(S[8+T]+S[56+T])+2048>>12,v=S[24+T],y=S[40+T],x=p-m+1>>1,p=p+m+1>>1,m=x,x=h*o+g*a+2048>>12,h=h*a-g*o+2048>>12,g=x,x=_-y+1>>1,_=_+y+1>>1,y=x,x=b+v+1>>1,v=b-v+1>>1,b=x,x=p-g+1>>1,p=p+g+1>>1,g=x,x=m-h+1>>1,m=m+h+1>>1,h=x,x=_*i+b*r+2048>>12,_=_*r-b*i+2048>>12,b=x,x=v*n+y*t+2048>>12,v=v*t-y*n+2048>>12,y=x,S[0+T]=p+b,S[56+T]=p-b,S[8+T]=m+y,S[48+T]=m-y,S[16+T]=h+v,S[40+T]=h-v,S[24+T]=g+_,S[32+T]=g-_}for(C=0;C<64;++C){var E=128+(S[C]+8>>4);u[C]=E<0?0:E>255?255:E}}g(p*f*8);for(var v,y,b=0;b<f;b++){var x=b<<3;for(v=0;v<8;v++)u.push(new Uint8Array(p));for(var S=0;S<d;S++){_(l.blocks[b][S],h,m);var C=0,w=S<<3;for(y=0;y<8;y++){var T=u[x+y];for(v=0;v<8;v++)T[w+v]=h[C++]}}}return u}function p(e){return e<0?0:e>255?255:e}l.prototype={load:function(e){var t=new XMLHttpRequest;t.open(`GET`,e,!0),t.responseType=`arraybuffer`,t.onload=(function(){var e=new Uint8Array(t.response||t.mozResponseArrayBuffer);this.parse(e),this.onload&&this.onload()}).bind(this),t.send(null)},parse:function(t){var n=this.opts.maxResolutionInMP*1e3*1e3,r=0;t.length;function i(){var e=t[r]<<8|t[r+1];return r+=2,e}function a(){var e=i(),n=t.subarray(r,r+e-2);return r+=n.length,n}function o(e){var t=1,n=1,r,i;for(i in e.components)e.components.hasOwnProperty(i)&&(r=e.components[i],t<r.h&&(t=r.h),n<r.v&&(n=r.v));var a=Math.ceil(e.samplesPerLine/8/t),o=Math.ceil(e.scanLines/8/n);for(i in e.components)if(e.components.hasOwnProperty(i)){r=e.components[i];var s=Math.ceil(Math.ceil(e.samplesPerLine/8)*r.h/t),c=Math.ceil(Math.ceil(e.scanLines/8)*r.v/n),l=a*r.h,u=o*r.v,d=u*l,f=[];g(d*256);for(var p=0;p<u;p++){for(var m=[],h=0;h<l;h++)m.push(new Int32Array(64));f.push(m)}r.blocksPerLine=s,r.blocksPerColumn=c,r.blocks=f}e.maxH=t,e.maxV=n,e.mcusPerLine=a,e.mcusPerColumn=o}var s=null,c=null,l,p,m=[],h=[],_=[],v=[],y=i(),b=-1;if(this.comments=[],y!=65496)throw Error(`SOI not found`);for(y=i();y!=65497;){var x,S;switch(y){case 65280:break;case 65504:case 65505:case 65506:case 65507:case 65508:case 65509:case 65510:case 65511:case 65512:case 65513:case 65514:case 65515:case 65516:case 65517:case 65518:case 65519:case 65534:var C=a();if(y===65534){var w=String.fromCharCode.apply(null,C);this.comments.push(w)}y===65504&&C[0]===74&&C[1]===70&&C[2]===73&&C[3]===70&&C[4]===0&&(s={version:{major:C[5],minor:C[6]},densityUnits:C[7],xDensity:C[8]<<8|C[9],yDensity:C[10]<<8|C[11],thumbWidth:C[12],thumbHeight:C[13],thumbData:C.subarray(14,14+3*C[12]*C[13])}),y===65505&&C[0]===69&&C[1]===120&&C[2]===105&&C[3]===102&&C[4]===0&&(this.exifBuffer=C.subarray(5,C.length)),y===65518&&C[0]===65&&C[1]===100&&C[2]===111&&C[3]===98&&C[4]===101&&C[5]===0&&(c={version:C[6],flags0:C[7]<<8|C[8],flags1:C[9]<<8|C[10],transformCode:C[11]});break;case 65499:for(var T=i()+r-2;r<T;){var E=t[r++];g(256);var D=new Int32Array(64);if(!(E>>4))for(S=0;S<64;S++){var O=e[S];D[O]=t[r++]}else if(E>>4==1)for(S=0;S<64;S++){var O=e[S];D[O]=i()}else throw Error(`DQT: invalid table spec`);m[E&15]=D}break;case 65472:case 65473:case 65474:i(),l={},l.extended=y===65473,l.progressive=y===65474,l.precision=t[r++],l.scanLines=i(),l.samplesPerLine=i(),l.components={},l.componentsOrder=[];var k=l.scanLines*l.samplesPerLine;if(k>n){var A=Math.ceil((k-n)/1e6);throw Error(`maxResolutionInMP limit exceeded by ${A}MP`)}var j=t[r++],M;for(x=0;x<j;x++){M=t[r];var N=t[r+1]>>4,P=t[r+1]&15,F=t[r+2];if(N<=0||P<=0)throw Error(`Invalid sampling factor, expected values above 0`);l.componentsOrder.push(M),l.components[M]={h:N,v:P,quantizationIdx:F},r+=3}o(l),h.push(l);break;case 65476:var I=i();for(x=2;x<I;){var L=t[r++],R=new Uint8Array(16),z=0;for(S=0;S<16;S++,r++)z+=R[S]=t[r];g(16+z);var B=new Uint8Array(z);for(S=0;S<z;S++,r++)B[S]=t[r];x+=17+z,(L>>4?_:v)[L&15]=u(R,B)}break;case 65501:i(),p=i();break;case 65500:i(),i();break;case 65498:i();var V=t[r++],H=[],U;for(x=0;x<V;x++){U=l.components[t[r++]];var W=t[r++];U.huffmanTableDC=v[W>>4],U.huffmanTableAC=_[W&15],H.push(U)}var G=t[r++],K=t[r++],q=t[r++],J=d(t,r,l,H,p,G,K,q>>4,q&15,this.opts);r+=J;break;case 65535:t[r]!==255&&r--;break;default:if(t[r-3]==255&&t[r-2]>=192&&t[r-2]<=254){r-=3;break}if(y===224||y==225){if(b!==-1)throw Error(`first unknown JPEG marker at offset ${b.toString(16)}, second unknown JPEG marker ${y.toString(16)} at offset ${(r-1).toString(16)}`);b=r-1;let e=i();if(t[r+e-2]===255){r+=e-2;break}}throw Error(`unknown JPEG marker `+y.toString(16))}y=i()}if(h.length!=1)throw Error(`only single frame JPEGs supported`);for(var x=0;x<h.length;x++){var Y=h[x].components;for(var S in Y)Y[S].quantizationTable=m[Y[S].quantizationIdx],delete Y[S].quantizationIdx}this.width=l.samplesPerLine,this.height=l.scanLines,this.jfif=s,this.adobe=c,this.components=[];for(var x=0;x<l.componentsOrder.length;x++){var U=l.components[l.componentsOrder[x]];this.components.push({lines:f(l,U),scaleX:U.h/l.maxH,scaleY:U.v/l.maxV})}},getData:function(e,t){var n=this.width/e,r=this.height/t,i,a,o,s,c,l,u,d,f,m,h=0,_,v,y,b,x,S,C,w,T,E,D,O=e*t*this.components.length;g(O);var k=new Uint8Array(O);switch(this.components.length){case 1:for(i=this.components[0],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],f=0;f<e;f++)_=c[0|f*i.scaleX*n],k[h++]=_;break;case 2:for(i=this.components[0],a=this.components[1],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],f=0;f<e;f++)_=c[0|f*i.scaleX*n],k[h++]=_,_=l[0|f*a.scaleX*n],k[h++]=_;break;case 3:for(D=!0,this.adobe&&this.adobe.transformCode?D=!0:this.opts.colorTransform!==void 0&&(D=!!this.opts.colorTransform),i=this.components[0],a=this.components[1],o=this.components[2],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],u=o.lines[0|m*o.scaleY*r],f=0;f<e;f++)D?(_=c[0|f*i.scaleX*n],v=l[0|f*a.scaleX*n],y=u[0|f*o.scaleX*n],w=p(_+1.402*(y-128)),T=p(_-.3441363*(v-128)-.71413636*(y-128)),E=p(_+1.772*(v-128))):(w=c[0|f*i.scaleX*n],T=l[0|f*a.scaleX*n],E=u[0|f*o.scaleX*n]),k[h++]=w,k[h++]=T,k[h++]=E;break;case 4:if(!this.adobe)throw Error(`Unsupported color mode (4 components)`);for(D=!1,this.adobe&&this.adobe.transformCode?D=!0:this.opts.colorTransform!==void 0&&(D=!!this.opts.colorTransform),i=this.components[0],a=this.components[1],o=this.components[2],s=this.components[3],m=0;m<t;m++)for(c=i.lines[0|m*i.scaleY*r],l=a.lines[0|m*a.scaleY*r],u=o.lines[0|m*o.scaleY*r],d=s.lines[0|m*s.scaleY*r],f=0;f<e;f++)D?(_=c[0|f*i.scaleX*n],v=l[0|f*a.scaleX*n],y=u[0|f*o.scaleX*n],b=d[0|f*s.scaleX*n],x=255-p(_+1.402*(y-128)),S=255-p(_-.3441363*(v-128)-.71413636*(y-128)),C=255-p(_+1.772*(v-128))):(x=c[0|f*i.scaleX*n],S=l[0|f*a.scaleX*n],C=u[0|f*o.scaleX*n],b=d[0|f*s.scaleX*n]),k[h++]=255-x,k[h++]=255-S,k[h++]=255-C,k[h++]=255-b;break;default:throw Error(`Unsupported color mode`)}return k},copyToImageData:function(e,t){var n=e.width,r=e.height,i=e.data,a=this.getData(n,r),o=0,s=0,c,l,u,d,f,m,h,g,_;switch(this.components.length){case 1:for(l=0;l<r;l++)for(c=0;c<n;c++)u=a[o++],i[s++]=u,i[s++]=u,i[s++]=u,t&&(i[s++]=255);break;case 3:for(l=0;l<r;l++)for(c=0;c<n;c++)h=a[o++],g=a[o++],_=a[o++],i[s++]=h,i[s++]=g,i[s++]=_,t&&(i[s++]=255);break;case 4:for(l=0;l<r;l++)for(c=0;c<n;c++)f=a[o++],m=a[o++],u=a[o++],d=a[o++],h=255-p(f*(1-d/255)+d),g=255-p(m*(1-d/255)+d),_=255-p(u*(1-d/255)+d),i[s++]=h,i[s++]=g,i[s++]=_,t&&(i[s++]=255);break;default:throw Error(`Unsupported color mode`)}}};var m=0,h=0;function g(e=0){var t=m+e;if(t>h){var n=Math.ceil((t-h)/1024/1024);throw Error(`maxMemoryUsageInMB limit exceeded by at least ${n}MB`)}m=t}return l.resetMaxMemoryUsage=function(e){m=0,h=e},l.getBytesAllocated=function(){return m},l.requestMemoryAllocation=g,l})();t===void 0?typeof window<`u`&&(window[`jpeg-js`]=window[`jpeg-js`]||{},window[`jpeg-js`].decode=r):t.exports=r;function r(e,t={}){var r={colorTransform:void 0,useTArray:!1,formatAsRGBA:!0,tolerantDecoding:!0,maxResolutionInMP:100,maxMemoryUsageInMB:512,...t},i=new Uint8Array(e),a=new n;a.opts=r,n.resetMaxMemoryUsage(r.maxMemoryUsageInMB*1024*1024),a.parse(i);var o=r.formatAsRGBA?4:3,s=a.width*a.height*o;try{n.requestMemoryAllocation(s);var c={width:a.width,height:a.height,exifBuffer:a.exifBuffer,data:r.useTArray?new Uint8Array(s):Buffer.alloc(s)};a.comments.length>0&&(c.comments=a.comments)}catch(e){throw e instanceof RangeError?Error(`Could not allocate enough memory for the image. Required: `+s):e instanceof ReferenceError&&e.message===`Buffer is not defined`?Error(`Buffer is not globally defined in this environment. Consider setting useTArray to true`):e}return a.copyToImageData(c,r.formatAsRGBA),c}})),c=e(((e,t)=>{t.exports={encode:o(),decode:s()}}))();const l=Buffer.from([255,216,255]);function u(e){if(n(e))return`png`;if(e.subarray(0,l.length).equals(l))return`jpeg`}function d(e,t,n){a(e,t,n);let i=u(e);if(i===`png`)return r(e,t);if(i===`jpeg`)return p(e,t,n);throw m(t,e)}function f(e,t){let n=u(e);if(n===`png`)return e;if(n===`jpeg`)return i.PNG.sync.write(p(e,t));throw m(t,e)}function p(e,n,r){try{let t=(0,c.decode)(e,{useTArray:!0,formatAsRGBA:!0,...r!=null&&r>0?{maxResolutionInMP:(Math.floor(r)+.5)/1e6}:{}}),n=new i.PNG({width:t.width,height:t.height});return n.data=Buffer.from(t.data.buffer,t.data.byteOffset,t.data.byteLength),n}catch(e){throw new t(`COMMAND_FAILED`,`Failed to decode ${n} as JPEG`,{label:n,reason:e instanceof Error?e.message:String(e)})}}function m(e,n){return new t(`COMMAND_FAILED`,`${e} is neither PNG nor JPEG`,{label:e,leadingBytes:n.subarray(0,4).toString(`hex`)})}export{d as decodeScreenshotImage,f as transcodeScreenshotToPng};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime.js";import{R as t,s as n,x as r}from"./sdk-contracts.js";import{Ct as i,bt as a,mt as o,xt as s}from"./tv-remote.js";import{O as c,_ as l,j as u}from"./sdk-device.js";import{$r as d,Br as f,Lt as p,Pr as m,Ur as h,Vr as g,_n as _,ii as v,oi as y,ri as b}from"./sdk-batch.js";import{t as ee}from"./session-paths.js";import{t as x}from"./snapshot-state.js";import{n as S}from"./snapshot-runtime-capture-input.js";import{i as te,t as ne}from"./selector-pipeline-policy.js";import{i as re,o as ie,r as ae}from"./png-worker-client.js";import{f as C,i as w,n as T}from"./runtime-session.js";import{t as oe}from"./command-policy.js";import{a as se,i as ce,n as le,t as ue}from"./session-runtime-admission.js";import{t as de}from"./react-native-overlay2.js";import{t as fe}from"./png-size.js";import{r as pe,t as me}from"./screenshot-density.js";import{a as E,o as D,s as O,t as he}from"./screenshot-overlay-draw.js";import{promises as k}from"node:fs";import A from"node:os";import j from"node:path";const M=o.pendingPixelIdentityEvidence,N=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:M},{target:`macos-app-window`,status:`rejected`,rejectionReason:M},{target:`ios-physical`,status:`accepted`},{target:`ios-physical-xctest`,status:`rejected`,rejectionReason:M},{target:`ipados-physical`,status:`rejected`,rejectionReason:M},{target:`macos-helper`,status:`rejected`,rejectionReason:M},{target:`web`,status:`rejected`,rejectionReason:M},{target:`linux`,status:`rejected`,rejectionReason:M},{target:`tvos`,status:`rejected`,rejectionReason:M},{target:`harmonyos`,status:`rejected`,rejectionReason:M},{target:`vega`,status:`rejected`,rejectionReason:M}];function P(e,t){switch(e.platform){case`apple`:return F(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 F(e,t){let n=u(e);switch(n){case`ios`:return e.kind===`device`?e.iosPhysicalDeviceBackend===`xctest`?`ios-physical-xctest`:`ios-physical`:`ios-simulator`;case`ipados`:return e.kind===`device`?`ipados-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return I(t);case`watchos`:case`visionos`:throw L(n)}}function I(e){return(e??`app`)===`app`?`macos-app-window`:`macos-helper`}function L(e,n){return new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${e} targets`,{reason:o.targetNotAccepted,...n?{rejectionReason:n}:{}})}function R(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:o.frameMismatch});try{_(e.cropOn)}catch{throw new t(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:o.selectorInvalid})}let n=P(e.device,e.surface),r=N.find(e=>e.target===n);if(!r||r.status===`rejected`)throw L(n,r?.status===`rejected`?r.rejectionReason:void 0)}function ge(e,t){if(P(e,void 0)===`ios-physical`&&t.iosPhysicalCaptureBackend!==`coredevice`)throw L(`ios-physical-non-coredevice-capture`,M)}async function _e(e,n){if(!ve(n))throw new t(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await ae(await k.readFile(e),n,`screenshot`);r!==null&&await k.writeFile(e,r)}function ve(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 ye(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:o.targetNotAccepted})}}function z(e,t,n,r,i){if(e===`device-pixels`||t===null)return Ce(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 be(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 B(e){let t=null;for(let n of e)!m(n)||!d(n.rect)||(!t||b(n.rect)>b(t))&&(t=n.rect);return t||xe(e.filter(e=>d(e.rect)&&!Se(e)))}function xe(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)d(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 Se(e){return g(e.type??``)===`image`&&!f(e.label)}function Ce(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const we=`${o.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Te(e){return e?.partialIntersection?[we]:[]}async function Ee(e){let{device:n,session:r,surface:i,cropOn:a,screenshotPath:s,logPath:c,dispatchContext:l}=e,u={snapshotInteractiveOnly:!1},d=await w({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:S(l)})}),f=x(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:o.captureUnreadable});let p=await De(f.nodes,a,f.truncated,n),m=await fe(s),h=z(ye(f.backend),B(f.nodes),p.rect,m.width,m.height),g=be(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:o.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await _e(s,g),{partialIntersection:_}}async function De(e,n,r,i){let a=await te(ne.cropTarget,e,n,{platform:c(i)});if(a.kind===`ambiguous`)throw new t(`COMMAND_FAILED`,`--crop-on matched ${a.matchedNodes.length} nodes and must resolve to one`,{reason:o.targetAmbiguous,candidates:a.matchedNodes.map(e=>e.label??e.ref),matches:a.matchedNodes.length});if(a.kind===`none`)throw r?new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:o.captureIncomplete}):new t(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:o.targetNotFound,hint:`find ${n} list`});return a.node}const Oe=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function ke(e,t,n){if(e.backend!==`android`||!n.hittable||!D(n.rect)||m(n))return!1;let r=g(n.type??``);return!(Oe.some(e=>r.includes(e))||t&&O(n.rect)>O(t)*.25)}function Ae(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:je(e,t,r)}function je(e,t,n){let r=e.rect,i=Me(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 Me(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&Pe(t,e,i)&&Ne(t,n)&&D(t.rect)&&v(r,t.rect)).map(e=>e.rect);return a.length<2?null:y(a)}function Ne(e,t){let n=g(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function Pe(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 Fe=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await k.readFile(e.screenshotPath),n=await re(t,`screenshot`),r=Ie(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)he(n,e);return await k.writeFile(e.screenshotPath,await ie(n)),r}function Ie(e,t,n,i={}){let a=B(e.nodes),o=new Map;for(let r of e.nodes){if(!ze(e,a,r))continue;let i=Be(e.nodes,r);if(!i?.ref||!i.rect||!D(i.rect))continue;let s=Ve(r,i,e.nodes),c=He(r,i,s),l=H(e,a,Re(e,i,e.nodes),t,n);if(!D(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 Le(e,a,o,t,n),Ue([...o.values()]).sort(Y).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:r(e.overlayRect)}))}function Le(e,t,n,r,i){let a=de(e.nodes).primaryAction;if(!a?.ref||!a.rect||!D(a.rect))return;let o=H(e,t,a.rect,r,i);if(!D(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 Re(e,t,n){return e.backend===`android`?Ae(t,n,U,e=>!!q(e))??t.rect:t.rect}function ze(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return ke(e,t,n)?!0:U(n)?r:r&&We(n)}function Be(e,t){return[W(t)?t:null,h(e,t,W),t.hittable?t:null,h(e,t,e=>e.hittable===!0)].find(Ge)??null}function Ve(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:Ke(t,n)||q(t)}function He(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),f(t.value)&&(r+=1),r}function Ue(e){let t=[];for(let n of e.sort((e,t)=>O(e.overlayRect)-O(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(v(e.overlayRect,n.overlayRect)||v(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}O(n.overlayRect)<O(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Qe(z(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=>g(e??``)).join(` `);return Fe.some(e=>t.includes(e))}function W(e){return U(e)&&!m(e)}function We(e){let t=g(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ge(e){return!!(e?.rect&&D(e.rect)&&!m(e))}function G(e){return f(e)?!Ye(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Xe(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 Ke(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!qe(r,e,t))continue;let i=q(r);if(!i)continue;let a=Je(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function qe(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 Je(e){let t=0;return g(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Ye(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Xe(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Ze(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Qe(e,t,n){let r=E(e.x,0,Math.max(0,t-1)),i=E(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:E(e.width,1,a),height:E(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?Ze(e.ref,t.ref):r}function Y(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function X(e){let t=p({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ue({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await $e(e.bindDevice,n)}:{ok:!1,response:tt(t.kind,n.operation,n.fact)}}async function $e(e,t){let n=le(e),{device:r,plan:i}=se(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:et(e)})}}}function Z(e){return async t=>await e.operations.captureScreenshot(t)}function et(e){return async t=>await e.operations.captureSnapshot(t)}function tt(e,t,r){return t===`captureScreenshot`?ce(`screenshot`,r):e===`capture-with-crop-on`?n(`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:r.available?void 0:r.reason},{hint:(r.available?void 0:r.hint)??`Re-run screenshot without --crop-on.`}):n(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:r.available?void 0:r.reason},{hint:(r.available?void 0:r.hint)??`Re-run screenshot without --overlay-refs.`})}var nt=e({captureScreenshotArtifact:()=>Q,resolveScreenshotGenericExecution:()=>rt,screenshotExecutionFromContext:()=>$});async function rt(e){let{req:n,session:r}=e,i=a(`screenshot`,n.flags);if(i)throw new t(`INVALID_ARGS`,i);me(r.device,n.flags?.screenshotPixelDensity);let o=ct(n,e.hostCwd),s=typeof n.flags?.screenshotCropOn==`string`&&n.flags.screenshotCropOn.length>0?n.flags.screenshotCropOn:void 0;s!==void 0&&R({device:r.device,surface:r.surface,cropOn:s,overlayRefs:n.flags?.overlayRefs===!0,fullscreen:n.flags?.screenshotFullscreen===!0});let c=await X({device:r.device,overlayRefs:n.flags?.overlayRefs===!0,cropOn:s,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]},{createCommandSurface:d}=e;return{ok:!0,recorded:o.recorded,execute:async e=>await it({createCommandSurface:d,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:r,dispatchContext:a}=e;return await(await e.createCommandSurface({backend:lt(e),artifacts:ut(),sessions:T(n,t),policy:oe()})).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...i(a),surface:t.surface,...r?{out:{kind:`path`,path:r}}:{}})}function $(e){return S(e)}async function it(e){let{session:t,runtime:n,flags:r}=e,i=at({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({createCommandSurface:e.createCommandSurface,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 ot({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await pe({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function at(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 ot(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await st({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function st(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await w({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=x(i,r);return C(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function ct(e,t){let n=e.positionals??[],r=e.flags??{},i=n=>n===void 0?void 0:ee(n,e.meta?.cwd??t),a=i(n[0]),o=i(r.out);return{outPath:a??o,recorded:{positionals:a?[a,...n.slice(1)]:n,flags:o?{...r,out:o}:r}}}function lt(e){let{session:t,dispatchContext:n,captureScreenshot:r,crop:a}=e;return{platform:c(t.device),captureScreenshot:async(e,o,c)=>{let u=i({...n,...s(c)}),d=await r({outPath:o,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:c?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(l(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:$(n)});if(a){ge(t.device,d);let e=await Ee({device:t.device,session:t,surface:t.surface,cropOn:a.cropOn,screenshotPath:o,logPath:a.logPath,dispatchContext:n,captureSnapshot:a.captureSnapshot});a.run.warnings.push(...Te(e))}return d.displayRotation?{displayRotation:d.displayRotation}:void 0}}}function ut(){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 k.mkdtemp(j.join(A.tmpdir(),`agent-device-screenshot-`)),n=j.join(t,`screenshot.png`)),await k.mkdir(j.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await k.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await k.mkdtemp(j.join(A.tmpdir(),`${e.prefix}-`));return{path:j.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await k.rm(t,{recursive:!0,force:!0})}}}}}export{V as a,X as i,$ as n,nt as r,Q as t};
1
+ import{r as e}from"./rolldown-runtime.js";import{R as t,s as n,x as r}from"./sdk-contracts.js";import{Dt as i,Tt as a,vt as o,wt as s}from"./tv-remote.js";import{O as c,_ as l,j as u}from"./sdk-device.js";import{Kr as d,Lr as f,Rt as p,Ur as m,Wr as h,bn as g,li as _,ni as v,oi as y,si as b}from"./sdk-batch.js";import{t as ee}from"./session-paths.js";import{t as x}from"./snapshot-state.js";import{n as S}from"./snapshot-runtime-capture-input.js";import{i as te,t as ne}from"./selector-pipeline-policy.js";import{i as re,o as ie,r as ae}from"./png-worker-client.js";import{f as oe,i as C,n as w}from"./runtime-session.js";import{t as T}from"./command-policy.js";import{a as se,i as ce,n as le,t as ue}from"./session-runtime-admission.js";import{t as de}from"./react-native-overlay2.js";import{t as fe}from"./png-size.js";import{r as pe,t as me}from"./screenshot-density.js";import{a as E,o as D,s as O,t as he}from"./screenshot-overlay-draw.js";import{promises as k}from"node:fs";import A from"node:os";import j from"node:path";const M=o.pendingPixelIdentityEvidence,N=[{target:`ios-simulator`,status:`accepted`},{target:`android-emulator`,status:`accepted`},{target:`android-device`,status:`rejected`,rejectionReason:M},{target:`macos-app-window`,status:`rejected`,rejectionReason:M},{target:`ios-physical`,status:`accepted`},{target:`ios-physical-xctest`,status:`rejected`,rejectionReason:M},{target:`ipados-physical`,status:`rejected`,rejectionReason:M},{target:`macos-helper`,status:`rejected`,rejectionReason:M},{target:`web`,status:`rejected`,rejectionReason:M},{target:`linux`,status:`rejected`,rejectionReason:M},{target:`tvos`,status:`rejected`,rejectionReason:M},{target:`harmonyos`,status:`rejected`,rejectionReason:M},{target:`vega`,status:`rejected`,rejectionReason:M}];function P(e,t){switch(e.platform){case`apple`:return F(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 F(e,t){let n=u(e);switch(n){case`ios`:return e.kind===`device`?e.iosPhysicalDeviceBackend===`xctest`?`ios-physical-xctest`:`ios-physical`:`ios-simulator`;case`ipados`:return e.kind===`device`?`ipados-physical`:`ios-simulator`;case`tvos`:return`tvos`;case`macos`:return I(t);case`watchos`:case`visionos`:throw L(n)}}function I(e){return(e??`app`)===`app`?`macos-app-window`:`macos-helper`}function L(e,n){return new t(`UNSUPPORTED_OPERATION`,`screenshot --crop-on is not accepted on ${e} targets`,{reason:o.targetNotAccepted,...n?{rejectionReason:n}:{}})}function R(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:o.frameMismatch});try{g(e.cropOn)}catch{throw new t(`INVALID_ARGS`,`screenshot --crop-on requires a valid selector expression`,{reason:o.selectorInvalid})}let n=P(e.device,e.surface),r=N.find(e=>e.target===n);if(!r||r.status===`rejected`)throw L(n,r?.status===`rejected`?r.rejectionReason:void 0)}function ge(e,t){if(P(e,void 0)===`ios-physical`&&t.iosPhysicalCaptureBackend!==`coredevice`)throw L(`ios-physical-non-coredevice-capture`,M)}async function _e(e,n){if(!ve(n))throw new t(`INVALID_ARGS`,`Screenshot crop box must be positive integer pixel offsets`);let r=await ae(await k.readFile(e),n,`screenshot`);r!==null&&await k.writeFile(e,r)}function ve(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 ye(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:o.targetNotAccepted})}}function z(e,t,n,r,i){if(e===`device-pixels`||t===null)return Ce(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 be(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 B(e){let t=null;for(let n of e)!f(n)||!v(n.rect)||(!t||y(n.rect)>y(t))&&(t=n.rect);return t||xe(e.filter(e=>v(e.rect)&&!Se(e)))}function xe(e){let t=1/0,n=1/0,r=-1/0,i=-1/0;for(let a of e)v(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 Se(e){return h(e.type??``)===`image`&&!m(e.label)}function Ce(e){return{x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}const we=`${o.partialIntersection}: the selector frame extends past the captured image; the crop was clipped to the image frame`;function Te(e){return e?.partialIntersection?[we]:[]}async function Ee(e){let{device:n,session:r,surface:i,cropOn:a,screenshotPath:s,logPath:c,dispatchContext:l}=e,u={snapshotInteractiveOnly:!1},d=await C({device:n,session:r,flags:u,logPath:c,snapshotScope:void 0,captureData:async()=>await e.captureSnapshot({options:{appBundleId:l.appBundleId,interactiveOnly:!1,includeRects:!0,surface:i},execution:S(l)})}),f=x(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:o.captureUnreadable});let p=await De(f.nodes,a,f.truncated,n),m=await fe(s),h=z(ye(f.backend),B(f.nodes),p.rect,m.width,m.height),g=be(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:o.emptyIntersection});let _=g.x!==h.x||g.y!==h.y||g.width<h.width||g.height<h.height;return await _e(s,g),{partialIntersection:_}}async function De(e,n,r,i){let a=await te(ne.cropTarget,e,n,{platform:c(i)});if(a.kind===`ambiguous`)throw new t(`COMMAND_FAILED`,`--crop-on matched ${a.matchedNodes.length} nodes and must resolve to one`,{reason:o.targetAmbiguous,candidates:a.matchedNodes.map(e=>e.label??e.ref),matches:a.matchedNodes.length});if(a.kind===`none`)throw r?new t(`COMMAND_FAILED`,`the snapshot taken for --crop-on was truncated, so a missing match is not proven`,{reason:o.captureIncomplete}):new t(`COMMAND_FAILED`,`--crop-on matched no node: ${n}`,{reason:o.targetNotFound,hint:`find ${n} list`});return a.node}const Oe=[`scroll`,`list`,`recyclerview`,`edittext`,`textfield`];function ke(e,t,n){if(e.backend!==`android`||!n.hittable||!D(n.rect)||f(n))return!1;let r=h(n.type??``);return!(Oe.some(e=>r.includes(e))||t&&O(n.rect)>O(t)*.25)}function Ae(e,t,n,r){return!e.rect||e.hittable!==!0||n(e)||r(e)?null:je(e,t,r)}function je(e,t,n){let r=e.rect,i=Me(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 Me(e,t,n){let r=e.rect,i=new Map(t.map(e=>[e.index,e])),a=t.filter(t=>t.ref!==e.ref&&Pe(t,e,i)&&Ne(t,n)&&D(t.rect)&&b(r,t.rect)).map(e=>e.rect);return a.length<2?null:_(a)}function Ne(e,t){let n=h(e.type??``);return n.includes(`text`)||n.includes(`image`)&&t(e)}function Pe(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 Fe=[`button`,`link`,`menu`,`tab`,`textfield`,`searchfield`,`securetextfield`,`checkbox`,`radio`,`switch`,`cell`];async function V(e){let t=await k.readFile(e.screenshotPath),n=await re(t,`screenshot`),r=Ie(e.snapshot,n.width,n.height,{maxRefs:e.maxRefs});for(let e of r)he(n,e);return await k.writeFile(e.screenshotPath,await ie(n)),r}function Ie(e,t,n,i={}){let a=B(e.nodes),o=new Map;for(let r of e.nodes){if(!ze(e,a,r))continue;let i=Be(e.nodes,r);if(!i?.ref||!i.rect||!D(i.rect))continue;let s=Ve(r,i,e.nodes),c=He(r,i,s),l=H(e,a,Re(e,i,e.nodes),t,n);if(!D(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 Le(e,a,o,t,n),Ue([...o.values()]).sort(Y).slice(0,i.maxRefs??24).sort(J).map(e=>({ref:e.ref,label:e.label,rect:e.rect,overlayRect:e.overlayRect,center:r(e.overlayRect)}))}function Le(e,t,n,r,i){let a=de(e.nodes).primaryAction;if(!a?.ref||!a.rect||!D(a.rect))return;let o=H(e,t,a.rect,r,i);if(!D(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 Re(e,t,n){return e.backend===`android`?Ae(t,n,U,e=>!!q(e))??t.rect:t.rect}function ze(e,t,n){let r=[n.label,n.value].some(G)||K(n.identifier);return ke(e,t,n)?!0:U(n)?r:r&&We(n)}function Be(e,t){return[W(t)?t:null,d(e,t,W),t.hittable?t:null,d(e,t,e=>e.hittable===!0)].find(Ge)??null}function Ve(e,t,n){let r=q(e);return e.ref!==t.ref&&r?r:Ke(t,n)||q(t)}function He(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),m(t.value)&&(r+=1),r}function Ue(e){let t=[];for(let n of e.sort((e,t)=>O(e.overlayRect)-O(t.overlayRect))){let e=t.findIndex(e=>e.label!==void 0&&e.label===n.label&&(b(e.overlayRect,n.overlayRect)||b(n.overlayRect,e.overlayRect)));if(e===-1){t.push(n);continue}O(n.overlayRect)<O(t[e].overlayRect)&&(t[e]=n)}return t}function H(e,t,n,r,i){return Qe(z(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=>h(e??``)).join(` `);return Fe.some(e=>t.includes(e))}function W(e){return U(e)&&!f(e)}function We(e){let t=h(e.type??``);return t.includes(`statictext`)||t.includes(`image`)||t.includes(`text`)||t.includes(`other`)}function Ge(e){return!!(e?.rect&&D(e.rect)&&!f(e))}function G(e){return m(e)?!Ye(e):!1}function K(e){return typeof e!=`string`||!G(e)?!1:!Xe(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 Ke(e,t){let n=null;for(let r of t){if(r.ref===e.ref||!qe(r,e,t))continue;let i=q(r);if(!i)continue;let a=Je(r);(!n||a>n.score)&&(n={label:i,score:a})}return n?.label}function qe(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 Je(e){let t=0;return h(e.type??``).includes(`text`)&&(t+=2),G(e.label)&&(t+=2),G(e.value)&&(t+=1),t}function Ye(e){let t=e?.trim().toLowerCase();return t===`toolbar`||t===`window`||t===`application`||t?.startsWith(`vertical scroll bar`)===!0}function Xe(e){return/^[a-z0-9_.]+:id\/[a-z0-9_.-]+$/i.test(e.trim())}function Ze(e,t){return Number.parseInt(e.replace(/^\D+/,``),10)-Number.parseInt(t.replace(/^\D+/,``),10)}function Qe(e,t,n){let r=E(e.x,0,Math.max(0,t-1)),i=E(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:E(e.width,1,a),height:E(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?Ze(e.ref,t.ref):r}function Y(e,t){return t.score===e.score?J(e,t):t.score-e.score}async function X(e){let t=p({overlayRefs:e.overlayRefs,cropOn:e.cropOn!==void 0}),n=await ue({device:e.device,plan:t,inspectFacts:e.inspectFacts});return n.admitted?{ok:!0,runtime:await $e(e.bindDevice,n)}:{ok:!1,response:tt(t.kind,n.operation,n.fact)}}async function $e(e,t){let n=le(e),{device:r,plan:i}=se(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:et(e)})}}}function Z(e){return async t=>await e.operations.captureScreenshot(t)}function et(e){return async t=>await e.operations.captureSnapshot(t)}function tt(e,t,r){return t===`captureScreenshot`?ce(`screenshot`,r):e===`capture-with-crop-on`?n(`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:r.available?void 0:r.reason},{hint:(r.available?void 0:r.hint)??`Re-run screenshot without --crop-on.`}):n(`UNSUPPORTED_OPERATION`,`--overlay-refs annotates a capture with the refs of a snapshot taken on the same screen, which this target cannot capture.`,{reason:r.available?void 0:r.reason},{hint:(r.available?void 0:r.hint)??`Re-run screenshot without --overlay-refs.`})}var nt=e({captureScreenshotArtifact:()=>Q,resolveScreenshotGenericExecution:()=>rt,screenshotExecutionFromContext:()=>$});async function rt(e){let{req:n,session:r}=e,i=s(`screenshot`,n.flags);if(i)throw new t(`INVALID_ARGS`,i);me(r.device,n.flags?.screenshotPixelDensity);let a=ct(n,e.hostCwd),o=typeof n.flags?.screenshotCropOn==`string`&&n.flags.screenshotCropOn.length>0?n.flags.screenshotCropOn:void 0;o!==void 0&&R({device:r.device,surface:r.surface,cropOn:o,overlayRefs:n.flags?.overlayRefs===!0,fullscreen:n.flags?.screenshotFullscreen===!0});let c=await X({device:r.device,overlayRefs:n.flags?.overlayRefs===!0,cropOn:o,inspectFacts:e.inspectFacts,platformServices:e.platformServices,bindDevice:e.bindDevice});if(!c.ok)return c;let l=c.runtime,u={warnings:[]},{createCommandSurface:d}=e;return{ok:!0,recorded:a.recorded,execute:async e=>await it({createCommandSurface:d,session:e.session,sessionName:e.sessionName,logPath:e.logPath,dispatchContext:e.dispatchContext,flags:e.request.flags,outPath:a.outPath,runtime:l,cropOn:o,cropRun:u})}}async function Q(e){let{session:t,sessionName:n,outPath:r,dispatchContext:a}=e;return await(await e.createCommandSurface({backend:lt(e),artifacts:ut(),sessions:w(n,t),policy:T()})).capture.screenshot({session:n,requestId:a.requestId,appBundleId:t.appBundleId,...i(a),surface:t.surface,...r?{out:{kind:`path`,path:r}}:{}})}function $(e){return S(e)}async function it(e){let{session:t,runtime:n,flags:r}=e,i=at({cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,cropRun:e.cropRun,logPath:e.logPath}),a=await Q({createCommandSurface:e.createCommandSurface,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 ot({session:t,cropOn:e.cropOn,captureSnapshot:n.captureSnapshot,screenshotPath:a.path,logPath:e.logPath,dispatchContext:e.dispatchContext}),...await pe({device:t.device,path:a.path,requestedPixelDensity:r?.screenshotPixelDensity,scale:r?.screenshotScale})}}function at(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 ot(e){let{session:t,cropOn:n,captureSnapshot:r}=e;return n!==void 0||r===void 0?{}:{overlayRefs:await st({session:t,logPath:e.logPath,screenshotPath:e.screenshotPath,dispatchContext:e.dispatchContext,captureSnapshot:r})}}async function st(e){let{session:t,dispatchContext:n}=e,r={snapshotInteractiveOnly:!0},i=await C({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=x(i,r);return oe(t,a),await V({screenshotPath:e.screenshotPath,snapshot:a})}function ct(e,t){let n=e.positionals??[],r=e.flags??{},i=n=>n===void 0?void 0:ee(n,e.meta?.cwd??t),a=i(n[0]),o=i(r.out);return{outPath:a??o,recorded:{positionals:a?[a,...n.slice(1)]:n,flags:o?{...r,out:o}:r}}}function lt(e){let{session:t,dispatchContext:n,captureScreenshot:r,crop:o}=e;return{platform:c(t.device),captureScreenshot:async(e,s,c)=>{let u=i({...n,...a(c)}),d=await r({outPath:s,options:{appBundleId:n.appBundleId,pixelDensity:u.pixelDensity,fullscreen:u.fullscreen,normalizeStatusBar:u.normalizeStatusBar,stabilize:u.stabilize,surface:c?.surface,skipIosSimulatorBootCheck:n.skipIosSimulatorBootCheck??(l(t.device)&&t.device.kind===`simulator`),captureBackend:n.screenshotCaptureBackend},execution:$(n)});if(o){ge(t.device,d);let e=await Ee({device:t.device,session:t,surface:t.surface,cropOn:o.cropOn,screenshotPath:s,logPath:o.logPath,dispatchContext:n,captureSnapshot:o.captureSnapshot});o.run.warnings.push(...Te(e))}return d.displayRotation?{displayRotation:d.displayRotation}:void 0}}}function ut(){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 k.mkdtemp(j.join(A.tmpdir(),`agent-device-screenshot-`)),n=j.join(t,`screenshot.png`)),await k.mkdir(j.dirname(n),{recursive:!0}),{path:n,visibility:`client-visible`,publish:async()=>void 0,...t?{cleanup:async()=>{await k.rm(t,{recursive:!0,force:!0})}}:{}}},createTempFile:async e=>{let t=await k.mkdtemp(j.join(A.tmpdir(),`${e.prefix}-`));return{path:j.join(t,`file${e.ext}`),visibility:`internal`,cleanup:async()=>{await k.rm(t,{recursive:!0,force:!0})}}}}}export{V as a,X as i,$ as n,nt as r,Q as t};
@@ -1,5 +1,5 @@
1
1
  import{R as e,c as t}from"./sdk-contracts.js";import{r as n}from"./agent-device-client.js";import{T as r}from"./command-metadata.js";import{c as i}from"./file.js";import{t as a}from"./command-policy.js";import{n as o}from"./shared.js";import{t as s}from"./cli-runner.js";import{n as c,t as l}from"./color.js";import u from"node:path";function d(e,t){let n=e.baselineInitialized===!0,i=e.summary??{},a=y(i.additions),o=y(i.removals),s=y(i.unchanged),u=c(t),d=r(e),f=d.length>0?`${d.join(`
2
2
  `)}\n`:``;if(n)return`${f}Baseline initialized (${s} lines).\n`;let p=b(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 u?l(e,`green`):e}if(e.kind===`removed`){let e=t.startsWith(` `)?`-${t}`:`- ${t}`;return u?l(e,`red`):e}return u?l(t,`dim`):t}),m=p.length>0?`${p.join(`
3
- `)}\n`:``;return u?`${f}${m}${[`${l(String(a),`green`)} additions`,`${l(String(o),`red`)} removals`,`${l(String(s),`dim`)} unchanged`].join(`, `)}\n`:`${f}${m}${a} additions, ${o} removals, ${s} unchanged\n`}function f(e,t){let n=c(t.env),r=e.match===!0,i=e.dimensionMismatch,a=[];return a.push(...p(e,n)),a.push(...m(e,r,n,t.cwd)),!r&&!i&&(a.push(...h(e,n)),a.push(...g(e,n))),`${a.join(`
4
- `)}\n`}function p(e,t){if(e.match===!0)return[`${t?l(`✓`,`green`):`✓`} Screenshots match.`];let n=e.dimensionMismatch,r=t?l(`✗`,`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=y(e.differentPixels),a=y(e.mismatchPercentage),o=`${a===0&&i>0?`<0.01`:String(a)}% pixels differ`;return[`${r} ${t?l(o,`red`):o}`]}function m(e,t,n,r){if(t)return[];let i=[];if(e.diffPath){let t=v(e.diffPath,r),a=n?l(`Diff image:`,`dim`):`Diff image:`,o=n?l(t,`green`):t;i.push(` ${a} ${o}`)}if(e.currentOverlayPath){let t=v(e.currentOverlayPath,r),a=n?l(`Current overlay:`,`dim`):`Current overlay:`,o=n?l(t,`green`):t,s=y(e.currentOverlayRefCount),c=s>0?` (${s} refs)`:``;i.push(` ${a} ${o}${c}`)}return i}function h(e,t){let n=y(e.differentPixels),r=y(e.totalPixels);return[` ${t?l(String(n),`red`):String(n)} different / ${r} total pixels`]}function g(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${x(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(..._(e));return r}function _(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 v(e,t){let n=u.relative(t,e);return n===``||!n.startsWith(`..`)&&!u.isAbsolute(n)?n===``?`.`:`.${u.sep}${n}`:e}function y(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function b(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 x(e,t){return t?l(e,`dim`):e}const S=async({positionals:e,flags:r,client:i,host:a})=>{let c=await s({client:i,command:`screenshot`,positionals:e,flags:r,env:a.env});if(t(r.responseLevel))return await o(r,c,()=>JSON.stringify(c,null,2)),!0;let l=n(c);return await o(r,l,()=>{let e=c.overlayRefs?`Annotated ${c.overlayRefs.length} refs onto ${c.path}`:T(c),t=c.warnings??[];return t.length>0?[e,...t].join(`
3
+ `)}\n`:``;return u?`${f}${m}${[`${l(String(a),`green`)} additions`,`${l(String(o),`red`)} removals`,`${l(String(s),`dim`)} unchanged`].join(`, `)}\n`:`${f}${m}${a} additions, ${o} removals, ${s} unchanged\n`}function f(e,t){let n=c(t.env),r=e.match===!0,i=[];if(i.push(...p(e,n)),e.normalization){let{baseline:t,current:n,scaledCurrent:r,compared:a}=e.normalization;i.push(` Baseline ${t.width}x${t.height}; current ${n.width}x${n.height} → ${r.width}x${r.height}`),i.push(` Compared ${a.width}x${a.height}, aligned top-left; regions use comparison pixels`)}return i.push(...m(e,r,n,t.cwd)),r||(i.push(...h(e,n)),i.push(...g(e,n))),`${i.join(`
4
+ `)}\n`}function p(e,t){if(e.match===!0)return[`${t?l(`✓`,`green`):`✓`} Screenshots match.`];let n=t?l(`✗`,`red`):`✗`,r=y(e.differentPixels),i=y(e.mismatchPercentage),a=`${i===0&&r>0?`<0.01`:String(i)}% pixels differ`;return[`${n} ${t?l(a,`red`):a}`]}function m(e,t,n,r){if(t)return[];let i=[];if(e.diffPath){let t=v(e.diffPath,r),a=n?l(`Diff image:`,`dim`):`Diff image:`,o=n?l(t,`green`):t;i.push(` ${a} ${o}`)}if(e.currentOverlayPath){let t=v(e.currentOverlayPath,r),a=n?l(`Current overlay:`,`dim`):`Current overlay:`,o=n?l(t,`green`):t,s=y(e.currentOverlayRefCount),c=s>0?` (${s} refs)`:``;i.push(` ${a} ${o}${c}`)}return i}function h(e,t){let n=y(e.differentPixels),r=y(e.totalPixels);return[` ${t?l(String(n),`red`):String(n)} different / ${r} total pixels`]}function g(e,t){let n=Array.isArray(e.regions)?e.regions:[];if(n.length===0)return[];let r=[` ${x(`Changed regions:`,t)}`];for(let e of n.slice(0,5))r.push(..._(e));return r}function _(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 v(e,t){let n=u.relative(t,e);return n===``||!n.startsWith(`..`)&&!u.isAbsolute(n)?n===``?`.`:`.${u.sep}${n}`:e}function y(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function b(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 x(e,t){return t?l(e,`dim`):e}const S=async({positionals:e,flags:r,client:i,host:a})=>{let c=await s({client:i,command:`screenshot`,positionals:e,flags:r,env:a.env});if(t(r.responseLevel))return await o(r,c,()=>JSON.stringify(c,null,2)),!0;let l=n(c);return await o(r,l,()=>{let e=c.overlayRefs?`Annotated ${c.overlayRefs.length} refs onto ${c.path}`:T(c),t=c.warnings??[];return t.length>0?[e,...t].join(`
5
5
  `):e}),!0},C=async({positionals:t,flags:n,client:r,host:c})=>{if(t[0]===`snapshot`){let e=await s({client:r,command:`diff`,positionals:t,flags:n,env:c.env});return await o(n,e,()=>d(e,c.env)),!0}if(t[0]!==`screenshot`)return!1;let l=n.baseline;if(!l||typeof l!=`string`)throw new e(`INVALID_ARGS`,`diff screenshot requires --baseline <path>`);let u=i(l,{cwd:c.cwd}),p=typeof n.out==`string`?i(n.out,{cwd:c.cwd}):void 0,m=t[1];if(t.length>2)throw new e(`INVALID_ARGS`,`diff screenshot accepts at most one current screenshot path`);let[{createAgentDevice:h},{createLocalArtifactAdapter:g}]=await Promise.all([import(`./runtime10.js`),import(`./sdk-io.js`).then(e=>e.n)]),_=await h({backend:w(r,n),artifacts:g({cwd:c.cwd}),sessions:{get:e=>({name:e}),set:()=>{}},policy:a()}).capture.diffScreenshot({session:n.session,baseline:{kind:`path`,path:u},current:m?{kind:`path`,path:i(m,{cwd:c.cwd})}:{kind:`live`},...p?{out:{kind:`path`,path:p}}:{},threshold:D(n.threshold),overlayRefs:n.overlayRefs,normalizeStatusBar:n.screenshotNormalizeStatusBar,surface:n.surface});return await o(n,_,()=>f(_,c)),!0};function w(e,t){return{platform:E(t),captureScreenshot:async(t,r,i)=>{let a=await e.capture.screenshot({path:r,session:t.session,overlayRefs:i?.overlayRefs,pixelDensity:i?.pixelDensity,fullscreen:i?.fullscreen,normalizeStatusBar:i?.normalizeStatusBar,stabilize:i?.stabilize,surface:i?.surface});return n(a)}}}function T(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 E(e){switch(e.platform){case`android`:case`linux`:case`macos`:return e.platform;default:return`ios`}}function D(e){if(e!=null&&e!==``)return Number(e)}export{C as diffCommand,S as screenshotCommand};