agent-device 0.21.5 → 0.21.7

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 (307) hide show
  1. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.5.apk → agent-device-android-ime-helper-0.21.7.apk} +0 -0
  2. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.7.apk.sha256 +1 -0
  3. package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.5.manifest.json → agent-device-android-ime-helper-0.21.7.manifest.json} +4 -4
  4. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.5.apk → agent-device-android-snapshot-helper-0.21.7.apk} +0 -0
  5. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.7.apk.sha256 +1 -0
  6. package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.5.manifest.json → agent-device-android-snapshot-helper-0.21.7.manifest.json} +6 -6
  7. package/apple/snapshot-bridge/SnapshotBridgeRuntime.m +8 -1
  8. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.h +4 -0
  9. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerAXSnapshotBridge.m +20 -0
  10. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerScrollViewportPolicy.swift +1 -2
  11. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+AXSnapshotFallback.swift +25 -12
  12. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +56 -1
  13. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandJournal.swift +1 -1
  14. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Interaction.swift +36 -108
  15. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Keyboard.swift +241 -0
  16. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +29 -0
  17. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +46 -0
  18. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+PrivateAXPresentation.swift +85 -26
  19. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Snapshot.swift +134 -117
  20. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotBackendCapabilities.swift +1 -3
  21. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCapturePlan.swift +25 -4
  22. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SystemModal.swift +1 -1
  23. package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests.swift +3 -0
  24. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotCoordinateSpace.swift +197 -0
  25. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotModels.swift +30 -4
  26. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentation.swift +0 -81
  27. package/dist/apple/snapshot-presentation/Sources/AgentDeviceSnapshotPresentation/SnapshotPresentationInvariant.swift +1 -9
  28. package/dist/src/absence-observation-errors.js +1 -1
  29. package/dist/src/adapter.js +1 -1
  30. package/dist/src/adb-executor.js +2 -2
  31. package/dist/src/adb-failure.js +1 -1
  32. package/dist/src/adb-transport.js +1 -0
  33. package/dist/src/adb.js +1 -1
  34. package/dist/src/agent-browser-lifecycle.js +1 -1
  35. package/dist/src/agent-browser-process-record.js +1 -1
  36. package/dist/src/agent-browser-provider.js +1 -1
  37. package/dist/src/agent-browser-tool.js +1 -1
  38. package/dist/src/agent-device-client.js +2 -2
  39. package/dist/src/ai-sdk.js +1 -1
  40. package/dist/src/alert-runtime.js +1 -1
  41. package/dist/src/android-adb.d.ts +29 -2
  42. package/dist/src/android-adb.js +1 -1
  43. package/dist/src/android-input-ownership.js +1 -1
  44. package/dist/src/android.js +1 -1
  45. package/dist/src/app-catalog.js +1 -1
  46. package/dist/src/app-deployment-resolution.js +1 -1
  47. package/dist/src/app-helpers.js +1 -1
  48. package/dist/src/app-inventory.js +1 -1
  49. package/dist/src/app-launch.js +2 -2
  50. package/dist/src/app-lifecycle.js +3 -3
  51. package/dist/src/app-lifecycle2.js +2 -2
  52. package/dist/src/app-log-files.js +1 -1
  53. package/dist/src/app-log-reconnect.js +1 -1
  54. package/dist/src/app-log-runtime2.js +3 -3
  55. package/dist/src/app-resolution.js +2 -2
  56. package/dist/src/app-state.js +1 -1
  57. package/dist/src/apple-runner-platform.js +1 -1
  58. package/dist/src/application-lifecycle-interaction.js +1 -1
  59. package/dist/src/archive.js +1 -1
  60. package/dist/src/artifact-download.js +1 -1
  61. package/dist/src/auth-session.js +1 -1
  62. package/dist/src/auth.js +1 -1
  63. package/dist/src/back-mode.js +1 -1
  64. package/dist/src/backend-snapshot-options.js +1 -1
  65. package/dist/src/boot-diagnostics.js +1 -1
  66. package/dist/src/capture-disclosure.js +1 -0
  67. package/dist/src/capture.js +1 -1
  68. package/dist/src/cli-config.js +1 -1
  69. package/dist/src/cli-help.js +15 -2
  70. package/dist/src/cli-output.js +1 -1
  71. package/dist/src/cli.js +4 -4
  72. package/dist/src/click-button.js +1 -1
  73. package/dist/src/client-metro.js +1 -1
  74. package/dist/src/client-types.d.ts +32 -2
  75. package/dist/src/clipboard-shell-response.js +1 -0
  76. package/dist/src/command-schema.js +1 -1
  77. package/dist/src/command-tools.js +4 -2
  78. package/dist/src/command.js +1 -1
  79. package/dist/src/config.js +1 -1
  80. package/dist/src/connection-runtime.js +1 -1
  81. package/dist/src/connection.js +1 -1
  82. package/dist/src/contracts.d.ts +1 -1
  83. package/dist/src/contracts.js +1 -1
  84. package/dist/src/daemon-client-lifecycle.js +1 -1
  85. package/dist/src/daemon.js +1 -1
  86. package/dist/src/debug-symbols-facade.js +1 -1
  87. package/dist/src/device-boot.js +1 -1
  88. package/dist/src/device-claim-inspection.js +1 -1
  89. package/dist/src/device-claim-rule.js +2 -1
  90. package/dist/src/device-input-state.d.ts +7 -8
  91. package/dist/src/device-inventory-context.js +1 -1
  92. package/dist/src/device-rotation.js +1 -1
  93. package/dist/src/device-selection-resolver.js +1 -1
  94. package/dist/src/device-session.js +1 -1
  95. package/dist/src/device-shell.js +1 -0
  96. package/dist/src/device.js +1 -1
  97. package/dist/src/device2.js +1 -1
  98. package/dist/src/devicectl.js +1 -0
  99. package/dist/src/diagnostics.js +1 -1
  100. package/dist/src/dispatch-resolve.js +1 -1
  101. package/dist/src/display-inventory.js +1 -0
  102. package/dist/src/doctor-facade.js +1 -1
  103. package/dist/src/doctor2.js +1 -1
  104. package/dist/src/durable-resource.js +1 -1
  105. package/dist/src/engine-eval-script.js +1 -1
  106. package/dist/src/error.js +1 -1
  107. package/dist/src/exec.js +1 -1
  108. package/dist/src/file.js +1 -1
  109. package/dist/src/find.js +1 -1
  110. package/dist/src/finders.js +1 -1
  111. package/dist/src/format.js +2 -1
  112. package/dist/src/generic.js +1 -1
  113. package/dist/src/gesture-admission.js +1 -1
  114. package/dist/src/gesture-plan.js +1 -1
  115. package/dist/src/gesture-runtime.js +1 -1
  116. package/dist/src/harmonyos.js +1 -1
  117. package/dist/src/hdc.js +1 -1
  118. package/dist/src/helper.js +1 -1
  119. package/dist/src/human-control-contract.js +1 -1
  120. package/dist/src/human-control.js +1 -1
  121. package/dist/src/index.d.ts +1 -1
  122. package/dist/src/index.js +1 -1
  123. package/dist/src/input-actions.js +1 -1
  124. package/dist/src/input-actions2.js +1 -1
  125. package/dist/src/install-artifact-facade.js +1 -1
  126. package/dist/src/install-source-network-transport.js +1 -1
  127. package/dist/src/install-source2.js +1 -1
  128. package/dist/src/interaction-positionals.js +1 -1
  129. package/dist/src/interaction-ref-policy.js +1 -1
  130. package/dist/src/interaction.js +1 -1
  131. package/dist/src/interaction2.js +1 -1
  132. package/dist/src/interactor-operation-catalog.js +1 -1
  133. package/dist/src/interactor.js +5 -5
  134. package/dist/src/interactor2.js +1 -1
  135. package/dist/src/interactors.js +1 -1
  136. package/dist/src/internal/bin.js +1 -1
  137. package/dist/src/internal/daemon.js +2 -2
  138. package/dist/src/internal/png-worker.d.ts +4 -1
  139. package/dist/src/internal/png-worker.js +1 -1
  140. package/dist/src/internal/run-script-http-child.d.ts +1 -1
  141. package/dist/src/internal/run-script-http-child.js +1 -1
  142. package/dist/src/inventory.js +4 -4
  143. package/dist/src/inventory2.js +1 -1
  144. package/dist/src/inventory3.js +2 -2
  145. package/dist/src/inventory5.js +1 -1
  146. package/dist/src/ios-snapshot-acquisition.js +1 -1
  147. package/dist/src/ios-snapshot-runtime.js +1 -1
  148. package/dist/src/ios-target-activation.js +1 -0
  149. package/dist/src/lease-context.js +1 -1
  150. package/dist/src/lease-scope.js +1 -1
  151. package/dist/src/lease.js +1 -1
  152. package/dist/src/limrun-download-file.js +1 -0
  153. package/dist/src/limrun-runtime-dependencies.js +1 -1
  154. package/dist/src/limrun.d.ts +10 -4
  155. package/dist/src/linux.js +1 -1
  156. package/dist/src/local-interactor-operation-set.js +1 -1
  157. package/dist/src/location-coordinates.js +1 -1
  158. package/dist/src/logcat.js +1 -1
  159. package/dist/src/managed-device-scope.js +1 -1
  160. package/dist/src/mechanics.js +16 -16
  161. package/dist/src/mobile-snapshot-semantics.js +1 -1
  162. package/dist/src/multitouch-support.js +1 -1
  163. package/dist/src/observation.js +2 -2
  164. package/dist/src/output-common.js +5 -2
  165. package/dist/src/parameterized-recorded-fill.js +1 -1
  166. package/dist/src/perf-facade.js +2 -2
  167. package/dist/src/perf-runtime-operation-builder.js +1 -1
  168. package/dist/src/perf-runtime-plan.js +1 -1
  169. package/dist/src/perf.js +1 -1
  170. package/dist/src/physical-device-control.js +1 -1
  171. package/dist/src/platform-request-scope.js +1 -1
  172. package/dist/src/platform-runtime-android-adb-host.js +1 -1
  173. package/dist/src/platform-runtime-host.js +1 -1
  174. package/dist/src/platform-runtime-managed-owner.js +1 -1
  175. package/dist/src/platform-runtime-open-target.js +1 -1
  176. package/dist/src/platform-runtime-operation-host.js +4 -4
  177. package/dist/src/platform-runtime-runtime-hints.js +2 -2
  178. package/dist/src/platform-runtime-screen-recording-android-host.js +1 -1
  179. package/dist/src/platform-runtime-screen-recording-apple-runner-transport.js +1 -1
  180. package/dist/src/platform-runtime-screen-recording-apple-simulator-host.js +1 -1
  181. package/dist/src/platform-runtime-screen-recording-apple-transport.js +1 -1
  182. package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
  183. package/dist/src/platform-runtime-screen-recording-harmony-host.js +1 -1
  184. package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
  185. package/dist/src/platform-runtime-unavailable.js +1 -1
  186. package/dist/src/platform-runtime.js +1 -1
  187. package/dist/src/platform-runtime2.js +1 -1
  188. package/dist/src/png-crop-bytes.js +1 -1
  189. package/dist/src/png-transcode.js +1 -0
  190. package/dist/src/png-worker-client.js +1 -0
  191. package/dist/src/png.js +1 -1
  192. package/dist/src/prepare-kind.js +1 -1
  193. package/dist/src/provider-session-ownership.js +1 -1
  194. package/dist/src/provider-webdriver.js +1 -1
  195. package/dist/src/proxy.js +1 -1
  196. package/dist/src/quality-warnings.js +1 -1
  197. package/dist/src/react-native.js +1 -1
  198. package/dist/src/record-runtime.js +1 -1
  199. package/dist/src/record-trace.js +1 -1
  200. package/dist/src/rect-center.js +1 -1
  201. package/dist/src/register-builtins.js +1 -1
  202. package/dist/src/registry.js +35 -35
  203. package/dist/src/remote-config2.js +1 -1
  204. package/dist/src/replay-divergence.js +1 -1
  205. package/dist/src/replay.js +2 -2
  206. package/dist/src/reporting.js +1 -1
  207. package/dist/src/request-admission.js +1 -1
  208. package/dist/src/request-cancel.js +1 -1
  209. package/dist/src/request-runtime-binding.js +1 -1
  210. package/dist/src/result-serialization.js +1 -1
  211. package/dist/src/retry.js +1 -1
  212. package/dist/src/runner-cache-metadata.js +2 -2
  213. package/dist/src/runner-client.js +1 -1
  214. package/dist/src/runner-disposal.js +1 -1
  215. package/dist/src/runner-operations-facade.js +1 -1
  216. package/dist/src/runner-presentation.js +1 -1
  217. package/dist/src/runner.js +1 -1
  218. package/dist/src/runtime-transport-hints.js +1 -1
  219. package/dist/src/runtime.js +3 -3
  220. package/dist/src/runtime10.js +1 -1
  221. package/dist/src/runtime2.js +4 -4
  222. package/dist/src/runtime3.js +1 -1
  223. package/dist/src/runtime4.js +5 -5
  224. package/dist/src/runtime5.js +1 -1
  225. package/dist/src/runtime6.js +1 -1
  226. package/dist/src/runtime7.js +1 -1
  227. package/dist/src/runtime8.js +1 -1
  228. package/dist/src/runtime9.js +1 -1
  229. package/dist/src/screen-recording-admission-ledger.js +1 -0
  230. package/dist/src/screen-recording-completion.js +1 -1
  231. package/dist/src/screen-recording-options.js +1 -1
  232. package/dist/src/screen-recording-resource-recovery.js +1 -1
  233. package/dist/src/screen-recording-transport.js +1 -0
  234. package/dist/src/screenshot-density.js +1 -1
  235. package/dist/src/screenshot-runtime.js +1 -1
  236. package/dist/src/screenshot.js +1 -1
  237. package/dist/src/screenshot3.js +1 -1
  238. package/dist/src/script.js +1 -1
  239. package/dist/src/scroll-command.js +1 -1
  240. package/dist/src/scroll-gesture.js +1 -1
  241. package/dist/src/sdk-batch-runner.js +2 -2
  242. package/dist/src/sdk-batch.js +2 -2
  243. package/dist/src/sdk-contracts.d.ts +76 -1
  244. package/dist/src/sdk-contracts.js +1 -1
  245. package/dist/src/sdk-device.js +1 -1
  246. package/dist/src/sdk-finders.d.ts +1 -1
  247. package/dist/src/sdk-finders.js +1 -1
  248. package/dist/src/sdk-io.js +1 -1
  249. package/dist/src/sdk-remote-config.js +1 -1
  250. package/dist/src/sdk-selectors.d.ts +18 -1
  251. package/dist/src/sdk-selectors.js +1 -1
  252. package/dist/src/selection.js +0 -0
  253. package/dist/src/selector-runtime.js +1 -1
  254. package/dist/src/selectors.js +1 -1
  255. package/dist/src/semantic-index.js +1 -1
  256. package/dist/src/server.js +1 -1
  257. package/dist/src/session-allocation.js +1 -1
  258. package/dist/src/session-observation.js +1 -1
  259. package/dist/src/session-routing.js +1 -1
  260. package/dist/src/session-runtime-admission.js +1 -1
  261. package/dist/src/session-snapshot.js +1 -1
  262. package/dist/src/session-store.js +3 -3
  263. package/dist/src/session2.js +4 -5
  264. package/dist/src/settings.js +1 -1
  265. package/dist/src/simctl-facade.js +1 -1
  266. package/dist/src/simctl.js +1 -1
  267. package/dist/src/simulator-boot.js +1 -1
  268. package/dist/src/simulator.js +1 -1
  269. package/dist/src/snapshot-capture-annotations.js +1 -1
  270. package/dist/src/snapshot-diagnostics.js +1 -1
  271. package/dist/src/snapshot-quality-backend-capabilities.js +1 -1
  272. package/dist/src/snapshot-runtime-binding.js +1 -1
  273. package/dist/src/snapshot-runtime.js +1 -1
  274. package/dist/src/snapshot-state.js +1 -1
  275. package/dist/src/snapshot.js +1 -1
  276. package/dist/src/snapshot2.js +1 -1
  277. package/dist/src/snapshot3.js +1 -1
  278. package/dist/src/snapshot4.js +1 -1
  279. package/dist/src/src.js +1 -1
  280. package/dist/src/src4.js +1 -1
  281. package/dist/src/src7.js +1 -1
  282. package/dist/src/src8.js +1 -1
  283. package/dist/src/stop-sequence.js +1 -1
  284. package/dist/src/string-enum.js +1 -1
  285. package/dist/src/takeover.js +1 -1
  286. package/dist/src/text-entry-focus.js +1 -1
  287. package/dist/src/tool-provider.js +1 -1
  288. package/dist/src/tool-provider2.js +1 -1
  289. package/dist/src/touch-runtime.js +1 -1
  290. package/dist/src/transport.js +1 -1
  291. package/dist/src/tree.js +1 -1
  292. package/dist/src/tv-remote.js +1 -1
  293. package/dist/src/type-text-runtime.js +1 -1
  294. package/dist/src/verified-file.js +1 -1
  295. package/dist/src/video.js +2 -2
  296. package/dist/src/viewport.js +1 -1
  297. package/dist/src/web.js +1 -1
  298. package/dist/src/web2.js +1 -1
  299. package/dist/src/webdriver-source.js +1 -1
  300. package/dist/src/window-state.js +1 -1
  301. package/package.json +3 -2
  302. package/server.json +2 -2
  303. package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.5.apk.sha256 +0 -1
  304. package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.5.apk.sha256 +0 -1
  305. package/dist/src/adb-host.js +0 -1
  306. package/dist/src/session-target-evidence.js +0 -1
  307. package/dist/src/vars.js +0 -2
package/dist/src/png.js CHANGED
@@ -1 +1 @@
1
- import{i as e,t}from"./rolldown-runtime.js";import{C as n}from"./sdk-contracts.js";var r=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=n.exports=function(){i.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};r.inherits(a,i),a.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},a.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},a.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},a.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},a.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),i=t((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),a=t(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),o=t(((e,t)=>{let n=i(),r=a();function o(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let s=t.exports=function(e,t){let r=e.width,i=e.height,a=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],a){let e=n.getImagePasses(r,i);for(let t=0;t<e.length;t++)this._images.push({byteWidth:o(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:o(r,s,c),height:i,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},s.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},s.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},s.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},s.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},s.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),s=t(((t,n)=>{let i=e(`util`),a=r(),s=o(),c=n.exports=function(e){a.call(this);let t=[],n=this;this._filter=new s(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};i.inherits(c,a)})),c=t(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),l=t(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),u=t(((e,t)=>{let n=c(),r=l(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),d=t((e=>{let t=i(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function a(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function o(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function s(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,i=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=a(e,c));let f;f=c<=8?Buffer.alloc(r*i*4):new Uint16Array(r*i*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,i),g=t.getInterlaceIterator(r,i);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:i}]}for(let t=0;t<h.length;t++)c===8?m=o(h[t],f,g,l,e,m):s(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),f=t(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),p=t(((t,n)=>{let i=e(`util`),a=e(`zlib`),o=r(),c=s(),l=u(),p=d(),m=f(),h=n.exports=function(e){o.call(this),this._parser=new l(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};i.inherits(h,o),h.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},h.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=a.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,a.Z_MIN_CHUNK);this._inflate=a.createInflate({chunkSize:t});let n=e,r=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&r(e)}),this._filter.on(`complete`,this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,i(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},h.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new c(this._bitmapInfo)},h.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},h.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},h.prototype._simpleTransparency=function(){this._metaData.alpha=!0},h.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},h.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},h.prototype._complete=function(e){if(this.errord)return;let t;try{let n=p.dataToBitMap(e,this._bitmapInfo);t=m(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),m=t(((e,t)=>{let n=c();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),h=t(((e,t)=>{let n=a();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function o(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function s(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function c(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:o,2:c,3:u,4:f},h={0:i,1:s,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),g=t(((t,n)=>{let r=c(),i=l(),a=m(),o=h(),s=e(`zlib`),u=n.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:r.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:r.COLORTYPE_COLOR_ALPHA,[r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};u.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},u.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},u.prototype.filterData=function(e,t,n){let i=a(e,t,n,this._options),s=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(i,t,n,this._options,s)},u.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(i.crc32(r.slice(4,r.length-4)),r.length-4),r},u.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*r.GAMMA_DIVISION),0),this._packChunk(r.TYPE_gAMA,t)},u.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(r.TYPE_IHDR,n)},u.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},u.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),_=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=c(),o=g(),s=n.exports=function(e){i.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};r.inherits(s,i),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(a.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(i)}})),v=t(((t,n)=>{let r=e(`assert`).ok,i=e(`zlib`),a=e(`util`),o=e(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<i.Z_MIN_CHUNK&&(e.chunkSize=i.Z_MIN_CHUNK),i.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,n){if(typeof n==`function`)return i.Inflate._processChunk.call(this,e,t,n);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let n=c-t;if(r(n>=0,`have should not go down`),n>0){let e=a._buffer.slice(a._offset,a._offset+n);if(a._offset+=n,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0&&(d+=s-e,s=e,!0)}r(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},a.inherits(s,i.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=i.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}n.exports=t=d,t.Inflate=s,t.createInflate=c,t.inflateSync=d})),y=t(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),b=t((e=>{let t=y(),n=o();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),x=t(((t,n)=>{let r=!0,i=e(`zlib`),a=v();i.deflateSync||(r=!1);let o=y(),s=b(),c=u(),l=d(),p=f();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n;function u(e){n=e}let d;function f(e){d=e}function m(e){d.transColor=e}function h(e){d.palette=e}function g(){d.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:u,metadata:f,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),n)throw n;let S=Buffer.concat(y);y.length=0;let C;if(d.interlace)C=i.inflateSync(S);else{let e=((d.width*d.bpp*d.depth+7>>3)+1)*d.height;C=a(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,d);S=null;let T=l.dataToBitMap(w,d);w=null;let E=p(T,d,t.skipRescale);return d.data=E,d.gamma=_||0,d}})),S=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=c(),o=g();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n=new o(t||{}),s=[];s.push(Buffer.from(a.PNG_SIGNATURE)),s.push(n.packIHDR(e.width,e.height)),e.gamma&&s.push(n.packGAMA(e.gamma));let c=n.filterData(e.data,e.width,e.height),l=i.deflateSync(c,n.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(n.packIDAT(l)),s.push(n.packIEND()),Buffer.concat(s)}})),C=t((e=>{let t=x(),n=S();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),w=t((t=>{let n=e(`util`),r=e(`stream`),i=p(),a=_(),o=C(),s=t.PNG=function(e){r.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new i(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new a(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};n.inherits(s,r),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();function T(e,t){try{return w.PNG.sync.read(e)}catch(e){throw new n(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{w as n,T as t};
1
+ import{i as e,t}from"./rolldown-runtime.js";import{D as n}from"./sdk-contracts.js";var r=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=n.exports=function(){i.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};r.inherits(a,i),a.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},a.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},a.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},a.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},a.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),i=t((e=>{let t=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),a=t(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),o=t(((e,t)=>{let n=i(),r=a();function o(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let s=t.exports=function(e,t){let r=e.width,i=e.height,a=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],a){let e=n.getImagePasses(r,i);for(let t=0;t<e.length;t++)this._images.push({byteWidth:o(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:o(r,s,c),height:i,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};s.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},s.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},s.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},s.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},s.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},s.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),s=t(((t,n)=>{let i=e(`util`),a=r(),s=o(),c=n.exports=function(e){a.call(this);let t=[],n=this;this._filter=new s(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};i.inherits(c,a)})),c=t(((e,t)=>{t.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}})),l=t(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),u=t(((e,t)=>{let n=c(),r=l(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),d=t((e=>{let t=i(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function a(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function o(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function s(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,i=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=a(e,c));let f;f=c<=8?Buffer.alloc(r*i*4):new Uint16Array(r*i*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,i),g=t.getInterlaceIterator(r,i);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:i}]}for(let t=0;t<h.length;t++)c===8?m=o(h[t],f,g,l,e,m):s(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),f=t(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),p=t(((t,n)=>{let i=e(`util`),a=e(`zlib`),o=r(),c=s(),l=u(),p=d(),m=f(),h=n.exports=function(e){o.call(this),this._parser=new l(e,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,`gamma`),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=e,this.writable=!0,this._parser.start()};i.inherits(h,o),h.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},h.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=a.createInflate(),this._inflate.on(`error`,this.emit.bind(this,`error`)),this._filter.on(`complete`,this._complete.bind(this)),this._inflate.pipe(this._filter);else{let e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,a.Z_MIN_CHUNK);this._inflate=a.createInflate({chunkSize:t});let n=e,r=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&r(e)}),this._filter.on(`complete`,this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,i(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},h.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new c(this._bitmapInfo)},h.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},h.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},h.prototype._simpleTransparency=function(){this._metaData.alpha=!0},h.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},h.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},h.prototype._complete=function(e){if(this.errord)return;let t;try{let n=p.dataToBitMap(e,this._bitmapInfo);t=m(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),m=t(((e,t)=>{let n=c();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),h=t(((e,t)=>{let n=a();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function o(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function s(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function c(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function l(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function u(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function d(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function f(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function p(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let m={0:r,1:o,2:c,3:u,4:f},h={0:i,1:s,2:l,3:d,4:p};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=h[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,m[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),g=t(((t,n)=>{let r=c(),i=l(),a=m(),o=h(),s=e(`zlib`),u=n.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||s.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:r.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:r.COLORTYPE_COLOR_ALPHA,[r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([r.COLORTYPE_GRAYSCALE,r.COLORTYPE_COLOR,r.COLORTYPE_COLOR_ALPHA,r.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};u.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},u.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},u.prototype.filterData=function(e,t,n){let i=a(e,t,n,this._options),s=r.COLORTYPE_TO_BPP_MAP[this._options.colorType];return o(i,t,n,this._options,s)},u.prototype._packChunk=function(e,t){let n=t?t.length:0,r=Buffer.alloc(n+12);return r.writeUInt32BE(n,0),r.writeUInt32BE(e,4),t&&t.copy(r,8),r.writeInt32BE(i.crc32(r.slice(4,r.length-4)),r.length-4),r},u.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*r.GAMMA_DIVISION),0),this._packChunk(r.TYPE_gAMA,t)},u.prototype.packIHDR=function(e,t){let n=Buffer.alloc(13);return n.writeUInt32BE(e,0),n.writeUInt32BE(t,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(r.TYPE_IHDR,n)},u.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},u.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),_=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=c(),o=g(),s=n.exports=function(e){i.call(this);let t=e||{};this._packer=new o(t),this._deflate=this._packer.createDeflate(),this.readable=!0};r.inherits(s,i),s.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(a.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let i=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(i)}})),v=t(((t,n)=>{let r=e(`assert`).ok,i=e(`zlib`),a=e(`util`),o=e(`buffer`).kMaxLength;function s(e){if(!(this instanceof s))return new s(e);e&&e.chunkSize<i.Z_MIN_CHUNK&&(e.chunkSize=i.Z_MIN_CHUNK),i.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function c(e){return new s(e)}function l(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}s.prototype._processChunk=function(e,t,n){if(typeof n==`function`)return i.Inflate._processChunk.call(this,e,t,n);let a=this,s=e&&e.length,c=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(a._hadError)return;let n=c-t;if(r(n>=0,`have should not go down`),n>0){let e=a._buffer.slice(a._offset,a._offset+n);if(a._offset+=n,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||a._offset>=a._chunkSize)&&(c=a._chunkSize,a._offset=0,a._buffer=Buffer.allocUnsafe(a._chunkSize)),t===0&&(d+=s-e,s=e,!0)}r(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,c),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=o)throw l(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+o.toString(16)+` bytes`);let _=Buffer.concat(f,p);return l(this),_},a.inherits(s,i.Inflate);function u(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=i.Z_FINISH,e._processChunk(t,n)}function d(e,t){return u(new s(t),e)}n.exports=t=d,t.Inflate=s,t.createInflate=c,t.inflateSync=d})),y=t(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}else break}if(this._reads.length>0)throw Error(`There are some read requests waitng on finished stream`);if(this._buffer.length>0)throw Error(`unrecognised content at end of stream`)}})),b=t((e=>{let t=y(),n=o();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),x=t(((t,n)=>{let r=!0,i=e(`zlib`),a=v();i.deflateSync||(r=!1);let o=y(),s=b(),c=u(),l=d(),p=f();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n;function u(e){n=e}let d;function f(e){d=e}function m(e){d.transColor=e}function h(e){d.palette=e}function g(){d.alpha=!0}let _;function v(e){_=e}let y=[];function b(e){y.push(e)}let x=new o(e);if(new c(t,{read:x.read.bind(x),error:u,metadata:f,gamma:v,palette:h,transColor:m,inflateData:b,simpleTransparency:g}).start(),x.process(),n)throw n;let S=Buffer.concat(y);y.length=0;let C;if(d.interlace)C=i.inflateSync(S);else{let e=((d.width*d.bpp*d.depth+7>>3)+1)*d.height;C=a(S,{chunkSize:e,maxLength:e})}if(S=null,!C||!C.length)throw Error(`bad png - invalid inflate data response`);let w=s.process(C,d);S=null;let T=l.dataToBitMap(w,d);w=null;let E=p(T,d,t.skipRescale);return d.data=E,d.gamma=_||0,d}})),S=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=c(),o=g();n.exports=function(e,t){if(!r)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let n=new o(t||{}),s=[];s.push(Buffer.from(a.PNG_SIGNATURE)),s.push(n.packIHDR(e.width,e.height)),e.gamma&&s.push(n.packGAMA(e.gamma));let c=n.filterData(e.data,e.width,e.height),l=i.deflateSync(c,n.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(n.packIDAT(l)),s.push(n.packIEND()),Buffer.concat(s)}})),C=t((e=>{let t=x(),n=S();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),w=t((t=>{let n=e(`util`),r=e(`stream`),i=p(),a=_(),o=C(),s=t.PNG=function(e){r.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new i(e),this._parser.on(`error`,this.emit.bind(this,`error`)),this._parser.on(`close`,this._handleClose.bind(this)),this._parser.on(`metadata`,this._metadata.bind(this)),this._parser.on(`gamma`,this._gamma.bind(this)),this._parser.on(`parsed`,function(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new a(e),this._packer.on(`data`,this.emit.bind(this,`data`)),this._packer.on(`end`,this.emit.bind(this,`end`)),this._parser.on(`close`,this._handleClose.bind(this)),this._packer.on(`error`,this.emit.bind(this,`error`))};n.inherits(s,r),s.sync=o,s.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},s.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},s.prototype.write=function(e){return this._parser.write(e),!0},s.prototype.end=function(e){this._parser.end(e)},s.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},s.prototype._gamma=function(e){this.gamma=e},s.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},s.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},s.prototype.bitblt=function(e,t,n,r,i,a,o){return s.bitblt(this,e,t,n,r,i,a,o),this},s.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},s.prototype.adjustGamma=function(){s.adjustGamma(this)}}))();const T=Buffer.from([137,80,78,71,13,10,26,10]);function E(e){return e.subarray(0,T.length).equals(T)}function D(e,t){try{return w.PNG.sync.read(e)}catch(e){throw new n(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}export{E as n,w as r,D as t};
@@ -1 +1 @@
1
- import{C as e}from"./sdk-contracts.js";const t=[`auto`,`react-native`,`expo`,`repack`];function n(n){if(n!==void 0){if(t.includes(n))return n;throw new e(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}export{n as t};
1
+ import{D as e}from"./sdk-contracts.js";const t=[`auto`,`react-native`,`expo`,`repack`];function n(n){if(n!==void 0){if(t.includes(n))return n;throw new e(`INVALID_ARGS`,`metro prepare --kind must be auto, react-native, expo, or repack`)}}export{n as t};
@@ -1,2 +1,2 @@
1
- import{C as e}from"./sdk-contracts.js";import{c as t}from"./exec.js";import"./command.js";import n from"node:path";import r from"node:fs";import i from"node:crypto";import a from"node:os";function o(t,n){return new e(`COMMAND_FAILED`,`${t.label} not found or expired: ${n}`,{reason:`RESOURCE_EXPIRED`,hint:t.expiredHint})}function s(t,n,r,i){let a=t.get(n);if(!a)throw o(i,n);if(a.tenantId&&a.tenantId!==r)throw new e(`UNAUTHORIZED`,`${i.label} ${i.plural?`belong`:`belongs`} to a different tenant`);return a}const c=9e5,l={label:`Artifact`,expiredHint:`Downloadable artifacts are removed after download or after ${c/6e4} minutes. Re-run the command that produced the artifact and download it again.`},u=new Map;function d(e){let t=i.randomUUID(),n=Date.now(),r=setTimeout(()=>{C(t)},c);return r.unref(),u.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,artifactType:e.artifactType,fileName:e.fileName,deleteAfterDownload:e.deleteAfterDownload!==!1,createdAt:n,timer:r}),t}async function f(t,n){let{entry:r,stat:i}=h(t,n),a=await g(t,r,i);if(!a)throw new e(`COMMAND_FAILED`,`Artifact path is not a regular file or directory: ${r.artifactPath}`);return a}async function p(e){let t=[];for(let[n,i]of u){if(!b(i,e))continue;let a;try{a=r.statSync(i.artifactPath)}catch{C(n);continue}let o=await m(n,i,a);o&&t.push({id:n,...i.artifactType===void 0?{}:{artifactType:i.artifactType},filename:o.fileName??n,mimeType:o.mimeType,sizeBytes:o.sizeBytes,createdAt:new Date(i.createdAt).toISOString(),expiresAt:new Date(i.createdAt+c).toISOString()})}return t}async function m(e,t,n){try{return await g(e,t,n)}catch{return null}}function h(t,n){let i=s(u,t,n,l),a;try{a=r.statSync(i.artifactPath)}catch{throw C(t),new e(`COMMAND_FAILED`,`Artifact file is missing: ${i.artifactPath}`)}return{entry:i,stat:a}}async function g(e,t,n){if(n.isFile())return{artifactPath:t.artifactPath,fileName:x(t.fileName,e),mimeType:`application/octet-stream`,sizeBytes:n.size};if(!n.isDirectory())return null;let r=await _(e,t);return{artifactPath:r.archivePath,fileName:r.fileName,mimeType:`application/gzip`,sizeBytes:r.sizeBytes}}async function _(e,t){if(t.directoryArchive&&r.existsSync(t.directoryArchive.archivePath))return t.directoryArchive;if(t.directoryArchivePromise)return await t.directoryArchivePromise;let n=v(e,t);t.directoryArchivePromise=n;try{return await n}finally{t.directoryArchivePromise===n&&(t.directoryArchivePromise=void 0)}}async function v(s,c){w(c);let d=y(x(c.fileName,n.basename(c.artifactPath)||s)),f=r.mkdtempSync(n.join(a.tmpdir(),`agent-device-download-${i.randomUUID()}-`)),p=n.join(f,d);try{await t(`tar`,[`czf`,p,`-C`,n.dirname(c.artifactPath),`--`,n.basename(c.artifactPath)],{env:{...process.env,COPYFILE_DISABLE:`1`}});let e={archivePath:p,tempDir:f,fileName:d,sizeBytes:r.statSync(p).size};if(u.get(s)!==c)throw r.rmSync(f,{recursive:!0,force:!0}),o(l,s);return c.directoryArchive=e,e}catch(t){throw r.rmSync(f,{recursive:!0,force:!0}),t instanceof e?t:new e(`COMMAND_FAILED`,`Failed to archive downloadable artifact: ${c.artifactPath}`,{artifactPath:c.artifactPath},t instanceof Error?t:void 0)}}function y(e){let t=e.toLowerCase();return t.endsWith(`.tar.gz`)||t.endsWith(`.tgz`)?e:`${e}.tar.gz`}function b(e,t){return!e.tenantId||e.tenantId===t}function x(e,t){let n=e?.trim();return n&&!S(n)?n:t}function S(e){return e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.includes(`\r`)||e.includes(`
1
+ import{D as e}from"./sdk-contracts.js";import{c as t}from"./exec.js";import"./command.js";import n from"node:path";import r from"node:fs";import i from"node:crypto";import a from"node:os";function o(t,n){return new e(`COMMAND_FAILED`,`${t.label} not found or expired: ${n}`,{reason:`RESOURCE_EXPIRED`,hint:t.expiredHint})}function s(t,n,r,i){let a=t.get(n);if(!a)throw o(i,n);if(a.tenantId&&a.tenantId!==r)throw new e(`UNAUTHORIZED`,`${i.label} ${i.plural?`belong`:`belongs`} to a different tenant`);return a}const c=9e5,l={label:`Artifact`,expiredHint:`Downloadable artifacts are removed after download or after ${c/6e4} minutes. Re-run the command that produced the artifact and download it again.`},u=new Map;function d(e){let t=i.randomUUID(),n=Date.now(),r=setTimeout(()=>{C(t)},c);return r.unref(),u.set(t,{artifactPath:e.artifactPath,tenantId:e.tenantId,artifactType:e.artifactType,fileName:e.fileName,deleteAfterDownload:e.deleteAfterDownload!==!1,createdAt:n,timer:r}),t}async function f(t,n){let{entry:r,stat:i}=h(t,n),a=await g(t,r,i);if(!a)throw new e(`COMMAND_FAILED`,`Artifact path is not a regular file or directory: ${r.artifactPath}`);return a}async function p(e){let t=[];for(let[n,i]of u){if(!b(i,e))continue;let a;try{a=r.statSync(i.artifactPath)}catch{C(n);continue}let o=await m(n,i,a);o&&t.push({id:n,...i.artifactType===void 0?{}:{artifactType:i.artifactType},filename:o.fileName??n,mimeType:o.mimeType,sizeBytes:o.sizeBytes,createdAt:new Date(i.createdAt).toISOString(),expiresAt:new Date(i.createdAt+c).toISOString()})}return t}async function m(e,t,n){try{return await g(e,t,n)}catch{return null}}function h(t,n){let i=s(u,t,n,l),a;try{a=r.statSync(i.artifactPath)}catch{throw C(t),new e(`COMMAND_FAILED`,`Artifact file is missing: ${i.artifactPath}`)}return{entry:i,stat:a}}async function g(e,t,n){if(n.isFile())return{artifactPath:t.artifactPath,fileName:x(t.fileName,e),mimeType:`application/octet-stream`,sizeBytes:n.size};if(!n.isDirectory())return null;let r=await _(e,t);return{artifactPath:r.archivePath,fileName:r.fileName,mimeType:`application/gzip`,sizeBytes:r.sizeBytes}}async function _(e,t){if(t.directoryArchive&&r.existsSync(t.directoryArchive.archivePath))return t.directoryArchive;if(t.directoryArchivePromise)return await t.directoryArchivePromise;let n=v(e,t);t.directoryArchivePromise=n;try{return await n}finally{t.directoryArchivePromise===n&&(t.directoryArchivePromise=void 0)}}async function v(s,c){w(c);let d=y(x(c.fileName,n.basename(c.artifactPath)||s)),f=r.mkdtempSync(n.join(a.tmpdir(),`agent-device-download-${i.randomUUID()}-`)),p=n.join(f,d);try{await t(`tar`,[`czf`,p,`-C`,n.dirname(c.artifactPath),`--`,n.basename(c.artifactPath)],{env:{...process.env,COPYFILE_DISABLE:`1`}});let e={archivePath:p,tempDir:f,fileName:d,sizeBytes:r.statSync(p).size};if(u.get(s)!==c)throw r.rmSync(f,{recursive:!0,force:!0}),o(l,s);return c.directoryArchive=e,e}catch(t){throw r.rmSync(f,{recursive:!0,force:!0}),t instanceof e?t:new e(`COMMAND_FAILED`,`Failed to archive downloadable artifact: ${c.artifactPath}`,{artifactPath:c.artifactPath},t instanceof Error?t:void 0)}}function y(e){let t=e.toLowerCase();return t.endsWith(`.tar.gz`)||t.endsWith(`.tgz`)?e:`${e}.tar.gz`}function b(e,t){return!e.tenantId||e.tenantId===t}function x(e,t){let n=e?.trim();return n&&!S(n)?n:t}function S(e){return e.includes(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.includes(`\r`)||e.includes(`
2
2
  `)}function C(e){let t=u.get(e);if(t&&(clearTimeout(t.timer),u.delete(e),w(t),t.deleteAfterDownload))try{r.rmSync(t.artifactPath,{recursive:!0,force:!0})}catch{}}function w(e){if(e.directoryArchive)try{r.rmSync(e.directoryArchive.tempDir,{recursive:!0,force:!0})}catch{}finally{e.directoryArchive=void 0}}const T=3e5,E={label:`Uploaded artifact`,expiredHint:`Uploaded artifacts expire ${T/6e4} minutes after upload. Upload the file again and retry with the new upload id.`},D=new Map;function O(e){let t=i.randomUUID(),n=setTimeout(()=>{A(t)},T);return n.unref(),D.set(t,{artifactPath:e.artifactPath,tempDir:e.tempDir,tenantId:e.tenantId,timer:n}),t}function k(e,t){let n=s(D,e,t,E);return clearTimeout(n.timer),n.artifactPath}function A(e){let t=D.get(e);t&&(clearTimeout(t.timer),D.delete(e),r.rmSync(t.tempDir,{recursive:!0,force:!0}))}function j(e){let t=e?.providerSessionId;return typeof t==`string`&&t.trim().length>0?t.trim():void 0}var M=class{records=new Map;now;retentionMs;constructor(e={}){this.now=e.now??(()=>Date.now()),this.retentionMs=Number.isInteger(e.retentionMs)?Math.max(0,Number(e.retentionMs)):3e5}record(e,t){let n=e.leaseProvider?.trim(),r=t.trim();if(!n||!r)return;this.prune();let i={provider:n,providerSessionId:r,leaseId:e.leaseId,tenantId:e.tenantId};this.records.set(this.key(n,r),i)}markLeaseReleased(e,t=this.now()){let n=e.leaseProvider?.trim();if(!n)return;this.prune();let r=t+this.retentionMs;for(let[t,i]of this.records)i.provider===n&&i.leaseId===e.leaseId&&this.records.set(t,{...i,retainedUntil:r})}resolve(e){let t=e.provider?.trim(),n=e.providerSessionId?.trim(),r=e.tenantId?.trim();if(!t||!n||!r)return;this.prune();let i=this.records.get(this.key(t,n));if(!(!i||i.tenantId!==r))return{...i}}prune(){let e=this.now();for(let[t,n]of this.records)n.retainedUntil!==void 0&&n.retainedUntil<=e&&this.records.delete(t)}key(e,t){return JSON.stringify([e,t])}};export{p as a,d as c,A as i,O as l,j as n,f as o,C as r,k as s,M as t,s as u};
@@ -1 +1 @@
1
- import{C as e,D as t}from"./sdk-contracts.js";import{a as n,v as r}from"./sdk-device.js";import{Jt as i}from"./sdk-batch.js";import{d as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{i as s,r as c}from"./device-rotation.js";import{c as l}from"./exec.js";import"./command.js";import{r as u}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as ee}from"./webdriver-source.js";import{t as m}from"./providers.js";import h from"node:path";import te from"node:fs";import g from"node:fs/promises";import{setTimeout as ne}from"node:timers/promises";function re(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:ae(e?.launchTarget,n,r)}}function ie(e){return e===`ios`?`xctest`:`android`}function ae(...e){return e.find(e=>e!==void 0)}function oe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await ce(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),re(s,i)};return Object.freeze({fact:t=>se(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function se(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function ce(t,n,i,a,o,s,c){if(!p(n.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,f(n.capabilities,`install`),{provider:t.provider,deviceId:i.id,platform:r(i)});let l=n.prepared.uploadApp??t.uploadApp;if(l)return await l({provider:t.provider,lease:n.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}function v(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 le(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function ue(n,r){try{await r()}catch(r){n instanceof e&&(n.details={...n.details,cleanupError:t(r)})}}function de(e,t){return typeof e==`function`?e(t):e}function b(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function fe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function pe(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 me(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}const x=`webdriver_request_timeout`;function S(t){return t instanceof e&&t.details?.reason===x}var he=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=me(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:b(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.requestValueWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??this.requestPolicy.retryAttempts,timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestValueWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestValueOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!ge(e,a,r.retryAttempts,r.signal))throw e;await ne(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestValueOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?ve(s):{};if(!a)throw ye(o,c);return _e(c)}async fetchWebDriver(e,t,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a;try{let r=await fetch(new URL(fe(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:o});return{ok:r.ok,status:r.status,text:await r.text()}}catch(n){throw a.aborted&&!i?.aborted?be(e,t,r,n):n}}};function ge(e,t,n,r){return!r?.aborted&&xe(e)&&t<n}function _e(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function ve(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function ye(t,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 ${t}.`;return new e(`COMMAND_FAILED`,i,{status:t,response:n})}function be(t,n,r,i){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} timed out after ${r}ms.`,{reason:x,method:t,path:n,timeoutMs:r},i instanceof Error?i:void 0)}function xe(t){if(S(t))return!0;if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return t instanceof TypeError}var Se=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new he(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=we(await this.requestValue(`POST`,`/session`,{capabilities:Ce(e)},{retryAttempts:0,timeoutMs:Oe(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){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(O(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=De(await this.sessionRequest(`GET`,`/element/active`,void 0,T(t)))}catch(e){if(O(e))return`unsupported`;if(D(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,T(t));return{id:n,rect:C(e)}}catch(e){if(O(e))return`unsupported`;if(D(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(t){let n=await this.sessionRequest(`GET`,`/source`,void 0,t);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await g.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return C(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}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 e(`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 C(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:w(n,`x`),y:w(n,`y`),width:w(n,`width`),height:w(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function w(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ce(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function we(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}const Te=new Set([405,501]),Ee=new Set([`unknown command`,`unknown method`]);function De(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 T(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:E(e)}}function Oe(e,t){return t===void 0?e:Math.min(e,E(t))}function E(e){return Math.max(0,e-Date.now())}function D(t){return t instanceof e&&k(t).toLowerCase()===`no such element`}function O(t){if(!(t instanceof e))return!1;let n=t.details?.status;return typeof n==`number`&&Te.has(n)?!0:Ee.has(k(t).toLowerCase())}function k(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 A(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function ke(e){return j(ee(e,`android`).nodes)}function Ae(e){return j(ee(e).nodes)}function j(e){let t=e.flatMap(e=>je(e)&&Me(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 je(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Me(e){return!!e&&e.width>=50&&e.height>=50}async function Ne(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Re(t,e,r);return}catch(t){if(!Ie(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{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})}const Pe=new Set([`unknown command`,`unknown method`]),Fe=new Set([404,405]);function Ie(t){if(!(t instanceof e)||t.code===`SESSION_NOT_FOUND`)return!1;let n=Le(t.details?.response);if(n)return Pe.has(n);let r=t.details?.status;return typeof r==`number`&&Fe.has(r)}function Le(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function Re(e,t,n){if(t===`rotation`){await e.setRotation(s(n));return}await e.setOrientation(c(n))}const M=1500;function ze(e){return new Promise(t=>setTimeout(t,e))}function N(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,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 Be(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,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 Ve(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function He(e){return new Ue(e.client,e.backend,e.capabilities,e.targetId)}var Ue=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(t,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new e(`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(t,n);let o=await this.awaitTextEntryReadiness(a,t,n);return await this.type(r),{backend:`webdriver`,x:t,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(Ge(e)),await this.client.performActions(e.pointers.map(e=>A(`gesture-pointer-${e.pointerId}`,We(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=await this.readSource(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(t,this.targetId)}let{parseWebDriverSourceFacts:n}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:n(t,`android`).nodes}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw S(e)?Ke(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 Ne(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 readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`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 readAlert(){this.unsupported(`alert`)}async awaitAlert(){this.unsupported(`alert`)}async acceptAlert(){this.unsupported(`alert`)}async dismissAlert(){this.unsupported(`alert`)}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||Ve(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw N(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Be(t,n);if(r)throw N(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 N(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(M),this.client.activeElement(M)]);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(M,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await ze(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([A(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ae(e):ke(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,f(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function We(t){let n=t[0];if(!n)throw new e(`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 e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];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 Ge(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 Ke(t){return new e(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...t.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.`},t)}var qe=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;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new Se({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:He({client:r,backend:ie(n.platform),capabilities:s,targetId:a.id})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.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=S(e)?Je(e,this.options.provider,n,t):e;throw await ue(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:P(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...n(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 n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}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 le({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function P(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function Je(t,n,r,i){let a=t.details?.timeoutMs;return new e(`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.`},t)}function F(e){return new Ye(e)}var Ye=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new qe(e),this.deployment=oe({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-runtime2.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()}};async function I(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Ze(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function Xe(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Ze(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:Qe(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function Qe(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}m.awsDeviceFarm;const $e={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function L(e){let t=R(e);return{createRemoteAccessSession:async e=>z(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>z(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>z(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>Xe(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function et(t){return async({lease:n,req:r,base:i})=>{let a=await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:de(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration}),o,s;try{if(o=await rt(a.arn,t,r),s=tt(o),!s)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(e){throw await ue(e,()=>t.client.stopRemoteAccessSession(a.arn)),e}let c=o.device?.name??t.deviceName,l=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{},u=t.platform===`android`?{"appium:autoLaunch":!1}:{};return{...i,endpoint:s,platform:t.platform,deviceName:c,webdriverCapabilities:P(t.platform,c,{...u,...l}),cleanup:async()=>(await t.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function tt(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?nt(n):void 0}function nt(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function rt(t,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(t);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;at(c),await ne(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:c.status,result:c.result,timeoutMs:o-a})}const it=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function at(t){if(!(!t.status||!it.has(t.status)))throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t.arn,status:t.status,result:t.result})}async function ot(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function R(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await ot(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function z(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const B=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerAppiumVersion`,capability:`appiumVersion`,flag:`--provider-appium-version`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function st(e,t){pt(e);let n={};for(let r of B){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(ft(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function ct(e){return B.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function V(t,n){let r=ct(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function lt(e){let t={};for(let n of B){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&ut(t,n,r)}return t}function ut(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=dt(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function dt(t,n){let r=o.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:t.flag,capability:t.capability})}function ft(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function pt(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}m.browserStack;const mt={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function H(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:yt(e,t,await vt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function U(t,n,r){r?.throwIfAborted();let i=await g.readFile(t),a=new FormData;a.set(`file`,new Blob([i]),h.basename(t));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:b(n)},body:a,signal:r}),s=await o.json(),c=bt(s);if(!o.ok||!c)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function ht(e){return async({appPath:t,options:n,signal:r})=>({appReference:await U(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function gt(e){let{"bstack:options":t,...n}=e.configured??{};return{"appium:deviceName":e.deviceName,"appium:platformVersion":e.osVersion,...e.app?{"appium:app":e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},..._t(t)}}}function _t(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function vt(t,n){let r=new URL(`${pe(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:b(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function yt(e,t,n){return[W(e,t,n,`video_url`,`video`,`Session video`),W(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),W(e,t,n,`device_logs_url`,`device-log`,`Device logs`),W(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),W(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function W(e,t,n,r,i,a){let o=n[r];if(typeof o==`string`&&o.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function bt(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function G(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function xt(t,n){let r=R({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=K(i,`project`),c=K(a,`device`),l=Ct(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${q(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?St(K(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:q(s.name),reference:t.projectArn},device:{status:`verified`,name:q(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:q(c.os),availability:q(c.availability)},app:u}}function St(t,n){let r=q(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=q(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:q(t.name),reference:n.appArn}}function K(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function Ct(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function q(e){return typeof e==`string`&&e.length>0?e:void 0}async function wt(t,n){let r={username:t.username,accessKey:t.accessKey},i=Dt(await J(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&Et(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await Tt(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function Tt(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Ot(await J(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:h.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function J(t,n,r){try{let i=await fetch(t,{headers:{...y(r),Authorization:b(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function Et(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Dt(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Ot(t){let n=Y(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function kt(e,t){return e.provider===`browserstack`?await wt(e,t.clientVersion):await xt(e,t.runHostCommand)}function At(e){return[{provider:m.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:mt,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Nt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await jt({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:ht({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:gt({deviceName:l,osVersion:u,app:d,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:st(lt(a.flags),c),configured:P(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:$e,listArtifacts:async({provider:n,providerSessionId:r})=>await I(n,r,L({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??G(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`AWS Device Farm`);V(a.flags,m.awsDeviceFarm);let o=Nt(a,`AWS Device Farm`);return await et({client:L({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Pt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Pt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:Ft(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=L({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??G(t)});return await I(m.awsDeviceFarm,t,r)}}]}async function jt(t){if(Mt(t.app))return t.app;let n=h.resolve(t.cwd??process.cwd(),t.app);if(!te.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await U(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint},t.signal)}function Mt(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function X(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Nt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(t,n,r){let i=Q(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Pt(t,n,r,i,a){let o=Q(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${It(String(r))} or ${a}.`)}function Ft(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function It(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Lt(e){let t=At(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await kt(t,e)}}const Rt=Lt({clientVersion:u(),runHostCommand:async(e,t)=>({stdout:(await l(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{G as n,V as r,Rt as t};
1
+ import{D as e,j as t}from"./sdk-contracts.js";import{a as n,y as r}from"./sdk-device.js";import{Yt as i}from"./sdk-batch.js";import{d as a}from"./scroll-gesture.js";import{c as o}from"./sdk-remote-config.js";import"./device.js";import{i as s,r as c}from"./device-rotation.js";import{c as l}from"./exec.js";import"./command.js";import{r as u}from"./version.js";import{n as d,r as f,t as p}from"./capabilities.js";import{t as ee}from"./webdriver-source.js";import{t as m}from"./providers.js";import h from"node:path";import te from"node:fs";import g from"node:fs/promises";import{setTimeout as ne}from"node:timers/promises";function re(e,t){let n=e?.bundleId??t?.appIdentifierHint,r=e?.packageName??t?.packageNameHint;return{bundleId:n,packageName:r,appName:e?.appName,launchTarget:ae(e?.launchTarget,n,r)}}function ie(e){return e===`ios`?`xctest`:`android`}function ae(...e){return e.find(e=>e!==void 0)}function oe(e){let t=async(t,n,r,i,a)=>{let o=e.findSessionForDevice(t);if(!o)return;let s=await ce(e,o,t,n,r,i,a);return await o.client.installApp(s?.appReference??r,a),re(s,i)};return Object.freeze({fact:t=>se(e.findSessionForDevice(t)),installApp:t,installInstallablePath:async(e,n,r,i)=>await t(e,``,n,r,i),deployApp:async(e,n,r)=>_(await t(e,n.app,n.appPath,{relaunch:n.replaceExisting,appIdentifierHint:n.app,packageNameHint:n.app},r),n.app),deployMaterializedApp:async(e,n,r)=>_(await t(e,``,n.artifact.installablePath,{appIdentifierHint:n.artifact.bundleId,packageNameHint:n.artifact.packageName},r))})}function se(e){return e?p(e.capabilities,`install`)?Object.freeze({available:!0}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:f(e.capabilities,`install`)}):Object.freeze({available:!1,reason:`owner-capability-missing`,hint:`The WebDriver provider session is no longer active for this device.`})}async function ce(t,n,i,a,o,s,c){if(!p(n.capabilities,`install`))throw new e(`UNSUPPORTED_OPERATION`,f(n.capabilities,`install`),{provider:t.provider,deviceId:i.id,platform:r(i)});let l=n.prepared.uploadApp??t.uploadApp;if(l)return await l({provider:t.provider,lease:n.lease,device:i,app:a,appPath:o,options:s,signal:c})}function _(t,n){if(!t)throw new e(`UNSUPPORTED_OPERATION`,`The WebDriver provider session no longer supports app deployment.`);return{...t.bundleId?{bundleId:t.bundleId}:{},...t.packageName?{packageName:t.packageName}:{},...t.appName?{appName:t.appName}:{},...t.launchTarget??n?{launchTarget:t.launchTarget??n}:{}}}function v(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 le(e){return{provider:e.provider,providerSessionId:e.providerSessionId,status:`unavailable`,cloudArtifacts:[],message:e.error instanceof Error?e.error.message:String(e.error)}}function y(e){return{"x-agent-device-client":`agent-device-cli`,"x-agent-device-version":e}}async function ue(n,r){try{await r()}catch(r){n instanceof e&&(n.details={...n.details,cleanupError:t(r)})}}function de(e,t){return typeof e==`function`?e(t):e}function b(e){return`Basic ${Buffer.from(`${e.username}:${e.accessKey}`).toString(`base64`)}`}function fe(e){let t=0;for(;t<e.length&&e.charCodeAt(t)===47;)t+=1;return t===0?e:e.slice(t)}function pe(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 me(e){if(e.pathname.endsWith(`/`))return e;let t=new URL(e);return t.pathname=`${t.pathname}/`,t}const x=`webdriver_request_timeout`;function S(t){return t instanceof e&&t.details?.reason===x}var he=class{endpoint;headers;requestPolicy;constructor(e){this.endpoint=me(new URL(e.endpoint)),this.headers={...y(e.clientVersion),...e.auth?{Authorization:b(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.requestValueWithRetries(e,t,n,{retryAttempts:r?.retryAttempts??this.requestPolicy.retryAttempts,timeoutMs:r?.timeoutMs??this.requestPolicy.timeoutMs,signal:r?.signal})}async requestValueWithRetries(e,t,n,r){let i;for(let a=0;a<=r.retryAttempts;a+=1)try{return await this.requestValueOnce(e,t,n,r.timeoutMs,r.signal)}catch(e){if(i=e,!ge(e,a,r.retryAttempts,r.signal))throw e;await ne(this.requestPolicy.retryDelayMs,void 0,{signal:r.signal})}throw i}async requestValueOnce(e,t,n,r,i){let{ok:a,status:o,text:s}=await this.fetchWebDriver(e,t,n,r,i),c=s?ve(s):{};if(!a)throw ye(o,c);return _e(c)}async fetchWebDriver(e,t,n,r,i){let a=AbortSignal.timeout(r),o=i?AbortSignal.any([i,a]):a;try{let r=await fetch(new URL(fe(t),this.endpoint),{method:e,headers:{Accept:`application/json`,...n===void 0?{}:{"Content-Type":`application/json`},...this.headers},body:n===void 0?void 0:JSON.stringify(n),signal:o});return{ok:r.ok,status:r.status,text:await r.text()}}catch(n){throw a.aborted&&!i?.aborted?be(e,t,r,n):n}}};function ge(e,t,n,r){return!r?.aborted&&xe(e)&&t<n}function _e(e){if(!e||typeof e!=`object`)return e;let t=e;return`value`in t?t.value:e}function ve(t){try{return JSON.parse(t)}catch(n){throw new e(`COMMAND_FAILED`,`WebDriver response was not valid JSON.`,{text:t},n)}}function ye(t,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 ${t}.`;return new e(`COMMAND_FAILED`,i,{status:t,response:n})}function be(t,n,r,i){return new e(`COMMAND_FAILED`,`WebDriver ${t} ${n} timed out after ${r}ms.`,{reason:x,method:t,path:n,timeoutMs:r},i instanceof Error?i:void 0)}function xe(t){if(S(t))return!0;if(t instanceof e){let e=t.details?.status;return typeof e==`number`&&e>=500}return t instanceof TypeError}var Se=class{transport;sessionCreateTimeoutMs;sessionId;constructor(e){this.transport=new he(e),this.sessionCreateTimeoutMs=e.requestPolicy?.sessionCreateTimeoutMs??18e4}async createSession(e,t){let n=we(await this.requestValue(`POST`,`/session`,{capabilities:Ce(e)},{retryAttempts:0,timeoutMs:Oe(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){try{await this.sessionRequest(`POST`,`/appium/device/activate_app`,{appId:e})}catch{await this.executeScript(`mobile: activateApp`,[{appId:e,bundleId:e}])}}async terminateApp(e){try{await this.sessionRequest(`POST`,`/appium/device/terminate_app`,{appId:e})}catch{await this.executeScript(`mobile: terminateApp`,[{appId:e,bundleId:e}])}}async performActions(e){await this.sessionRequest(`POST`,`/actions`,{actions:e})}async releaseActions(){await this.sessionRequest(`DELETE`,`/actions`,void 0,{retryAttempts:0})}async sendKeys(e){await this.sessionRequest(`POST`,`/keys`,{value:Array.from(e)})}async hideKeyboard(){await this.sessionRequest(`POST`,`/appium/device/hide_keyboard`,void 0,{retryAttempts:0})}async isKeyboardShown(e){let t;try{t=await this.sessionRequest(`GET`,`/appium/device/is_keyboard_shown`,void 0,{retryAttempts:0,...e===void 0?{}:{timeoutMs:e}})}catch(e){if(O(e))return`unsupported`;throw e}return typeof t==`boolean`?t:`unsupported`}async activeElement(e){let t=e===void 0?void 0:Date.now()+e,n;try{n=De(await this.sessionRequest(`GET`,`/element/active`,void 0,T(t)))}catch(e){if(O(e))return`unsupported`;if(D(e))return`none`;throw e}if(n===void 0)return`unsupported`;try{let e=await this.sessionRequest(`GET`,`/element/${encodeURIComponent(n)}/rect`,void 0,T(t));return{id:n,rect:C(e)}}catch(e){if(O(e))return`unsupported`;if(D(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(t){let n=await this.sessionRequest(`GET`,`/source`,void 0,t);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver source response was not a string`,{valueType:typeof n});return n}async screenshot(t){let n=await this.sessionRequest(`GET`,`/screenshot`);if(typeof n!=`string`)throw new e(`COMMAND_FAILED`,`WebDriver screenshot response was not base64 text`,{valueType:typeof n});await g.writeFile(t,Buffer.from(n,`base64`))}async windowRect(){return C(await this.sessionRequest(`GET`,`/window/rect`))}async executeScript(e,t=[]){return await this.sessionRequest(`POST`,`/execute/sync`,{script:e,args:t})}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 e(`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 C(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was empty.`);let n=t,r={x:w(n,`x`),y:w(n,`y`),width:w(n,`width`),height:w(n,`height`)};if(r.x===void 0||r.y===void 0||r.width===void 0||r.height===void 0)throw new e(`COMMAND_FAILED`,`WebDriver window rect response was invalid.`,{response:n});return r}function w(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ce(e){return`alwaysMatch`in e||`firstMatch`in e?e:{alwaysMatch:e}}function we(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`WebDriver create-session response was empty.`);let n=t,r=typeof n.sessionId==`string`?n.sessionId:typeof n.session_id==`string`?n.session_id:void 0;if(!r)throw new e(`COMMAND_FAILED`,`WebDriver create-session response missed sessionId.`,{response:n});return{sessionId:r,capabilities:n.capabilities&&typeof n.capabilities==`object`?n.capabilities:{}}}const Te=new Set([405,501]),Ee=new Set([`unknown command`,`unknown method`]);function De(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 T(e){return e===void 0?{retryAttempts:0}:{retryAttempts:0,timeoutMs:E(e)}}function Oe(e,t){return t===void 0?e:Math.min(e,E(t))}function E(e){return Math.max(0,e-Date.now())}function D(t){return t instanceof e&&k(t).toLowerCase()===`no such element`}function O(t){if(!(t instanceof e))return!1;let n=t.details?.status;return typeof n==`number`&&Te.has(n)?!0:Ee.has(k(t).toLowerCase())}function k(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 A(e,t){return{type:`pointer`,id:e,parameters:{pointerType:`touch`},actions:t}}async function ke(e){return j(ee(e,`android`).nodes)}function Ae(e){return j(ee(e).nodes)}function j(e){let t=e.flatMap(e=>je(e)&&Me(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 je(e){let t=e.type?.toLowerCase()??``;return e.visibleToUser!==!1&&(t.includes(`scrollview`)||t.includes(`listview`)||t.includes(`recyclerview`))}function Me(e){return!!e&&e.width>=50&&e.height>=50}async function Ne(t,n,r){let i=[];for(let e of n===`android`?[`rotation`,`orientation`]:[`orientation`,`rotation`])try{await Re(t,e,r);return}catch(t){if(!Ie(t))throw t;i.push({transport:e,error:t instanceof Error?t.message:String(t)})}throw new e(`COMMAND_FAILED`,`Could not set device orientation to ${r} on the hosted WebDriver session.`,{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})}const Pe=new Set([`unknown command`,`unknown method`]),Fe=new Set([404,405]);function Ie(t){if(!(t instanceof e)||t.code===`SESSION_NOT_FOUND`)return!1;let n=Le(t.details?.response);if(n)return Pe.has(n);let r=t.details?.status;return typeof r==`number`&&Fe.has(r)}function Le(e){if(!e||typeof e!=`object`)return``;let t=e.value;if(!t||typeof t!=`object`)return``;let n=t.error;return typeof n==`string`?n:``}async function Re(e,t,n){if(t===`rotation`){await e.setRotation(s(n));return}await e.setOrientation(c(n))}const M=1500;function ze(e){return new Promise(t=>setTimeout(t,e))}function N(t,n,r){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but ${r}`,{reason:`text_entry_focus_not_observed`,x:t,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 Be(t,n){return new e(`COMMAND_FAILED`,`fill tapped (${t}, ${n}) but this driver reports neither the focused element nor keyboard state, so the text was not sent`,{reason:`text_entry_focus_unobservable`,x:t,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 Ve(e,t,n){return t>=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height}function He(e){return new Ue(e.client,e.backend,e.capabilities,e.targetId)}var Ue=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(t,n,r,i){if(this.requireSupport(`fill`),r.length===0)throw new e(`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(t,n);let o=await this.awaitTextEntryReadiness(a,t,n);return await this.type(r),{backend:`webdriver`,x:t,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(Ge(e)),await this.client.performActions(e.pointers.map(e=>A(`gesture-pointer-${e.pointerId}`,We(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=await this.readSource(e);if(this.backend===`xctest`){let{acquireWebDriverIosSnapshot:e}=await import(`./webdriver-ios-snapshot.js`);return e(t,this.targetId)}let{parseWebDriverSourceFacts:n}=await import(`./webdriver-source.js`).then(e=>e.n);return{backend:`android`,producer:`appium-source`,nodes:n(t,`android`).nodes}}async readSource(e){try{return await this.client.source(e===void 0?{}:{signal:e})}catch(e){throw S(e)?Ke(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 Ne(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 actionButton(){throw new e(`UNSUPPORTED_OPERATION`,`action-button presses iPhone Action Button hardware, which no WebDriver backend exposes`,{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:`actionButton`,reason:`unsupported-provider-mode`})}async readClipboard(){this.requireSupport(`clipboard.read`);let e=await this.client.executeScript(`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 readAlert(){this.unsupported(`alert`)}async awaitAlert(){this.unsupported(`alert`)}async acceptAlert(){this.unsupported(`alert`)}async dismissAlert(){this.unsupported(`alert`)}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||Ve(r.rect,t,n)?`satisfied`:`retry`});if(o===`satisfied`)return`focused-element`;if(o===`expired`)throw N(t,n,`nothing there took text-entry focus, so the text was not sent`);if(r===`unsupported`)throw Be(t,n);if(r)throw N(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 N(t,n,`no keyboard appeared, so the text was not sent`)}async readTextEntryState(){let[e,t]=await Promise.all([this.client.isKeyboardShown(M),this.client.activeElement(M)]);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(M,i));if(n=!0,e!==`retry`)return e}catch(e){r=e}let a=e-Date.now();if(a<=0)break;await ze(Math.min(100,a))}if(!n&&r!==void 0)throw r;return`expired`}async pointerGesture(e,t){await this.client.performActions([A(e,t)]),await this.client.releaseActions().catch(()=>void 0)}async scrollGestureFrame(){return await this.client.source().then(e=>this.backend===`xctest`?Ae(e):ke(e)).catch(()=>void 0)||await this.client.windowRect()}requireSupport(e){p(this.capabilities,e)||this.unsupported(e)}unsupported(t){throw new e(`UNSUPPORTED_OPERATION`,f(this.capabilities,t),{provider:this.capabilities.provider,platform:this.capabilities.platform,operation:t})}};function We(t){let n=t[0];if(!n)throw new e(`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 e=1;e<t.length;e+=1){let n=t[e-1],i=t[e];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 Ge(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 Ke(t){return new e(`COMMAND_FAILED`,`The cloud driver did not finish reading the screen in its budget.`,{...t.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.`},t)}var qe=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;if(this.sessionsByLeaseId.has(e.leaseId))return this.heartbeat(e);let n=await this.prepareSession(e,t),r=new Se({clientVersion:this.options.clientVersion,endpoint:n.endpoint,auth:n.auth,headers:n.headers,requestPolicy:this.options.requestPolicy}),i=await this.createSessionWithPreparedCleanup(r,n,e,t),a=this.deviceForLease(e,n),o=n.providerSessionId??i.sessionId,s=d({provider:this.options.provider,platform:n.platform,overrides:this.options.capabilityOverrides});return this.sessionsByLeaseId.set(e.leaseId,Object.freeze({lease:e,device:a,client:r,prepared:n,capabilities:s,webDriverSessionId:i.sessionId,providerSessionId:o,interactor:He({client:r,backend:ie(n.platform),capabilities:s,targetId:a.id})})),this.ownedDeviceIds.add(a.id),{provider:this.options.provider,deviceId:a.id,sessionId:i.sessionId,providerSessionId:o,capabilities:s,...n.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=S(e)?Je(e,this.options.provider,n,t):e;throw await ue(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:P(this.options.platform,this.options.deviceName,t)}}deviceForLease(e,t){return{...n(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 n=[],r;try{await e.client.deleteSession()}catch(e){n.push({code:`WEBDRIVER_SESSION_DELETE_FAILED`,message:t(e)})}try{r=await e.prepared.cleanup?.()}catch(e){n.push({code:`PROVIDER_CLEANUP_FAILED`,message:t(e)})}return{cleanup:r,warnings:n}}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 le({provider:this.options.provider,providerSessionId:e.providerSessionId,error:t})}}};function P(e,t,n={}){return{platformName:e===`ios`?`iOS`:`Android`,"appium:deviceName":t,...n}}function Je(t,n,r,i){let a=t.details?.timeoutMs;return new e(`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.`},t)}function F(e){return new Ye(e)}var Ye=class{provider;owner;leaseLifecycle;cloudArtifacts;deviceInventoryProvider;capabilities;platformRuntimeModule;sessions;deployment;constructor(e){this.provider=e.provider,this.owner=i(e.provider,e.platform),this.capabilities=d({provider:e.provider,platform:e.platform,overrides:e.capabilityOverrides}),this.sessions=new qe(e),this.deployment=oe({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-runtime2.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()}};async function I(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:(await Promise.all([n.listArtifacts(t,`FILE`),n.listArtifacts(t,`LOG`)])).flat().flatMap(n=>Ze(e,t,n)),pendingMessage:`AWS Device Farm artifacts are not ready yet.`}):void 0}function Xe(e){if(!e||typeof e!=`object`)return[];let t=e.artifacts;return Array.isArray(t)?t:[]}function Ze(e,t,n){let r=n.url;return typeof r!=`string`||r.length===0?[]:[{provider:e,providerSessionId:t,kind:Qe(n.type),name:n.name??n.type??`AWS Device Farm artifact`,url:r,providerArtifactId:n.arn,extension:n.extension,availability:`ready`,metadata:{awsType:n.type,...n.metadata?{awsMetadata:n.metadata}:{}}}]}function Qe(e){switch(e){case`VIDEO`:return`video`;case`APPIUM_SERVER_OUTPUT`:return`appium-log`;case`DEVICE_LOG`:return`device-log`;case`MESSAGE_LOG`:case`UNKNOWN`:return`automation-log`;default:return`raw`}}m.awsDeviceFarm;const $e={install:{support:`unsupported`,note:`Pass appArn when creating the remote access session; local artifact upload/install is not implemented.`},portReverse:{support:`unsupported`,note:`AWS Device Farm remote access does not expose agent-device port reverse.`},artifacts:{support:`supported`,note:`AWS Device Farm remote access exposes provider-hosted video, Appium logs, and device logs after session completion.`}};function L(e){let t=R(e);return{createRemoteAccessSession:async e=>z(await t(`create-remote-access-session`,[`--project-arn`,e.projectArn,`--device-arn`,e.deviceArn,`--name`,e.name,...e.appArn?[`--app-arn`,e.appArn]:[],...e.interactionMode?[`--interaction-mode`,e.interactionMode]:[],...e.configuration?[`--configuration`,JSON.stringify(e.configuration)]:[]])),getRemoteAccessSession:async e=>z(await t(`get-remote-access-session`,[`--arn`,e])),stopRemoteAccessSession:async e=>z(await t(`stop-remote-access-session`,[`--arn`,e])),listArtifacts:async(e,n)=>Xe(await t(`list-artifacts`,[`--arn`,e,`--type`,n]))}}function et(t){return async({lease:n,req:r,base:i})=>{let a=await t.client.createRemoteAccessSession({projectArn:t.projectArn,deviceArn:t.deviceArn,appArn:t.appArn,name:de(t.sessionName,n)??`agent-device-${n.leaseId}`,interactionMode:t.interactionMode,configuration:t.configuration}),o,s;try{if(o=await rt(a.arn,t,r),s=tt(o),!s)throw new e(`COMMAND_FAILED`,`AWS Device Farm did not expose a WebDriver endpoint.`,{sessionArn:o.arn,status:o.status})}catch(e){throw await ue(e,()=>t.client.stopRemoteAccessSession(a.arn)),e}let c=o.device?.name??t.deviceName,l=typeof t.webdriverCapabilities==`function`?t.webdriverCapabilities(n):t.webdriverCapabilities??{},u=t.platform===`android`?{"appium:autoLaunch":!1}:{};return{...i,endpoint:s,platform:t.platform,deviceName:c,webdriverCapabilities:P(t.platform,c,{...u,...l}),cleanup:async()=>(await t.client.stopRemoteAccessSession(o.arn),{awsDeviceFarmSessionArn:o.arn}),providerSessionId:o.arn,providerData:{awsDeviceFarmSessionArn:o.arn}}}}function tt(e){let t=e.endpoints&&typeof e.endpoints==`object`?Object.values(e.endpoints):[],n=[e.remoteDriverEndpoint,e.endpoint,...t,e.remoteDebugUrl,e.remoteRecordAppUrl].filter(e=>typeof e==`string`&&e.length>0).find(e=>!/^wss?:\/\//i.test(e));return n?nt(n):void 0}function nt(e){return/^https?:\/\//i.test(e)?e:`http://${e}`}async function rt(t,n,r){let i=n.pollIntervalMs??5e3,a=Date.now(),o=r?.deadline??a+(n.startupTimeoutMs??12e4),s=r?.signal,c=await n.client.getRemoteAccessSession(t);for(;Date.now()<o;){if(s?.throwIfAborted(),c.status===`RUNNING`)return c;at(c),await ne(i,void 0,{signal:s}).catch(()=>s?.throwIfAborted()),c=await n.client.getRemoteAccessSession(t)}throw new e(`COMMAND_FAILED`,`Timed out waiting for AWS Device Farm remote access.`,{sessionArn:t,status:c.status,result:c.result,timeoutMs:o-a})}const it=new Set([`ERRORED`,`STOPPED`,`COMPLETED`]);function at(t){if(!(!t.status||!it.has(t.status)))throw new e(`COMMAND_FAILED`,`AWS Device Farm remote access session did not start.`,{sessionArn:t.arn,status:t.status,result:t.result})}async function ot(t,n,r){let i=await t(n,r);try{return JSON.parse(i.stdout)}catch(t){throw new e(`COMMAND_FAILED`,`AWS Device Farm returned invalid JSON.`,void 0,t)}}function R(e){let t=e.region?[`--region`,e.region]:[],n=e.awsCommand??`aws`;return async(r,i)=>await ot(e.runHostCommand,n,[`devicefarm`,r,...t,...i,`--output`,`json`])}function z(t){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response was not an object.`,{response:t});let n=t.remoteAccessSession;if(!n||typeof n!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed remoteAccessSession.`,{response:t});return n}const B=[{field:`providerDeviceOrientation`,capability:`deviceOrientation`,flag:`--provider-device-orientation`,type:`enum`,enumValues:o},{field:`providerGeoLocation`,capability:`geoLocation`,flag:`--provider-geo-location`,type:`string`},{field:`providerTimezone`,capability:`timezone`,flag:`--provider-timezone`,type:`string`},{field:`providerAppiumVersion`,capability:`appiumVersion`,flag:`--provider-appium-version`,type:`string`},{field:`providerLanguage`,capability:`language`,flag:`--provider-language`,type:`string`},{field:`providerLocale`,capability:`locale`,flag:`--provider-locale`,type:`string`},{field:`providerNetworkProfile`,capability:`networkProfile`,flag:`--provider-network-profile`,type:`string`},{field:`providerCustomNetwork`,capability:`customNetwork`,flag:`--provider-custom-network`,type:`string`},{field:`providerNoResignApp`,capability:`resignApp`,flag:`--provider-no-resign-app`,type:`negated-boolean`,platform:`ios`}];function st(e,t){pt(e);let n={};for(let r of B){let i=e[r.field];i!==void 0&&i!==!1&&i!==``&&(ft(r,t),n[r.capability]=r.type!==`negated-boolean`&&i)}return n}function ct(e){return B.filter(t=>{let n=e?.[t.field];return n!==void 0&&n!==!1&&n!==``}).map(e=>e.flag)}function V(t,n){let r=ct(t);if(r.length===0)return;let i=r.length!==1;throw new e(`INVALID_ARGS`,`${r.join(`, `)} ${i?`are`:`is`} only supported by BrowserStack, not ${n}.`,{hint:`Drop ${i?`those flags`:`the flag`} or use the browserstack provider.`,provider:n,flags:r})}function lt(e){let t={};for(let n of B){let r=e?.[n.field];if(n.type===`negated-boolean`){r===!0&&(t.providerNoResignApp=!0);continue}typeof r==`string`&&r.length!==0&&ut(t,n,r)}return t}function ut(e,t,n){if(t.field===`providerDeviceOrientation`){e.providerDeviceOrientation=dt(t,n);return}t.field!==`providerNoResignApp`&&(e[t.field]=n)}function dt(t,n){let r=o.find(e=>e===n);if(r)return r;throw new e(`INVALID_ARGS`,`Invalid ${t.flag} value: ${n}.`,{hint:`Use ${o.join(`|`)}.`,flag:t.flag,capability:t.capability})}function ft(t,n){if(!(!t.platform||t.platform===n))throw new e(`INVALID_ARGS`,`${t.flag} applies to ${t.platform} sessions only, but the session platform is ${n}.`,{hint:`Drop ${t.flag} or connect with --platform ${t.platform}.`,flag:t.flag,capability:t.capability,platform:n})}function pt(t){if(!(!t.providerNetworkProfile||!t.providerCustomNetwork))throw new e(`INVALID_ARGS`,`BrowserStack accepts either a named network profile or a custom network shape, not both.`,{hint:`Pass only one of --provider-network-profile or --provider-custom-network.`,networkProfile:t.providerNetworkProfile,customNetwork:t.providerCustomNetwork})}m.browserStack;const mt={install:{support:`partial`,note:`Local app artifacts are uploaded to BrowserStack App Automate, then installed with Appium.`},portReverse:{support:`unsupported`,note:`Use BrowserStack Local for network tunneling; agent-device port reverse is not available.`},artifacts:{support:`supported`,note:`BrowserStack session details expose provider-hosted video, Appium logs, device logs, and dashboard links.`}};async function H(e,t,n){return t?v({provider:e,providerSessionId:t,artifacts:yt(e,t,await vt(t,n)),pendingMessage:`BrowserStack artifacts are not ready yet.`}):void 0}async function U(t,n,r){r?.throwIfAborted();let i=await g.readFile(t),a=new FormData;a.set(`file`,new Blob([i]),h.basename(t));let o=await fetch(n.endpoint??`https://api-cloud.browserstack.com/app-automate/upload`,{method:`POST`,headers:{...y(n.clientVersion),Authorization:b(n)},body:a,signal:r}),s=await o.json(),c=bt(s);if(!o.ok||!c)throw new e(`COMMAND_FAILED`,`BrowserStack app upload failed.`,{status:o.status,response:s});return c}function ht(e){return async({appPath:t,options:n,signal:r})=>({appReference:await U(t,e,r),bundleId:n?.appIdentifierHint,packageName:n?.packageNameHint,launchTarget:n?.appIdentifierHint??n?.packageNameHint})}function gt(e){let{"bstack:options":t,...n}=e.configured??{};return{"appium:deviceName":e.deviceName,"appium:platformVersion":e.osVersion,...e.app?{"appium:app":e.app}:{},...n,"bstack:options":{...e.projectName?{projectName:e.projectName}:{},buildName:e.buildName,sessionName:e.sessionName,...e.deviceFeatures??{},..._t(t)}}}function _t(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:{}}async function vt(t,n){let r=new URL(`${pe(String(n.endpoint??`https://api-cloud.browserstack.com/app-automate/sessions`))}/${t}.json`),i=await fetch(r,{headers:{...y(n.clientVersion),Authorization:b(n)}}),a=await i.json();if(!i.ok||!a||typeof a!=`object`)throw new e(`COMMAND_FAILED`,`BrowserStack session details lookup failed.`,{status:i.status,response:a});let o=a.automation_session??a;return o&&typeof o==`object`?o:{}}function yt(e,t,n){return[W(e,t,n,`video_url`,`video`,`Session video`),W(e,t,n,`appium_logs_url`,`appium-log`,`Appium logs`),W(e,t,n,`device_logs_url`,`device-log`,`Device logs`),W(e,t,n,`browser_url`,`provider-session`,`BrowserStack dashboard`),W(e,t,n,`public_url`,`provider-session`,`Public session link`)].filter(e=>e!==void 0)}function W(e,t,n,r,i,a){let o=n[r];if(typeof o==`string`&&o.length!==0)return{provider:e,providerSessionId:t,kind:i,name:a,url:o,availability:`ready`}}function bt(e){if(!e||typeof e!=`object`)return;let t=e.app_url;return typeof t==`string`?t:void 0}function G(e){return/^arn:[^:]+:devicefarm:([^:]+):/.exec(e)?.[1]}async function xt(t,n){let r=R({runHostCommand:n,region:t.region}),[i,a,o]=await Promise.all([r(`get-project`,[`--arn`,t.projectArn]),r(`get-device`,[`--arn`,t.deviceArn]),t.appArn?r(`get-upload`,[`--arn`,t.appArn]):void 0]),s=K(i,`project`),c=K(a,`device`),l=Ct(c.platform);if(l!==t.platform)throw new e(`INVALID_ARGS`,`AWS Device Farm device "${q(c.name)??t.deviceArn}" is ${l}, not ${t.platform}.`);let u=t.appArn?St(K(o,`upload`),t):{status:`missing`,message:`No app upload is attached; AWS Device Farm does not support install after allocation. Reconnect with --aws-app-arn <arn>.`};return{provider:`aws-device-farm`,service:`AWS Device Farm`,verificationMessage:t.appArn?`Credentials, project, device, and app upload verified.`:`Credentials, project, and device verified.`,project:{name:q(s.name),reference:t.projectArn},device:{status:`verified`,name:q(c.name)??t.deviceArn,reference:t.deviceArn,platform:l,osVersion:q(c.os),availability:q(c.availability)},app:u}}function St(t,n){let r=q(t.status);if(r!==`SUCCEEDED`)throw new e(`COMMAND_FAILED`,`AWS Device Farm app upload is not ready (${r??`unknown status`}).`,{status:r,hint:`Wait for the upload to succeed or reconnect with a different --aws-app-arn.`});let i=n.platform===`android`?`ANDROID_APP`:`IOS_APP`,a=q(t.type);if(a!==i)throw new e(`INVALID_ARGS`,`AWS Device Farm app upload type is ${a??`unknown`}, expected ${i}.`);return{status:`verified`,name:q(t.name),reference:n.appArn}}function K(t,n){if(!t||typeof t!=`object`)throw new e(`COMMAND_FAILED`,`AWS Device Farm ${n} response was not an object.`);let r=t[n];if(!r||typeof r!=`object`||Array.isArray(r))throw new e(`COMMAND_FAILED`,`AWS Device Farm response missed ${n}.`);return r}function Ct(t){if(t===`ANDROID`)return`android`;if(t===`IOS`)return`ios`;throw new e(`UNSUPPORTED_PLATFORM`,`AWS Device Farm device platform is ${String(t)}.`)}function q(e){return typeof e==`string`&&e.length>0?e:void 0}async function wt(t,n){let r={username:t.username,accessKey:t.accessKey},i=Dt(await J(t.devicesEndpoint??`https://api-cloud.browserstack.com/app-automate/devices.json`,r,n)).find(e=>e.device===t.deviceName&&e.os.toLowerCase()===t.platform&&Et(e.osVersion,t.osVersion));if(!i)throw new e(`INVALID_ARGS`,`BrowserStack device "${t.deviceName}" with ${t.platform} ${t.osVersion} is not available.`,{hint:`Choose an exact device and OS version from the BrowserStack App Automate device list.`});let a=await Tt(t,r,n);return{provider:`browserstack`,service:`BrowserStack`,verificationMessage:a.status===`verified`?`Credentials, device, and uploaded app verified.`:`Credentials and device access verified; app availability is checked when the session is created.`,device:{status:`verified`,name:i.device,platform:t.platform,osVersion:i.osVersion},app:a}}async function Tt(e,t,n){let{app:r}=e;if(r.startsWith(`bs://`)){let i=Ot(await J(e.appsEndpoint??`https://api-cloud.browserstack.com/app-automate/recent_apps?limit=100`,t,n)).find(e=>e.reference===r);return i?{status:`verified`,...i}:{status:`configured`,reference:r,message:`App reference was not found in the 100 most recent uploads; BrowserStack validates it when creating the session.`}}return/^https?:\/\//i.test(r)?{status:`configured`,reference:r,message:`Public app URL configured; BrowserStack validates it when creating the session.`}:{status:`configured`,name:h.basename(r),reference:r,message:`Local app artifact is ready and will be uploaded when creating the session.`}}async function J(t,n,r){try{let i=await fetch(t,{headers:{...y(r),Authorization:b(n)},signal:AbortSignal.timeout(15e3)});if(!i.ok){let t=i.status===401||i.status===403;throw new e(t?`UNAUTHORIZED`:`COMMAND_FAILED`,`BrowserStack rejected connection verification.`,{status:i.status,hint:t?`Check BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY.`:`Retry connect or check the BrowserStack service status.`})}return await i.json()}catch(t){throw t instanceof e?t:new e(`COMMAND_FAILED`,`BrowserStack connection verification failed.`,{hint:`Check network access to api-cloud.browserstack.com and retry connect.`},t)}}function Et(e,t){let n=e=>e.replace(/(?:\.0)+$/,``);return n(e)===n(t)}function Dt(t){if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack device verification response was not a list.`);return t.flatMap(e=>{let t=Y(e),n=t?.os_version;return t&&typeof t.device==`string`&&typeof t.os==`string`&&(typeof n==`string`||typeof n==`number`)?[{device:t.device,os:t.os,osVersion:String(n)}]:[]})}function Ot(t){let n=Y(t);if(n&&Object.keys(n).length===0)return[];if(!Array.isArray(t))throw new e(`COMMAND_FAILED`,`BrowserStack app verification response was not a list.`);return t.flatMap(e=>{let t=Y(e);return!t||typeof t.app_url!=`string`?[]:[{reference:t.app_url,...typeof t.app_name==`string`?{name:t.app_name}:{},...typeof t.app_version==`string`?{version:t.app_version}:{}}]})}function Y(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}async function kt(e,t){return e.provider===`browserstack`?await wt(e,t.clientVersion):await xt(e,t.runHostCommand)}function At(e){return[{provider:m.browserStack,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.browserStack,platform:`android`,deviceName:`BrowserStack device`,endpoint:t.BROWSERSTACK_WEBDRIVER_ENDPOINT??`https://hub-cloud.browserstack.com/wd/hub/`,capabilityOverrides:mt,listArtifacts:async({provider:n,providerSessionId:r})=>{let i=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),a=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(n,r,{clientVersion:e.clientVersion,username:i,accessKey:a,endpoint:t.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})},prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`BrowserStack`),o=$(t,`BROWSERSTACK_USERNAME`,`BrowserStack`),s=$(t,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack`),c=Nt(a,`BrowserStack`),l=Z(a,`device`,`BrowserStack requires --device <name>.`),u=Z(a,`providerOsVersion`,`BrowserStack requires --provider-os-version <version>.`),d=await jt({clientVersion:e.clientVersion,app:Z(a,`providerApp`,`BrowserStack requires --provider-app <bs://app-id-or-local-path>.`),cwd:a.cwd,username:o,accessKey:s,uploadEndpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT,signal:a.signal});return{...i,platform:c,deviceName:l,auth:{username:o,accessKey:s},uploadApp:ht({clientVersion:e.clientVersion,username:o,accessKey:s,endpoint:t.BROWSERSTACK_APP_UPLOAD_ENDPOINT??`https://api-cloud.browserstack.com/app-automate/upload`}),webdriverCapabilities:gt({deviceName:l,osVersion:u,app:d,projectName:Q(a,`providerProject`),buildName:Q(a,`providerBuild`)??r.runId,sessionName:Q(a,`providerSessionName`)??r.leaseId,deviceFeatures:st(lt(a.flags),c),configured:P(c,l)})}}}),listArtifactsFromEnv:async(t,n)=>{let r=$(n,`BROWSERSTACK_USERNAME`,`BrowserStack artifact lookup`),i=$(n,`BROWSERSTACK_ACCESS_KEY`,`BrowserStack artifact lookup`);return await H(m.browserStack,t,{clientVersion:e.clientVersion,username:r,accessKey:i,endpoint:n.BROWSERSTACK_SESSION_DETAILS_ENDPOINT})}},{provider:m.awsDeviceFarm,createRuntime:t=>F({clientVersion:e.clientVersion,provider:m.awsDeviceFarm,endpoint:`http://127.0.0.1/`,platform:`android`,deviceName:`AWS Device Farm device`,capabilityOverrides:$e,listArtifacts:async({provider:n,providerSessionId:r})=>await I(n,r,L({runHostCommand:e.runHostCommand,region:t.AWS_REGION??t.AWS_DEFAULT_REGION??G(r??``)})),prepareSession:async({req:n,lease:r,base:i})=>{let a=X(n,`AWS Device Farm`);V(a.flags,m.awsDeviceFarm);let o=Nt(a,`AWS Device Farm`);return await et({client:L({runHostCommand:e.runHostCommand,region:Q(a,`awsRegion`)??t.AWS_REGION??t.AWS_DEFAULT_REGION}),projectArn:Pt(a,t,`awsProjectArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_PROJECT_ARN`,`AWS_DEVICE_FARM_PROJECT_ARN`),deviceArn:Pt(a,t,`awsDeviceArn`,`AGENT_DEVICE_AWS_DEVICE_FARM_DEVICE_ARN`,`AWS_DEVICE_FARM_DEVICE_ARN`),appArn:Q(a,`awsAppArn`)??t.AGENT_DEVICE_AWS_DEVICE_FARM_APP_ARN??t.AWS_DEVICE_FARM_APP_ARN,platform:o,deviceName:Q(a,`device`)??`AWS Device Farm device`,sessionName:Q(a,`providerSessionName`)??r.leaseId,interactionMode:Ft(a)})({lease:r,req:n,base:i})}}),listArtifactsFromEnv:async(t,n)=>{let r=L({runHostCommand:e.runHostCommand,region:n.AWS_REGION??n.AWS_DEFAULT_REGION??G(t)});return await I(m.awsDeviceFarm,t,r)}}]}async function jt(t){if(Mt(t.app))return t.app;let n=h.resolve(t.cwd??process.cwd(),t.app);if(!te.existsSync(n))throw new e(`INVALID_ARGS`,`BrowserStack --provider-app must be a bs:// app id, URL, or existing local app path.`,{providerApp:t.app});return await U(n,{clientVersion:t.clientVersion,username:t.username,accessKey:t.accessKey,endpoint:t.uploadEndpoint},t.signal)}function Mt(e){return e.startsWith(`bs://`)||/^https?:\/\//.test(e)}function X(t,n){if(t)return t;throw new e(`INVALID_ARGS`,`${n} lease allocation requires provider profile flags on the request.`)}function Nt(t,n){let r=t.flags?.platform;if(r===`android`||r===`ios`)return r;throw new e(`INVALID_ARGS`,`${n} requires --platform ios|android.`)}function Z(t,n,r){let i=Q(t,n);if(i)return i;throw new e(`INVALID_ARGS`,r)}function Q(e,t){let n=e.flags?.[t];return typeof n==`string`&&n.length>0?n:void 0}function $(t,n,r){let i=t[n];if(i)return i;throw new e(`INVALID_ARGS`,`${r} requires ${n} in the environment.`)}function Pt(t,n,r,i,a){let o=Q(t,r)??n[i]??n[a];if(o)return o;throw new e(`INVALID_ARGS`,`AWS Device Farm requires --${It(String(r))} or ${a}.`)}function Ft(e){let t=Q(e,`awsInteractionMode`);if(t===`INTERACTIVE`||t===`NO_VIDEO`||t===`VIDEO_ONLY`)return t}function It(e){return e.replaceAll(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Lt(e){let t=At(e);return{providerIds:t.map(e=>e.provider),createDefaultRuntimes:(e=process.env)=>t.map(t=>t.createRuntime(e)),listArtifactsFromEnv:async(e,n)=>{if(e.providerSessionId)return await t.find(t=>t.provider===e.provider)?.listArtifactsFromEnv(e.providerSessionId,n)},verifyConnection:async t=>await kt(t,e)}}const Rt=Lt({clientVersion:u(),runHostCommand:async(e,t)=>({stdout:(await l(e,[...t],{maxBuffer:10485760,timeoutMs:3e4})).stdout})});export{G as n,V as r,Rt as t};
package/dist/src/proxy.js CHANGED
@@ -1,2 +1,2 @@
1
- import{C as e,N as t}from"./sdk-contracts.js";import{a as n,c as r,d as i,f as a,l as o,m as s,o as c,r as l,s as u,u as d}from"./transport.js";import{i as f,s as p}from"./daemon-client-lifecycle.js";import{r as m}from"./version.js";import{t as h}from"./shared.js";import{n as ee,t as te}from"./color.js";import{randomBytes as ne,randomUUID as g}from"node:crypto";import{Readable as _}from"node:stream";import{pipeline as v}from"node:stream/promises";import y from"node:http";function b(e){let t=S(e);if(!t)return!1;let n=T(t.meta);return C(n)?!1:w(t.source)||w(n?.installSource)}function x(n,r){let i=new e(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});n.statusCode=400,n.setHeader(`content-type`,`application/json`),n.end(JSON.stringify({jsonrpc:`2.0`,id:r,error:{code:-32602,message:i.message,data:t(i)}}))}function S(e){if(e)try{return T(T(JSON.parse(e))?.params)}catch{return}}function C(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function w(e){return T(e)?.kind===`path`}function T(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const E=`${c}/`,D=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,o],O=[`content-type`,`content-disposition`,`x-request-id`];function k(e){let t=V(e);return y.createServer((e,n)=>{A(e,n,t).catch(e=>{de(n,e)})})}async function A(e,t,n){let r=W(e.url??`/`);if(e.method===`GET`&&r===`/health`){await j(t,n);return}if(!G(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await l(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!ae(e,n.clientToken,i)){ue(t,r,Z(i));return}if(b(i)){x(t,Z(i));return}await N({req:e,res:t,route:r,options:n,rpcBody:i})}async function j(e,t){let n=await M(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,m(),{upstream:n})))}async function M(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:X({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function N(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=Y(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=X(t,i.upstreamToken,r),l=ie(t,r,a,i.upstreamToken);await F({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:P(t,n,i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}function P(t,n,r){let i=new AbortController,a=()=>{n.writableFinished||i.signal.aborted||i.abort(new e(`COMMAND_FAILED`,`Proxy client disconnected before the upstream response ended`))};return t.on(`aborted`,a),n.on(`close`,a),AbortSignal.any([i.signal,AbortSignal.timeout(r)])}async function F(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,I(i,n),L(t,n),J(r)){await R({req:t,res:n,response:i,clientToken:a});return}await B(i,n)}function I(e,t){for(let n of O){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function L(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,le(e))}async function R(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(z(a,t,i))}function z(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let a=r;if(!a.upload||typeof a.upload.url!=`string`)return e;let o=re(a.upload.url,t);if(!o)return e;let s=a.upload.headers&&typeof a.upload.headers==`object`?{...a.upload.headers}:{};return Object.assign(s,i(n)),JSON.stringify({...r,upload:{...a.upload,url:o,headers:s}})}function re(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function B(e,t){if(!e.body){t.end();return}await v(_.fromWeb(e.body),t)}function V(e){return{upstreamBaseUrl:H(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:U(e.upstreamToken,`upstreamToken`),clientToken:U(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function H(t,n){try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`unsupported protocol`);return e.toString().replace(/\/+$/,``)}catch(r){throw new e(`INVALID_ARGS`,`Invalid ${n}`,{[n]:t},r)}}function U(t,n){let r=t.trim();if(!r)throw new e(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function W(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(E)?`/${t.slice(E.length)}`:t}function G(e,t){return e===`/rpc`?t===`POST`:q(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)||K(e)?t===`GET`:!1}function K(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function q(e,t){return e===`/upload`||J(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function J(e){return e===`/upload/preflight`}function Y(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function X(e,t,n){let a=new Headers;for(let t of D){let n=e.headers[t];typeof n==`string`&&n.trim()&&a.set(t,n)}n===`/rpc`&&!a.has(`content-type`)&&a.set(`content-type`,`application/json`),n===`/rpc`&&a.set(u,r);for(let[e,n]of Object.entries(i(t)))a.set(e,n);return a}function ie(e,t,n,r){if(e.method!==`GET`&&e.method!==`HEAD`)return t===`/rpc`?se(n??``,r):e}function ae(e,t,r){let i=oe(e,r);return i.length>0&&n(i,t)}function oe(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=ce(t);if(e)return e}return``}function se(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function ce(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Z(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function le(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function ue(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:t(new e(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function de(e,n){if(e.destroyed)return;if(e.headersSent){e.destroy(n instanceof Error?n:void 0);return}let r=t(n);e.statusCode=r.code===`INVALID_ARGS`?400:500,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const fe=async({positionals:t,flags:n})=>{if(t.length>0)throw new e(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await pe(n);return await h(n,r,()=>_e(r)),await ve(),!0};async function pe(t){let n=p({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:t.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await f(n),i=me(r.info.httpPort),o=Q(t),s=k({upstreamBaseUrl:i,upstreamToken:r.info.token,clientToken:o});await he(s,t.proxyHost?.trim()||`127.0.0.1`,t.proxyPort??0);let c=s.address();if(!c||typeof c==`string`)throw new e(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let l=`http://${ge(c.address)}:${c.port}`;return{proxyBaseUrl:l,agentDeviceBaseUrl:a(l),token:o,upstreamBaseUrl:i,stateDir:n.paths.baseDir}}function me(t){if(!t)throw new e(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${t}`}function Q(e){return e.daemonAuthToken?.trim()||ne(32).toString(`hex`)}function he(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ge(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function _e(e,t={}){let n=t.useColor??ee(),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(`
1
+ import{D as e,L as t}from"./sdk-contracts.js";import{a as n,c as r,d as i,f as a,l as o,m as s,o as c,r as l,s as u,u as d}from"./transport.js";import{i as f,s as p}from"./daemon-client-lifecycle.js";import{r as m}from"./version.js";import{t as h}from"./shared.js";import{n as ee,t as te}from"./color.js";import{randomBytes as ne,randomUUID as g}from"node:crypto";import{Readable as _}from"node:stream";import{pipeline as v}from"node:stream/promises";import y from"node:http";function b(e){let t=S(e);if(!t)return!1;let n=T(t.meta);return C(n)?!1:w(t.source)||w(n?.installSource)}function x(n,r){let i=new e(`INVALID_ARGS`,`Invalid params: an install source of kind "path" names a file on the daemon host and is not accepted through the proxy`,{hint:`Upload the artifact, or use a "url" or "github-actions-artifact" source.`});n.statusCode=400,n.setHeader(`content-type`,`application/json`),n.end(JSON.stringify({jsonrpc:`2.0`,id:r,error:{code:-32602,message:i.message,data:t(i)}}))}function S(e){if(e)try{return T(T(JSON.parse(e))?.params)}catch{return}}function C(e){let t=e?.uploadedArtifactId;return typeof t==`string`&&t.trim().length>0}function w(e){return T(e)?.kind===`path`}function T(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}const E=`${c}/`,D=[`content-type`,`content-range`,`x-artifact-type`,`x-artifact-filename`,`x-artifact-hash`,`x-artifact-hash-algorithm`,o],O=[`content-type`,`content-disposition`,`x-request-id`];function k(e){let t=V(e);return y.createServer((e,n)=>{A(e,n,t).catch(e=>{de(n,e)})})}async function A(e,t,n){let r=W(e.url??`/`);if(e.method===`GET`&&r===`/health`){await j(t,n);return}if(!G(r,e.method)){t.statusCode=404,t.end(`Not found`);return}let i;if(r===`/rpc`&&(i=(await l(e,n.maxRpcBodyBytes,`Proxy request body is too large.`)).toString(`utf8`)),!ae(e,n.clientToken,i)){ue(t,r,Z(i));return}if(b(i)){x(t,Z(i));return}await N({req:e,res:t,route:r,options:n,rpcBody:i})}async function j(e,t){let n=await M(t);e.statusCode=200,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify(d(`agent-device-proxy`,m(),{upstream:n})))}async function M(e){let t=new URL(s(e.upstreamBaseUrl,`health`)),n=await e.fetchImpl(t,{method:`GET`,headers:X({headers:{}},e.upstreamToken,`/health`),signal:AbortSignal.timeout(e.upstreamTimeoutMs)}),r=await n.text();try{return r?JSON.parse(r):{ok:n.ok,status:n.status}}catch{return{ok:n.ok,status:n.status}}}async function N(e){let{req:t,res:n,route:r,options:i,rpcBody:a}=e,o=Y(i.upstreamBaseUrl,r,t.url??`/`),s=t.method??`GET`,c=X(t,i.upstreamToken,r),l=ie(t,r,a,i.upstreamToken);await F({req:t,res:n,route:r,response:await i.fetchImpl(o,{method:s,headers:c,signal:P(t,n,i.upstreamTimeoutMs),...l?{body:l,duplex:`half`}:{}}),clientToken:i.clientToken})}function P(t,n,r){let i=new AbortController,a=()=>{n.writableFinished||i.signal.aborted||i.abort(new e(`COMMAND_FAILED`,`Proxy client disconnected before the upstream response ended`))};return t.on(`aborted`,a),n.on(`close`,a),AbortSignal.any([i.signal,AbortSignal.timeout(r)])}async function F(e){let{req:t,res:n,route:r,response:i,clientToken:a}=e;if(n.statusCode=i.status,I(i,n),L(t,n),J(r)){await R({req:t,res:n,response:i,clientToken:a});return}await B(i,n)}function I(e,t){for(let n of O){let r=e.headers.get(n);r&&t.setHeader(n,r)}}function L(e,t){t.hasHeader(`x-request-id`)||t.setHeader(`x-request-id`,le(e))}async function R(e){let{req:t,res:n,response:r,clientToken:i}=e,a=await r.text();n.setHeader(`content-type`,r.headers.get(`content-type`)??`application/json`),n.end(z(a,t,i))}function z(e,t,n){let r;try{r=JSON.parse(e)}catch{return e}if(!r||typeof r!=`object`)return e;let a=r;if(!a.upload||typeof a.upload.url!=`string`)return e;let o=re(a.upload.url,t);if(!o)return e;let s=a.upload.headers&&typeof a.upload.headers==`object`?{...a.upload.headers}:{};return Object.assign(s,i(n)),JSON.stringify({...r,upload:{...a.upload,url:o,headers:s}})}function re(e,t){let n;try{n=new URL(e)}catch{return null}if(!n.pathname.startsWith(`/upload/`))return null;let r=typeof t.headers.host==`string`?t.headers.host:``;if(!r)return null;let i=new URL(t.url??`/`,`http://127.0.0.1`).pathname,a=i.lastIndexOf(`/upload/preflight`),o=a>=0?i.slice(0,a):``,s=t.headers[`x-forwarded-proto`],c=Array.isArray(s)?s[0]:s,l=new URL(`${c||`http`}://${r}`);return l.pathname=`${o}${n.pathname}`,l.search=n.search,l.toString()}async function B(e,t){if(!e.body){t.end();return}await v(_.fromWeb(e.body),t)}function V(e){return{upstreamBaseUrl:H(e.upstreamBaseUrl,`upstreamBaseUrl`),upstreamToken:U(e.upstreamToken,`upstreamToken`),clientToken:U(e.clientToken,`clientToken`),maxRpcBodyBytes:e.maxRpcBodyBytes??1048576,upstreamTimeoutMs:e.upstreamTimeoutMs??3e5,fetchImpl:e.fetchImpl??fetch}}function H(t,n){try{let e=new URL(t);if(e.protocol!==`http:`&&e.protocol!==`https:`)throw Error(`unsupported protocol`);return e.toString().replace(/\/+$/,``)}catch(r){throw new e(`INVALID_ARGS`,`Invalid ${n}`,{[n]:t},r)}}function U(t,n){let r=t.trim();if(!r)throw new e(`INVALID_ARGS`,`Proxy ${n} is required.`);return r}function W(e){let t=new URL(e,`http://127.0.0.1`).pathname;return t===`/agent-device`?`/`:t.startsWith(E)?`/${t.slice(E.length)}`:t}function G(e,t){return e===`/rpc`?t===`POST`:q(e,t)?!0:e===`/artifacts`||e===`/artifacts/`||e.startsWith(`/artifacts/`)||K(e)?t===`GET`:!1}function K(e){let t=e.split(`/`);return t.length===6&&t[1]===`sessions`&&t[3]===`requests`&&t[5]===`diagnostics`&&t[2]!==``&&t[4]!==``}function q(e,t){return e===`/upload`||J(e)||e===`/upload/finalize`?t===`POST`:e.startsWith(`/upload/direct/`)?t===`PUT`:!1}function J(e){return e===`/upload/preflight`}function Y(e,t,n){let r=new URL(s(e,t)),i=n.indexOf(`?`);return i>=0&&(r.search=n.slice(i)),r}function X(e,t,n){let a=new Headers;for(let t of D){let n=e.headers[t];typeof n==`string`&&n.trim()&&a.set(t,n)}n===`/rpc`&&!a.has(`content-type`)&&a.set(`content-type`,`application/json`),n===`/rpc`&&a.set(u,r);for(let[e,n]of Object.entries(i(t)))a.set(e,n);return a}function ie(e,t,n,r){if(e.method!==`GET`&&e.method!==`HEAD`)return t===`/rpc`?se(n??``,r):e}function ae(e,t,r){let i=oe(e,r);return i.length>0&&n(i,t)}function oe(e,t){let n=typeof e.headers.authorization==`string`?e.headers.authorization:``;if(n.toLowerCase().startsWith(`bearer `))return n.slice(7);let r=e.headers[`x-agent-device-token`];if(typeof r==`string`)return r;if(t){let e=ce(t);if(e)return e}return``}function se(e,t){let n=JSON.parse(e);return n.params={...n.params??{},token:t},JSON.stringify(n)}function ce(e){try{let t=JSON.parse(e);return typeof t.params?.token==`string`?t.params.token:``}catch{return``}}function Z(e){if(!e)return null;try{return JSON.parse(e).id??null}catch{return null}}function le(e){let t=e.headers[`x-request-id`];return typeof t==`string`&&t.trim()?t.trim().slice(0,128):g()}function ue(n,r,i){if(n.statusCode=401,n.setHeader(`content-type`,`application/json`),r===`/rpc`){n.end(JSON.stringify({jsonrpc:`2.0`,id:i,error:{code:-32001,message:`Invalid proxy token`,data:t(new e(`UNAUTHORIZED`,`Invalid proxy token`))}}));return}n.end(JSON.stringify({ok:!1,error:`Invalid proxy token`,code:`UNAUTHORIZED`}))}function de(e,n){if(e.destroyed)return;if(e.headersSent){e.destroy(n instanceof Error?n:void 0);return}let r=t(n);e.statusCode=r.code===`INVALID_ARGS`?400:500,e.setHeader(`content-type`,`application/json`),e.end(JSON.stringify({ok:!1,error:r.message,code:r.code}))}const fe=async({positionals:t,flags:n})=>{if(t.length>0)throw new e(`INVALID_ARGS`,`proxy does not accept positional arguments.`);let r=await pe(n);return await h(n,r,()=>_e(r)),await ve(),!0};async function pe(t){let n=p({session:`default`,command:`proxy`,positionals:[],flags:{stateDir:t.stateDir,daemonBaseUrl:``,daemonTransport:`http`,daemonServerMode:`http`}}),r=await f(n),i=me(r.info.httpPort),o=Q(t),s=k({upstreamBaseUrl:i,upstreamToken:r.info.token,clientToken:o});await he(s,t.proxyHost?.trim()||`127.0.0.1`,t.proxyPort??0);let c=s.address();if(!c||typeof c==`string`)throw new e(`COMMAND_FAILED`,`Proxy did not bind to a TCP address.`);let l=`http://${ge(c.address)}:${c.port}`;return{proxyBaseUrl:l,agentDeviceBaseUrl:a(l),token:o,upstreamBaseUrl:i,stateDir:n.paths.baseDir}}function me(t){if(!t)throw new e(`COMMAND_FAILED`,`Local daemon HTTP endpoint is unavailable.`,{hint:`Retry after cleaning daemon state, or run proxy with a fresh --state-dir.`});return`http://127.0.0.1:${t}`}function Q(e){return e.daemonAuthToken?.trim()||ne(32).toString(`hex`)}function he(e,t,n){return new Promise((r,i)=>{e.once(`error`,i),e.listen(n,t,()=>{e.off(`error`,i),r()})})}function ge(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}function _e(e,t={}){let n=t.useColor??ee(),r=$(`✓`,`green`,n),i=$(e.proxyBaseUrl,`cyan`,n),a=$(`<tunnel URL>`,`cyan`,n),o=$(e.token,`yellow`,n);return[`${r} Proxy listening at ${i}`,``,`Provide this to the agent-device instance connecting:`,``,`Daemon base URL: ${a}`,`Daemon auth token: ${o}`].join(`
2
2
  `)}function $(e,t,n){return n?te(e,t,{validateStream:!1}):e}function ve(){return new Promise(()=>{})}export{fe as proxyCommand};
@@ -1 +1 @@
1
- import{C as e,z as t}from"./sdk-contracts.js";import{i as n}from"./capture.js";import{n as r}from"./snapshot-quality-backend-capabilities.js";import{r as i}from"./diagnostics.js";import"./diagnostics2.js";import{n as a,t as o}from"./png.js";import{n as s,r as c,t as l}from"./png-worker-contract.js";import u from"node:path";import d,{promises as f}from"node:fs";import{fileURLToPath as p}from"node:url";import{Worker as m}from"node:worker_threads";const h=new Set([`healthy`,`recovered`,`sparse`]),g=new Set(Object.keys(r)),_=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`,`presentation-failed`,`deferred`,`requested-backend`]);function v(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.state!=`string`||!h.has(t.state)||typeof t.backend!=`string`||!g.has(t.backend))return;let n=y(t.timing);return{state:t.state,backend:t.backend,reason:typeof t.reason==`string`?t.reason:void 0,reasonCode:typeof t.reasonCode==`string`&&_.has(t.reasonCode)?t.reasonCode:void 0,customActions:b(t.customActions),effectiveDepth:typeof t.effectiveDepth==`number`?t.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(t.collapsedLeafIndexes)?t.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0,...n?{timing:n}:{}}}function y(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.acquisitionMs==`number`&&typeof t.presentationMs==`number`)return{acquisitionMs:t.acquisitionMs,presentationMs:t.presentationMs}}function b(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.read==`number`&&typeof t.candidates==`number`)return{read:t.read,candidates:t.candidates,truncated:typeof t.truncated==`number`?t.truncated:0,blocked:t.blocked===!0}}function x(e){return e?.state===`sparse`}function S(e){return e?.backend===`private-ax`?`private-ax`:void 0}function C(e,t){try{let n=p(e),r=u.extname(n)||`.js`;return[u.join(u.dirname(n),`${t}${r}`),u.join(u.dirname(n),`internal`,`${t}${r}`)].find(e=>d.existsSync(e))??null}catch{return null}}var w=class extends Error{};let T=null,E=!1,D=!1,O=0;const k=new Map;function A(e){E=!0,!D&&(D=!0,i({level:`warn`,phase:`png_worker_unavailable`,data:{reason:e}}),process.emitWarning(`PNG worker unavailable, falling back to in-process PNG processing: ${e}`))}function j(n){let r=k.get(n.id);r&&(k.delete(n.id),P(),n.ok?r.resolve(n.result):r.reject(new e(t(n.error.code),n.error.message,n.error.details)))}function M(e,t){T===e&&(A(t.message),T=null,e.terminate().catch(()=>{}),N(new w(`PNG worker failed: ${t.message}`)))}function N(e){let t=[...k.values()];k.clear();for(let n of t)n.reject(e)}function P(){T&&(k.size>0?T.ref():T.unref())}function F(){if(E)return null;if(T)return T;let e=C(import.meta.url,`png-worker`);if(!e)return A(`worker entry module not found next to the current module`),null;try{let t=new m(e,{execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,j),t.on(`error`,e=>{M(t,e)}),t.on(`exit`,e=>{M(t,Error(`PNG worker exited with code ${e}`))}),t.unref(),T=t,t}catch(e){return A(`failed to spawn worker: ${e instanceof Error?e.message:String(e)}`),null}}function I(e){let t=F();if(!t)return Promise.reject(new w(`PNG worker is unavailable`));O+=1;let n=O;return new Promise((r,i)=>{k.set(n,{resolve:r,reject:i}),P();try{t.postMessage({...e,id:n})}catch(e){k.delete(n),P(),i(new w(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function L(e,t){try{return await I(e)}catch(e){if(e instanceof w)return await t();throw e}}function R(){F()}async function z(){let e=T;T=null,N(new w(`PNG worker terminated`)),e&&await e.terminate()}async function B(e,t){let n=await L({kind:`decode`,png:e,label:t},()=>{let n=o(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}),r=new a.PNG({width:n.width,height:n.height});return r.data=l(n.data),r}async function V(e){let t=await L({kind:`encode`,width:e.width,height:e.height,data:e.data},()=>({kind:`encode`,png:a.PNG.sync.write(e)}));return l(t.png)}async function H(e,t,n){let r=await L({kind:`crop`,png:e,label:n,box:t},async()=>{let{cropPngBytes:r}=await import(`./png-crop-bytes.js`).then(e=>e.n);return{kind:`crop`,png:r(e,t,n)}});return r.png===null?null:l(r.png)}async function U(e,t,n){let{kind:r,...i}=await L({kind:`rgb-difference`,firstPng:e,secondPng:t,label:n},()=>({kind:`rgb-difference`,...s(o(e,n),o(t,n))}));return i}async function W(e){let{kind:t,...n}=await L({kind:`diff-pixels`,...e},()=>({kind:`diff-pixels`,...c(e)}));return{...n,diffData:l(n.diffData)}}async function G(t,r){let{min:i,max:a}=n;if(!Number.isFinite(r)||r<i||r>a)throw new e(`INVALID_ARGS`,`Screenshot scale must be between ${i} and ${a}`);if(r===1)return;let o=await B(await f.readFile(t),`screenshot`),s=Math.max(1,Math.round(o.width*r)),c=Math.max(1,Math.round(o.height*r));await f.writeFile(t,await V(q(o,s,c)))}async function K(t,n,r){if(!Number.isInteger(n)||n<1||!Number.isInteger(r)||r<1)throw new e(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await B(await f.readFile(t),`screenshot`);(i.width!==n||i.height!==r)&&await f.writeFile(t,await V(q(i,n,r)))}function q(e,t,n){let r=new a.PNG({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}function J(e,t){return[...Q(e),...Y(e),...ee(e),...te(e,t)]}function Y(e){let t=e.customActions;if(!t)return[];let n=[];return t.blocked?n.push(`Custom actions were not read: an earlier accessibility read is still hung, so this capture skipped the read pass instead of queueing behind it. No element’s actions list is authoritative here. Reads resume once that call returns.`):t.read<t.candidates&&n.push(`Custom actions were read for ${t.read} of ${t.candidates} merged elements, on-screen ones first; the remaining ${t.candidates-t.read} were not read, so an absent actions list on those is not evidence that they have none. Scroll them into view and re-run to read them.`),t.truncated>0&&n.push(`${t.truncated} element(s) published more custom actions than are shown; those lists are clipped to the first 8 names, and long names are shortened.`),n}function X(e){return e===!0?[`This capture was cut at a backend limit, so elements later in the tree — footers, tab bars, items after a long list — may be missing even when they are on screen; their refs and selectors cannot be resolved from this snapshot. Navigate or scroll so fewer elements render and re-run, and use screenshot as visual truth for what is missing.`]:[]}function Z(e){return`Detected an overly complex or slow accessibility tree. Fell back to the ${e} snapshot backend. It is OK to continue; use --json to inspect snapshotQuality.reason if you need recovery details.`}function Q(e){return e.state===`recovered`?e.reasonCode===`deferred`||e.reasonCode===`requested-backend`?[]:e.reasonCode===`presentation-failed`?[`Agent Device could not safely present the captured accessibility tree and fell back to the ${e.backend} snapshot backend. This is an Agent Device runner bug, not an app accessibility-tree issue. Use screenshot as visual truth and report snapshotQuality.reason with the screenshot.`]:[Z(e.backend)]:e.state===`sparse`?[`No snapshot backend could read this screen`+(e.reason?` (${e.reason})`:``)+`. Its refs and selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`,...$(e)]:[]}function $(e){return e.reasonCode===`sparse-tree`?[`This screen publishes no accessibility content at all; assistive technologies see the same empty tree, so it is worth flagging as an app accessibility bug rather than only an automation limitation.`]:[]}function ee(e){return e.effectiveDepth===void 0?[]:[`Some deeper accessibility nodes were omitted; the accessibility backend capped this tree at depth ${e.effectiveDepth}. Navigate so the content you need sits higher in the tree, and use screenshot as visual truth for the rest.`]}function te(e,t){let n=[];for(let r of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===r);if(!e)continue;let i=e.identifier?` (${e.identifier})`:``;n.push(`@${e.ref} [${e.type??`element`}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return n}export{G as a,H as c,R as d,z as f,v as h,K as i,B as l,S as m,J as n,U as o,x as p,X as r,W as s,Z as t,V as u};
1
+ import{D as e}from"./sdk-contracts.js";import{i as t}from"./capture.js";import{n}from"./snapshot-quality-backend-capabilities.js";import{a as r,i}from"./png-worker-client.js";import{r as a}from"./png.js";import{promises as o}from"node:fs";const s=new Set([`healthy`,`recovered`,`sparse`]),c=new Set(Object.keys(n)),l=new Set([`ax-rejected`,`sparse-tree`,`budget`,`no-nodes`,`capture-failed`,`presentation-failed`,`deferred`,`requested-backend`]);function u(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.state!=`string`||!s.has(t.state)||typeof t.backend!=`string`||!c.has(t.backend))return;let n=d(t.timing);return{state:t.state,backend:t.backend,reason:typeof t.reason==`string`?t.reason:void 0,reasonCode:typeof t.reasonCode==`string`&&l.has(t.reasonCode)?t.reasonCode:void 0,customActions:f(t.customActions),effectiveDepth:typeof t.effectiveDepth==`number`?t.effectiveDepth:void 0,collapsedLeafIndexes:Array.isArray(t.collapsedLeafIndexes)?t.collapsedLeafIndexes.filter(e=>typeof e==`number`):void 0,...n?{timing:n}:{}}}function d(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.acquisitionMs==`number`&&typeof t.presentationMs==`number`)return{acquisitionMs:t.acquisitionMs,presentationMs:t.presentationMs}}function f(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.read==`number`&&typeof t.candidates==`number`)return{read:t.read,candidates:t.candidates,truncated:typeof t.truncated==`number`?t.truncated:0,blocked:t.blocked===!0}}function p(e){return e?.state===`sparse`}function m(e){return e?.backend===`private-ax`?`private-ax`:void 0}async function h(n,a){let{min:s,max:c}=t;if(!Number.isFinite(a)||a<s||a>c)throw new e(`INVALID_ARGS`,`Screenshot scale must be between ${s} and ${c}`);if(a===1)return;let l=await i(await o.readFile(n),`screenshot`),u=Math.max(1,Math.round(l.width*a)),d=Math.max(1,Math.round(l.height*a));await o.writeFile(n,await r(_(l,u,d)))}async function g(t,n,a){if(!Number.isInteger(n)||n<1||!Number.isInteger(a)||a<1)throw new e(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let s=await i(await o.readFile(t),`screenshot`);(s.width!==n||s.height!==a)&&await o.writeFile(t,await r(_(s,n,a)))}function _(e,t,n){let r=new a.PNG({width:t,height:n});for(let i=0;i<n;i+=1){let a=i*e.height/n,o=(i+1)*e.height/n;for(let n=0;n<t;n+=1){let s=n*e.width/t,c=(n+1)*e.width/t,l=0,u=0,d=0,f=0,p=0;for(let t=Math.floor(a);t<Math.ceil(o);t+=1){let n=Math.min(t+1,o)-Math.max(t,a);for(let r=Math.floor(s);r<Math.ceil(c);r+=1){let i=n*(Math.min(r+1,c)-Math.max(r,s)),a=(t*e.width+r)*4;l+=(e.data[a]??0)*i,u+=(e.data[a+1]??0)*i,d+=(e.data[a+2]??0)*i,f+=(e.data[a+3]??0)*i,p+=i}}let m=(i*r.width+n)*4;r.data[m]=Math.round(l/p),r.data[m+1]=Math.round(u/p),r.data[m+2]=Math.round(d/p),r.data[m+3]=Math.round(f/p)}}return r}function v(e,t){return[...S(e),...y(e),...w(e),...T(e,t)]}function y(e){let t=e.customActions;if(!t)return[];let n=[];return t.blocked?n.push(`Custom actions were not read: an earlier accessibility read is still hung, so this capture skipped the read pass instead of queueing behind it. No element’s actions list is authoritative here. Reads resume once that call returns.`):t.read<t.candidates&&n.push(`Custom actions were read for ${t.read} of ${t.candidates} merged elements, on-screen ones first; the remaining ${t.candidates-t.read} were not read, so an absent actions list on those is not evidence that they have none. Scroll them into view and re-run to read them.`),t.truncated>0&&n.push(`${t.truncated} element(s) published more custom actions than are shown; those lists are clipped to the first 8 names, and long names are shortened.`),n}function b(e){return e===!0?[`This capture was cut at a backend limit, so elements later in the tree — footers, tab bars, items after a long list — may be missing even when they are on screen; their refs and selectors cannot be resolved from this snapshot. Navigate or scroll so fewer elements render and re-run, and use screenshot as visual truth for what is missing.`]:[]}function x(e){return`Detected an overly complex or slow accessibility tree. Fell back to the ${e} snapshot backend. It is OK to continue; use --json to inspect snapshotQuality.reason if you need recovery details.`}function S(e){return e.state===`recovered`?e.reasonCode===`deferred`||e.reasonCode===`requested-backend`?[]:e.reasonCode===`presentation-failed`?[`Agent Device could not safely present the captured accessibility tree and fell back to the ${e.backend} snapshot backend. This is an Agent Device runner bug, not an app accessibility-tree issue. Use screenshot as visual truth and report snapshotQuality.reason with the screenshot.`]:[x(e.backend)]:e.state===`sparse`?[`No snapshot backend could read this screen`+(e.reason?` (${e.reason})`:``)+`. Its refs and selectors are invalid. Use screenshot as visual truth and coordinate taps; retry snapshot after navigating.`,...C(e)]:[]}function C(e){return e.reasonCode===`sparse-tree`?[`This screen publishes no accessibility content at all; assistive technologies see the same empty tree, so it is worth flagging as an app accessibility bug rather than only an automation limitation.`]:[]}function w(e){return e.effectiveDepth===void 0?[]:[`Some deeper accessibility nodes were omitted; the accessibility backend capped this tree at depth ${e.effectiveDepth}. Navigate so the content you need sits higher in the tree, and use screenshot as visual truth for the rest.`]}function T(e,t){let n=[];for(let r of e.collapsedLeafIndexes??[]){let e=t.find(e=>e.index===r);if(!e)continue;let i=e.identifier?` (${e.identifier})`:``;n.push(`@${e.ref} [${e.type??`element`}]${i} merges many labels into a single accessibility element. The app likely marks a container as accessible, which hides every descendant from assistive tech and automation — the children cannot be addressed individually. Fix the app's accessibility (mark the rows, not the container); until then use screenshot as visual truth and coordinate taps.`)}return n}export{h as a,u as c,g as i,v as n,p as o,b as r,m as s,x as t};
@@ -1 +1 @@
1
- import{N as e}from"./sdk-contracts.js";import{D as t}from"./sdk-batch-runner.js";import{M as n}from"./runtime.js";import{n as r}from"./catalog.js";import{r as i}from"./success-text.js";import{a,i as o}from"./request-runtime-binding.js";import{E as s,d as c,u as l}from"./session-snapshot.js";import{n as u}from"./touch-reference-frame.js";import{p as d}from"./quality-warnings.js";import{o as f}from"./interaction-ref-policy.js";import{captureSnapshotForSession as p}from"./interaction.js";async function m(t){let{req:i,sessionName:s,sessionStore:l}=t;if(i.command!==r.reactNative)return null;let u=h(i.positionals??[]);if(!u.ok)return u.response;let f=l.get(s);if(!f)return a();let m=await c({device:f.device,command:`press`,requiresCapture:!1,inspectFacts:t.inspectFacts,bindDevice:t.bindDevice,unavailableResponse:e=>o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`,void 0,e.hint?{hint:e.hint}:void 0)});if(!m.ok)return m.response;try{let e=await p(f,i.flags,l,t.contextFromFlags,{interactiveOnly:!0});if(d(e.snapshotQuality))return _(e.snapshotQuality);let r=n(e.nodes),a=r.primaryAction;return a?await v(t,f,e,a,m.runtime):g(r.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:o(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?o(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...i(`No React Native overlay detected`)}}}function _(e){return o(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,r,a,c){let{req:d,sessionStore:p}=e,m=e.contextFromFlags(d.flags,n.appBundleId,n.trace?.outPath),h=l(c,m).tapPoint;if(!h)return o(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`);let g=Date.now();s(n);let _=await h(a.point),v=Date.now(),x=await y(e,n),S=t({...u(r.nodes),..._,action:`dismiss-overlay`,overlayAction:a.action,x:a.point.x,y:a.point.y,ref:a.ref,label:a.label,warning:a.warning,dismissed:!0,verified:x.verified,verificationRequired:!x.verified,verificationWarning:x.verificationWarning,nextCommand:x.nextCommand,...i(b(x))});return f({session:n,sessionStore:p,command:d.command,positionals:d.positionals??[],flags:d.flags,result:S,responseData:S,actionStartedAt:g,actionFinishedAt:v})}async function y(e,t){let{req:r,sessionStore:i}=e,a=await p(t,r.flags,i,e.contextFromFlags,{interactiveOnly:!0});return d(a.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:n(a.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
1
+ import{L as e,o as t,u as n}from"./sdk-contracts.js";import{O as r}from"./sdk-batch-runner.js";import{M as i,d as a,u as o}from"./session-snapshot.js";import{M as s}from"./runtime.js";import{n as c}from"./catalog.js";import{r as l}from"./success-text.js";import{n as u}from"./touch-reference-frame.js";import{o as d}from"./quality-warnings.js";import{o as f}from"./interaction-ref-policy.js";import{captureSnapshotForSession as p}from"./interaction.js";async function m(r){let{req:i,sessionName:o,sessionStore:l}=r;if(i.command!==c.reactNative)return null;let u=h(i.positionals??[]);if(!u.ok)return u.response;let f=l.get(o);if(!f)return n();let m=await a({device:f.device,command:`press`,requiresCapture:!1,inspectFacts:r.inspectFacts,bindDevice:r.bindDevice,unavailableResponse:e=>t(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`,void 0,e.hint?{hint:e.hint}:void 0)});if(!m.ok)return m.response;try{let e=await p(f,i.flags,l,r.contextFromFlags,{interactiveOnly:!0});if(d(e.snapshotQuality))return _(e.snapshotQuality);let t=s(e.nodes),n=t.primaryAction;return n?await v(r,f,e,n,m.runtime):g(t.detected)}catch(t){return{ok:!1,error:e(t)}}}function h(e){return e.length===1&&e[0]===`dismiss-overlay`?{ok:!0}:{ok:!1,response:t(`INVALID_ARGS`,`react-native supports only: dismiss-overlay`)}}function g(e){return e?t(`COMMAND_FAILED`,`React Native overlay detected, but no safe dismiss target was found`,{hint:`Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`}):{ok:!0,data:{action:`dismiss-overlay`,detected:!1,dismissed:!1,...l(`No React Native overlay detected`)}}}function _(e){return t(`COMMAND_FAILED`,`React Native overlay state could not be determined because the accessibility tree is unreadable`,{reason:e.reason,hint:`The snapshot quality verdict is sparse. Use screenshot as visual truth; if an overlay is visible, report it or navigate with coordinates, then retry snapshot or dismiss-overlay on a readable screen.`})}async function v(e,n,a,s,c){let{req:d,sessionStore:p}=e,m=e.contextFromFlags(d.flags,n.appBundleId,n.trace?.outPath),h=o(c,m).tapPoint;if(!h)return t(`UNSUPPORTED_OPERATION`,`react-native dismiss-overlay is not supported on this device`);let g=Date.now();i(n);let _=await h(s.point),v=Date.now(),x=await y(e,n),S=r({...u(a.nodes),..._,action:`dismiss-overlay`,overlayAction:s.action,x:s.point.x,y:s.point.y,ref:s.ref,label:s.label,warning:s.warning,dismissed:!0,verified:x.verified,verificationRequired:!x.verified,verificationWarning:x.verificationWarning,nextCommand:x.nextCommand,...l(b(x))});return f({session:n,sessionStore:p,command:d.command,positionals:d.positionals??[],flags:d.flags,result:S,responseData:S,actionStartedAt:g,actionFinishedAt:v})}async function y(e,t){let{req:n,sessionStore:r}=e,i=await p(t,n.flags,r,e.contextFromFlags,{interactiveOnly:!0});return d(i.snapshotQuality)?{verified:!1,verificationWarning:`React Native overlay dismissal could not be verified because the post-dismiss accessibility tree is unreadable. Use screenshot as visual truth.`,nextCommand:`agent-device screenshot`}:s(i.nodes).detected?{verified:!1,verificationWarning:`React Native overlay is still detected after dismissal. Use screenshot --overlay-refs for visual evidence and report the overlay instead of pressing the warning body.`,nextCommand:`agent-device screenshot --overlay-refs`}:{verified:!0}}function b(e){return e.verified?`React Native overlay dismiss action sent and verified gone`:`React Native overlay dismiss action sent, but verification still detects an overlay`}export{m as handleReactNativeCommands};
@@ -1 +1 @@
1
- import{C as e,N as t}from"./sdk-contracts.js";import{c as n}from"./capture.js";import{g as r}from"./sdk-batch-runner.js";import{D as i,w as a}from"./sdk-device.js";import{D as o,E as s,O as c}from"./sdk-batch.js";import{n as l,r as u}from"./recording-export-quality.js";import{c as d,l as f}from"./back-mode.js";import{c as p}from"./session-store.js";import{r as m}from"./diagnostics.js";import"./diagnostics2.js";import{i as h}from"./output-path.js";import{i as ee,n as g}from"./recording-stop-observation.js";import{n as _}from"./request-runtime-binding.js";import{n as v}from"./dispatch-resolve.js";import{a as y,t as b}from"./session-routing.js";import{a as x,c as S,i as C,o as w,s as T,t as E}from"./screen-recording-resource-recovery.js";import{t as D}from"./telemetry.js";import O from"node:path";import k from"node:fs";const A=[`clientOutPath`,`telemetryPath`,`warning`,`overlayWarning`];function j(e){let{resourcePath:t,record:n}=N(e);if(n.status!==`decoded`)return{kind:`none`};if(P(e,n.envelope),n.envelope.lifecycle!==`completed`)return{kind:`open`,resourcePath:t};let r=F(n.envelope.metadata);return r===void 0?(m({level:`warn`,phase:`screen_recording_completed_manifest_unreplayable`,data:{resourcePath:t}}),{kind:`none`}):k.existsSync(r.outPath)?{kind:`completed`,completion:r}:{kind:`none`}}function M(e){let{record:t}=N(e);return t.status===`decoded`&&t.envelope.lifecycle===`completed`}function N(e){let t=S.resourcePath(e.sessionStore,e.sessionName);return{resourcePath:t,record:S.store.read(t)}}function P(t,n){if(n.sessionId!==t.sessionName)throw new e(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!i(n.device,a(t.device)))throw new e(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`})}function F(e){let t=e?.[C];if(!(!r(t)||!I(t)||!L(t)||!R(t)))return t}function I(e){return z(e.outPath)&&z(e.backend)&&V(e.startedAt)&&V(e.completedAt)&&(e.capturedDurationMs===void 0||V(e.capturedDurationMs))&&d(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function L(e){return A.every(t=>B(e[t]))&&te(e.activeSessionApp)&&W(e.chunks)}function R(e){return(e.stopObservation===void 0||g(e.stopObservation))&&(e.nativePathDisposition===void 0||ee(e.nativePathDisposition))}function z(e){return typeof e==`string`&&e.length>0}function B(e){return e===void 0||z(e)}function V(e){return typeof e==`number`&&Number.isFinite(e)}function H(e){return!r(e)||!z(e.bundleId)?!1:B(e.name)}function te(e){return e===void 0||H(e)}function U(e){return Array.isArray(e)&&e.every(e=>r(e)&&Number.isFinite(e.index)&&z(e.path)&&B(e.clientOutPath))}function W(e){return e===void 0||U(e)}function G(t){let r=n(`record`,t.flags);if(r)throw new e(`INVALID_ARGS`,r);let i=t.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new e(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(t.flags?.quality);if(t.flags?.quality!==void 0&&a===void 0)throw new e(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:K(t.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:t.flags?.hideTouches!==!0,hideTouchesRequested:t.flags?.hideTouches===!0}}function K(t){if(t===void 0)return`app`;if(t===`app`||t===`device`||t===`system`)return t;throw new e(`INVALID_ARGS`,`record scope must be app, device, or system`)}function q(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:b(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function J(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function Y(e){return{action:`start`,...e.clientOutPath?{requestedFileName:O.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function X(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function Z(e){let t=[Q(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:O.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?D(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:O.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{recorder:e.stopObservation.recorder},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function Q(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:O.basename(e.clientOutPath??e.outPath)}}async function ne(e){try{return await re(e)}catch(e){return{ok:!1,error:t(e)}}}async function re(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=ie(t,i);if(a.kind===`start`&&!f(o)&&!i)return q(t);let s=await ae(e,i),{session:c}=s;return a.kind===`start`?await oe(e,c,G(t),a.use,s.needsReadiness):await le(e,c,a.kind,s.needsReadiness)}function ie(e,t){let n=K(e.flags?.recordingScope);return{scope:n,plan:s({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function ae(e,t){let n=t?.device??await v(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t?{session:t,needsReadiness:!1}:{session:fe(e,n),needsReadiness:!0}}async function oe(e,t,n,r,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=await e.bindDevice(t.device,o);i&&await _(a);let s=a.facts.screenRecordingStart;if(!s.available)return X(s);let c=await e.bindDevice(t.device,r),{fence:l,outputPaths:u}=$(e,t),d=await c.operations.screenRecordingStart(se(e,t,n,l,u.outputPath));await x({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:c.owner,fence:l,...d,throwIfCanceled:e.throwIfCanceled});let f=e.sessionStore.get(e.sessionName)?.screenRecording;if(!f)throw TypeError(`Screen recording adoption did not publish a live handle`);let m=f.handle.inspect();return p(e.sessionStore,t,e.req,e.req.command,Y(m)),J(m,e.sessionStore.ensureSessionDir(e.sessionName),u.requestedPath)}function $(e,t){let n=S.resourcePath(e.sessionStore,e.sessionName);return{fence:S.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:h({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function se(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:ce(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function ce(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function le(e,t,n,r){let i;try{i=n===`stop-live`?{completion:await w({intent:`capture`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}),recordsSessionAction:!0}:await de(e,t,r)}catch(n){throw ue(e,t),n}let a=i.completion,o=Z(a);return i.recordsSessionAction&&p(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:a.outPath,...a.clientOutPath?{requestedFileName:O.basename(a.clientOutPath)}:{},showTouches:a.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),o}function ue(e,t){t.recordOnlySession&&M(e)&&e.sessionStore.delete(e.sessionName)}async function de(t,n,r){let i=j({sessionName:t.sessionName,sessionStore:t.sessionStore,device:n.device});if(i.kind===`completed`)return{completion:i.completion,recordsSessionAction:!1};if(i.kind===`none`)throw new e(`INVALID_ARGS`,`no active recording`);return{completion:await T({resourcePath:i.resourcePath,scope:t.requestScope,acquireControl:async(e,i)=>{let a=await t.bindExactDevice(n.device,e.owner,e.fence,c,i);return r&&await _(a),E({runtime:a,dispose:async()=>{}})}}),recordsSessionAction:!0}}function fe(e,t){return{name:e.sessionName,sessionScope:y(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{ne as t};
1
+ import{D as e,L as t}from"./sdk-contracts.js";import{c as n}from"./capture.js";import{g as r}from"./sdk-batch-runner.js";import{O as i,T as a}from"./sdk-device.js";import{D as o,E as s,O as c}from"./sdk-batch.js";import{n as l,r as u}from"./recording-export-quality.js";import{c as d,l as f}from"./back-mode.js";import{c as p}from"./session-store.js";import{r as m}from"./diagnostics.js";import"./diagnostics2.js";import{i as h}from"./output-path.js";import{i as ee,n as g}from"./recording-stop-observation.js";import{n as _}from"./request-runtime-binding.js";import{n as v}from"./dispatch-resolve.js";import"./screen-recording-admission-ledger.js";import{a as y,t as b}from"./session-routing.js";import{a as x,c as S,i as C,o as w,s as T,t as E}from"./screen-recording-resource-recovery.js";import{t as D}from"./telemetry.js";import O from"node:path";import k from"node:fs";const A=[`clientOutPath`,`telemetryPath`,`warning`,`overlayWarning`];function j(e){let{resourcePath:t,record:n}=N(e);if(n.status!==`decoded`)return{kind:`none`};if(P(e,n.envelope),n.envelope.lifecycle!==`completed`)return{kind:`open`,resourcePath:t};let r=F(n.envelope.metadata);return r===void 0?(m({level:`warn`,phase:`screen_recording_completed_manifest_unreplayable`,data:{resourcePath:t}}),{kind:`none`}):k.existsSync(r.outPath)?{kind:`completed`,completion:r}:{kind:`none`}}function M(e){let{record:t}=N(e);return t.status===`decoded`&&t.envelope.lifecycle===`completed`}function N(e){let t=S.resourcePath(e.sessionStore,e.sessionName);return{resourcePath:t,record:S.store.read(t)}}function P(t,n){if(n.sessionId!==t.sessionName)throw new e(`COMMAND_FAILED`,`Screen recording recovery record does not belong to the requested session`,{reason:`runtime-contract-invalid`});if(!i(n.device,a(t.device)))throw new e(`COMMAND_FAILED`,`Screen recording recovery device does not match the selected device`,{reason:`runtime-contract-invalid`})}function F(e){let t=e?.[C];if(!(!r(t)||!I(t)||!L(t)||!R(t)))return t}function I(e){return z(e.outPath)&&z(e.backend)&&V(e.startedAt)&&V(e.completedAt)&&(e.capturedDurationMs===void 0||V(e.capturedDurationMs))&&d(e.scope)&&typeof e.showTouches==`boolean`&&typeof e.recordOnlySession==`boolean`}function L(e){return A.every(t=>B(e[t]))&&te(e.activeSessionApp)&&W(e.chunks)}function R(e){return(e.stopObservation===void 0||g(e.stopObservation))&&(e.nativePathDisposition===void 0||ee(e.nativePathDisposition))}function z(e){return typeof e==`string`&&e.length>0}function B(e){return e===void 0||z(e)}function V(e){return typeof e==`number`&&Number.isFinite(e)}function H(e){return!r(e)||!z(e.bundleId)?!1:B(e.name)}function te(e){return e===void 0||H(e)}function U(e){return Array.isArray(e)&&e.every(e=>r(e)&&Number.isFinite(e.index)&&z(e.path)&&B(e.clientOutPath))}function W(e){return e===void 0||U(e)}function G(t){let r=n(`record`,t.flags);if(r)throw new e(`INVALID_ARGS`,r);let i=t.flags?.fps;if(i!==void 0&&(!Number.isInteger(i)||i<1||i>120))throw new e(`INVALID_ARGS`,`fps must be an integer between 1 and 120`);let a=u(t.flags?.quality);if(t.flags?.quality!==void 0&&a===void 0)throw new e(`INVALID_ARGS`,`quality must be one of: ${l.join(`, `)} (legacy numeric values 5-10 are accepted)`);return{scope:K(t.flags?.recordingScope),...i===void 0?{}:{fps:i},...a===void 0?{}:{exportQuality:a},showTouches:t.flags?.hideTouches!==!0,hideTouchesRequested:t.flags?.hideTouches===!0}}function K(t){if(t===void 0)return`app`;if(t===`app`||t===`device`||t===`system`)return t;throw new e(`INVALID_ARGS`,`record scope must be app, device, or system`)}function q(e){return{ok:!1,error:{code:`INVALID_ARGS`,message:b(e)?`record start with app scope and an explicit session requires an active app session; run open <app> first, or use --scope device to record the full screen`:`record start defaults to app scope and requires an active app session; run open <app> first, or use --scope device to record the full screen`}}}function J(e,t,n){return{ok:!0,data:{recording:`started`,outPath:e.clientOutPath??n,sessionStateDir:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,showTouches:e.showTouches}}}function Y(e){return{action:`start`,...e.clientOutPath?{requestedFileName:O.basename(e.clientOutPath)}:{},showTouches:e.showTouches}}function X(e){return{ok:!1,error:{code:`UNSUPPORTED_OPERATION`,message:`record is not supported on this device`,hint:e.hint??`Select an Apple, Android, physical HarmonyOS, or web target that supports screen recording.`,details:{reason:e.reason}}}}function Z(e){let t=[Q(e)];if(e.chunks&&e.chunks.length>1&&t.push(...e.chunks.slice(1).map(e=>({field:`chunkPath`,artifactType:`screen-recording-chunk`,path:e.path,localPath:e.clientOutPath,fileName:O.basename(e.clientOutPath??e.path)}))),e.telemetryPath){let n=e.clientOutPath?D(e.clientOutPath):void 0;t.push({field:`telemetryPath`,artifactType:`screen-recording-telemetry`,path:e.telemetryPath,localPath:n,fileName:O.basename(e.telemetryPath)})}return{ok:!0,data:{recording:`stopped`,outPath:e.outPath,telemetryPath:e.telemetryPath,artifacts:t,recordingBackend:e.backend,recordingScope:e.scope,recordOnlySession:e.recordOnlySession,activeSessionApp:e.activeSessionApp,durationMs:Math.max(0,e.completedAt-e.startedAt),...e.capturedDurationMs===void 0?{}:{capturedDurationMs:e.capturedDurationMs},...e.stopObservation===void 0?{}:{recorder:e.stopObservation.recorder},...e.nativePathDisposition===void 0?{}:{nativePathDisposition:e.nativePathDisposition},showTouches:e.showTouches,warning:e.warning,overlayWarning:e.overlayWarning,chunks:e.chunks?.map(e=>({index:e.index,path:e.clientOutPath??e.path}))}}}function Q(e){return{field:`outPath`,artifactType:`screen-recording`,path:e.outPath,localPath:e.clientOutPath,fileName:O.basename(e.clientOutPath??e.outPath)}}async function ne(e){try{return await re(e)}catch(e){return{ok:!1,error:t(e)}}}async function re(e){let{req:t,sessionName:n,sessionStore:r}=e,i=r.get(n),{plan:a,scope:o}=ie(t,i);if(a.kind===`start`&&!f(o)&&!i)return q(t);let s=await ae(e,i),{session:c}=s;return a.kind===`start`?await oe(e,c,G(t),a.use,s.needsReadiness):await le(e,c,a.kind,s.needsReadiness)}function ie(e,t){let n=K(e.flags?.recordingScope);return{scope:n,plan:s({action:e.positionals?.[0],scope:n,hasLiveHandle:t?.screenRecording!==void 0})}}async function ae(e,t){let n=t?.device??await v(e.req.flags??{});return await e.retainDeviceExecutionLock(n.id),t?{session:t,needsReadiness:!1}:{session:fe(e,n),needsReadiness:!0}}async function oe(e,t,n,r,i){if(t.screenRecording)return{ok:!1,error:{code:`INVALID_ARGS`,message:`recording already in progress`}};let a=await e.bindDevice(t.device,o);i&&await _(a);let s=a.facts.screenRecordingStart;if(!s.available)return X(s);let c=await e.bindDevice(t.device,r),{fence:l,outputPaths:u}=$(e,t),d=await c.operations.screenRecordingStart(se(e,t,n,l,u.outputPath));await x({admissionLedger:e.admissionLedger,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore,device:t.device,owner:c.owner,fence:l,...d,throwIfCanceled:e.throwIfCanceled});let f=e.sessionStore.get(e.sessionName)?.screenRecording;if(!f)throw TypeError(`Screen recording adoption did not publish a live handle`);let m=f.handle.inspect();return p(e.sessionStore,t,e.req,e.req.command,Y(m)),J(m,e.sessionStore.ensureSessionDir(e.sessionName),u.requestedPath)}function $(e,t){let n=S.resourcePath(e.sessionStore,e.sessionName);return{fence:S.createNextFence({admissionLedger:e.admissionLedger,resourcePath:n,device:t.device}),outputPaths:h({requestedPath:e.req.positionals?.[1],platform:t.device.platform,cwd:e.req.meta?.cwd})}}function se(e,t,n,r,i){return{sessionId:e.sessionName,outputPath:i,clientOutputPath:e.req.meta?.clientArtifactPaths?.outPath,scope:n.scope,showTouches:n.showTouches,hideTouchesRequested:n.hideTouchesRequested,recordOnlySession:t.recordOnlySession===!0,activeSessionApp:ce(t),exportQuality:n.exportQuality,fps:n.fps,fence:r}}function ce(e){if(e.appBundleId)return{bundleId:e.appBundleId,...e.appName?{name:e.appName}:{}}}async function le(e,t,n,r){let i;try{i=n===`stop-live`?{completion:await w({intent:`capture`,session:t,sessionName:e.sessionName,sessionStore:e.sessionStore}),recordsSessionAction:!0}:await de(e,t,r)}catch(n){throw ue(e,t),n}let a=i.completion,o=Z(a);return i.recordsSessionAction&&p(e.sessionStore,t,e.req,e.req.command,{action:`stop`,outPath:a.outPath,...a.clientOutPath?{requestedFileName:O.basename(a.clientOutPath)}:{},showTouches:a.showTouches}),t.recordOnlySession&&e.sessionStore.delete(e.sessionName),o}function ue(e,t){t.recordOnlySession&&M(e)&&e.sessionStore.delete(e.sessionName)}async function de(t,n,r){let i=j({sessionName:t.sessionName,sessionStore:t.sessionStore,device:n.device});if(i.kind===`completed`)return{completion:i.completion,recordsSessionAction:!1};if(i.kind===`none`)throw new e(`INVALID_ARGS`,`no active recording`);return{completion:await T({resourcePath:i.resourcePath,scope:t.requestScope,acquireControl:async(e,i)=>{let a=await t.bindExactDevice(n.device,e.owner,e.fence,c,i);return r&&await _(a),E({runtime:a,dispose:async()=>{}})}}),recordsSessionAction:!0}}function fe(e,t){return{name:e.sessionName,sessionScope:y(e.req),device:t,createdAt:Date.now(),recordOnlySession:!0,actions:[]}}export{ne as t};
@@ -1 +1 @@
1
- import{c as e,t}from"./session-store.js";import{i as n}from"./request-runtime-binding.js";import{t as r}from"./record-runtime.js";import i from"node:path";import a from"node:fs";function o(e){let t=(e.req.positionals?.[0]??``).toLowerCase();if(t!==`start`&&t!==`stop`)return n(`INVALID_ARGS`,`trace requires start|stop`);let r=e.sessionStore.get(e.sessionName);return r?t===`start`?s(e.req,e.sessionStore,r):c(e.req,e.sessionStore,r):n(`SESSION_NOT_FOUND`,`No active session`)}function s(r,o,s){if(s.trace)return n(`INVALID_ARGS`,`trace already in progress`);let c=t.expandHome(r.positionals?.[1]??o.defaultTracePath(s));return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),s.trace={outPath:c,startedAt:Date.now()},e(o,s,r,r.command,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}function c(t,r,a){if(!a.trace)return n(`INVALID_ARGS`,`no active trace`);let o=l(a.trace.outPath,t.positionals?.[1]);a.trace=void 0,e(r,a,t,t.command,{action:`stop`,outPath:o});let s=t.meta?.clientArtifactPaths?.outPath??o;return{ok:!0,data:{trace:`stopped`,outPath:o,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:o,localPath:s,fileName:i.basename(s)}]}}}function l(e,n){if(!n)return e;let r=t.expandHome(n);return a.mkdirSync(i.dirname(r),{recursive:!0}),a.existsSync(e)?a.renameSync(e,r):a.appendFileSync(r,``),r}async function u(e){let{req:t,sessionName:n,sessionStore:i}=e,a=t.command;return a===`record`?r({req:t,sessionName:n,sessionStore:i,bindDevice:e.bindDevice,bindExactDevice:e.bindExactDevice,admissionLedger:e.admissionLedger,requestScope:e.requestScope,retainDeviceExecutionLock:e.retainDeviceExecutionLock,throwIfCanceled:e.throwIfCanceled}):a===`trace`?o({req:t,sessionName:n,sessionStore:i}):null}export{u as handleRecordTraceCommands};
1
+ import{o as e}from"./sdk-contracts.js";import{c as t,t as n}from"./session-store.js";import"./screen-recording-admission-ledger.js";import{t as r}from"./record-runtime.js";import i from"node:path";import a from"node:fs";function o(t){let n=(t.req.positionals?.[0]??``).toLowerCase();if(n!==`start`&&n!==`stop`)return e(`INVALID_ARGS`,`trace requires start|stop`);let r=t.sessionStore.get(t.sessionName);return r?n===`start`?s(t.req,t.sessionStore,r):c(t.req,t.sessionStore,r):e(`SESSION_NOT_FOUND`,`No active session`)}function s(r,o,s){if(s.trace)return e(`INVALID_ARGS`,`trace already in progress`);let c=n.expandHome(r.positionals?.[1]??o.defaultTracePath(s));return a.mkdirSync(i.dirname(c),{recursive:!0}),a.appendFileSync(c,``),s.trace={outPath:c,startedAt:Date.now()},t(o,s,r,r.command,{action:`start`,outPath:c}),{ok:!0,data:{trace:`started`,outPath:c}}}function c(n,r,a){if(!a.trace)return e(`INVALID_ARGS`,`no active trace`);let o=l(a.trace.outPath,n.positionals?.[1]);a.trace=void 0,t(r,a,n,n.command,{action:`stop`,outPath:o});let s=n.meta?.clientArtifactPaths?.outPath??o;return{ok:!0,data:{trace:`stopped`,outPath:o,artifacts:[{field:`outPath`,artifactType:`trace-log`,path:o,localPath:s,fileName:i.basename(s)}]}}}function l(e,t){if(!t)return e;let r=n.expandHome(t);return a.mkdirSync(i.dirname(r),{recursive:!0}),a.existsSync(e)?a.renameSync(e,r):a.appendFileSync(r,``),r}async function u(e){let{req:t,sessionName:n,sessionStore:i}=e,a=t.command;return a===`record`?r({req:t,sessionName:n,sessionStore:i,bindDevice:e.bindDevice,bindExactDevice:e.bindExactDevice,admissionLedger:e.admissionLedger,requestScope:e.requestScope,retainDeviceExecutionLock:e.retainDeviceExecutionLock,throwIfCanceled:e.throwIfCanceled}):a===`trace`?o({req:t,sessionName:n,sessionStore:i}):null}export{u as handleRecordTraceCommands};
@@ -1 +1 @@
1
- import{p as e}from"./sdk-contracts.js";const t=[`x`,`y`,`width`,`height`];function n(t){let n=r(t);if(!n)return null;let i=e(n);return!Number.isFinite(i.x)||!Number.isFinite(i.y)?null:i}function r(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function i(e,n){return!e||!n?!1:t.every(t=>Math.abs(e[t]-n[t])<=.5)}function a(e){return{x:o(e.x,e.width),y:o(e.y,e.height)}}function o(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}export{n as i,r as n,a as r,i as t};
1
+ import{g as e}from"./sdk-contracts.js";const t=[`x`,`y`,`width`,`height`];function n(t){let n=r(t);if(!n)return null;let i=e(n);return!Number.isFinite(i.x)||!Number.isFinite(i.y)?null:i}function r(e){if(!e)return null;let t=Number(e.x),n=Number(e.y),r=Number(e.width),i=Number(e.height);return!Number.isFinite(t)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(i)||r<0||i<0?null:{x:t,y:n,width:r,height:i}}function i(e,n){return!e||!n?!1:t.every(t=>Math.abs(e[t]-n[t])<=.5)}function a(e){return{x:o(e.x,e.width),y:o(e.y,e.height)}}function o(e,t){if(t<=1)return Math.floor(e);let n=Math.ceil(e),r=Math.floor(e+t-1);return Math.round(Math.min(r,Math.max(n,e+t/2)))}export{n as i,r as n,a as r,i as t};