@agent-device/revyl 0.21.37-nightly.20261111.157 → 0.21.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/errors.mjs CHANGED
@@ -1 +1 @@
1
- const e=Symbol.for(`agent-device.AppError`);var t=class t extends Error{static[Symbol.hasInstance](n){return this===t?typeof n==`object`&&!!n&&n[e]===!0:Function.prototype[Symbol.hasInstance].call(this,n)}code;details;cause;constructor(t,n,r,i){super(n),Object.defineProperty(this,e,{value:!0}),this.code=t,this.details=r,this.cause=i}};function n(e,t=`COMMAND_FAILED`){return typeof e==`string`&&e.length>0?e:t}function r(e){return e instanceof Error?e.message:String(e)}function i(e,t,n={}){return e.details={...e.details,...n,dispatched:t},e}function a(e,t){if(t===0)return e;let n=e?.dispatchedSteps;return{...e,dispatchedSteps:t+(typeof n==`number`?n:0),dispatched:`unknown`}}function o(e,n){return e instanceof t&&(e.details=a(e.details,n)),e}export{n as a,r as i,i as n,o as r,t};
1
+ const e=Symbol.for(`agent-device.AppError`);var t=class t extends Error{static[Symbol.hasInstance](n){return this===t?typeof n==`object`&&!!n&&n[e]===!0:Function.prototype[Symbol.hasInstance].call(this,n)}code;details;cause;constructor(t,n,r,i){super(n),Object.defineProperty(this,e,{value:!0}),this.code=t,this.details=r,this.cause=i}};function n(e,t=`COMMAND_FAILED`){return typeof e==`string`&&e.length>0?e:t}function r(e){return new t(`COMMAND_FAILED`,e,{reason:`runtime-contract-invalid`,hint:`This is an agent-device runtime contract bug; report the selected device and command.`})}function i(e){return e instanceof Error?e.message:String(e)}function a(e,t,n={}){return e.details={...e.details,...n,dispatched:t},e}function o(e,t){if(t===0)return e;let n=e?.dispatchedSteps;return{...e,dispatchedSteps:t+(typeof n==`number`?n:0),dispatched:`unknown`}}function s(e,n){return e instanceof t&&(e.details=o(e.details,n)),e}export{i as a,s as i,r as n,n as o,a as r,t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime.mjs";import{t}from"./errors.mjs";var n=e({providerInteractorSource:()=>i,requireInteractorMethod:()=>r});function r(e,n){if(e)return e;throw new t(`COMMAND_FAILED`,`${n} was admitted but its bound interactor has no implementation.`,{reason:`interactor-method-missing`})}function i(e){return async n=>{let r=e.resolveInteractor(n);if(r)return r;throw new t(`UNSUPPORTED_OPERATION`,`Provider-owned ${e.operation} operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id})}}export{i as n,r,n as t};
1
+ import{n as e}from"./rolldown-runtime.mjs";import{n as t,t as n}from"./errors.mjs";var r=e({providerInteractorSource:()=>a,requireInteractorMethod:()=>i});function i(e,n){if(e)return e;throw t(`${n} was admitted but its bound interactor has no implementation.`)}function a(e){return async t=>{let r=e.resolveInteractor(t);if(r)return r;throw new n(`UNSUPPORTED_OPERATION`,`Provider-owned ${e.operation} operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id})}}export{a as n,i as r,r as t};
@@ -1 +1 @@
1
- import{i as e,t}from"./device.mjs";import{r as n,t as r}from"./errors.mjs";import{n as i}from"./device2.mjs";import{n as a,r as o}from"./interactor-operation-binding.mjs";import{a as s,i as c,r as ee,t as l}from"./open-target.mjs";import{setTimeout as te}from"node:timers/promises";function u(e){return Object.freeze({family:e.platform,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}const ne=[`resolveOpenTarget`,`prepareApplicationOpen`,`openApplication`,`applyRuntimeHints`,`clearRuntimeHints`,`closeApplication`,`finalizeApplicationClose`,`prepareAppleRunner`,`configureProviderPortReverse`];function d(e){return Object.freeze({resolveOpenTarget:e.resolveOpenTarget,prepareApplicationOpen:e.prepareApplicationOpen,openApplication:e.openApplication,applyRuntimeHints:e.applyRuntimeHints,clearRuntimeHints:e.clearRuntimeHints,closeApplication:e.closeApplication,finalizeApplicationClose:e.finalizeApplicationClose,prepareAppleRunner:e.prepareAppleRunner,configureProviderPortReverse:e.configureProviderPortReverse})}function re(e,t){return Object.freeze(Object.fromEntries(ne.flatMap(n=>t[n].available?[[n,e[n]]]:[])))}function ie(e){return()=>({captureBackendRefusal:e})}async function ae(e,t={}){let n=e?.captureBackend;if(n!==void 0&&!t.captureBackends?.includes(n))throw new r(`UNSUPPORTED_OPERATION`,`--capture-backend ${n} is not supported: ${t.captureBackendRefusal??`this capture owner declares no such backend`}`,{reason:`screenshot-capture-backend-unsupported`});if(e?.screenMask===void 0)return;let{readScreenshotScreenMask:i}=await import(`./screenshot.mjs`).then(e=>e.n);if(i(e?.screenMask)!==void 0&&t.screenMask!==!0)throw new r(`UNSUPPORTED_OPERATION`,`--screen-mask requires a handheld iOS simulator simctl capture`,{reason:`screenshot-screen-mask-unsupported`})}function f(e){return Object.freeze({captureScreenshot:e.capture})}function oe(e,t){let{captureBackend:n,preferredCaptureBackend:r,...i}=e??{};return n?{...i,captureBackend:n}:r&&t.captureCapabilities(i).captureBackends?.includes(r)?{...i,captureBackend:r}:i}function se(e,t){return Object.freeze({captureScreenshot:async n=>{let r=oe(n.options,e);return await ae(r,e.captureCapabilities(r)),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e.signal})).screenshot(n.outPath,r)??{}}})}function ce(e){return se(e,a({...e,operation:`screenshot`}))}function le(e,t){return t.signal===void 0?e:AbortSignal.any([e,t.signal])}function p(e){return Object.freeze({captureSnapshot:e.capture,captureSnapshotWithCustomActions:e.customActions,captureSnapshotWithoutActiveApp:e.withoutActiveApp})}function ue(e){let t=async t=>{await de(e,t);let n=le(e.signal,t),i={...t.execution,appBundleId:t.options?.appBundleId,signal:n},a=e.ownership===`local`?await e.resolveInteractor(e.device,i):e.resolveInteractor(i);if(!a)throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned snapshot operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id});let o=await a.snapshot({...t.options,signal:n});if(!pe(o))return o;if(!e.presentIosAcquisition)throw new r(`COMMAND_FAILED`,`Acquired iOS snapshot has no host presentation owner.`,{reason:`ios-snapshot-presenter-missing`,deviceId:e.device.id});return await e.presentIosAcquisition(o,t.options)};return Object.freeze({captureSnapshot:t,captureSnapshotWithCustomActions:t,captureSnapshotWithoutActiveApp:t})}async function de(e,t){if(t.options?.observeOnly!==!0)return;let{isHandheldAppleDevice:n}=await import(`./device2.mjs`).then(e=>e.t);if(!(e.ownership===`local`&&n(e.device)))throw new r(`UNSUPPORTED_OPERATION`,`observe-only snapshot requires a local iOS or iPadOS runner.`)}function fe(e){return ue({...e,ownership:`provider`})}function pe(e){return`stage`in e&&e.stage===`acquired`}function m(e){return Object.freeze({findText:e.findText,querySelector:e.querySelector})}function h(e){return Object.freeze({setViewport:e.setViewport})}function me(e){return Object.freeze({focusPoint:e.focus})}function he(e,t){return Object.freeze({focusPoint:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).focus(n.point.x,n.point.y)}})}function ge(e){return he(e.signal,a({...e,operation:`focus`}))}function _e(e){let t=t=>t??e.unsupported;return Object.freeze({performGesturePlan:t(e.plan),performDirectionalFlingPlan:t(e.directionalFling),performMultiTouchGesturePlan:t(e.multiTouch),performTargetAuthoredDrag:t(e.targetAuthoredDrag),gestureViewport:t(e.viewport)})}function ve(e){let t=e??{},n=g(t.pixels),r=g(t.x1),i=g(t.y1),a=g(t.x2),o=g(t.y2),s=r===void 0||i===void 0||a===void 0||o===void 0?void 0:{x:r/2+a/2,y:i/2+o/2};return{report:t,...n===void 0?{}:{pixels:n},...s===void 0?{}:{midpoint:s}}}function g(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function _(e){return Object.freeze({scrollDirection:e.scroll})}function ye(e,t){return Object.freeze({scrollDirection:async n=>(e.throwIfAborted(),ve(await(await t({...n.execution,appBundleId:n.target?.appBundleId,signal:e})).scroll(n.direction,n.options)))})}function be(e){return ye(e.signal,a({...e,operation:`scroll`}))}function v(e){return Object.freeze({typeText:e.type})}function xe(e,t){return Object.freeze({typeText:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).type(n.text,n.delayMs))})}function Se(e){return xe(e.signal,a({...e,operation:`type`}))}function y(e){return Object.freeze({readTextAtPoint:e.readTextAtPoint})}function b(e){return Object.freeze({back:e.back})}function Ce(e,t){return Object.freeze({back:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).back(n.mode)}})}const we=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`orientation auto is only supported on ADB-backed Android.`});function x(e){return Object.freeze({setOrientation:e.orientation,unlockOrientation:e.unlock??we})}function Te(e,t){return Object.freeze({setOrientation:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).setOrientation(n.rotation))})}function Ee(e,t){return Object.freeze({unlockOrientation:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.unlockOrientation,`orientation auto`).call(r)}})}function S(e){let{tvRemote:t,buttonSupport:n}=e;return Object.freeze({tvRemote:t.available&&n?Object.freeze({available:!0,subjects:Object.freeze(Object.fromEntries(n.supported.map(e=>[e,{available:!0}]))),unlisted:n.unsupported}):t})}const C=`tv-remote`;function De(e,t){return Object.freeze({tvRemote:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.tvRemote,C).call(r,n.button,n.durationMs)}})}function Oe(e){let t=t=>t??e.unsupported;return Object.freeze({keyboardStatus:t(e.status),keyboardDismiss:t(e.dismiss),keyboardEnter:t(e.enter)})}async function ke(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}const w={keyboardStatus:`keyboard status`,keyboardDismiss:`keyboard dismiss`,keyboardEnter:`keyboard enter`};function T(e,t,n){let r=async r=>{let i=await ke(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],w[e]).call(i)};return Object.freeze({[e]:r})}function E(e){let t=t=>t??e.unsupported;return Object.freeze({readClipboard:t(e.read),writeClipboard:t(e.write)})}const D={readClipboard:`clipboard read`,writeClipboard:`clipboard write`};async function Ae(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}async function je(e,t){let{requireInteractorMethod:n}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return n(e[t],D[t])}function Me(e,t){return Object.freeze({readClipboard:async n=>{let r=await Ae(e,t,n);return await(await je(r,`readClipboard`)).call(r)}})}function Ne(e,t){return Object.freeze({writeClipboard:async n=>{let r=await Ae(e,t,n);await(await je(r,`writeClipboard`)).call(r,n.text)}})}const Pe=[`home`,`appSwitcher`,`actionButton`,`volumeUp`,`volumeDown`,`power`,`mute`,`sleep`,`wake`,`mediaPlayPause`,`mediaNext`,`mediaPrevious`,`mediaRewind`,`mediaFastForward`],O={home:`home`,appSwitcher:`app-switcher`,actionButton:`action-button`,volumeUp:`volume-up`,volumeDown:`volume-down`,power:`power`,mute:`mute`,sleep:`sleep`,wake:`wake`,mediaPlayPause:`media-play-pause`,mediaNext:`media-next`,mediaPrevious:`media-previous`,mediaRewind:`media-rewind`,mediaFastForward:`media-fast-forward`};function k(e){let t={};for(let n of Pe)t[n]=e[n]??e.unsupported;return Object.freeze(t)}Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is not supported on Android TV targets; use tv-remote.`}),Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is supported on Android emulators and physical devices.`}),Object.freeze({available:!0}),Pe.filter(e=>e!==`home`&&e!==`appSwitcher`&&e!==`actionButton`);function A(e,t,n){let r=async r=>{t.throwIfAborted();let i=await n({...r.execution,appBundleId:r.options?.appBundleId,signal:t});await o(i[e],O[e]).call(i)};return Object.freeze({[e]:r})}function j(e){return Object.freeze({triggerAppEvent:e.triggerAppEvent})}function Fe(e,t){return Object.freeze({triggerAppEvent:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).open(n.eventUrl,{appBundleId:n.options?.appBundleId})}})}function M(e){return Object.freeze({readAlert:e.read,awaitAlert:e.wait,acceptAlert:e.accept,dismissAlert:e.dismiss})}async function Ie(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Le(e,t){return{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e.surface===void 0?{}:{surface:e.surface},...t?{signal:t}:{}}}const N={readAlert:`alert get`,awaitAlert:`alert wait`,acceptAlert:`alert accept`,dismissAlert:`alert dismiss`};function P(e,t,n){return Object.freeze({[e]:async r=>{let i=await Ie(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],N[e]).call(i,Le(r,t))}})}function F(e){return Object.freeze({audioProbeStart:e.capture,audioProbeReattach:e.capture,audioProbeCleanup:e.capture,audioProbeQuery:e.query})}function I(e){return Object.freeze({perfFrames:e.frames,perfMemorySample:e.memorySample,perfMemorySnapshot:e.memorySnapshot,perfNativeCaptureStart:e.nativeCapture,perfNativeCaptureReattach:e.nativeCapture,perfNativeCaptureCleanup:e.nativeCapture,perfProfileReport:e.profileReport})}function L(e){let t=t=>t??e.unsupported;return Object.freeze({tapPoint:e.tap,tapRef:t(e.tapRef),longPressPoint:e.longPress,hoverPoint:R(t(e.hover)),hoverRef:R(t(e.hoverRef)),fillPoint:e.fill,fillRef:t(e.fillRef),tapElementSelector:t(e.tapElementSelector)})}function R(e){return e.available?e:Object.freeze({...e,hint:e.hint??`hover raises pointer hover state and is available on web targets only. On touch platforms use longpress for hold gestures.`})}function Re(e,t){return{...e.execution,appBundleId:e.appBundleId,signal:t}}function ze(e,t,n,i){let a=async n=>(e.throwIfAborted(),await t(Re(n,e))),o=async t=>{e.throwIfAborted(),Be(t.options,n.longPressPoint);let r=await a(t);return t.options.button!==`primary`&&r.alternateClick?await r.alternateClick(t.point,t.options.button):r.pressPoint?await r.pressPoint(t.point,t.options):await He(r,t.point,t.options,i)},s=async e=>{let t=await a(e);if(!t.hover)throw new r(`UNSUPPORTED_OPERATION`,`Bound runtime advertised hover without an interactor.`);return await t.hover(e.point.x,e.point.y)},c=async e=>await(await a(e)).fill(e.point.x,e.point.y,e.text,e.delayMs,{allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback});return Object.freeze({...n.tapPoint.available?{tapPoint:o}:{},...n.tapRef.available?{tapRef:async e=>{let t=await a(e);return t.tapRef?await t.tapRef(e.ref):z(`tapRef`)}}:{},...n.longPressPoint.available?{longPressPoint:async e=>await(await a(e)).longPress(e.point.x,e.point.y,e.durationMs)}:{},...n.hoverPoint.available?{hoverPoint:s}:{},...n.hoverRef.available?{hoverRef:async e=>{let t=await a(e);return t.hoverRef?await t.hoverRef(e.ref):z(`hoverRef`)}}:{},...n.fillPoint.available?{fillPoint:c}:{},...n.fillRef.available?{fillRef:async e=>{let t=await a(e);return t.fillRef?await t.fillRef(e.ref,e.text,e.delayMs):z(`fillRef`)}}:{},...n.tapElementSelector.available?{tapElementSelector:async e=>{let t=await a(e);return t.tapElementSelector?await t.tapElementSelector(e.selector):z(`tapElementSelector`)}}:{}})}function z(e){throw new r(`UNSUPPORTED_OPERATION`,`Bound runtime advertised ${e} without an interactor.`)}function Be(e,t){if(!(e.holdMs<=0||t.available))throw new r(`UNSUPPORTED_OPERATION`,`press-and-hold is not supported by this runtime.`,{reason:t.reason,...t.hint===void 0?{}:{hint:t.hint}})}function Ve(e){if(e.doubleTap)return e.doubleTap;throw new r(`UNSUPPORTED_OPERATION`,`double-tap is not supported by this runtime.`,{reason:`owner-capability-missing`,hint:`This runtime drives single presses; use --count to repeat them.`})}async function He(e,t,i,a){if(i.button!==`primary`)throw new r(`UNSUPPORTED_OPERATION`,`Bound runtime does not implement ${i.button} click.`);let o=i.doubleTap?Ve(e):void 0,s,c=0;try{for(let n=0;n<i.count;n+=1){let[r,ee]=We(n,i.jitterPx),l=await Ue(e,o,t.x+r,t.y+ee,i);c+=1,s??=l,n<i.count-1&&i.intervalMs>0&&await a(i.intervalMs)}}catch(e){throw n(e,c)}return s}async function Ue(e,t,n,r,i){return t?await t.call(e,n,r):i.holdMs>0?await e.longPress(n,r,i.holdMs):await e.tap(n,r)}const B=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function We(e,t){if(t<=0)return[0,0];let[n,r]=B[e%B.length];return[n*t,r*t]}function Ge(e){return ze(e.signal,a({...e,operation:`touch`}),e.facts,e.pause)}const Ke={appLog:!0,apps:!0,appDeployment:!0,appState:!0,network:!0,screenRecording:!0,screenshot:!0,snapshot:!0,viewport:!0,focus:!0,gesture:!0,scroll:!0,typeText:!0,touch:!0,elementText:!0,back:!0,orientation:!0,fold:!0,telephony:!0,tvRemote:!0,keyboard:!0,clipboard:!0,systemButton:!0,triggerAppEvent:!0,settings:!0,readAlert:!0,awaitAlert:!0,acceptAlert:!0,dismissAlert:!0,audioProbeCapture:!0,audioProbeQuery:!0,perf:!0,readiness:!0,shutdown:!0};function qe(e){let t={};for(let n of Object.keys(Ke))t[n]=e(n);return t}function V(e,t,n){let r=Ye(n);return Object.freeze({device:{...u(e),providerMode:Je(t)},operations:{appLogInspect:r.appLog,appLogDoctor:r.appLog,appLogStart:r.appLog,appLogReattach:r.appLog,appLogCleanup:r.appLog,listApps:r.apps,deployApp:r.appDeployment,materializeAppSource:r.appDeployment,deployMaterializedApp:r.appDeployment,sendPushNotification:r.appDeployment,uninstallApp:r.appDeployment,appState:r.appState,networkDump:r.network,screenRecordingStart:r.screenRecording,screenRecordingReattach:r.screenRecording,screenRecordingCleanup:r.screenRecording,...f({capture:r.screenshot}),...p({capture:r.snapshot,customActions:r.snapshot,withoutActiveApp:r.snapshot}),...m({findText:r.snapshot,querySelector:r.snapshot}),...h({setViewport:r.viewport}),...me({focus:r.focus}),..._e({unsupported:r.gesture}),..._({scroll:r.scroll}),...v({type:r.typeText}),...L({unsupported:r.touch,tap:r.touch,longPress:r.touch,fill:r.touch}),...y({readTextAtPoint:r.elementText}),...b({back:r.back}),...x({orientation:r.orientation,unlock:r.orientation}),setFoldPose:r.fold,sendTelephonyEvent:r.telephony,...S({tvRemote:r.tvRemote}),...Oe({unsupported:r.keyboard}),...E({unsupported:r.clipboard}),...k({unsupported:r.systemButton}),...j({triggerAppEvent:r.triggerAppEvent}),setSetting:r.settings,readSetting:r.settings,...M({read:r.readAlert,wait:r.awaitAlert,accept:r.acceptAlert,dismiss:r.dismissAlert}),...F({capture:r.audioProbeCapture,query:r.audioProbeQuery}),...I({frames:r.perf,memorySample:r.perf,memorySnapshot:r.perf,nativeCapture:r.perf,profileReport:r.perf}),ensureReady:r.readiness,bootTarget:r.readiness,bootTargetHeadless:r.readiness,shutdownTarget:r.shutdown,...r.lifecycle}})}function Je(e){switch(e.kind){case`local-family`:return`local`;case`provider-runtime`:return`provider-runtime`}}function Ye(e){return Object.freeze({...qe(t=>Object.freeze({...e[t]??e.network})),lifecycle:d(e.lifecycle)})}function Xe(e){return Object.freeze({setSetting:H(e,e.write),readSetting:H(e,e.read??{})})}function H(e,t){if(!e.target.available)return e.target;let n=Object.values(t).filter(e=>e!==void 0);if(!n.some(e=>e.available))return n[0]??e.unsupported;let r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.available?Ze:t]));return Object.freeze({available:!0,subjects:Object.freeze(r),unlisted:e.unsupported})}const Ze=Object.freeze({available:!0});async function Qe(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function $e(e,t){return Object.freeze({setSetting:async n=>await(await Qe(e,t,n)).setSetting(n.setting,n.state,n.appBundleId,n.options)})}function et(e,t){return Object.freeze({readSetting:async n=>{let r=await Qe(e,t,n),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await i(r.readSetting,`settings read`).call(r,n.setting)}})}const tt=[{operation:`back`,label:`back`,bind:Ce},{operation:`home`,label:O.home,bind:(e,t)=>A(`home`,e,t)},{operation:`setOrientation`,label:`orientation`,bind:Te},{operation:`unlockOrientation`,label:`orientation auto`,bind:Ee},{operation:`tvRemote`,label:C,bind:De},{operation:`keyboardStatus`,label:w.keyboardStatus,bind:(e,t)=>T(`keyboardStatus`,e,t)},{operation:`keyboardDismiss`,label:w.keyboardDismiss,bind:(e,t)=>T(`keyboardDismiss`,e,t)},{operation:`keyboardEnter`,label:w.keyboardEnter,bind:(e,t)=>T(`keyboardEnter`,e,t)},{operation:`readClipboard`,label:D.readClipboard,bind:Me},{operation:`writeClipboard`,label:D.writeClipboard,bind:Ne},{operation:`appSwitcher`,label:O.appSwitcher,bind:(e,t)=>A(`appSwitcher`,e,t)},{operation:`actionButton`,label:O.actionButton,bind:(e,t)=>A(`actionButton`,e,t)},{operation:`volumeUp`,label:O.volumeUp,bind:(e,t)=>A(`volumeUp`,e,t)},{operation:`volumeDown`,label:O.volumeDown,bind:(e,t)=>A(`volumeDown`,e,t)},{operation:`power`,label:O.power,bind:(e,t)=>A(`power`,e,t)},{operation:`mute`,label:O.mute,bind:(e,t)=>A(`mute`,e,t)},{operation:`sleep`,label:O.sleep,bind:(e,t)=>A(`sleep`,e,t)},{operation:`wake`,label:O.wake,bind:(e,t)=>A(`wake`,e,t)},{operation:`mediaPlayPause`,label:O.mediaPlayPause,bind:(e,t)=>A(`mediaPlayPause`,e,t)},{operation:`mediaNext`,label:O.mediaNext,bind:(e,t)=>A(`mediaNext`,e,t)},{operation:`mediaPrevious`,label:O.mediaPrevious,bind:(e,t)=>A(`mediaPrevious`,e,t)},{operation:`mediaRewind`,label:O.mediaRewind,bind:(e,t)=>A(`mediaRewind`,e,t)},{operation:`mediaFastForward`,label:O.mediaFastForward,bind:(e,t)=>A(`mediaFastForward`,e,t)},{operation:`triggerAppEvent`,label:`trigger-app-event`,bind:Fe},{operation:`setSetting`,label:`settings`,bind:$e},{operation:`readSetting`,label:`settings read`,bind:et},{operation:`readAlert`,label:N.readAlert,bind:(e,t)=>P(`readAlert`,e,t)},{operation:`awaitAlert`,label:N.awaitAlert,bind:(e,t)=>P(`awaitAlert`,e,t)},{operation:`acceptAlert`,label:N.acceptAlert,bind:(e,t)=>P(`acceptAlert`,e,t)},{operation:`dismissAlert`,label:N.dismissAlert,bind:(e,t)=>P(`dismissAlert`,e,t)}];function nt(e,t){let n={};for(let r of tt)e.facts[r.operation]?.available&&Object.assign(n,r.bind(e.signal,t(r)));return n}function rt(e){return nt(e,t=>a({...e,operation:t.label}))}const U=Object.freeze({available:!0}),it=s(`unsupported-provider-mode`,`Revyl enters text at a point; run fill <field> "text" instead of type.`),at=s(`unsupported-provider-mode`,`Revyl does not expose portable gesture execution.`),ot=s(`unsupported-provider-mode`,`Revyl does not expose keyboard status, dismissal, or a return-key press.`),st=s(`unsupported-provider-mode`,`Revyl does not expose the pasteboard.`),W=s(`unsupported-provider-mode`,`Revyl does not expose orientation control.`),ct=s(`unsupported-provider-mode`,`Revyl has a back button only on Android; on iOS, click the app's own back control.`),lt=s(`unsupported-provider-mode`,`Revyl exposes the home button only.`),ut=s(`unsupported-provider-mode`,`Revyl does not expose settings control.`),G=s(`unsupported-provider-mode`,`Revyl does not deliver a push notification to a session.`),K=s(`unsupported-provider-mode`,`Revyl has no alert surface of its own; a system alert appears in the snapshot tree.`),dt=s(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets; Revyl rents phones and tablets.`),q=s(`owner-capability-missing`,`Revyl requires a matching live provider session for this device.`),ft=s(`unsupported-provider-mode`,`fold runs a HID helper inside a foldable iPhone simulator on the daemon host; a Revyl session has no such simulator.`),pt=s(`unsupported-provider-mode`,`telephony sends calls and SMS to an Android emulator's console through local adb; agent-device does not route it through a Revyl session.`);function mt(e){let t=e??U;return Object.freeze({...me({focus:t}),...v({type:e??it}),...L({unsupported:e??s(`unsupported-provider-mode`,`Revyl taps and fills at a point; it has no action for a hover or for a selector target.`),tap:t,longPress:t,fill:t}),..._e({unsupported:e??at}),..._({scroll:t})})}function ht(e,t){return Object.freeze(t?{...b({back:t}),...x({orientation:t,unlock:t}),...k({unsupported:t}),...S({tvRemote:t})}:{...b({back:e.platform===`android`?U:ct}),...x({orientation:W,unlock:W}),...k({unsupported:lt,home:U}),...S({tvRemote:dt})})}function gt(e){return Object.freeze({...Oe({unsupported:e??ot}),...E({unsupported:e??st}),...Xe({target:e??U,unsupported:e??ut,write:{}}),...j({triggerAppEvent:e??G}),...M({read:e??K,wait:e??K,accept:e??K,dismiss:e??K}),setFoldPose:e??ft,sendTelephonyEvent:e??pt})}function _t(e){let{device:t,signal:n}=e,r=n=>e.getInteractor(t,n);return Object.freeze({...fe({device:t,signal:n,resolveInteractor:r,presentIosAcquisition:e.presentIosAcquisition}),...ce({device:t,signal:n,resolveInteractor:r,captureCapabilities:ie(`Revyl captures through its provider endpoint`)}),...ge({device:t,signal:n,resolveInteractor:r}),...Se({device:t,signal:n,resolveInteractor:r}),...Ge({device:t,signal:n,resolveInteractor:r,facts:mt(),pause:async e=>await te(e,void 0,{signal:n})}),...be({device:t,signal:n,resolveInteractor:r})})}const vt=`--launch-console requires a direct app launch and cannot be used with URL opens`;function yt(e,t,n){return{requestId:e.requestId,signal:n,appBundleId:t,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function bt(e){let{device:t,signal:n,ownership:i}=e;return Object.freeze({device:t,signal:n,resolveInteractor:async(a,o)=>{let s=yt(a,o,n);if(i===`local`)return await e.resolveLocalInteractor(t,s);if(a.launchConsole)throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for a local or Limrun iOS simulator app launch`,{reason:`launch-console-owner-unadmitted`,deviceId:t.id,hint:`Remove --launch-console, or use a local or Limrun iOS simulator for launch output.`});let c=i.resolveInteractor(s);if(c)return c;throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned application lifecycle operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:t.id})}})}function xt(e){return bt({device:e.device,signal:e.signal,ownership:{kind:`provider`,resolveInteractor:e.resolveInteractor}})}async function St(e){let{device:t,positionals:n,execution:r}=e;Ct(n);let i=n[0],a=n[1];if(!i){await wt(e);return}return Tt(t,r),a===void 0?await Dt(e,i):await Et(e,i,a)}function Ct(e){if(e.length>2)throw new r(`INVALID_ARGS`,`open accepts at most two arguments: <app|url> [url]`)}async function wt(e){if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,`--launch-console requires an app target`);if(e.execution.launchArgs&&e.execution.launchArgs.length>0)throw new r(`INVALID_ARGS`,`--launch-args requires an app target`);await e.interactor.openDevice()}function Tt(e,t){if(t.launchConsole&&(!i(e)||e.kind!==`simulator`))throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for iOS simulator app launches`);if(e.platform===`linux`&&t.launchArgs&&t.launchArgs.length>0)throw new r(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on Linux.`)}async function Et(e,t,n){if(l(t))throw new r(`INVALID_ARGS`,`open <app> <url> requires an app target as the first argument`);if(!l(n))throw new r(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,vt);return await e.interactor.open(t,{activity:e.execution.activity,appBundleId:e.appBundleId,launchArgs:e.execution.launchArgs?[...e.execution.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp,url:n})}async function Dt(e,t){let{execution:n,interactor:i}=e;if(n.launchConsole&&l(t))throw new r(`INVALID_ARGS`,vt);if(n.clearAppState){if(l(t))throw new r(`INVALID_ARGS`,`Clearing app state requires an app target, not a deep link.`);await i.setSetting(`clear-app-state`,`clear`,t)}return await i.open(t,{activity:n.activity,appBundleId:e.appBundleId,launchConsole:n.launchConsole,launchArgs:n.launchArgs?[...n.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp})}function Ot(e){let{binding:t}=e,n=async()=>{throw new r(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for ${e.owner}.`)};return Object.freeze({resolveOpenTarget:async t=>jt(e.openTargetIdentity,t),prepareApplicationOpen:async()=>void 0,openApplication:async t=>await kt(e,t),applyRuntimeHints:n,clearRuntimeHints:n,closeApplication:async e=>{await Mt({device:t.device,interactor:await t.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async()=>({}),prepareAppleRunner:n,configureProviderPortReverse:e.configureProviderPortReverse??n})}async function kt(e,t){let{binding:n}=e,r=await n.resolveInteractor(t.execution,t.appBundleId);e.closeBeforeRelaunch&&t.relaunch&&t.target!==void 0&&await Mt({device:n.device,interactor:r,positionals:[t.appBundleId??t.target]}),await St({device:n.device,interactor:r,positionals:t.positionals,appBundleId:t.appBundleId,execution:t.execution});let i=At(t);return i&&await St({device:n.device,interactor:r,positionals:[i],appBundleId:t.appBundleId,execution:{...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),{appBundleId:t.appBundleId,timing:{}}}function At(e){let t=e.runtimeLaunchUrl?.trim(),n=e.positionals.length===1?e.positionals[0]?.trim():void 0;if(!(!t||!n||l(n)))return t}function jt(e,t){let n=t.target;if(e===`app-name`)return Object.freeze(n===void 0?{}:{appName:n});let r=n?.trim(),i=r&&r.includes(`.`)&&!l(r)?r:t.currentAppBundleId;return Object.freeze({...i===void 0?{}:{appBundleId:i},...n===void 0?{}:{appName:n}})}async function Mt(e){let{device:t,interactor:n,positionals:r}=e,i=r[0];if(!i){t.platform===`web`&&await n.close(``);return}await n.close(i)}function Nt(e){let t=xt({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)}),n=Ot({owner:`Revyl`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!1,binding:t});return Object.freeze({...n,openApplication:async e=>(e.relaunch&&e.target!==void 0&&await(await t.resolveInteractor(e.execution,e.appBundleId)).close(``),await n.openApplication(e))})}const J=s(`unsupported-provider-mode`,`Revyl installs an app when the session starts. Pass --provider-app <URL> to connect, and run open afterwards.`),Pt=s(`unsupported-provider-mode`,`Revyl does not uninstall an app from a session.`),Ft=s(`unsupported-provider-mode`,`Revyl does not report which app the device has in the foreground.`),Y=s(`unsupported-provider-mode`,`Revyl does not expose an app log stream.`),It=s(`unsupported-provider-mode`,`Revyl does not report the apps installed on a session.`),Lt=s(`unsupported-provider-mode`,`Revyl does not expose a network capture for a session.`),X=s(`unsupported-provider-mode`,`Revyl streams the screen for its own viewer and does not expose a recording.`),Rt=s(`unsupported-provider-mode`,`Custom snapshot actions are available only on a local iOS runner.`),zt=s(`unsupported-provider-mode`,`Revyl rents a device at the size its model has.`),Z=s(`unsupported-provider-mode`,`Revyl-owned devices read element text from the captured tree only.`),Bt=s(`unsupported-provider-mode`,`Headless boot is unavailable for provider-owned devices.`),Vt=s(`unsupported-provider-mode`,`Apple runner preparation is unavailable for Revyl-owned devices.`),Ht=s(`unsupported-provider-mode`,`Revyl owns the target lifecycle for provider-owned devices.`),Ut=s(`unsupported-provider-mode`,`Runtime hints are not applied to provider-owned devices.`),Wt=s(`unsupported-provider-mode`,`Revyl does not expose port reverse; publish the app server at a public URL instead.`),Gt=s(`unsupported-provider-mode`,`Revyl does not expose the audio probe.`),Q=s(`unsupported-provider-mode`,`Revyl does not expose frame, memory, or profiler counters for a session.`),Kt=s(`unsupported-provider-mode`,`Revyl open requires the app the session was started with.`),qt=s(`unsupported-provider-mode`,`Revyl close requires the app the session was started with.`);function $(t,n){let r=e(t),i=r?n?U:q:Kt,a=r?n?U:q:qt;return d({resolveOpenTarget:i,prepareApplicationOpen:i,openApplication:i,applyRuntimeHints:Ut,clearRuntimeHints:Ut,closeApplication:a,finalizeApplicationClose:a,prepareAppleRunner:Vt,configureProviderPortReverse:Wt})}function Jt(e){return Object.freeze({device:{...u(e),providerMode:`provider-runtime`},operations:{appLogInspect:Y,appLogDoctor:Y,appLogStart:Y,appLogReattach:Y,appLogCleanup:Y,listApps:It,deployApp:J,materializeAppSource:J,deployMaterializedApp:J,sendPushNotification:G,uninstallApp:Pt,appState:Ft,networkDump:Lt,screenRecordingStart:X,screenRecordingReattach:X,screenRecordingCleanup:X,...p({capture:U,customActions:Rt,withoutActiveApp:U}),...f({capture:U}),...m({findText:Z,querySelector:Z}),...h({setViewport:zt}),...mt(),...y({readTextAtPoint:Z}),...ht(e),...gt(),...F({capture:Gt,query:Gt}),...I({frames:Q,memorySample:Q,memorySnapshot:Q,nativeCapture:Q,profileReport:Q}),ensureReady:U,bootTarget:U,bootTargetHeadless:Bt,shutdownTarget:Ht,...$(e,!0)}})}const Yt=Object.freeze({appLog:q,appState:q,appDeployment:q,apps:q,network:q,screenRecording:q,screenshot:q,snapshot:q,viewport:q,focus:q,gesture:q,scroll:q,typeText:q,touch:q,elementText:q,back:q,orientation:q,fold:ft,telephony:pt,tvRemote:q,keyboard:q,clipboard:q,systemButton:q,triggerAppEvent:q,settings:q,readAlert:q,awaitAlert:q,acceptAlert:q,dismissAlert:q,audioProbeCapture:q,audioProbeQuery:q,perf:q,readiness:q,shutdown:q});function Xt(n){let i=ee(t,n.runtimeInstance),a=t=>e(t)&&n.ownsDevice(t),o=e=>a(e)&&n.hasLiveSession(e);return Object.freeze({owner:i,ownsDevice:a,inspectFacts:async e=>o(e)?Jt(e):V(e,i,{...Yt,lifecycle:$(e,!1)}),bind:async t=>{if(t.intent.kind===`exact-owner`&&!c(t.intent.owner,i))throw new r(`UNSUPPORTED_OPERATION`,`Revyl runtime owner identity does not match`);if(!e(t.device))throw new r(`UNSUPPORTED_PLATFORM`,`Revyl requires an iOS simulator or Android emulator device identity`);let a=o(t.device);if(t.intent.kind!==`exact-owner`&&!a)throw new r(`UNSUPPORTED_OPERATION`,`Revyl provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return Zt(n,i,t.device,t.scope.signal,a)},shutdown:async()=>void 0})}function Zt(e,t,n,r,i){let a=i?Jt(n):V(n,t,{...Yt,lifecycle:$(n,!1)}),o={ensureReady:async()=>({...n,booted:!0}),bootTarget:async()=>({...n,booted:!0}),...re(Nt({device:n,signal:r,getInteractor:e.getInteractor}),$(n,i)),..._t({device:n,signal:r,getInteractor:e.getInteractor,presentIosAcquisition:e.host.snapshot.presentIosAcquisition}),...rt({device:n,signal:r,resolveInteractor:t=>e.getInteractor(n,t),facts:a.operations})};return Object.freeze({device:n,owner:t,facts:a,operations:Object.freeze(Qt(a,o)),[Symbol.asyncDispose]:async()=>void 0})}function Qt(e,t){let n={};for(let[r,i]of Object.entries(t))e.operations[r]?.available&&(n[r]=i);return n}export{Xt as createRevylPlatformRuntimeOwner};
1
+ import{i as e,t}from"./device.mjs";import{i as n,t as r}from"./errors.mjs";import{n as i}from"./device2.mjs";import{n as a,r as o}from"./interactor-operation-binding.mjs";import{a as s,i as c,r as l,t as u}from"./open-target.mjs";import{setTimeout as ee}from"node:timers/promises";function d(e){return Object.freeze({family:e.platform,...e.appleOs===void 0?{}:{appleOs:e.appleOs},kind:e.kind,...e.target===void 0?{}:{target:e.target},...e.iosPhysicalDeviceBackend===void 0?{}:{iosPhysicalDeviceBackend:e.iosPhysicalDeviceBackend}})}const te=[`resolveOpenTarget`,`prepareApplicationOpen`,`openApplication`,`applyRuntimeHints`,`clearRuntimeHints`,`closeApplication`,`finalizeApplicationClose`,`prepareAppleRunner`,`configureProviderPortReverse`];function f(e){return Object.freeze({resolveOpenTarget:e.resolveOpenTarget,prepareApplicationOpen:e.prepareApplicationOpen,openApplication:e.openApplication,applyRuntimeHints:e.applyRuntimeHints,clearRuntimeHints:e.clearRuntimeHints,closeApplication:e.closeApplication,finalizeApplicationClose:e.finalizeApplicationClose,prepareAppleRunner:e.prepareAppleRunner,configureProviderPortReverse:e.configureProviderPortReverse})}function ne(e,t){return Object.freeze(Object.fromEntries(te.flatMap(n=>t[n].available?[[n,e[n]]]:[])))}function re(e){return()=>({captureBackendRefusal:e})}async function ie(e,t={}){let n=e?.captureBackend;if(n!==void 0&&!t.captureBackends?.includes(n))throw new r(`UNSUPPORTED_OPERATION`,`--capture-backend ${n} is not supported: ${t.captureBackendRefusal??`this capture owner declares no such backend`}`,{reason:`screenshot-capture-backend-unsupported`});if(e?.screenMask===void 0)return;let{readScreenshotScreenMask:i}=await import(`./screenshot.mjs`).then(e=>e.n);if(i(e?.screenMask)!==void 0&&t.screenMask!==!0)throw new r(`UNSUPPORTED_OPERATION`,`--screen-mask requires a handheld iOS simulator simctl capture`,{reason:`screenshot-screen-mask-unsupported`})}function p(e){return Object.freeze({captureScreenshot:e.capture})}function ae(e,t){let{captureBackend:n,preferredCaptureBackend:r,...i}=e??{};return n?{...i,captureBackend:n}:r&&t.captureCapabilities(i).captureBackends?.includes(r)?{...i,captureBackend:r}:i}function oe(e,t){return Object.freeze({captureScreenshot:async n=>{let r=ae(n.options,e);return await ie(r,e.captureCapabilities(r)),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e.signal})).screenshot(n.outPath,r)??{}}})}function se(e){return oe(e,a({...e,operation:`screenshot`}))}function ce(e,t){return t.signal===void 0?e:AbortSignal.any([e,t.signal])}function le(e){return Object.freeze({captureSnapshot:e.capture,captureSnapshotWithCustomActions:e.customActions,captureSnapshotWithoutActiveApp:e.withoutActiveApp})}function ue(e){let t=async t=>{await de(e,t);let n=ce(e.signal,t),i={...t.execution,appBundleId:t.options?.appBundleId,signal:n},a=e.ownership===`local`?await e.resolveInteractor(e.device,i):e.resolveInteractor(i);if(!a)throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned snapshot operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:e.device.id});let o=await a.snapshot({...t.options,signal:n});if(!pe(o))return o;if(!e.presentIosAcquisition)throw new r(`COMMAND_FAILED`,`Acquired iOS snapshot has no host presentation owner.`,{reason:`ios-snapshot-presenter-missing`,deviceId:e.device.id});return await e.presentIosAcquisition(o,t.options)};return Object.freeze({captureSnapshot:t,captureSnapshotWithCustomActions:t,captureSnapshotWithoutActiveApp:t})}async function de(e,t){if(t.options?.observeOnly!==!0)return;let{isHandheldAppleDevice:n}=await import(`./device2.mjs`).then(e=>e.t);if(!(e.ownership===`local`&&n(e.device)))throw new r(`UNSUPPORTED_OPERATION`,`observe-only snapshot requires a local iOS or iPadOS runner.`)}function fe(e){return ue({...e,ownership:`provider`})}function pe(e){return`stage`in e&&e.stage===`acquired`}function me(e){return Object.freeze({findText:e.findText,querySelector:e.querySelector})}function he(e){return Object.freeze({setViewport:e.setViewport})}function ge(e){return Object.freeze({focusPoint:e.focus})}function _e(e,t){return Object.freeze({focusPoint:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).focus(n.point.x,n.point.y)}})}function ve(e){return _e(e.signal,a({...e,operation:`focus`}))}function m(e){let t=t=>t??e.unsupported;return Object.freeze({performGesturePlan:t(e.plan),performDirectionalFlingPlan:t(e.directionalFling),performMultiTouchGesturePlan:t(e.multiTouch),performTargetAuthoredDrag:t(e.targetAuthoredDrag),gestureViewport:t(e.viewport)})}function ye(e){let t=e??{},n=h(t.pixels),r=h(t.x1),i=h(t.y1),a=h(t.x2),o=h(t.y2),s=r===void 0||i===void 0||a===void 0||o===void 0?void 0:{x:r/2+a/2,y:i/2+o/2};return{report:t,...n===void 0?{}:{pixels:n},...s===void 0?{}:{midpoint:s}}}function h(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function g(e){return Object.freeze({scrollDirection:e.scroll})}function be(e,t){return Object.freeze({scrollDirection:async n=>(e.throwIfAborted(),ye(await(await t({...n.execution,appBundleId:n.target?.appBundleId,signal:e})).scroll(n.direction,n.options)))})}function xe(e){return be(e.signal,a({...e,operation:`scroll`}))}function _(e){return Object.freeze({typeText:e.type})}function Se(e,t){return Object.freeze({typeText:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).type(n.text,n.delayMs))})}function Ce(e){return Se(e.signal,a({...e,operation:`type`}))}function v(e){return Object.freeze({readTextAtPoint:e.readTextAtPoint})}function y(e){return Object.freeze({back:e.back})}function we(e,t){return Object.freeze({back:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).back(n.mode)}})}const Te=Object.freeze({available:!1,reason:`unsupported-platform-leaf`,hint:`orientation auto is only supported on ADB-backed Android.`});function b(e){return Object.freeze({setOrientation:e.orientation,unlockOrientation:e.unlock??Te})}function Ee(e,t){return Object.freeze({setOrientation:async n=>(e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).setOrientation(n.rotation))})}function De(e,t){return Object.freeze({unlockOrientation:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.unlockOrientation,`orientation auto`).call(r)}})}function x(e){let{tvRemote:t,buttonSupport:n}=e;return Object.freeze({tvRemote:t.available&&n?Object.freeze({available:!0,subjects:Object.freeze(Object.fromEntries(n.supported.map(e=>[e,{available:!0}]))),unlisted:n.unsupported}):t})}const S=`tv-remote`;function Oe(e,t){return Object.freeze({tvRemote:async n=>{e.throwIfAborted();let r=await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e}),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);await i(r.tvRemote,S).call(r,n.button,n.durationMs)}})}function C(e){let t=t=>t??e.unsupported;return Object.freeze({keyboardStatus:t(e.status),keyboardDismiss:t(e.dismiss),keyboardEnter:t(e.enter)})}async function ke(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}const w={keyboardStatus:`keyboard status`,keyboardDismiss:`keyboard dismiss`,keyboardEnter:`keyboard enter`};function T(e,t,n){let r=async r=>{let i=await ke(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],w[e]).call(i)};return Object.freeze({[e]:r})}function E(e){let t=t=>t??e.unsupported;return Object.freeze({readClipboard:t(e.read),writeClipboard:t(e.write)})}const D={readClipboard:`clipboard read`,writeClipboard:`clipboard write`};async function O(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})}async function k(e,t){let{requireInteractorMethod:n}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return n(e[t],D[t])}function Ae(e,t){return Object.freeze({readClipboard:async n=>{let r=await O(e,t,n);return await(await k(r,`readClipboard`)).call(r)}})}function je(e,t){return Object.freeze({writeClipboard:async n=>{let r=await O(e,t,n);await(await k(r,`writeClipboard`)).call(r,n.text)}})}const A=[`home`,`appSwitcher`,`actionButton`,`volumeUp`,`volumeDown`,`power`,`mute`,`sleep`,`wake`,`mediaPlayPause`,`mediaNext`,`mediaPrevious`,`mediaRewind`,`mediaFastForward`],j={home:`home`,appSwitcher:`app-switcher`,actionButton:`action-button`,volumeUp:`volume-up`,volumeDown:`volume-down`,power:`power`,mute:`mute`,sleep:`sleep`,wake:`wake`,mediaPlayPause:`media-play-pause`,mediaNext:`media-next`,mediaPrevious:`media-previous`,mediaRewind:`media-rewind`,mediaFastForward:`media-fast-forward`};function M(e){let t={};for(let n of A)t[n]=e[n]??e.unsupported;return Object.freeze(t)}Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is not supported on Android TV targets; use tv-remote.`}),Object.freeze({available:!1,reason:`unsupported-device-kind`,hint:`hardware-button is supported on Android emulators and physical devices.`}),Object.freeze({available:!0}),A.filter(e=>e!==`home`&&e!==`appSwitcher`&&e!==`actionButton`);function N(e,t,n){let r=async r=>{t.throwIfAborted();let i=await n({...r.execution,appBundleId:r.options?.appBundleId,signal:t});await o(i[e],j[e]).call(i)};return Object.freeze({[e]:r})}function P(e){return Object.freeze({triggerAppEvent:e.triggerAppEvent})}function Me(e,t){return Object.freeze({triggerAppEvent:async n=>{e.throwIfAborted(),await(await t({...n.execution,appBundleId:n.options?.appBundleId,signal:e})).open(n.eventUrl,{appBundleId:n.options?.appBundleId})}})}function F(e){return Object.freeze({readAlert:e.read,awaitAlert:e.wait,acceptAlert:e.accept,dismissAlert:e.dismiss})}async function Ne(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Pe(e,t){return{...e.timeoutMs===void 0?{}:{timeoutMs:e.timeoutMs},...e.appBundleId===void 0?{}:{appBundleId:e.appBundleId},...e.surface===void 0?{}:{surface:e.surface},...t?{signal:t}:{}}}const I={readAlert:`alert get`,awaitAlert:`alert wait`,acceptAlert:`alert accept`,dismissAlert:`alert dismiss`};function L(e,t,n){return Object.freeze({[e]:async r=>{let i=await Ne(t,n,r),{requireInteractorMethod:a}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await a(i[e],I[e]).call(i,Pe(r,t))}})}function Fe(e){return Object.freeze({audioProbeStart:e.capture,audioProbeReattach:e.capture,audioProbeCleanup:e.capture,audioProbeQuery:e.query})}function R(e){return Object.freeze({perfFrames:e.frames,perfMemorySample:e.memorySample,perfMemorySnapshot:e.memorySnapshot,perfNativeCaptureStart:e.nativeCapture,perfNativeCaptureReattach:e.nativeCapture,perfNativeCaptureCleanup:e.nativeCapture,perfProfileReport:e.profileReport})}function z(e){let t=t=>t??e.unsupported;return Object.freeze({tapPoint:e.tap,tapRef:t(e.tapRef),longPressPoint:e.longPress,hoverPoint:B(t(e.hover)),hoverRef:B(t(e.hoverRef)),fillPoint:e.fill,fillRef:t(e.fillRef),tapElementSelector:t(e.tapElementSelector)})}function B(e){return e.available?e:Object.freeze({...e,hint:e.hint??`hover raises pointer hover state and is available on web targets only. On touch platforms use longpress for hold gestures.`})}function Ie(e,t){return{...e.execution,appBundleId:e.appBundleId,signal:t}}function Le(e,t,n,r){let i=async n=>(e.throwIfAborted(),await t(Ie(n,e))),a=async t=>{e.throwIfAborted(),Re(t.options,n.longPressPoint);let a=await i(t);return t.options.button!==`primary`&&a.alternateClick?await a.alternateClick(t.point,t.options.button):a.pressPoint?await a.pressPoint(t.point,t.options):await Be(a,t.point,t.options,r)},s=async e=>{let t=await i(e);return await o(t.hover,`hoverPoint`).call(t,e.point.x,e.point.y)},c=async e=>await(await i(e)).fill(e.point.x,e.point.y,e.text,e.delayMs,{allowNonHittableCoordinateFallback:e.allowNonHittableCoordinateFallback});return Object.freeze({...n.tapPoint.available?{tapPoint:a}:{},...n.tapRef.available?{tapRef:async e=>{let t=await i(e);return await o(t.tapRef,`tapRef`).call(t,e.ref)}}:{},...n.longPressPoint.available?{longPressPoint:async e=>await(await i(e)).longPress(e.point.x,e.point.y,e.durationMs)}:{},...n.hoverPoint.available?{hoverPoint:s}:{},...n.hoverRef.available?{hoverRef:async e=>{let t=await i(e);return await o(t.hoverRef,`hoverRef`).call(t,e.ref)}}:{},...n.fillPoint.available?{fillPoint:c}:{},...n.fillRef.available?{fillRef:async e=>{let t=await i(e);return await o(t.fillRef,`fillRef`).call(t,e.ref,e.text,e.delayMs)}}:{},...n.tapElementSelector.available?{tapElementSelector:async e=>{let t=await i(e);return await o(t.tapElementSelector,`tapElementSelector`).call(t,e.selector)}}:{}})}function Re(e,t){if(!(e.holdMs<=0||t.available))throw new r(`UNSUPPORTED_OPERATION`,`press-and-hold is not supported by this runtime.`,{reason:t.reason,...t.hint===void 0?{}:{hint:t.hint}})}function ze(e){if(e.doubleTap)return e.doubleTap;throw new r(`UNSUPPORTED_OPERATION`,`double-tap is not supported by this runtime.`,{reason:`owner-capability-missing`,hint:`This runtime drives single presses; use --count to repeat them.`})}async function Be(e,t,i,a){if(i.button!==`primary`)throw new r(`UNSUPPORTED_OPERATION`,`Bound runtime does not implement ${i.button} click.`);let o=i.doubleTap?ze(e):void 0,s,c=0;try{for(let n=0;n<i.count;n+=1){let[r,l]=He(n,i.jitterPx),u=await Ve(e,o,t.x+r,t.y+l,i);c+=1,s??=u,n<i.count-1&&i.intervalMs>0&&await a(i.intervalMs)}}catch(e){throw n(e,c)}return s}async function Ve(e,t,n,r,i){return t?await t.call(e,n,r):i.holdMs>0?await e.longPress(n,r,i.holdMs):await e.tap(n,r)}const V=[[0,0],[1,0],[0,1],[-1,0],[0,-1],[1,1],[-1,1],[1,-1],[-1,-1]];function He(e,t){if(t<=0)return[0,0];let[n,r]=V[e%V.length];return[n*t,r*t]}function Ue(e){return Le(e.signal,a({...e,operation:`touch`}),e.facts,e.pause)}const We={appLog:!0,apps:!0,appDeployment:!0,appState:!0,network:!0,screenRecording:!0,screenshot:!0,snapshot:!0,viewport:!0,focus:!0,gesture:!0,scroll:!0,typeText:!0,touch:!0,elementText:!0,back:!0,orientation:!0,fold:!0,telephony:!0,tvRemote:!0,keyboard:!0,clipboard:!0,systemButton:!0,triggerAppEvent:!0,settings:!0,readAlert:!0,awaitAlert:!0,acceptAlert:!0,dismissAlert:!0,audioProbeCapture:!0,audioProbeQuery:!0,perf:!0,readiness:!0,shutdown:!0};function Ge(e){let t={};for(let n of Object.keys(We))t[n]=e(n);return t}function H(e,t,n){let r=qe(n);return Object.freeze({device:{...d(e),providerMode:Ke(t)},operations:{appLogInspect:r.appLog,appLogDoctor:r.appLog,appLogStart:r.appLog,appLogReattach:r.appLog,appLogCleanup:r.appLog,listApps:r.apps,deployApp:r.appDeployment,materializeAppSource:r.appDeployment,deployMaterializedApp:r.appDeployment,sendPushNotification:r.appDeployment,uninstallApp:r.appDeployment,appState:r.appState,networkDump:r.network,screenRecordingStart:r.screenRecording,screenRecordingReattach:r.screenRecording,screenRecordingCleanup:r.screenRecording,...p({capture:r.screenshot}),...le({capture:r.snapshot,customActions:r.snapshot,withoutActiveApp:r.snapshot}),...me({findText:r.snapshot,querySelector:r.snapshot}),...he({setViewport:r.viewport}),...ge({focus:r.focus}),...m({unsupported:r.gesture}),...g({scroll:r.scroll}),..._({type:r.typeText}),...z({unsupported:r.touch,tap:r.touch,longPress:r.touch,fill:r.touch}),...v({readTextAtPoint:r.elementText}),...y({back:r.back}),...b({orientation:r.orientation,unlock:r.orientation}),setFoldPose:r.fold,sendTelephonyEvent:r.telephony,...x({tvRemote:r.tvRemote}),...C({unsupported:r.keyboard}),...E({unsupported:r.clipboard}),...M({unsupported:r.systemButton}),...P({triggerAppEvent:r.triggerAppEvent}),setSetting:r.settings,readSetting:r.settings,...F({read:r.readAlert,wait:r.awaitAlert,accept:r.acceptAlert,dismiss:r.dismissAlert}),...Fe({capture:r.audioProbeCapture,query:r.audioProbeQuery}),...R({frames:r.perf,memorySample:r.perf,memorySnapshot:r.perf,nativeCapture:r.perf,profileReport:r.perf}),ensureReady:r.readiness,bootTarget:r.readiness,bootTargetHeadless:r.readiness,shutdownTarget:r.shutdown,...r.lifecycle}})}function Ke(e){switch(e.kind){case`local-family`:return`local`;case`provider-runtime`:return`provider-runtime`}}function qe(e){return Object.freeze({...Ge(t=>Object.freeze({...e[t]??e.network})),lifecycle:f(e.lifecycle)})}function Je(e){return Object.freeze({setSetting:U(e,e.write),readSetting:U(e,e.read??{})})}function U(e,t){if(!e.target.available)return e.target;let n=Object.values(t).filter(e=>e!==void 0);if(!n.some(e=>e.available))return n[0]??e.unsupported;let r=Object.fromEntries(Object.entries(t).map(([e,t])=>[e,t.available?Ye:t]));return Object.freeze({available:!0,subjects:Object.freeze(r),unlisted:e.unsupported})}const Ye=Object.freeze({available:!0});async function Xe(e,t,n){return e.throwIfAborted(),await t({...n.execution,appBundleId:n.appBundleId,signal:e})}function Ze(e,t){return Object.freeze({setSetting:async n=>await(await Xe(e,t,n)).setSetting(n.setting,n.state,n.appBundleId,n.options)})}function Qe(e,t){return Object.freeze({readSetting:async n=>{let r=await Xe(e,t,n),{requireInteractorMethod:i}=await import(`./interactor-operation-binding.mjs`).then(e=>e.t);return await i(r.readSetting,`settings read`).call(r,n.setting)}})}const $e=[{operation:`back`,label:`back`,bind:we},{operation:`home`,label:j.home,bind:(e,t)=>N(`home`,e,t)},{operation:`setOrientation`,label:`orientation`,bind:Ee},{operation:`unlockOrientation`,label:`orientation auto`,bind:De},{operation:`tvRemote`,label:S,bind:Oe},{operation:`keyboardStatus`,label:w.keyboardStatus,bind:(e,t)=>T(`keyboardStatus`,e,t)},{operation:`keyboardDismiss`,label:w.keyboardDismiss,bind:(e,t)=>T(`keyboardDismiss`,e,t)},{operation:`keyboardEnter`,label:w.keyboardEnter,bind:(e,t)=>T(`keyboardEnter`,e,t)},{operation:`readClipboard`,label:D.readClipboard,bind:Ae},{operation:`writeClipboard`,label:D.writeClipboard,bind:je},{operation:`appSwitcher`,label:j.appSwitcher,bind:(e,t)=>N(`appSwitcher`,e,t)},{operation:`actionButton`,label:j.actionButton,bind:(e,t)=>N(`actionButton`,e,t)},{operation:`volumeUp`,label:j.volumeUp,bind:(e,t)=>N(`volumeUp`,e,t)},{operation:`volumeDown`,label:j.volumeDown,bind:(e,t)=>N(`volumeDown`,e,t)},{operation:`power`,label:j.power,bind:(e,t)=>N(`power`,e,t)},{operation:`mute`,label:j.mute,bind:(e,t)=>N(`mute`,e,t)},{operation:`sleep`,label:j.sleep,bind:(e,t)=>N(`sleep`,e,t)},{operation:`wake`,label:j.wake,bind:(e,t)=>N(`wake`,e,t)},{operation:`mediaPlayPause`,label:j.mediaPlayPause,bind:(e,t)=>N(`mediaPlayPause`,e,t)},{operation:`mediaNext`,label:j.mediaNext,bind:(e,t)=>N(`mediaNext`,e,t)},{operation:`mediaPrevious`,label:j.mediaPrevious,bind:(e,t)=>N(`mediaPrevious`,e,t)},{operation:`mediaRewind`,label:j.mediaRewind,bind:(e,t)=>N(`mediaRewind`,e,t)},{operation:`mediaFastForward`,label:j.mediaFastForward,bind:(e,t)=>N(`mediaFastForward`,e,t)},{operation:`triggerAppEvent`,label:`trigger-app-event`,bind:Me},{operation:`setSetting`,label:`settings`,bind:Ze},{operation:`readSetting`,label:`settings read`,bind:Qe},{operation:`readAlert`,label:I.readAlert,bind:(e,t)=>L(`readAlert`,e,t)},{operation:`awaitAlert`,label:I.awaitAlert,bind:(e,t)=>L(`awaitAlert`,e,t)},{operation:`acceptAlert`,label:I.acceptAlert,bind:(e,t)=>L(`acceptAlert`,e,t)},{operation:`dismissAlert`,label:I.dismissAlert,bind:(e,t)=>L(`dismissAlert`,e,t)}];function et(e,t){let n={};for(let r of $e)e.facts[r.operation]?.available&&Object.assign(n,r.bind(e.signal,t(r)));return n}function tt(e){return et(e,t=>a({...e,operation:t.label}))}const W=Object.freeze({available:!0}),nt=s(`unsupported-provider-mode`,`Revyl enters text at a point; run fill <field> "text" instead of type.`),rt=s(`unsupported-provider-mode`,`Revyl does not expose portable gesture execution.`),it=s(`unsupported-provider-mode`,`Revyl does not expose keyboard status, dismissal, or a return-key press.`),at=s(`unsupported-provider-mode`,`Revyl does not expose the pasteboard.`),ot=s(`unsupported-provider-mode`,`Revyl does not expose orientation control.`),st=s(`unsupported-provider-mode`,`Revyl has a back button only on Android; on iOS, click the app's own back control.`),ct=s(`unsupported-provider-mode`,`Revyl exposes the home button only.`),lt=s(`unsupported-provider-mode`,`Revyl does not expose settings control.`),ut=s(`unsupported-provider-mode`,`Revyl does not deliver a push notification to a session.`),G=s(`unsupported-provider-mode`,`Revyl has no alert surface of its own; a system alert appears in the snapshot tree.`),dt=s(`unsupported-device-kind`,`tv-remote is supported only on Android TV targets; Revyl rents phones and tablets.`),K=s(`owner-capability-missing`,`Revyl requires a matching live provider session for this device.`),ft=s(`unsupported-provider-mode`,`fold runs a HID helper inside a foldable iPhone simulator on the daemon host; a Revyl session has no such simulator.`),pt=s(`unsupported-provider-mode`,`telephony sends calls and SMS to an Android emulator's console through local adb; agent-device does not route it through a Revyl session.`);function mt(e){let t=e??W;return Object.freeze({...ge({focus:t}),..._({type:e??nt}),...z({unsupported:e??s(`unsupported-provider-mode`,`Revyl taps and fills at a point; it has no action for a hover or for a selector target.`),tap:t,longPress:t,fill:t}),...m({unsupported:e??rt}),...g({scroll:t})})}function ht(e,t){return Object.freeze(t?{...y({back:t}),...b({orientation:t,unlock:t}),...M({unsupported:t}),...x({tvRemote:t})}:{...y({back:e.platform===`android`?W:st}),...b({orientation:ot,unlock:ot}),...M({unsupported:ct,home:W}),...x({tvRemote:dt})})}function gt(e){return Object.freeze({...C({unsupported:e??it}),...E({unsupported:e??at}),...Je({target:e??W,unsupported:e??lt,write:{}}),...P({triggerAppEvent:e??ut}),...F({read:e??G,wait:e??G,accept:e??G,dismiss:e??G}),setFoldPose:e??ft,sendTelephonyEvent:e??pt})}function _t(e){let{device:t,signal:n}=e,r=n=>e.getInteractor(t,n);return Object.freeze({...fe({device:t,signal:n,resolveInteractor:r,presentIosAcquisition:e.presentIosAcquisition}),...se({device:t,signal:n,resolveInteractor:r,captureCapabilities:re(`Revyl captures through its provider endpoint`)}),...ve({device:t,signal:n,resolveInteractor:r}),...Ce({device:t,signal:n,resolveInteractor:r}),...Ue({device:t,signal:n,resolveInteractor:r,facts:mt(),pause:async e=>await ee(e,void 0,{signal:n})}),...xe({device:t,signal:n,resolveInteractor:r})})}const vt=`--launch-console requires a direct app launch and cannot be used with URL opens`;function yt(e,t,n){return{requestId:e.requestId,signal:n,appBundleId:t,verbose:e.verbose,logPath:e.logPath,traceLogPath:e.traceLogPath,iosXctestrunFile:e.iosXctestrunFile,iosXctestDerivedDataPath:e.iosXctestDerivedDataPath,iosXctestEnvDir:e.iosXctestEnvDir,runnerLeaseContext:e.runnerLeaseContext}}function bt(e){let{device:t,signal:n,ownership:i}=e;return Object.freeze({device:t,signal:n,resolveInteractor:async(a,o)=>{let s=yt(a,o,n);if(i===`local`)return await e.resolveLocalInteractor(t,s);if(a.launchConsole)throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for a local or Limrun iOS simulator app launch`,{reason:`launch-console-owner-unadmitted`,deviceId:t.id,hint:`Remove --launch-console, or use a local or Limrun iOS simulator for launch output.`});let c=i.resolveInteractor(s);if(c)return c;throw new r(`UNSUPPORTED_OPERATION`,`Provider-owned application lifecycle operation has no bound provider interactor.`,{reason:`provider-runtime-interactor-missing`,deviceId:t.id})}})}function xt(e){return bt({device:e.device,signal:e.signal,ownership:{kind:`provider`,resolveInteractor:e.resolveInteractor}})}async function St(e){let{device:t,positionals:n,execution:r}=e;Ct(n);let i=n[0],a=n[1];if(!i){await wt(e);return}return Tt(t,r),a===void 0?await Dt(e,i):await Et(e,i,a)}function Ct(e){if(e.length>2)throw new r(`INVALID_ARGS`,`open accepts at most two arguments: <app|url> [url]`)}async function wt(e){if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,`--launch-console requires an app target`);if(e.execution.launchArgs&&e.execution.launchArgs.length>0)throw new r(`INVALID_ARGS`,`--launch-args requires an app target`);await e.interactor.openDevice()}function Tt(e,t){if(t.launchConsole&&(!i(e)||e.kind!==`simulator`))throw new r(`UNSUPPORTED_OPERATION`,`--launch-console is supported only for iOS simulator app launches`);if(e.platform===`linux`&&t.launchArgs&&t.launchArgs.length>0)throw new r(`UNSUPPORTED_OPERATION`,`--launch-args is not supported on Linux.`)}async function Et(e,t,n){if(u(t))throw new r(`INVALID_ARGS`,`open <app> <url> requires an app target as the first argument`);if(!u(n))throw new r(`INVALID_ARGS`,`open <app> <url> requires a valid URL target`);if(e.execution.launchConsole)throw new r(`INVALID_ARGS`,vt);return await e.interactor.open(t,{activity:e.execution.activity,appBundleId:e.appBundleId,launchArgs:e.execution.launchArgs?[...e.execution.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp,url:n})}async function Dt(e,t){let{execution:n,interactor:i}=e;if(n.launchConsole&&u(t))throw new r(`INVALID_ARGS`,vt);if(n.clearAppState){if(u(t))throw new r(`INVALID_ARGS`,`Clearing app state requires an app target, not a deep link.`);await i.setSetting(`clear-app-state`,`clear`,t)}return await i.open(t,{activity:n.activity,appBundleId:e.appBundleId,launchConsole:n.launchConsole,launchArgs:n.launchArgs?[...n.launchArgs]:void 0,terminateRunningApp:e.terminateRunningApp})}function Ot(e){let{binding:t}=e,n=async()=>{throw new r(`UNSUPPORTED_OPERATION`,`This lifecycle operation is unavailable for ${e.owner}.`)};return Object.freeze({resolveOpenTarget:async t=>jt(e.openTargetIdentity,t),prepareApplicationOpen:async()=>void 0,openApplication:async t=>await kt(e,t),applyRuntimeHints:n,clearRuntimeHints:n,closeApplication:async e=>{await Mt({device:t.device,interactor:await t.resolveInteractor(e.execution,e.appBundleId),positionals:e.positionals})},finalizeApplicationClose:async()=>({}),prepareAppleRunner:n,configureProviderPortReverse:e.configureProviderPortReverse??n})}async function kt(e,t){let{binding:n}=e,r=await n.resolveInteractor(t.execution,t.appBundleId);e.closeBeforeRelaunch&&t.relaunch&&t.target!==void 0&&await Mt({device:n.device,interactor:r,positionals:[t.appBundleId??t.target]}),await St({device:n.device,interactor:r,positionals:t.positionals,appBundleId:t.appBundleId,execution:t.execution,...e.closeBeforeRelaunch?{}:{terminateRunningApp:t.relaunch}});let i=At(t);return i&&await St({device:n.device,interactor:r,positionals:[i],appBundleId:t.appBundleId,execution:{...t.execution,clearAppState:void 0,launchConsole:void 0,launchArgs:void 0}}),{appBundleId:t.appBundleId,timing:{}}}function At(e){let t=e.runtimeLaunchUrl?.trim(),n=e.positionals.length===1?e.positionals[0]?.trim():void 0;if(!(!t||!n||u(n)))return t}function jt(e,t){let n=t.target;if(e===`app-name`)return Object.freeze(n===void 0?{}:{appName:n});let r=n?.trim(),i=r&&r.includes(`.`)&&!u(r)?r:t.currentAppBundleId;return Object.freeze({...i===void 0?{}:{appBundleId:i},...n===void 0?{}:{appName:n}})}async function Mt(e){let{device:t,interactor:n,positionals:r}=e,i=r[0];if(!i){t.platform===`web`&&await n.close(``);return}await n.close(i)}function Nt(e){let t=xt({device:e.device,signal:e.signal,resolveInteractor:t=>e.getInteractor(e.device,t)}),n=Ot({owner:`Revyl`,openTargetIdentity:`bundle-id`,closeBeforeRelaunch:!1,binding:t});return Object.freeze({...n,openApplication:async e=>(e.relaunch&&e.target!==void 0&&await(await t.resolveInteractor(e.execution,e.appBundleId)).close(``),await n.openApplication(e))})}const q=s(`unsupported-provider-mode`,`Revyl installs an app when the session starts. Pass --provider-app <URL> to connect, and run open afterwards.`),Pt=s(`unsupported-provider-mode`,`Revyl does not uninstall an app from a session.`),Ft=s(`unsupported-provider-mode`,`Revyl does not report which app the device has in the foreground.`),J=s(`unsupported-provider-mode`,`Revyl does not expose an app log stream.`),It=s(`unsupported-provider-mode`,`Revyl does not report the apps installed on a session.`),Lt=s(`unsupported-provider-mode`,`Revyl does not expose a network capture for a session.`),Y=s(`unsupported-provider-mode`,`Revyl streams the screen for its own viewer and does not expose a recording.`),Rt=s(`unsupported-provider-mode`,`Custom snapshot actions are available only on a local iOS runner.`),zt=s(`unsupported-provider-mode`,`Revyl rents a device at the size its model has.`),X=s(`unsupported-provider-mode`,`Revyl-owned devices read element text from the captured tree only.`),Bt=s(`unsupported-provider-mode`,`Headless boot is unavailable for provider-owned devices.`),Vt=s(`unsupported-provider-mode`,`Apple runner preparation is unavailable for Revyl-owned devices.`),Ht=s(`unsupported-provider-mode`,`Revyl owns the target lifecycle for provider-owned devices.`),Z=s(`unsupported-provider-mode`,`Runtime hints are not applied to provider-owned devices.`),Ut=s(`unsupported-provider-mode`,`Revyl does not expose port reverse; publish the app server at a public URL instead.`),Wt=s(`unsupported-provider-mode`,`Revyl does not expose the audio probe.`),Q=s(`unsupported-provider-mode`,`Revyl does not expose frame, memory, or profiler counters for a session.`),Gt=s(`unsupported-provider-mode`,`Revyl open requires the app the session was started with.`),Kt=s(`unsupported-provider-mode`,`Revyl close requires the app the session was started with.`);function $(t,n){let r=e(t),i=r?n?W:K:Gt,a=r?n?W:K:Kt;return f({resolveOpenTarget:i,prepareApplicationOpen:i,openApplication:i,applyRuntimeHints:Z,clearRuntimeHints:Z,closeApplication:a,finalizeApplicationClose:a,prepareAppleRunner:Vt,configureProviderPortReverse:Ut})}function qt(e){return Object.freeze({device:{...d(e),providerMode:`provider-runtime`},operations:{appLogInspect:J,appLogDoctor:J,appLogStart:J,appLogReattach:J,appLogCleanup:J,listApps:It,deployApp:q,materializeAppSource:q,deployMaterializedApp:q,sendPushNotification:ut,uninstallApp:Pt,appState:Ft,networkDump:Lt,screenRecordingStart:Y,screenRecordingReattach:Y,screenRecordingCleanup:Y,...le({capture:W,customActions:Rt,withoutActiveApp:W}),...p({capture:W}),...me({findText:X,querySelector:X}),...he({setViewport:zt}),...mt(),...v({readTextAtPoint:X}),...ht(e),...gt(),...Fe({capture:Wt,query:Wt}),...R({frames:Q,memorySample:Q,memorySnapshot:Q,nativeCapture:Q,profileReport:Q}),ensureReady:W,bootTarget:W,bootTargetHeadless:Bt,shutdownTarget:Ht,...$(e,!0)}})}const Jt=Object.freeze({appLog:K,appState:K,appDeployment:K,apps:K,network:K,screenRecording:K,screenshot:K,snapshot:K,viewport:K,focus:K,gesture:K,scroll:K,typeText:K,touch:K,elementText:K,back:K,orientation:K,fold:ft,telephony:pt,tvRemote:K,keyboard:K,clipboard:K,systemButton:K,triggerAppEvent:K,settings:K,readAlert:K,awaitAlert:K,acceptAlert:K,dismissAlert:K,audioProbeCapture:K,audioProbeQuery:K,perf:K,readiness:K,shutdown:K});function Yt(n){let i=l(t,n.runtimeInstance),a=t=>e(t)&&n.ownsDevice(t),o=e=>a(e)&&n.hasLiveSession(e);return Object.freeze({owner:i,ownsDevice:a,inspectFacts:async e=>o(e)?qt(e):H(e,i,{...Jt,lifecycle:$(e,!1)}),bind:async t=>{if(t.intent.kind===`exact-owner`&&!c(t.intent.owner,i))throw new r(`UNSUPPORTED_OPERATION`,`Revyl runtime owner identity does not match`);if(!e(t.device))throw new r(`UNSUPPORTED_PLATFORM`,`Revyl requires an iOS simulator or Android emulator device identity`);let a=o(t.device);if(t.intent.kind!==`exact-owner`&&!a)throw new r(`UNSUPPORTED_OPERATION`,`Revyl provider session is no longer live for the selected device`,{reason:`provider-session-unavailable`});return Xt(n,i,t.device,t.scope.signal,a)},shutdown:async()=>void 0})}function Xt(e,t,n,r,i){let a=i?qt(n):H(n,t,{...Jt,lifecycle:$(n,!1)}),o={ensureReady:async()=>({...n,booted:!0}),bootTarget:async()=>({...n,booted:!0}),...ne(Nt({device:n,signal:r,getInteractor:e.getInteractor}),$(n,i)),..._t({device:n,signal:r,getInteractor:e.getInteractor,presentIosAcquisition:e.host.snapshot.presentIosAcquisition}),...tt({device:n,signal:r,resolveInteractor:t=>e.getInteractor(n,t),facts:a.operations})};return Object.freeze({device:n,owner:t,facts:a,operations:Object.freeze(Zt(a,o)),[Symbol.asyncDispose]:async()=>void 0})}function Zt(e,t){let n={};for(let[r,i]of Object.entries(t))e.operations[r]?.available&&(n[r]=i);return n}export{Yt as createRevylPlatformRuntimeOwner};
@@ -1 +1 @@
1
- import{r as e,t}from"./rolldown-runtime.mjs";import{a as n,t as r}from"./errors.mjs";import{t as i}from"./screenshot.mjs";import a,{promises as o}from"node:fs";import{Worker as s}from"node:worker_threads";import c from"node:path";import{fileURLToPath as l}from"node:url";var u=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)}}})),d=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}}})),f=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}})),p=t(((e,t)=>{let n=d(),r=f();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=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=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.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}},a.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}},a.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}},a.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}},a.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())}})),m=t(((t,n)=>{let r=e(`util`),i=u(),a=p(),o=n.exports=function(e){i.call(this);let t=[],n=this;this._filter=new a(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};r.inherits(o,i)})),h=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}})),g=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}})),_=t(((e,t)=>{let n=h(),r=g(),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()}})),v=t((e=>{let t=d(),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 i(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 a(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 o(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,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),y=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}})),b=t(((t,n)=>{let r=e(`util`),i=e(`zlib`),a=u(),o=m(),s=_(),c=v(),l=y(),d=n.exports=function(e){a.call(this),this._parser=new s(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()};r.inherits(d,a),d.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},d.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=i.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,i.Z_MIN_CHUNK);this._inflate=i.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 a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},d.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new o(this._bitmapInfo)},d.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},d.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},d.prototype._simpleTransparency=function(){this._metaData.alpha=!0},d.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},d.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},d.prototype._complete=function(e){if(this.errord)return;let t;try{let n=c.dataToBitMap(e,this._bitmapInfo);t=l(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),x=t(((e,t)=>{let n=h();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}})),S=t(((e,t)=>{let n=f();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 a(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 o(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 s(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 c(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 l(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 u(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 d(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:a,2:s,3:l,4:d},h={0:i,1:o,2:c,3:u,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}})),C=t(((t,n)=>{let r=h(),i=g(),a=x(),o=S(),s=e(`zlib`),c=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`)};c.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},c.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},c.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)},c.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},c.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)},c.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)},c.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},c.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),w=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=h(),o=C(),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)}})),T=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})),E=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`)}})),D=t((e=>{let t=E(),n=p();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)}})),O=t(((t,n)=>{let r=!0,i=e(`zlib`),a=T();i.deflateSync||(r=!1);let o=E(),s=D(),c=_(),l=v(),u=y();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 d(e){n=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.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:d,metadata:p,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(f.interlace)C=i.inflateSync(S);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.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,f);S=null;let T=l.dataToBitMap(w,f);w=null;let E=u(T,f,t.skipRescale);return f.data=E,f.gamma=_||0,f}})),k=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=h(),o=C();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)}})),A=t((e=>{let t=O(),n=k();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),j=t((t=>{let n=e(`util`),r=e(`stream`),i=b(),a=w(),o=A(),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)}}))();Buffer.from([137,80,78,71,13,10,26,10]);function M(e,t){try{return j.PNG.sync.read(e)}catch(e){throw new r(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}function N(e,t){try{let n=l(e),r=c.extname(n)||`.js`;return[c.join(c.dirname(n),`${t}${r}`),c.join(c.dirname(n),`internal`,`${t}${r}`)].find(e=>a.existsSync(e))??null}catch{return null}}function P(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var F=class extends Error{};let I=null,L;const R=new Set;let z=0;const B=new Map;function V(e){if(!L){L=e;for(let t of R)t(e)}}function H(e){let t=B.get(e.id);t&&(B.delete(e.id),G(),e.ok?t.resolve(e.result):t.reject(new r(n(e.error.code),e.error.message,e.error.details)))}function U(e,t){I===e&&(V(t),I=null,e.terminate().catch(()=>{}),W(new F(`PNG worker failed: ${t.kind}`)))}function W(e){let t=[...B.values()];B.clear();for(let n of t)n.reject(e)}function G(){I&&(B.size>0?I.ref():I.unref())}function K(){if(L)return null;if(I)return I;let e=N(import.meta.url,`png-worker`);if(!e)return V({kind:`entry-not-found`}),null;try{let t=new s(e,{env:{},execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,H),t.on(`error`,e=>{U(t,{kind:`worker-error`,detail:e.message})}),t.on(`exit`,e=>{U(t,{kind:`worker-exited`,detail:`exit code ${e}`})}),t.unref(),I=t,t}catch(e){return V({kind:`spawn-failed`,detail:e instanceof Error?e.message:String(e)}),null}}function q(e){let t=K();if(!t)return Promise.reject(new F(`PNG worker is unavailable`));z+=1;let n=z;return new Promise((r,i)=>{B.set(n,{resolve:r,reject:i}),G();try{t.postMessage({...e,id:n})}catch(e){B.delete(n),G(),i(new F(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function J(e,t){try{return await q(e)}catch(e){if(e instanceof F)return await t();throw e}}async function Y(e,t){return X(await J({kind:`decode`,png:e,label:t},()=>{let n=M(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}))}function X(e){let t=new j.PNG({width:e.width,height:e.height});return t.data=P(e.data),t}async function Z(e){return P((await J({kind:`encode`,width:e.width,height:e.height,data:e.data},async()=>{let{encodePngPixels:t}=await import(`./png-encode.mjs`);return{kind:`encode`,png:t(e.data,e.width,e.height,4)}})).png)}async function Q(e,t){let{min:n,max:a}=i;if(!Number.isFinite(t)||t<n||t>a)throw new r(`INVALID_ARGS`,`Screenshot scale must be between ${n} and ${a}`);if(t===1)return;let s=await Y(await o.readFile(e),`screenshot`),c=Math.max(1,Math.round(s.width*t)),l=Math.max(1,Math.round(s.height*t));await o.writeFile(e,await Z($(s,c,l)))}async function ee(e,t,n){if(!Number.isInteger(t)||t<1||!Number.isInteger(n)||n<1)throw new r(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await Y(await o.readFile(e),`screenshot`);(i.width!==t||i.height!==n)&&await o.writeFile(e,await Z($(i,t,n)))}function $(e,t,n){let r=new j.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}export{$ as resizePngBox,ee as resizePngFile,Q as resizePngFileToScale};
1
+ import{r as e,t}from"./rolldown-runtime.mjs";import{o as n,t as r}from"./errors.mjs";import{t as i}from"./screenshot.mjs";import a,{promises as o}from"node:fs";import{Worker as s}from"node:worker_threads";import c from"node:path";import{fileURLToPath as l}from"node:url";var u=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)}}})),d=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}}})),f=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}})),p=t(((e,t)=>{let n=d(),r=f();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=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=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.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}},a.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}},a.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}},a.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}},a.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())}})),m=t(((t,n)=>{let r=e(`util`),i=u(),a=p(),o=n.exports=function(e){i.call(this);let t=[],n=this;this._filter=new a(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};r.inherits(o,i)})),h=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}})),g=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}})),_=t(((e,t)=>{let n=h(),r=g(),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()}})),v=t((e=>{let t=d(),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 i(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 a(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 o(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,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),y=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}})),b=t(((t,n)=>{let r=e(`util`),i=e(`zlib`),a=u(),o=m(),s=_(),c=v(),l=y(),d=n.exports=function(e){a.call(this),this._parser=new s(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()};r.inherits(d,a),d.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},d.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=i.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,i.Z_MIN_CHUNK);this._inflate=i.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 a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},d.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new o(this._bitmapInfo)},d.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},d.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},d.prototype._simpleTransparency=function(){this._metaData.alpha=!0},d.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},d.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},d.prototype._complete=function(e){if(this.errord)return;let t;try{let n=c.dataToBitMap(e,this._bitmapInfo);t=l(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),x=t(((e,t)=>{let n=h();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}})),S=t(((e,t)=>{let n=f();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 a(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 o(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 s(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 c(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 l(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 u(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 d(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:a,2:s,3:l,4:d},h={0:i,1:o,2:c,3:u,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}})),C=t(((t,n)=>{let r=h(),i=g(),a=x(),o=S(),s=e(`zlib`),c=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`)};c.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},c.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},c.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)},c.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},c.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)},c.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)},c.prototype.packIDAT=function(e){return this._packChunk(r.TYPE_IDAT,e)},c.prototype.packIEND=function(){return this._packChunk(r.TYPE_IEND,null)}})),w=t(((t,n)=>{let r=e(`util`),i=e(`stream`),a=h(),o=C(),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)}})),T=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})),E=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`)}})),D=t((e=>{let t=E(),n=p();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)}})),O=t(((t,n)=>{let r=!0,i=e(`zlib`),a=T();i.deflateSync||(r=!1);let o=E(),s=D(),c=_(),l=v(),u=y();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 d(e){n=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.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:d,metadata:p,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(f.interlace)C=i.inflateSync(S);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.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,f);S=null;let T=l.dataToBitMap(w,f);w=null;let E=u(T,f,t.skipRescale);return f.data=E,f.gamma=_||0,f}})),k=t(((t,n)=>{let r=!0,i=e(`zlib`);i.deflateSync||(r=!1);let a=h(),o=C();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)}})),A=t((e=>{let t=O(),n=k();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),j=t((t=>{let n=e(`util`),r=e(`stream`),i=b(),a=w(),o=A(),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)}}))();Buffer.from([137,80,78,71,13,10,26,10]);function M(e,t){try{return j.PNG.sync.read(e)}catch(e){throw new r(`COMMAND_FAILED`,`Failed to decode ${t} as PNG`,{label:t,reason:e instanceof Error?e.message:String(e)})}}function N(e,t){try{let n=l(e),r=c.extname(n)||`.js`;return[c.join(c.dirname(n),`${t}${r}`),c.join(c.dirname(n),`internal`,`${t}${r}`)].find(e=>a.existsSync(e))??null}catch{return null}}function P(e){return Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var F=class extends Error{};let I=null,L;const R=new Set;let z=0;const B=new Map;function V(e){if(!L){L=e;for(let t of R)t(e)}}function H(e){let t=B.get(e.id);t&&(B.delete(e.id),G(),e.ok?t.resolve(e.result):t.reject(new r(n(e.error.code),e.error.message,e.error.details)))}function U(e,t){I===e&&(V(t),I=null,e.terminate().catch(()=>{}),W(new F(`PNG worker failed: ${t.kind}`)))}function W(e){let t=[...B.values()];B.clear();for(let n of t)n.reject(e)}function G(){I&&(B.size>0?I.ref():I.unref())}function K(){if(L)return null;if(I)return I;let e=N(import.meta.url,`png-worker`);if(!e)return V({kind:`entry-not-found`}),null;try{let t=new s(e,{env:{},execArgv:e.endsWith(`.ts`)?[`--experimental-strip-types`]:[]});return t.on(`message`,H),t.on(`error`,e=>{U(t,{kind:`worker-error`,detail:e.message})}),t.on(`exit`,e=>{U(t,{kind:`worker-exited`,detail:`exit code ${e}`})}),t.unref(),I=t,t}catch(e){return V({kind:`spawn-failed`,detail:e instanceof Error?e.message:String(e)}),null}}function q(e){let t=K();if(!t)return Promise.reject(new F(`PNG worker is unavailable`));z+=1;let n=z;return new Promise((r,i)=>{B.set(n,{resolve:r,reject:i}),G();try{t.postMessage({...e,id:n})}catch(e){B.delete(n),G(),i(new F(`failed to post job to PNG worker: ${e instanceof Error?e.message:String(e)}`))}})}async function J(e,t){try{return await q(e)}catch(e){if(e instanceof F)return await t();throw e}}async function Y(e,t){return X(await J({kind:`decode`,png:e,label:t},()=>{let n=M(e,t);return{kind:`decode`,width:n.width,height:n.height,data:n.data}}))}function X(e){let t=new j.PNG({width:e.width,height:e.height});return t.data=P(e.data),t}async function Z(e){return P((await J({kind:`encode`,width:e.width,height:e.height,data:e.data},async()=>{let{encodePngPixels:t}=await import(`./png-encode.mjs`);return{kind:`encode`,png:t(e.data,e.width,e.height,4)}})).png)}async function Q(e,t){let{min:n,max:a}=i;if(!Number.isFinite(t)||t<n||t>a)throw new r(`INVALID_ARGS`,`Screenshot scale must be between ${n} and ${a}`);if(t===1)return;let s=await Y(await o.readFile(e),`screenshot`),c=Math.max(1,Math.round(s.width*t)),l=Math.max(1,Math.round(s.height*t));await o.writeFile(e,await Z($(s,c,l)))}async function ee(e,t,n){if(!Number.isInteger(t)||t<1||!Number.isInteger(n)||n<1)throw new r(`INVALID_ARGS`,`Screenshot resize dimensions must be positive integers`);let i=await Y(await o.readFile(e),`screenshot`);(i.width!==t||i.height!==n)&&await o.writeFile(e,await Z($(i,t,n)))}function $(e,t,n){let r=new j.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}export{$ as resizePngBox,ee as resizePngFile,Q as resizePngFileToScale};
package/dist/runtime.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,o as t,r as n,t as r}from"./device.mjs";import{i,n as a,r as o,t as s}from"./errors.mjs";import{i as c,n as l,r as u}from"./snapshot-visibility.mjs";import{r as d}from"./device2.mjs";import{a as f,i as p,n as m,o as h,r as g}from"./revyl-client.mjs";import{n as ee,r as te,t as ne}from"./open-target.mjs";import _ from"node:fs";import v from"node:path";import{createHash as re,randomUUID as y}from"node:crypto";import{setTimeout as b}from"node:timers/promises";function x(e){let t=`${re(`sha256`).update(`agent-device:revyl:session:v1:${e}`).digest(`hex`).slice(0,32)}`;return[t.slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,`${(Number.parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}`,t.slice(20,32)].join(`-`)}const S=24e4,ie=m+S+1e4,ae=new Set([503,409]);async function oe(e,t,r){let i=x(t.leaseId);if(r.signal?.aborted)return{status:`failed`,error:C(r)};let a;try{a=await se(e,r,i)}catch(e){return{status:`failed`,error:e,...T(e)?{rented:{sessionId:i}}:{}}}let o=typeof a.workflow_run_id==`string`?a.workflow_run_id:void 0,c=typeof a.session_id==`string`?a.session_id:void 0;if(o&&c&&c!==i)return{status:`failed`,rented:{runId:o,sessionId:c},error:new s(`COMMAND_FAILED`,`Revyl started the device as session ${c} instead of ${i}.`,{reason:`provider-session-identity-mismatch`,runId:o,providerSessionId:c,hint:`Retry the command; agent-device ends a Revyl session by the identity it issued.`})};if(!o)return{status:`failed`,rented:{sessionId:c??i},error:new s(`COMMAND_FAILED`,`Revyl did not start a ${r.platform} device: ${a.error??a.message??`no workflow run was returned`}`,{reason:`provider-start-refused`,platform:r.platform,...a.trace_id===void 0?{}:{traceId:a.trace_id}})};if(r.onRented?.({runId:o,sessionId:i}),r.signal?.aborted)return{status:`failed`,rented:{runId:o,sessionId:i},error:C(r)};let l=le(r);try{let a=await ue(e,o,l,{...r,sessionId:i});return{status:`ready`,session:{platform:r.platform,runId:o,sessionId:i,screen:me(a),dragDuration:a.supports_explicit_drag_duration===!0,device:n(r.platform,t,o),client:e,lease:t,launchedApp:{}}}}catch(e){return{status:`failed`,error:e,rented:{runId:o,sessionId:i}}}}async function se(e,t,n){if(t.signal?.aborted)throw C(t);let r={platform:t.platform,is_simulation:!0,session_id:n,idle_timeout_seconds:1800,...t.appUrl===void 0?{}:{app_url:t.appUrl},...t.deviceModel===void 0?{}:{device_model:t.deviceModel},...t.osVersion===void 0?{}:{os_version:t.osVersion}};return await e.startDevice(r)}function C(e){return new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e.platform},e.signal?.reason)}function w(e,t,n,r){let i=`agent-device stops Revyl session ${r} once its start answers; end it from Revyl if it stays listed.`;return t.signal?.aborted?new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e,providerSessionId:r,hint:i},t.signal.reason):new s(`COMMAND_FAILED`,`Revyl did not report a ready device within ${n} ms.`,{reason:`provider-not-ready`,timeoutMs:n,providerSessionId:r,...t.deadline===void 0?{}:{deadline:t.deadline},hint:`Retry the command; Revyl may have had no device of that model available. ${i}`})}function T(e){return!h(e)}function ce(e,t={},n){let r=e.map(e=>e.sessionId).join(`, `),i=e.length===1?e[0]:void 0;return new s(`COMMAND_FAILED`,`Revyl did not release session${i?``:`s`} ${r}.`,{reason:`provider-cleanup-pending`,...t,providerSessionIds:e.map(e=>e.sessionId),causes:e.map(e=>e.failure),...i?{providerSessionId:i.sessionId,...i.runId===void 0?{}:{runId:i.runId},cause:i.failure}:{},hint:`End the Revyl session${i?``:`s`} ${r}; each device stays rented and billed until it is.`},n)}function le(e){let t=e.deadline===void 0?S:Math.min(S,e.deadline-Date.now());return{at:Date.now()+t,budgetMs:Math.max(0,t)}}async function ue(e,t,n,r){for(await fe(e,t,n,r);;){O(n,r);let i=await E(e,t,n,r);if(O(n,r),i.device_connected===!0)return i;await A(n,r.signal)}}async function E(e,t,n,r){try{return await D(()=>e.getWorkerHealth(t,k(n,r)),n,r)}catch(e){if(!de(e))throw e;return{}}}async function D(e,t,n){try{return await e()}catch(e){throw O(t,n),e}}function de(e){return e instanceof s&&typeof e.details?.providerStatus==`number`&&ae.has(e.details.providerStatus)}async function fe(e,t,n,r){for(;;){O(n,r);let i=await D(()=>e.getWorkerConnection(t,k(n,r)),n,r);if(O(n,r),i.status===`ready`&&i.worker_ws_url)return;if(i.status===`cancelled`||i.status===`stopped`||i.status===`failed`)throw new s(`COMMAND_FAILED`,`Revyl did not start the ${r.platform} device: ${i.status}${i.message===null||i.message===void 0?``:` (${i.message})`}`,{reason:`provider-start-failed`,runId:t,status:i.status});await A(n,r.signal)}}function O(e,t){if(!(Date.now()<e.at))throw w(t.platform,t,e.budgetMs,t.sessionId)}function k(e,t){let n=AbortSignal.timeout(Math.max(0,e.at-Date.now()));return t.signal===void 0?n:AbortSignal.any([t.signal,n])}async function A(e,t){await b(Math.min(2e3,Math.max(0,e.at-Date.now())),void 0,t===void 0?{}:{signal:t}).catch(()=>void 0)}async function pe(e,t){await e.stopDeviceSession(t)}function me(e){let{screen_width:t,screen_height:n}=e;if(!(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0))return{width:t,height:n}}var j=class{lease;generation;phase=`starting`;request;answerBy;abandon=new AbortController;start=Promise.resolve({status:`failed`,error:void 0});answered=!1;answer;markAnswered=()=>void 0;session=void 0;rentals=new Map;latest=void 0;unnamed=!1;waiters=new Set;followUpQueued=!1;ending=void 0;constructor(e,t,n,r){this.lease=e,this.generation=t,this.request=n,this.answerBy=r,this.answer=new Promise(e=>{this.markAnswered=e})}};function he(e){let t=new ge(e);return Object.freeze({live:e=>t.live(e),allocate:async(e,n,r)=>await t.allocate(e,n,r),release:async e=>await t.release(e),recover:async e=>await t.recover(e),shutdown:async()=>await t.shutdown()})}var ge=class{entries=new Map;shuttingDown=!1;generations=0;driver;constructor(e){this.driver=e}live(e){let t=this.entries.get(e);return t?.phase===`ready`?t.session:void 0}isCurrent(e){return this.entries.get(e.lease.leaseId)?.generation===e.generation}refusal(e,t,n){return this.shuttingDown?this.driver.shuttingDown(e):t&&(t.phase===`ending`||!this.isCurrent(t))?this.driver.releasing(e):n()}async allocate(e,t,n={}){let r=this.entries.get(e.leaseId);if(this.shuttingDown||r?.phase===`ending`)throw this.refusal(e,r,()=>0);r?.request!==void 0&&n.requireJoinable?.(r.request);let i=N(n),a=Date.now()+this.driver.startTimeoutMs,o=Math.min(i.deadline??a,a);if(!r&&P(i,o))throw this.driver.gaveUp(e,i,0,void 0);let s=r??this.rent(e,t,i,a),c=Math.max(0,o-Date.now()),l=await this.join(s,i,o);return this.deliver(s,l,i,o,c)}deliver(e,t,n,r,i){if(t.status===`failed`)throw this.refusal(e.lease,void 0,()=>t.error);let a=this.refusal(e.lease,e,()=>P(n,r)?this.driver.gaveUp(e.lease,n,i,e.latest):void 0);if(a!==void 0)throw a;return t.session}async release(e){let t=this.entries.get(e);if(!t)return;let n=await this.teardown(t);if(n.status===`pending`)throw this.pending(t,n,{route:`release`,leaseId:e});return n.status===`stopped`?{handle:n.handle,session:n.session}:void 0}async recover(e){let t=e.leaseId,n=this.entries.get(t);if(n===void 0){if(this.shuttingDown)throw this.driver.shuttingDown(e);n=this.recovering(e)}let r=await this.teardown(n);if(r.status===`pending`)throw this.pending(n,r,{route:`recover`,leaseId:t})}async shutdown(){this.shuttingDown=!0;let e=[],t=[...this.entries.values()];if((await Promise.all(t.map(async e=>await this.teardown(e)))).forEach((n,r)=>{if(n.status!==`pending`)return;let i=t[r].lease.leaseId;for(let t of n.owed)e.push({leaseId:i,...t})}),e.length>0)throw this.driver.cleanupPending(e,{route:`shutdown`})}rent(e,t,n,r){let i=new j(e,this.generations+=1,t,r);return i.start=this.runStart(i,t,n),this.entries.set(e.leaseId,i),i}recovering(e){let t=new j(e,this.generations+=1,void 0,Date.now());return t.answered=!0,t.markAnswered(),t.unnamed=!0,t.phase=`ending`,this.entries.set(e.leaseId,t),t}async runStart(e,t,n){let r=Date.now(),i=await this.callStart(e,t);if(_e(e,i,this.driver.handleKey),i.status===`ready`&&(e.session=i.session,e.phase===`starting`&&this.isCurrent(e)&&F(e)))return e.phase=`ready`,{status:`ready`,session:i.session};let a;try{a=this.startFailure(e,i,n,r)}catch(e){a=e}return await this.endFailedStart(e,a)}async callStart(e,t){try{return await this.driver.start(e.lease,t,{signal:e.abandon.signal,deadline:e.answerBy,rented:t=>{e.answered||(M(e,t,this.driver.handleKey(t)),e.phase===`ending`&&this.followUp(e))}})}catch(e){return{status:`rejected`,error:e}}}startFailure(e,t,n,r){let i=Math.max(0,e.answerBy-r);return this.refusal(e.lease,e,()=>t.status===`ready`?this.driver.gaveUp(e.lease,n,i,t.handle):t.error)}async endFailedStart(e,t){if(e.phase===`ending`)return this.followUp(e),{status:`failed`,error:t};let n=await this.teardown(e);if(n.status!==`pending`)return{status:`failed`,error:t};let r=e.lease.leaseId;return{status:`failed`,error:this.driver.cleanupPending(n.owed.map(e=>({leaseId:r,...e})),{route:`start`,leaseId:r},t)}}async join(e,t,n){if(e.phase===`ready`)return{status:`ready`,session:e.session};let r=Math.max(0,n-Date.now()),i=()=>{try{return this.refusal(e.lease,e,()=>this.driver.gaveUp(e.lease,t,r,e.latest))}catch(e){return e}},a=new AbortController,o=setTimeout(()=>a.abort(),r),s=t.signal?[t.signal,a.signal]:[a.signal],c={deadline:n,signal:t.signal},l=()=>void 0;try{if(e.waiters.add(c),s.some(e=>e.aborted))throw i();let t=new Promise((t,n)=>{l=()=>{let t=i();e.waiters.delete(c),this.abandonIfUnwanted(e),n(t)};for(let e of s)e.addEventListener(`abort`,l,{once:!0})});return await Promise.race([e.start,t])}finally{e.waiters.delete(c),this.abandonIfUnwanted(e),clearTimeout(o);for(let e of s)e.removeEventListener(`abort`,l)}}abandonIfUnwanted(e){e.answered||e.phase===`ending`||F(e)||this.teardown(e).catch(()=>void 0)}teardown(e){if(e.phase=`ending`,e.answered||e.abandon.abort(),e.ending)return e.ending;let t=this.runTeardown(e).finally(()=>{e.ending===t&&(e.ending=void 0)});return e.ending=t,t}async runTeardown(e){let t=new Map;for(;;){await this.untilAnswered(e);let n=await this.nameRental(e);if(n!==void 0)return n;let r=await this.stopRentals(e,t);if(r!==`progress`){if(r.length>0)return{status:`pending`,owed:r};if(!(e.unnamed||[...e.rentals.values()].some(e=>!e.stopped)))return this.finishTeardown(e)}}}async stopRentals(e,t){for(let n of e.rentals.values()){if(n.stopped)continue;if(t.get(n)!==void 0){if(n.stopping!==void 0)break;continue}let e=await this.stop(n);if(e===void 0)return`progress`;if(t.set(n,{handle:n.handle,cause:e.cause}),n.stopping!==void 0)break}return[...e.rentals.values()].filter(e=>!e.stopped).map(e=>t.get(e)??{handle:e.handle,cause:Error(`The stop waits for an earlier stop of this lease that is still in flight.`)})}async nameRental(e){if(e.unnamed)try{let t=await this.driver.findByLease(e.lease);M(e,t,this.driver.handleKey(t)),e.unnamed=!1;return}catch(e){return{status:`pending`,owed:[{handle:void 0,cause:e}]}}}finishTeardown(e){let t=e.latest;return e.answered?(this.isCurrent(e)&&this.entries.delete(e.lease.leaseId),t===void 0?{status:`nothing-rented`}:{status:`stopped`,handle:t,session:e.session}):{status:`pending`,owed:[{handle:t,cause:Error(`The provider start did not answer within its start timeout.`)}]}}followUp(e){let t=e.ending;if(t===void 0){this.teardown(e).catch(()=>void 0);return}e.followUpQueued||(e.followUpQueued=!0,t.then(async()=>(e.followUpQueued=!1,await this.teardown(e))).catch(()=>void 0))}async untilAnswered(e){if(e.answered)return;let t,n=new Promise(n=>{t=setTimeout(n,Math.max(0,e.answerBy-Date.now()))});try{await Promise.race([e.answer,n])}finally{clearTimeout(t)}}async stop(e){e.stopping??=this.stopHandle(e.handle).then(t=>(t===void 0&&(e.stopped=!0),e.stopping=void 0,t));let t=e.stopping,n=this.driver.stopTimeoutMs;if(n===void 0)return await t;let r,i=new Promise(e=>{r=setTimeout(()=>e({cause:Error(`The provider stop did not answer within ${n} ms.`)}),n)});try{return await Promise.race([t,i])}finally{clearTimeout(r)}}async stopHandle(e){try{await this.driver.stop(e);return}catch(e){return{cause:e}}}pending(e,t,n){return this.driver.cleanupPending(t.owed.map(t=>({leaseId:e.lease.leaseId,...t})),n)}};function _e(e,t,n){switch(t.status){case`ready`:M(e,t.handle,n(t.handle));break;case`failed`:t.rented!==void 0&&M(e,t.rented,n(t.rented));break;case`rejected`:e.rentals.size===0&&(e.unnamed=!0)}e.answered=!0,e.markAnswered()}function M(e,t,n){e.rentals.has(n)||e.rentals.set(n,{handle:t,stopped:!1,stopping:void 0}),e.latest=t}function N(e){return{...e.signal===void 0?{}:{signal:e.signal},...e.deadline===void 0?{}:{deadline:e.deadline}}}function P(e,t){return e.signal?.aborted===!0||Date.now()>=t}function F(e){if(e.phase===`ending`)return!1;let t=Date.now();for(let n of e.waiters)if(!n.signal?.aborted&&t<n.deadline)return!0;return!1}new Map([...Object.entries({ios:`ios-instance`,android:`android-instance`,harmonyos:`harmonyos-instance`}).flatMap(([e,t])=>t===void 0?[]:[[t,e]]),[`macos-app`,`macos`]]);function I(e,t={message:e=>`Invalid value: ${e}`}){let n=new Set(e),r=t.normalize??(e=>e);return{is:e=>typeof e==`string`&&n.has(e),parse:e=>{let i=r(e??``);if(n.has(i))return i;throw new s(`INVALID_ARGS`,t.message(e??``))}}}I([`up`,`down`,`left`,`right`],{message:e=>`Unknown direction: ${e}`});function ve(e){let t=e.direction,n=t===`up`||t===`down`,r=n?e.referenceHeight:e.referenceWidth,i=n?e.referenceWidth:e.referenceHeight,a=xe(e.amount),o=e.pixels===void 0?Math.round(r*a):Se(e.pixels),s=L(r),c=Math.max(1,r-s*2),l=Math.max(1,Math.min(o,c)),u=Math.round(l/2),d=Math.round(r/2),f={axisStart:d-u,axisEnd:d+u,cross:Math.round(i/2)},p=L(i),m=e.container?be(f,e.container,n,{axis:{min:s,max:r-s},cross:{min:p,max:i-p},crossFrame:{min:0,max:i}}):f,h=m.axisEnd-m.axisStart,g=h<l;return{direction:t,...ye(t,m),referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:g?h:l,...g?{requestedPixels:l}:{}}}function ye(e,t){let n=e===`up`||e===`down`,r=n?{x:t.cross,y:t.axisStart}:{x:t.axisStart,y:t.cross},i=n?{x:t.cross,y:t.axisEnd}:{x:t.axisEnd,y:t.cross},[a,o]=e===`up`||e===`left`?[r,i]:[i,r];return{x1:a.x,y1:a.y,x2:o.x,y2:o.y}}function L(e){return Math.max(1,Math.round(e*.1))}function be(e,t,n,r){let i=R(n?t.y:t.x,n?t.height:t.width,r.axis),a=n?t.x:t.y,o=n?t.width:t.height,s=R(a,o,r.cross)??R(a,o,r.crossFrame);if(!i||!s)return e;let c=e.cross>=s.min&&e.cross<=s.max?e.cross:Math.round((s.min+s.max)/2);if(e.axisEnd-e.axisStart>=i.max-i.min)return{axisStart:i.min,axisEnd:i.max,cross:c};let l=e.axisStart<i.min?i.min-e.axisStart:Math.min(0,i.max-e.axisEnd);return{axisStart:e.axisStart+l,axisEnd:e.axisEnd+l,cross:c}}function R(e,t,n){let r=Math.max(n.min,Math.ceil(e)+8),i=Math.min(n.max,Math.floor(e+t)-1-8);return i>r?{min:r,max:i}:void 0}function xe(e){if(e===void 0)return .6;if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll amount must be a positive number`);return e}function Se(e){if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(e))}Object.freeze({reason:`scroll_keyboard_occludes_surface`,hint:"The on-screen keyboard covers the surface this scroll would swipe, so it cannot reach it. Run `keyboard dismiss` and retry, accepting that it drops focus (re-tap the field to keep typing), or scroll before focusing the field."});const z=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function Ce(e){let t=B(e.packageName),n=(e.resourceId??``).toLowerCase(),r=B(e.activeInputMethodPackage);if(t&&r&&t===r)return{inputMethodOwned:!0,source:`active-input-method`};if(r&&n.startsWith(`${r}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(t&&z.has(t))return{inputMethodOwned:!0,source:`known-ime-package`};for(let e of z)if(n.startsWith(`${e}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function we(e){return Ce(e).inputMethodOwned}function Te(e){return we({packageName:e.bundleId,resourceId:e.identifier})}function B(e){return(e??``).trim().toLowerCase()||void 0}const Ee=new Set([`UIKeyboardDockItemButton`,`UIAccessibilityElementKBKey`]),De=new Set([`TUIPredictionViewCell`]),Oe=new Set([`UIKeyboardLayoutStar`,`TUIPredictionView`]),V=new Set([`_UIRemoteKeyboardPlaceholderView`,`TUISystemInputAssistantView`,`TUISystemInputAssistantPageView`]);function H(e,t){return e.role!==void 0&&t.has(e.role)}Object.freeze({reason:`tap_keyboard_occludes_target`,hint:"The visible keyboard covers this target, so the tap would land on a key instead of on it. End editing first: tap the app's own Done/Cancel/close control, or run `keyboard enter` when submitting is what you want (`keyboard dismiss` works only when the keyboard exposes its own dismiss key). This reads the snapshot the command measured against, so if the keyboard closed since it was taken, run `snapshot -i` and retry."});const ke=new Set([`keyboard`,`key`]);function U(e){return ke.has(l(e.type??``))||Te(e)}function W(e){return U(e)||Ee.has(e.role??``)}function G(e){return U(e)||H(e,Oe)}function Ae(e,t){if(W(e)||H(e,De)||H(e,V)||G(e))return!0;let n=new Set,r=e.parentIndex;for(;typeof r==`number`&&!n.has(r);){n.add(r);let e=t.get(r);if(!e)return!1;if(H(e,V)||G(e))return!0;r=e.parentIndex}return!1}function K(e){return e!==null&&u(e)}function q(e){return e.flatMap(e=>u(e.rect)?[e.rect]:[])}function je(e,t){let n=new Map(e.map(e=>[e.index,e.parentIndex])),r=new Set(t.map(e=>e.index)),i=new Set;for(let e of t)for(let t of Me(n,r,e.index))i.add(t);return i}function Me(e,t,n){let r=[],i=new Set,a=e.get(n);for(;typeof a==`number`&&!i.has(a);)i.add(a),t.has(a)&&r.push(a),a=e.get(a);return r}function Ne(e){let t=e.map(e=>[e.x,e.x+e.width]).sort((e,t)=>e[0]-t[0]),n=t[0]?.[1]??0;for(let[e,r]of t){if(e-n>2)return!1;n=Math.max(n,r)}return!0}function Pe(e){let t=Math.min(...e.anchorRects.map(e=>e.y)),n=Math.min(...e.anchorRects.map(e=>e.x)),r=Math.max(...e.anchorRects.map(e=>e.x+e.width)),i=e.viewport.y+e.viewport.height;return e.reportedBottom<i-80||r-n<=e.reportedBottom-t?null:{x:n,y:t,width:r-n,height:i-t}}function Fe(e){let t=q(e.anchorNodes.filter(t=>!e.planeIndices.has(t.index)));return Ne(t.length>0?t:e.anchorRects)}function Ie(e,t){let n=e.filter(U),r=q(n);if(r.length===0||!K(t))return null;let i=e.filter(W),a=q(i);if(a.length===0)return null;let o=Pe({anchorRects:r,reportedBottom:Math.max(...a.map(e=>e.y+e.height)),viewport:t});return!o||!u(o)||!Fe({anchorNodes:n,anchorRects:r,planeIndices:je(e,i)})?null:o}function J(e){let t=new Map(e.nodes.map(e=>[e.index,e]));return{nodes:e.nodes.map(e=>({...e,keyboardOwned:Ae(e,t)})),keyboard:Le(e)}}function Le(e){let t=Ie(e.nodes,e.viewport);return t?{kind:`derived`,derivation:`docked-tree`,frame:t,treeBound:!0}:K(e.viewport)&&e.nodes.some(U)?{kind:`tree-rejected`,derivation:`docked-tree`,...typeof e.visibility==`boolean`?{visible:e.visibility}:{}}:typeof e.visibility==`boolean`?{kind:`visibility-only`,visible:e.visibility}:{kind:`unmeasurable`,reason:e.nodes.some(U)?`keyboard-viewport-unavailable`:e.visibility===`failed`?`keyboard-visibility-probe-failed`:e.visibility===`unsupported`?`keyboard-visibility-probe-unsupported`:`keyboard-not-observed`}}function Re(e){return{readHierarchy:t=>e.client.getWorkerHierarchy(e.runId,t),viewport:()=>e.screen===void 0?void 0:c({x:0,y:0,...e.screen})}}async function ze(e,t,n){let r=await t.readHierarchy(n);return n?.throwIfAborted(),e.platform===`ios`?await Be(r,e.runId,t.viewport()):await He(r,t.viewport())}async function Be(e,t,n){let[{flattenIosTree:r,resolveIosAxTreeViewport:i},{interpretIosNode:a},o]=await Promise.all([import(`./ios-ax-tree.mjs`),import(`./ios-node-interpretation.mjs`),import(`./ios-snapshot-acquisition.mjs`)]),s=Ve(e),c=i(s,n);return o.createIosSnapshotAcquisition({producer:`revyl-ios-tree`,...J({nodes:r(s).map(e=>a(e)),viewport:c.kind===`missing`?null:c.rect}),viewport:c,lineage:{targetId:t}})}function Ve(e){let t;try{t=JSON.parse(e)}catch(e){throw X(e)}let n=Array.isArray(t)?t:[t];if(!n.every(Y))throw X();return n}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return[t.children,t.nodes,t.elements].every(e=>e===void 0||Array.isArray(e)&&e.every(Y))}function X(e){return new s(`COMMAND_FAILED`,`Revyl returned an iOS hierarchy that is not an accessibility node tree.`,{reason:`provider-response-invalid`},e)}async function He(e,t){let[{parseWebDriverAndroidSnapshotNodes:n},{stampSnapshotIdentity:r}]=await Promise.all([import(`./webdriver-android-source.mjs`),import(`./snapshot-producers.mjs`).then(e=>e.n)]),{nodes:i,keyboard:a}=J({nodes:n(e),viewport:t===void 0?null:{x:0,y:0,...t}});return r({nodes:i,keyboard:a,...t===void 0?{}:{viewport:t}},{backend:`android`,producer:`revyl-android-tree`})}var Ue=class{session;signal;constructor(e,t){this.session=e,this.signal=t}async open(e,t){let n=e.trim();if(t?.url)return await this.launch(n,t.launchArgs),await this.workerAction(`open_url`,{url:t.url}),n?{launchedAppBundleId:n}:void 0;if(ne(n)){await this.workerAction(`open_url`,{url:n});return}return await this.launch(n,t?.launchArgs),n?{launchedAppBundleId:n}:void 0}async launch(e,t){if(t?.length)throw new s(`UNSUPPORTED_OPERATION`,`Revyl launches an app without arguments.`,{reason:`unsupported-provider-mode`,hint:`Open a deep link instead: open <url>.`});await this.workerAction(`launch`,e?{bundle_id:e}:{}),e&&(this.session.launchedApp.bundleId=e)}async openDevice(){}async close(e){let t=e.trim();t&&this.requireCloseableApp(t,this.session.launchedApp.bundleId),await this.workerAction(`kill_app`)}requireCloseableApp(e,t){if(t===void 0)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl session has not launched ${e}, so it has no app to end.`,{reason:`provider-app-not-launched`,command:`close`,requestedApp:e,hint:`Close without an app name to end the app this session runs, or open the app first.`});if(e!==t)throw new s(`UNSUPPORTED_OPERATION`,`Revyl ends the app this session launched (${t}), not ${e}.`,{reason:`unsupported-provider-mode`,command:`close`,sessionApp:t,requestedApp:e,hint:"Revyl has no way to name an app to `/kill_app`; end the session to stop what it runs."})}async tap(e,t){await this.workerAction(`tap`,{x:e,y:t})}async doubleTap(e,t){await this.workerAction(`double_tap`,{x:e,y:t})}async longPress(e,t,n=1500){await this.workerAction(`longpress`,{x:e,y:t,duration_ms:n})}async focus(e,t){await this.tap(e,t)}type(){throw Z(`type`,`Revyl enters text at a point; run fill <field> "text" instead of type.`)}async fill(e,t,n,r,i){if(n===``){await this.workerAction(`clear_text`,{x:e,y:t});return}if(!r||r<=0){await this.workerAction(`input`,{x:e,y:t,text:n,clear_first:!0});return}let s=0,c=Array.from(n);try{for(let[n,i]of c.entries()){if(this.signal?.aborted)throw s===0?a(this.cancellation(),`no`):this.cancellation();if(await this.workerAction(`input`,{x:e,y:t,text:i,clear_first:s===0}),s+=1,n===c.length-1)return;await b(r,void 0,this.signal===void 0?{}:{signal:this.signal})}}catch(e){throw o(this.canceledAs(e),s)}}async scroll(e,t){let n=t?.durationMs;n!==void 0&&this.requireDragDuration(n);let r=this.session.screen;if(!r)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the scroll distance cannot be planned.`,{reason:`provider-viewport-unavailable`,runId:this.session.runId});let i=ve({direction:e,...t?.amount===void 0?{}:{amount:t.amount},...t?.pixels===void 0?{}:{pixels:t.pixels},referenceWidth:r.width,referenceHeight:r.height,...t?.containerRect===void 0?{}:{container:Ke(t.containerRect,r)}});return await this.workerAction(`drag`,{start_x:i.x1,start_y:i.y1,end_x:i.x2,end_y:i.y2,...n===void 0?{}:{duration_ms:n}}),{...i,...n===void 0?{}:{durationMs:n},backend:`revyl-device-proxy`}}requireDragDuration(e){if(!this.session.dragDuration)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl worker scrolls with one drag and cannot be told how fast the finger travels.`,{reason:`unsupported-provider-mode`,command:`scroll`,flag:`--duration-ms`,runId:this.session.runId,hint:`Scroll without --duration-ms; the drag runs at the speed Revyl gives it.`});if(e<1)throw new s(`INVALID_ARGS`,`Revyl drag --duration-ms must be at least 1.`,{flag:`--duration-ms`})}async screenshot(e,t){let n=await this.session.client.captureWorkerScreenshot(this.session.runId,this.signal),r=v.dirname(e);_.mkdirSync(r,{recursive:!0});let i=v.join(r,`.${v.basename(e)}.${process.pid}.${y()}.tmp`);try{if(await _.promises.writeFile(i,n,this.signal===void 0?{}:{signal:this.signal}),this.session.platform===`ios`&&await Ge(i,this.session.screen,t?.pixelDensity),this.signal?.aborted===!0)throw this.cancellation();await _.promises.rename(i,e)}catch(e){throw await _.promises.rm(i,{force:!0}).catch(()=>void 0),this.canceledAs(e)}}async snapshot(e){return await ze(this.session,Re(this.session),e?.signal??this.signal)}async back(){await this.workerAction(`back`)}async home(){await this.workerAction(`go_home`)}setOrientation(e){throw Z(`orientation`,`Revyl does not expose orientation control.`)}setSetting(){throw Z(`settings`,`Revyl does not expose settings control.`)}cancellation(e){return new s(`COMMAND_FAILED`,`The Revyl action was canceled before it finished.`,{reason:`request_canceled`,runId:this.session.runId},e??this.signal?.reason)}canceledAs(e){return!this.signal?.aborted||e instanceof s?e:this.cancellation(e)}workerAction(e,t){return this.session.client.workerAction(this.session.runId,e,t,this.signal)}};function We(e,t){return new Ue(e,t)}async function Ge(e,t,n){if(t===void 0)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the screenshot density cannot be known.`,{reason:`provider-viewport-unavailable`});let[{readPngSize:r},{resizePngFile:i},{computeDensityScaledScreenshotSize:a}]=await Promise.all([import(`./png-size.mjs`),import(`./png-resize.mjs`),import(`./screenshot-density.mjs`)]),o=await r(e),c=a(o,Math.max(o.width,o.height)/Math.max(t.width,t.height),n);c&&await i(e,c.width,c.height)}function Ke(e,t){let n=Math.min(e.width,t.width),r=Math.min(e.height,t.height);return{x:Math.max(0,Math.min(e.x,t.width-n)),y:Math.max(0,Math.min(e.y,t.height-r)),width:n,height:r}}function Z(e,t){return new s(`UNSUPPORTED_OPERATION`,t,{reason:`unsupported-provider-mode`,command:e})}function qe(e){return ee(r,[[`backendUrl`,f(e.backendUrl??`https://backend.revyl.ai`)],[`apiKey`,e.apiKey]])}function Je(e){let t=new Ye(e),n=te(r,qe({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl}}));if(n.kind!==`provider-runtime`)throw TypeError(`Invalid Revyl runtime owner`);return Object.freeze({runtime:t,platformModule:Object.freeze({owner:n,loadRuntime:async e=>await tt(t,n.instance,e)})})}var Ye=class{options;leases;provider=r;leaseLifecycle={allocate:(e,t)=>this.allocate(e,t),release:async e=>await this.release(e)};recoverExpiredLease=async e=>{$e(e,`recover`),await this.leases.recover(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.leases.live(e.leaseId);return t?d(t.device,e.platform)?[t.device]:[]:null};constructor(e){if(!e.apiKey.trim())throw TypeError(`Revyl runtime requires an apiKey`);this.options=e;let t=g({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl},clientVersion:e.clientVersion});this.leases=he(Xe(t))}ownsDevice(t){return e(t.id)!==void 0}hasLiveSession(e){return this.sessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.sessionForDevice(e);return n?We(n,t?.signal):void 0}async shutdown(){await this.leases.shutdown()}async allocate(e,n){let r=e.leaseProvider===this.provider?t(e.backend):void 0;if(r===void 0)return;let{rejectRefusedRevylProfileFields:i,requireSameRevylStartRequest:a,resolveRevylStartRequest:o}=await import(`./session-allocation.mjs`);i(n);let s={...o(n,{...this.options.deviceModel===void 0?{}:{deviceModel:this.options.deviceModel},...this.options.osVersion===void 0?{}:{osVersion:this.options.osVersion}}),platform:r};return $(await this.leases.allocate(e,s,{...Qe(n),requireJoinable:t=>a(e.leaseId,t,s)}))}async release(e){if(e.leaseProvider!==this.provider||!t(e.backend))return;let n=await this.leases.release(e.leaseId);if(n!==void 0)return n.session?$(n.session):{revylRunId:n.handle.runId,providerSessionId:n.handle.sessionId}}sessionForDevice(t){let n=e(t.id);if(!n)return;let r=this.leases.live(n.leaseId);return r?.platform===n.platform?r:void 0}};function Xe(e){return{startTimeoutMs:ie,start:async(t,n,r)=>{let i=await oe(e,t,{platform:n.platform,appUrl:n.appUrl,deviceModel:n.deviceModel,osVersion:n.osVersion,signal:r.signal,onRented:r.rented});if(i.status===`failed`)return i;let{runId:a,sessionId:o}=i.session;return{status:`ready`,session:i.session,handle:{runId:a,sessionId:o}}},stop:async t=>{try{await pe(e,t.sessionId)}catch(e){if(!p(e))throw e}},handleKey:e=>e.sessionId,findByLease:async e=>({sessionId:x(e.leaseId)}),shuttingDown:e=>et(e.leaseId,`allocate`),releasing:e=>new s(`COMMAND_FAILED`,`Revyl lease ${e.leaseId} is being released.`,{reason:`provider-lease-releasing`,leaseId:e.leaseId,hint:`Run open again; it allocates a new lease and rents a fresh device.`}),gaveUp:(e,t,n,r)=>w(Q(e),t,n,r?.sessionId??x(e.leaseId)),cleanupPending:(e,t,n)=>ce(e.map(e=>({...e.handle??{sessionId:x(e.leaseId)},failure:i(e.cause)})),Ze(t),n)}}function Ze(e){switch(e.route){case`shutdown`:return{operation:`shutdown`};case`start`:return{};case`release`:case`recover`:return{leaseId:e.leaseId}}}function Q(e){let n=t(e.backend);if(n===void 0)throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot serve this lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});return n}function Qe(e){return{...e?.signal===void 0?{}:{signal:e.signal},...e?.deadline===void 0?{}:{deadline:e.deadline}}}function $e(e,n){if(!(e.leaseProvider===`revyl`&&t(e.backend)))throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot ${n} this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend})}function et(e,t){return new s(`COMMAND_FAILED`,`The Revyl runtime is shutting down.`,{reason:`runtime-shutting-down`,operation:t,leaseId:e,hint:`Retry the command; the daemon is ending the sessions it holds.`})}async function tt(e,t,n){let{createRevylPlatformRuntimeOwner:r}=await import(`./platform-runtime.mjs`);return r({host:n,runtimeInstance:t,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n)})}function $(e){return{revylRunId:e.runId,providerSessionId:e.sessionId,device:e.device}}export{Je as createRevylRuntime};
1
+ import{a as e,o as t,r as n,t as r}from"./device.mjs";import{a as i,i as a,r as o,t as s}from"./errors.mjs";import{i as c,n as l,r as u}from"./snapshot-visibility.mjs";import{r as d}from"./device2.mjs";import{a as f,i as p,n as m,o as h,r as g}from"./revyl-client.mjs";import{n as ee,r as te,t as ne}from"./open-target.mjs";import _ from"node:fs";import v from"node:path";import{createHash as re,randomUUID as y}from"node:crypto";import{setTimeout as b}from"node:timers/promises";function x(e){let t=`${re(`sha256`).update(`agent-device:revyl:session:v1:${e}`).digest(`hex`).slice(0,32)}`;return[t.slice(0,8),t.slice(8,12),`4${t.slice(13,16)}`,`${(Number.parseInt(t.slice(16,17),16)&3|8).toString(16)}${t.slice(17,20)}`,t.slice(20,32)].join(`-`)}const S=24e4,ie=m+S+1e4,ae=new Set([503,409]);async function oe(e,t,r){let i=x(t.leaseId);if(r.signal?.aborted)return{status:`failed`,error:C(r)};let a;try{a=await se(e,r,i)}catch(e){return{status:`failed`,error:e,...T(e)?{rented:{sessionId:i}}:{}}}let o=typeof a.workflow_run_id==`string`?a.workflow_run_id:void 0,c=typeof a.session_id==`string`?a.session_id:void 0;if(o&&c&&c!==i)return{status:`failed`,rented:{runId:o,sessionId:c},error:new s(`COMMAND_FAILED`,`Revyl started the device as session ${c} instead of ${i}.`,{reason:`provider-session-identity-mismatch`,runId:o,providerSessionId:c,hint:`Retry the command; agent-device ends a Revyl session by the identity it issued.`})};if(!o)return{status:`failed`,rented:{sessionId:c??i},error:new s(`COMMAND_FAILED`,`Revyl did not start a ${r.platform} device: ${a.error??a.message??`no workflow run was returned`}`,{reason:`provider-start-refused`,platform:r.platform,...a.trace_id===void 0?{}:{traceId:a.trace_id}})};if(r.onRented?.({runId:o,sessionId:i}),r.signal?.aborted)return{status:`failed`,rented:{runId:o,sessionId:i},error:C(r)};let l=le(r);try{let a=await ue(e,o,l,{...r,sessionId:i});return{status:`ready`,session:{platform:r.platform,runId:o,sessionId:i,screen:me(a),dragDuration:a.supports_explicit_drag_duration===!0,device:n(r.platform,t,o),client:e,lease:t,launchedApp:{}}}}catch(e){return{status:`failed`,error:e,rented:{runId:o,sessionId:i}}}}async function se(e,t,n){if(t.signal?.aborted)throw C(t);let r={platform:t.platform,is_simulation:!0,session_id:n,idle_timeout_seconds:1800,...t.appUrl===void 0?{}:{app_url:t.appUrl},...t.deviceModel===void 0?{}:{device_model:t.deviceModel},...t.osVersion===void 0?{}:{os_version:t.osVersion}};return await e.startDevice(r)}function C(e){return new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e.platform},e.signal?.reason)}function w(e,t,n,r){let i=`agent-device stops Revyl session ${r} once its start answers; end it from Revyl if it stays listed.`;return t.signal?.aborted?new s(`COMMAND_FAILED`,`The Revyl device start was canceled before it was ready.`,{reason:`request_canceled`,platform:e,providerSessionId:r,hint:i},t.signal.reason):new s(`COMMAND_FAILED`,`Revyl did not report a ready device within ${n} ms.`,{reason:`provider-not-ready`,timeoutMs:n,providerSessionId:r,...t.deadline===void 0?{}:{deadline:t.deadline},hint:`Retry the command; Revyl may have had no device of that model available. ${i}`})}function T(e){return!h(e)}function ce(e,t={},n){let r=e.map(e=>e.sessionId).join(`, `),i=e.length===1?e[0]:void 0;return new s(`COMMAND_FAILED`,`Revyl did not release session${i?``:`s`} ${r}.`,{reason:`provider-cleanup-pending`,...t,providerSessionIds:e.map(e=>e.sessionId),causes:e.map(e=>e.failure),...i?{providerSessionId:i.sessionId,...i.runId===void 0?{}:{runId:i.runId},cause:i.failure}:{},hint:`End the Revyl session${i?``:`s`} ${r}; each device stays rented and billed until it is.`},n)}function le(e){let t=e.deadline===void 0?S:Math.min(S,e.deadline-Date.now());return{at:Date.now()+t,budgetMs:Math.max(0,t)}}async function ue(e,t,n,r){for(await fe(e,t,n,r);;){O(n,r);let i=await E(e,t,n,r);if(O(n,r),i.device_connected===!0)return i;await A(n,r.signal)}}async function E(e,t,n,r){try{return await D(()=>e.getWorkerHealth(t,k(n,r)),n,r)}catch(e){if(!de(e))throw e;return{}}}async function D(e,t,n){try{return await e()}catch(e){throw O(t,n),e}}function de(e){return e instanceof s&&typeof e.details?.providerStatus==`number`&&ae.has(e.details.providerStatus)}async function fe(e,t,n,r){for(;;){O(n,r);let i=await D(()=>e.getWorkerConnection(t,k(n,r)),n,r);if(O(n,r),i.status===`ready`&&i.worker_ws_url)return;if(i.status===`cancelled`||i.status===`stopped`||i.status===`failed`)throw new s(`COMMAND_FAILED`,`Revyl did not start the ${r.platform} device: ${i.status}${i.message===null||i.message===void 0?``:` (${i.message})`}`,{reason:`provider-start-failed`,runId:t,status:i.status});await A(n,r.signal)}}function O(e,t){if(!(Date.now()<e.at))throw w(t.platform,t,e.budgetMs,t.sessionId)}function k(e,t){let n=AbortSignal.timeout(Math.max(0,e.at-Date.now()));return t.signal===void 0?n:AbortSignal.any([t.signal,n])}async function A(e,t){await b(Math.min(2e3,Math.max(0,e.at-Date.now())),void 0,t===void 0?{}:{signal:t}).catch(()=>void 0)}async function pe(e,t){await e.stopDeviceSession(t)}function me(e){let{screen_width:t,screen_height:n}=e;if(!(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t)||!Number.isFinite(n)||t<=0||n<=0))return{width:t,height:n}}var j=class{lease;generation;phase=`starting`;request;answerBy;abandon=new AbortController;start=Promise.resolve({status:`failed`,error:void 0});answered=!1;answer;markAnswered=()=>void 0;session=void 0;rentals=new Map;latest=void 0;unnamed=!1;waiters=new Set;followUpQueued=!1;ending=void 0;constructor(e,t,n,r){this.lease=e,this.generation=t,this.request=n,this.answerBy=r,this.answer=new Promise(e=>{this.markAnswered=e})}};function he(e){let t=new ge(e);return Object.freeze({live:e=>t.live(e),allocate:async(e,n,r)=>await t.allocate(e,n,r),release:async e=>await t.release(e),recover:async e=>await t.recover(e),shutdown:async()=>await t.shutdown()})}var ge=class{entries=new Map;shuttingDown=!1;generations=0;driver;constructor(e){this.driver=e}live(e){let t=this.entries.get(e);return t?.phase===`ready`?t.session:void 0}isCurrent(e){return this.entries.get(e.lease.leaseId)?.generation===e.generation}refusal(e,t,n){return this.shuttingDown?this.driver.shuttingDown(e):t&&(t.phase===`ending`||!this.isCurrent(t))?this.driver.releasing(e):n()}async allocate(e,t,n={}){let r=this.entries.get(e.leaseId);if(this.shuttingDown||r?.phase===`ending`)throw this.refusal(e,r,()=>0);r?.request!==void 0&&n.requireJoinable?.(r.request);let i=N(n),a=Date.now()+this.driver.startTimeoutMs,o=Math.min(i.deadline??a,a);if(!r&&P(i,o))throw this.driver.gaveUp(e,i,0,void 0);let s=r??this.rent(e,t,i,a),c=Math.max(0,o-Date.now()),l=await this.join(s,i,o);return this.deliver(s,l,i,o,c)}deliver(e,t,n,r,i){if(t.status===`failed`)throw this.refusal(e.lease,void 0,()=>t.error);let a=this.refusal(e.lease,e,()=>P(n,r)?this.driver.gaveUp(e.lease,n,i,e.latest):void 0);if(a!==void 0)throw a;return t.session}async release(e){let t=this.entries.get(e);if(!t)return;let n=await this.teardown(t);if(n.status===`pending`)throw this.pending(t,n,{route:`release`,leaseId:e});return n.status===`stopped`?{handle:n.handle,session:n.session}:void 0}async recover(e){let t=e.leaseId,n=this.entries.get(t);if(n===void 0){if(this.shuttingDown)throw this.driver.shuttingDown(e);n=this.recovering(e)}let r=await this.teardown(n);if(r.status===`pending`)throw this.pending(n,r,{route:`recover`,leaseId:t})}async shutdown(){this.shuttingDown=!0;let e=[],t=[...this.entries.values()];if((await Promise.all(t.map(async e=>await this.teardown(e)))).forEach((n,r)=>{if(n.status!==`pending`)return;let i=t[r].lease.leaseId;for(let t of n.owed)e.push({leaseId:i,...t})}),e.length>0)throw this.driver.cleanupPending(e,{route:`shutdown`})}rent(e,t,n,r){let i=new j(e,this.generations+=1,t,r);return i.start=this.runStart(i,t,n),this.entries.set(e.leaseId,i),i}recovering(e){let t=new j(e,this.generations+=1,void 0,Date.now());return t.answered=!0,t.markAnswered(),t.unnamed=!0,t.phase=`ending`,this.entries.set(e.leaseId,t),t}async runStart(e,t,n){let r=Date.now(),i=await this.callStart(e,t);if(_e(e,i,this.driver.handleKey),i.status===`ready`&&(e.session=i.session,e.phase===`starting`&&this.isCurrent(e)&&F(e)))return e.phase=`ready`,{status:`ready`,session:i.session};let a;try{a=this.startFailure(e,i,n,r)}catch(e){a=e}return await this.endFailedStart(e,a)}async callStart(e,t){try{return await this.driver.start(e.lease,t,{signal:e.abandon.signal,deadline:e.answerBy,rented:t=>{e.answered||(M(e,t,this.driver.handleKey(t)),e.phase===`ending`&&this.followUp(e))}})}catch(e){return{status:`rejected`,error:e}}}startFailure(e,t,n,r){let i=Math.max(0,e.answerBy-r);return this.refusal(e.lease,e,()=>t.status===`ready`?this.driver.gaveUp(e.lease,n,i,t.handle):t.error)}async endFailedStart(e,t){if(e.phase===`ending`)return this.followUp(e),{status:`failed`,error:t};let n=await this.teardown(e);if(n.status!==`pending`)return{status:`failed`,error:t};let r=e.lease.leaseId;return{status:`failed`,error:this.driver.cleanupPending(n.owed.map(e=>({leaseId:r,...e})),{route:`start`,leaseId:r},t)}}async join(e,t,n){if(e.phase===`ready`)return{status:`ready`,session:e.session};let r=Math.max(0,n-Date.now()),i=()=>{try{return this.refusal(e.lease,e,()=>this.driver.gaveUp(e.lease,t,r,e.latest))}catch(e){return e}},a=new AbortController,o=setTimeout(()=>a.abort(),r),s=t.signal?[t.signal,a.signal]:[a.signal],c={deadline:n,signal:t.signal},l=()=>void 0;try{if(e.waiters.add(c),s.some(e=>e.aborted))throw i();let t=new Promise((t,n)=>{l=()=>{let t=i();e.waiters.delete(c),this.abandonIfUnwanted(e),n(t)};for(let e of s)e.addEventListener(`abort`,l,{once:!0})});return await Promise.race([e.start,t])}finally{e.waiters.delete(c),this.abandonIfUnwanted(e),clearTimeout(o);for(let e of s)e.removeEventListener(`abort`,l)}}abandonIfUnwanted(e){e.answered||e.phase===`ending`||F(e)||this.teardown(e).catch(()=>void 0)}teardown(e){if(e.phase=`ending`,e.answered||e.abandon.abort(),e.ending)return e.ending;let t=this.runTeardown(e).finally(()=>{e.ending===t&&(e.ending=void 0)});return e.ending=t,t}async runTeardown(e){let t=new Map;for(;;){await this.untilAnswered(e);let n=await this.nameRental(e);if(n!==void 0)return n;let r=await this.stopRentals(e,t);if(r!==`progress`){if(r.length>0)return{status:`pending`,owed:r};if(!(e.unnamed||[...e.rentals.values()].some(e=>!e.stopped)))return this.finishTeardown(e)}}}async stopRentals(e,t){for(let n of e.rentals.values()){if(n.stopped)continue;if(t.get(n)!==void 0){if(n.stopping!==void 0)break;continue}let e=await this.stop(n);if(e===void 0)return`progress`;if(t.set(n,{handle:n.handle,cause:e.cause}),n.stopping!==void 0)break}return[...e.rentals.values()].filter(e=>!e.stopped).map(e=>t.get(e)??{handle:e.handle,cause:Error(`The stop waits for an earlier stop of this lease that is still in flight.`)})}async nameRental(e){if(e.unnamed)try{let t=await this.driver.findByLease(e.lease);M(e,t,this.driver.handleKey(t)),e.unnamed=!1;return}catch(e){return{status:`pending`,owed:[{handle:void 0,cause:e}]}}}finishTeardown(e){let t=e.latest;return e.answered?(this.isCurrent(e)&&this.entries.delete(e.lease.leaseId),t===void 0?{status:`nothing-rented`}:{status:`stopped`,handle:t,session:e.session}):{status:`pending`,owed:[{handle:t,cause:Error(`The provider start did not answer within its start timeout.`)}]}}followUp(e){let t=e.ending;if(t===void 0){this.teardown(e).catch(()=>void 0);return}e.followUpQueued||(e.followUpQueued=!0,t.then(async()=>(e.followUpQueued=!1,await this.teardown(e))).catch(()=>void 0))}async untilAnswered(e){if(e.answered)return;let t,n=new Promise(n=>{t=setTimeout(n,Math.max(0,e.answerBy-Date.now()))});try{await Promise.race([e.answer,n])}finally{clearTimeout(t)}}async stop(e){e.stopping??=this.stopHandle(e.handle).then(t=>(t===void 0&&(e.stopped=!0),e.stopping=void 0,t));let t=e.stopping,n=this.driver.stopTimeoutMs;if(n===void 0)return await t;let r,i=new Promise(e=>{r=setTimeout(()=>e({cause:Error(`The provider stop did not answer within ${n} ms.`)}),n)});try{return await Promise.race([t,i])}finally{clearTimeout(r)}}async stopHandle(e){try{await this.driver.stop(e);return}catch(e){return{cause:e}}}pending(e,t,n){return this.driver.cleanupPending(t.owed.map(t=>({leaseId:e.lease.leaseId,...t})),n)}};function _e(e,t,n){switch(t.status){case`ready`:M(e,t.handle,n(t.handle));break;case`failed`:t.rented!==void 0&&M(e,t.rented,n(t.rented));break;case`rejected`:e.rentals.size===0&&(e.unnamed=!0)}e.answered=!0,e.markAnswered()}function M(e,t,n){e.rentals.has(n)||e.rentals.set(n,{handle:t,stopped:!1,stopping:void 0}),e.latest=t}function N(e){return{...e.signal===void 0?{}:{signal:e.signal},...e.deadline===void 0?{}:{deadline:e.deadline}}}function P(e,t){return e.signal?.aborted===!0||Date.now()>=t}function F(e){if(e.phase===`ending`)return!1;let t=Date.now();for(let n of e.waiters)if(!n.signal?.aborted&&t<n.deadline)return!0;return!1}new Map([...Object.entries({ios:`ios-instance`,android:`android-instance`,harmonyos:`harmonyos-instance`}).flatMap(([e,t])=>t===void 0?[]:[[t,e]]),[`macos-app`,`macos`]]);function I(e,t={message:e=>`Invalid value: ${e}`}){let n=new Set(e),r=t.normalize??(e=>e);return{is:e=>typeof e==`string`&&n.has(e),parse:e=>{let i=r(e??``);if(n.has(i))return i;throw new s(`INVALID_ARGS`,t.message(e??``))}}}I([`up`,`down`,`left`,`right`],{message:e=>`Unknown direction: ${e}`});function ve(e){let t=e.direction,n=t===`up`||t===`down`,r=n?e.referenceHeight:e.referenceWidth,i=n?e.referenceWidth:e.referenceHeight,a=xe(e.amount),o=e.pixels===void 0?Math.round(r*a):Se(e.pixels),s=L(r),c=Math.max(1,r-s*2),l=Math.max(1,Math.min(o,c)),u=Math.round(l/2),d=Math.round(r/2),f={axisStart:d-u,axisEnd:d+u,cross:Math.round(i/2)},p=L(i),m=e.container?be(f,e.container,n,{axis:{min:s,max:r-s},cross:{min:p,max:i-p},crossFrame:{min:0,max:i}}):f,h=m.axisEnd-m.axisStart,g=h<l;return{direction:t,...ye(t,m),referenceWidth:e.referenceWidth,referenceHeight:e.referenceHeight,amount:e.amount,pixels:g?h:l,...g?{requestedPixels:l}:{}}}function ye(e,t){let n=e===`up`||e===`down`,r=n?{x:t.cross,y:t.axisStart}:{x:t.axisStart,y:t.cross},i=n?{x:t.cross,y:t.axisEnd}:{x:t.axisEnd,y:t.cross},[a,o]=e===`up`||e===`left`?[r,i]:[i,r];return{x1:a.x,y1:a.y,x2:o.x,y2:o.y}}function L(e){return Math.max(1,Math.round(e*.1))}function be(e,t,n,r){let i=R(n?t.y:t.x,n?t.height:t.width,r.axis),a=n?t.x:t.y,o=n?t.width:t.height,s=R(a,o,r.cross)??R(a,o,r.crossFrame);if(!i||!s)return e;let c=e.cross>=s.min&&e.cross<=s.max?e.cross:Math.round((s.min+s.max)/2);if(e.axisEnd-e.axisStart>=i.max-i.min)return{axisStart:i.min,axisEnd:i.max,cross:c};let l=e.axisStart<i.min?i.min-e.axisStart:Math.min(0,i.max-e.axisEnd);return{axisStart:e.axisStart+l,axisEnd:e.axisEnd+l,cross:c}}function R(e,t,n){let r=Math.max(n.min,Math.ceil(e)+8),i=Math.min(n.max,Math.floor(e+t)-1-8);return i>r?{min:r,max:i}:void 0}function xe(e){if(e===void 0)return .6;if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll amount must be a positive number`);return e}function Se(e){if(!Number.isFinite(e)||e<=0)throw new s(`INVALID_ARGS`,`scroll pixels must be a positive integer`);return Math.max(1,Math.round(e))}Object.freeze({reason:`scroll_keyboard_occludes_surface`,hint:"The on-screen keyboard covers the surface this scroll would swipe, so it cannot reach it. Run `keyboard dismiss` and retry, accepting that it drops focus (re-tap the field to keep typing), or scroll before focusing the field."});const z=new Set([`com.google.android.inputmethod.latin`,`com.samsung.android.honeyboard`,`com.touchtype.swiftkey`,`com.microsoft.swiftkey`]);function Ce(e){let t=B(e.packageName),n=(e.resourceId??``).toLowerCase(),r=B(e.activeInputMethodPackage);if(t&&r&&t===r)return{inputMethodOwned:!0,source:`active-input-method`};if(r&&n.startsWith(`${r}:id/`))return{inputMethodOwned:!0,source:`active-input-method-resource`};if(t&&z.has(t))return{inputMethodOwned:!0,source:`known-ime-package`};for(let e of z)if(n.startsWith(`${e}:id/`))return{inputMethodOwned:!0,source:`known-ime-resource`};return{inputMethodOwned:!1,source:`app`}}function we(e){return Ce(e).inputMethodOwned}function Te(e){return we({packageName:e.bundleId,resourceId:e.identifier})}function B(e){return(e??``).trim().toLowerCase()||void 0}const Ee=new Set([`UIKeyboardDockItemButton`,`UIAccessibilityElementKBKey`]),De=new Set([`TUIPredictionViewCell`]),Oe=new Set([`UIKeyboardLayoutStar`,`TUIPredictionView`]),V=new Set([`_UIRemoteKeyboardPlaceholderView`,`TUISystemInputAssistantView`,`TUISystemInputAssistantPageView`]);function H(e,t){return e.role!==void 0&&t.has(e.role)}Object.freeze({reason:`tap_keyboard_occludes_target`,hint:"The visible keyboard covers this target, so the tap would land on a key instead of on it. End editing first: tap the app's own Done/Cancel/close control, or run `keyboard enter` when submitting is what you want (`keyboard dismiss` works only when the keyboard exposes its own dismiss key). This reads the snapshot the command measured against, so if the keyboard closed since it was taken, run `snapshot -i` and retry."});const ke=new Set([`keyboard`,`key`]);function U(e){return ke.has(l(e.type??``))||Te(e)}function W(e){return U(e)||Ee.has(e.role??``)}function G(e){return U(e)||H(e,Oe)}function Ae(e,t){if(W(e)||H(e,De)||H(e,V)||G(e))return!0;let n=new Set,r=e.parentIndex;for(;typeof r==`number`&&!n.has(r);){n.add(r);let e=t.get(r);if(!e)return!1;if(H(e,V)||G(e))return!0;r=e.parentIndex}return!1}function K(e){return e!==null&&u(e)}function q(e){return e.flatMap(e=>u(e.rect)?[e.rect]:[])}function je(e,t){let n=new Map(e.map(e=>[e.index,e.parentIndex])),r=new Set(t.map(e=>e.index)),i=new Set;for(let e of t)for(let t of Me(n,r,e.index))i.add(t);return i}function Me(e,t,n){let r=[],i=new Set,a=e.get(n);for(;typeof a==`number`&&!i.has(a);)i.add(a),t.has(a)&&r.push(a),a=e.get(a);return r}function Ne(e){let t=e.map(e=>[e.x,e.x+e.width]).sort((e,t)=>e[0]-t[0]),n=t[0]?.[1]??0;for(let[e,r]of t){if(e-n>2)return!1;n=Math.max(n,r)}return!0}function Pe(e){let t=Math.min(...e.anchorRects.map(e=>e.y)),n=Math.min(...e.anchorRects.map(e=>e.x)),r=Math.max(...e.anchorRects.map(e=>e.x+e.width)),i=e.viewport.y+e.viewport.height;return e.reportedBottom<i-80||r-n<=e.reportedBottom-t?null:{x:n,y:t,width:r-n,height:i-t}}function Fe(e){let t=q(e.anchorNodes.filter(t=>!e.planeIndices.has(t.index)));return Ne(t.length>0?t:e.anchorRects)}function Ie(e,t){let n=e.filter(U),r=q(n);if(r.length===0||!K(t))return null;let i=e.filter(W),a=q(i);if(a.length===0)return null;let o=Pe({anchorRects:r,reportedBottom:Math.max(...a.map(e=>e.y+e.height)),viewport:t});return!o||!u(o)||!Fe({anchorNodes:n,anchorRects:r,planeIndices:je(e,i)})?null:o}function J(e){let t=new Map(e.nodes.map(e=>[e.index,e]));return{nodes:e.nodes.map(e=>({...e,keyboardOwned:Ae(e,t)})),keyboard:Le(e)}}function Le(e){let t=Ie(e.nodes,e.viewport);return t?{kind:`derived`,derivation:`docked-tree`,frame:t,treeBound:!0}:K(e.viewport)&&e.nodes.some(U)?{kind:`tree-rejected`,derivation:`docked-tree`,...typeof e.visibility==`boolean`?{visible:e.visibility}:{}}:typeof e.visibility==`boolean`?{kind:`visibility-only`,visible:e.visibility}:{kind:`unmeasurable`,reason:e.nodes.some(U)?`keyboard-viewport-unavailable`:e.visibility===`failed`?`keyboard-visibility-probe-failed`:e.visibility===`unsupported`?`keyboard-visibility-probe-unsupported`:`keyboard-not-observed`}}function Re(e){return{readHierarchy:t=>e.client.getWorkerHierarchy(e.runId,t),viewport:()=>e.screen===void 0?void 0:c({x:0,y:0,...e.screen})}}async function ze(e,t,n){let r=await t.readHierarchy(n);return n?.throwIfAborted(),e.platform===`ios`?await Be(r,e.runId,t.viewport()):await He(r,t.viewport())}async function Be(e,t,n){let[{flattenIosTree:r,resolveIosAxTreeViewport:i},{interpretIosNode:a},o]=await Promise.all([import(`./ios-ax-tree.mjs`),import(`./ios-node-interpretation.mjs`),import(`./ios-snapshot-acquisition.mjs`)]),s=Ve(e),c=i(s,n);return o.createIosSnapshotAcquisition({producer:`revyl-ios-tree`,...J({nodes:r(s).map(e=>a(e)),viewport:c.kind===`missing`?null:c.rect}),viewport:c,lineage:{targetId:t}})}function Ve(e){let t;try{t=JSON.parse(e)}catch(e){throw X(e)}let n=Array.isArray(t)?t:[t];if(!n.every(Y))throw X();return n}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;return[t.children,t.nodes,t.elements].every(e=>e===void 0||Array.isArray(e)&&e.every(Y))}function X(e){return new s(`COMMAND_FAILED`,`Revyl returned an iOS hierarchy that is not an accessibility node tree.`,{reason:`provider-response-invalid`},e)}async function He(e,t){let[{parseWebDriverAndroidSnapshotNodes:n},{stampSnapshotIdentity:r}]=await Promise.all([import(`./webdriver-android-source.mjs`),import(`./snapshot-producers.mjs`).then(e=>e.n)]),{nodes:i,keyboard:a}=J({nodes:n(e),viewport:t===void 0?null:{x:0,y:0,...t}});return r({nodes:i,keyboard:a,...t===void 0?{}:{viewport:t}},{backend:`android`,producer:`revyl-android-tree`})}var Ue=class{session;signal;constructor(e,t){this.session=e,this.signal=t}async open(e,t){let n=e.trim();if(t?.url)return await this.launch(n,t.launchArgs),await this.workerAction(`open_url`,{url:t.url}),n?{launchedAppBundleId:n}:void 0;if(ne(n)){await this.workerAction(`open_url`,{url:n});return}return await this.launch(n,t?.launchArgs),n?{launchedAppBundleId:n}:void 0}async launch(e,t){if(t?.length)throw new s(`UNSUPPORTED_OPERATION`,`Revyl launches an app without arguments.`,{reason:`unsupported-provider-mode`,hint:`Open a deep link instead: open <url>.`});await this.workerAction(`launch`,e?{bundle_id:e}:{}),e&&(this.session.launchedApp.bundleId=e)}async openDevice(){}async close(e){let t=e.trim();t&&this.requireCloseableApp(t,this.session.launchedApp.bundleId),await this.workerAction(`kill_app`)}requireCloseableApp(e,t){if(t===void 0)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl session has not launched ${e}, so it has no app to end.`,{reason:`provider-app-not-launched`,command:`close`,requestedApp:e,hint:`Close without an app name to end the app this session runs, or open the app first.`});if(e!==t)throw new s(`UNSUPPORTED_OPERATION`,`Revyl ends the app this session launched (${t}), not ${e}.`,{reason:`unsupported-provider-mode`,command:`close`,sessionApp:t,requestedApp:e,hint:"Revyl has no way to name an app to `/kill_app`; end the session to stop what it runs."})}async tap(e,t){await this.workerAction(`tap`,{x:e,y:t})}async doubleTap(e,t){await this.workerAction(`double_tap`,{x:e,y:t})}async longPress(e,t,n=1500){await this.workerAction(`longpress`,{x:e,y:t,duration_ms:n})}async focus(e,t){await this.tap(e,t)}type(){throw Z(`type`,`Revyl enters text at a point; run fill <field> "text" instead of type.`)}async fill(e,t,n,r,i){if(n===``){await this.workerAction(`clear_text`,{x:e,y:t});return}if(!r||r<=0){await this.workerAction(`input`,{x:e,y:t,text:n,clear_first:!0});return}let s=0,c=Array.from(n);try{for(let[n,i]of c.entries()){if(this.signal?.aborted)throw s===0?o(this.cancellation(),`no`):this.cancellation();if(await this.workerAction(`input`,{x:e,y:t,text:i,clear_first:s===0}),s+=1,n===c.length-1)return;await b(r,void 0,this.signal===void 0?{}:{signal:this.signal})}}catch(e){throw a(this.canceledAs(e),s)}}async scroll(e,t){let n=t?.durationMs;n!==void 0&&this.requireDragDuration(n);let r=this.session.screen;if(!r)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the scroll distance cannot be planned.`,{reason:`provider-viewport-unavailable`,runId:this.session.runId});let i=ve({direction:e,...t?.amount===void 0?{}:{amount:t.amount},...t?.pixels===void 0?{}:{pixels:t.pixels},referenceWidth:r.width,referenceHeight:r.height,...t?.containerRect===void 0?{}:{container:Ke(t.containerRect,r)}});return await this.workerAction(`drag`,{start_x:i.x1,start_y:i.y1,end_x:i.x2,end_y:i.y2,...n===void 0?{}:{duration_ms:n}}),{...i,...n===void 0?{}:{durationMs:n},backend:`revyl-device-proxy`}}requireDragDuration(e){if(!this.session.dragDuration)throw new s(`UNSUPPORTED_OPERATION`,`This Revyl worker scrolls with one drag and cannot be told how fast the finger travels.`,{reason:`unsupported-provider-mode`,command:`scroll`,flag:`--duration-ms`,runId:this.session.runId,hint:`Scroll without --duration-ms; the drag runs at the speed Revyl gives it.`});if(e<1)throw new s(`INVALID_ARGS`,`Revyl drag --duration-ms must be at least 1.`,{flag:`--duration-ms`})}async screenshot(e,t){let n=await this.session.client.captureWorkerScreenshot(this.session.runId,this.signal),r=v.dirname(e);_.mkdirSync(r,{recursive:!0});let i=v.join(r,`.${v.basename(e)}.${process.pid}.${y()}.tmp`);try{if(await _.promises.writeFile(i,n,this.signal===void 0?{}:{signal:this.signal}),this.session.platform===`ios`&&await Ge(i,this.session.screen,t?.pixelDensity),this.signal?.aborted===!0)throw this.cancellation();await _.promises.rename(i,e)}catch(e){throw await _.promises.rm(i,{force:!0}).catch(()=>void 0),this.canceledAs(e)}}async snapshot(e){return await ze(this.session,Re(this.session),e?.signal??this.signal)}async back(){await this.workerAction(`back`)}async home(){await this.workerAction(`go_home`)}setOrientation(e){throw Z(`orientation`,`Revyl does not expose orientation control.`)}setSetting(){throw Z(`settings`,`Revyl does not expose settings control.`)}cancellation(e){return new s(`COMMAND_FAILED`,`The Revyl action was canceled before it finished.`,{reason:`request_canceled`,runId:this.session.runId},e??this.signal?.reason)}canceledAs(e){return!this.signal?.aborted||e instanceof s?e:this.cancellation(e)}workerAction(e,t){return this.session.client.workerAction(this.session.runId,e,t,this.signal)}};function We(e,t){return new Ue(e,t)}async function Ge(e,t,n){if(t===void 0)throw new s(`COMMAND_FAILED`,`Revyl reported no screen size for this session, so the screenshot density cannot be known.`,{reason:`provider-viewport-unavailable`});let[{readPngSize:r},{resizePngFile:i},{computeDensityScaledScreenshotSize:a}]=await Promise.all([import(`./png-size.mjs`),import(`./png-resize.mjs`),import(`./screenshot-density.mjs`)]),o=await r(e),c=a(o,Math.max(o.width,o.height)/Math.max(t.width,t.height),n);c&&await i(e,c.width,c.height)}function Ke(e,t){let n=Math.min(e.width,t.width),r=Math.min(e.height,t.height);return{x:Math.max(0,Math.min(e.x,t.width-n)),y:Math.max(0,Math.min(e.y,t.height-r)),width:n,height:r}}function Z(e,t){return new s(`UNSUPPORTED_OPERATION`,t,{reason:`unsupported-provider-mode`,command:e})}function qe(e){return ee(r,[[`backendUrl`,f(e.backendUrl??`https://backend.revyl.ai`)],[`apiKey`,e.apiKey]])}function Je(e){let t=new Ye(e),n=te(r,qe({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl}}));if(n.kind!==`provider-runtime`)throw TypeError(`Invalid Revyl runtime owner`);return Object.freeze({runtime:t,platformModule:Object.freeze({owner:n,loadRuntime:async e=>await tt(t,n.instance,e)})})}var Ye=class{options;leases;provider=r;leaseLifecycle={allocate:(e,t)=>this.allocate(e,t),release:async e=>await this.release(e)};recoverExpiredLease=async e=>{$e(e,`recover`),await this.leases.recover(e)};deviceInventoryProvider=async e=>{if(e.leaseProvider!==this.provider||!e.leaseId)return null;let t=this.leases.live(e.leaseId);return t?d(t.device,e.platform)?[t.device]:[]:null};constructor(e){if(!e.apiKey.trim())throw TypeError(`Revyl runtime requires an apiKey`);this.options=e;let t=g({apiKey:e.apiKey,...e.backendUrl===void 0?{}:{backendUrl:e.backendUrl},clientVersion:e.clientVersion});this.leases=he(Xe(t))}ownsDevice(t){return e(t.id)!==void 0}hasLiveSession(e){return this.sessionForDevice(e)!==void 0}getInteractor(e,t){let n=this.sessionForDevice(e);return n?We(n,t?.signal):void 0}async shutdown(){await this.leases.shutdown()}async allocate(e,n){let r=e.leaseProvider===this.provider?t(e.backend):void 0;if(r===void 0)return;let{rejectRefusedRevylProfileFields:i,requireSameRevylStartRequest:a,resolveRevylStartRequest:o}=await import(`./session-allocation.mjs`);i(n);let s={...o(n,{...this.options.deviceModel===void 0?{}:{deviceModel:this.options.deviceModel},...this.options.osVersion===void 0?{}:{osVersion:this.options.osVersion}}),platform:r};return $(await this.leases.allocate(e,s,{...Qe(n),requireJoinable:t=>a(e.leaseId,t,s)}))}async release(e){if(e.leaseProvider!==this.provider||!t(e.backend))return;let n=await this.leases.release(e.leaseId);if(n!==void 0)return n.session?$(n.session):{revylRunId:n.handle.runId,providerSessionId:n.handle.sessionId}}sessionForDevice(t){let n=e(t.id);if(!n)return;let r=this.leases.live(n.leaseId);return r?.platform===n.platform?r:void 0}};function Xe(e){return{startTimeoutMs:ie,start:async(t,n,r)=>{let i=await oe(e,t,{platform:n.platform,appUrl:n.appUrl,deviceModel:n.deviceModel,osVersion:n.osVersion,signal:r.signal,onRented:r.rented});if(i.status===`failed`)return i;let{runId:a,sessionId:o}=i.session;return{status:`ready`,session:i.session,handle:{runId:a,sessionId:o}}},stop:async t=>{try{await pe(e,t.sessionId)}catch(e){if(!p(e))throw e}},handleKey:e=>e.sessionId,findByLease:async e=>({sessionId:x(e.leaseId)}),shuttingDown:e=>et(e.leaseId,`allocate`),releasing:e=>new s(`COMMAND_FAILED`,`Revyl lease ${e.leaseId} is being released.`,{reason:`provider-lease-releasing`,leaseId:e.leaseId,hint:`Run open again; it allocates a new lease and rents a fresh device.`}),gaveUp:(e,t,n,r)=>w(Q(e),t,n,r?.sessionId??x(e.leaseId)),cleanupPending:(e,t,n)=>ce(e.map(e=>({...e.handle??{sessionId:x(e.leaseId)},failure:i(e.cause)})),Ze(t),n)}}function Ze(e){switch(e.route){case`shutdown`:return{operation:`shutdown`};case`start`:return{};case`release`:case`recover`:return{leaseId:e.leaseId}}}function Q(e){let n=t(e.backend);if(n===void 0)throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot serve this lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend});return n}function Qe(e){return{...e?.signal===void 0?{}:{signal:e.signal},...e?.deadline===void 0?{}:{deadline:e.deadline}}}function $e(e,n){if(!(e.leaseProvider===`revyl`&&t(e.backend)))throw new s(`UNSUPPORTED_OPERATION`,`Revyl cannot ${n} this expired lease.`,{leaseId:e.leaseId,leaseProvider:e.leaseProvider,leaseBackend:e.backend})}function et(e,t){return new s(`COMMAND_FAILED`,`The Revyl runtime is shutting down.`,{reason:`runtime-shutting-down`,operation:t,leaseId:e,hint:`Retry the command; the daemon is ending the sessions it holds.`})}async function tt(e,t,n){let{createRevylPlatformRuntimeOwner:r}=await import(`./platform-runtime.mjs`);return r({host:n,runtimeInstance:t,ownsDevice:t=>e.ownsDevice(t),hasLiveSession:t=>e.hasLiveSession(t),getInteractor:(t,n)=>e.getInteractor(t,n)})}function $(e){return{revylRunId:e.runId,providerSessionId:e.sessionId,device:e.device}}export{Je as createRevylRuntime};
@@ -1 +1 @@
1
- Object.freeze([`unknown`,`notRunning`,`runningBackgroundSuspended`,`runningBackground`,`runningForeground`].filter(e=>e!==`runningForeground`));const e={x:-Number.MAX_VALUE/2,y:-Number.MAX_VALUE/2,width:Number.MAX_VALUE,height:Number.MAX_VALUE};function t(t){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function n(e){if(!e)return!1;let{x:n,y:r,width:i,height:a}=e;return![n,r,i,a].every(Number.isFinite)||!Number.isFinite(n+i)||!Number.isFinite(r+a)||i<=0||a<=0?!1:!t(e)}function r(t,n){return t>=e.width||n>=e.height}function i(e){if(n(e)&&!r(e.width,e.height))return{width:e.width,height:e.height}}function a(e){let t=e.trim().replaceAll(/XCUIElementType/gi,``).replace(/^AX/,``).toLowerCase(),n=Math.max(t.lastIndexOf(`.`),t.lastIndexOf(`/`));return n!==-1&&(t=t.slice(n+1)),t}function o(e,t){let n=a(e);return n?t===`android`?n.includes(`edittext`)||n.includes(`autocompletetextview`):n.includes(`textfield`)||n.includes(`securetextfield`)||n.includes(`searchfield`)||n.includes(`textview`)||n.includes(`textarea`)||n===`search`:!0}function s({type:e,text:t,editable:n,password:r,hintShowing:i}){if(n===!0||r===!0||a(e??``)&&o(e??``,`android`))return i===!0?``:t??void 0}export{i,a as n,n as r,s as t};
1
+ Object.freeze([`unknown`,`notRunning`,`runningBackgroundSuspended`,`runningBackground`,`runningForeground`].filter(e=>e!==`runningForeground`));const e={x:-Number.MAX_VALUE/2,y:-Number.MAX_VALUE/2,width:Number.MAX_VALUE,height:Number.MAX_VALUE};function t(t){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function n(e){if(!e)return!1;let{x:n,y:r,width:i,height:a}=e;return![n,r,i,a].every(Number.isFinite)||!Number.isFinite(n+i)||!Number.isFinite(r+a)||i<=0||a<=0?!1:!t(e)}function r(t,n){return t>=e.width||n>=e.height}function i(e){if(n(e)&&!r(e.width,e.height))return{width:e.width,height:e.height}}function a(e){let t=e.trim().replaceAll(/XCUIElementType/gi,``).replace(/^AX/,``).toLowerCase(),n=Math.max(t.lastIndexOf(`.`),t.lastIndexOf(`/`));return n!==-1&&(t=t.slice(n+1)),t}function o(e,t){let n=a(e);return n?t===`android`?n.includes(`edittext`)||n.includes(`autocompletetextview`):t===`web`&&(n===`textbox`||n===`searchbox`)||n.includes(`textfield`)||n.includes(`securetextfield`)||n.includes(`searchfield`)||n.includes(`textview`)||n.includes(`textarea`)||n===`search`:!0}function s({type:e,text:t,editable:n,password:r,hintShowing:i}){if(n===!0||r===!0||a(e??``)&&o(e??``,`android`))return i===!0?``:t??void 0}export{i,a as n,n as r,s as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-device/revyl",
3
- "version": "0.21.37-nightly.20261111.157",
3
+ "version": "0.21.37",
4
4
  "type": "module",
5
5
  "description": "Revyl cloud iOS simulator and Android emulator plugin for agent-device.",
6
6
  "files": [
@@ -17,11 +17,11 @@
17
17
  "devDependencies": {
18
18
  "@agent-device/capture-kit": "0.0.0",
19
19
  "@agent-device/kernel": "0.0.0",
20
- "@agent-device/provider-webdriver": "0.0.0",
21
- "@agent-device/test-kit": "0.0.0",
22
- "@agent-device/provision-kit": "0.0.0",
23
20
  "@agent-device/contracts": "0.0.0",
24
- "agent-device": "0.21.37-nightly.20261111.157"
21
+ "@agent-device/provision-kit": "0.0.0",
22
+ "@agent-device/provider-webdriver": "0.0.0",
23
+ "agent-device": "0.21.37",
24
+ "@agent-device/test-kit": "0.0.0"
25
25
  },
26
26
  "agentDevicePlugin": {
27
27
  "apiVersion": 1,